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.

278692 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. #include <Carbon/Carbon.h>
  727. #endif
  728. #include <sys/dir.h>
  729. #endif
  730. #include <sys/socket.h>
  731. #include <sys/sysctl.h>
  732. #include <sys/stat.h>
  733. #include <sys/param.h>
  734. #include <sys/mount.h>
  735. #include <fnmatch.h>
  736. #include <utime.h>
  737. #include <dlfcn.h>
  738. #include <ifaddrs.h>
  739. #include <net/if_dl.h>
  740. #include <mach/mach_time.h>
  741. #include <mach-o/dyld.h>
  742. #if MACOS_10_4_OR_EARLIER
  743. #include <GLUT/glut.h>
  744. #endif
  745. #if ! CGFLOAT_DEFINED
  746. #define CGFloat float
  747. #endif
  748. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  749. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  750. #else
  751. #error "Unknown platform!"
  752. #endif
  753. #endif
  754. //==============================================================================
  755. #define DONT_SET_USING_JUCE_NAMESPACE 1
  756. #undef max
  757. #undef min
  758. #define NO_DUMMY_DECL
  759. #if JUCE_BUILD_NATIVE
  760. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  761. #endif
  762. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  763. #pragma warning (disable: 4309 4305)
  764. #endif
  765. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  766. BEGIN_JUCE_NAMESPACE
  767. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  768. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  769. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  770. /**
  771. Creates a floating carbon window that can be used to hold a carbon UI.
  772. This is a handy class that's designed to be inlined where needed, e.g.
  773. in the audio plugin hosting code.
  774. */
  775. class CarbonViewWrapperComponent : public Component,
  776. public ComponentMovementWatcher,
  777. public Timer
  778. {
  779. public:
  780. CarbonViewWrapperComponent()
  781. : ComponentMovementWatcher (this),
  782. wrapperWindow (0),
  783. carbonWindow (0),
  784. embeddedView (0),
  785. recursiveResize (false)
  786. {
  787. }
  788. virtual ~CarbonViewWrapperComponent()
  789. {
  790. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  791. }
  792. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  793. virtual void removeView (HIViewRef embeddedView) = 0;
  794. virtual void mouseDown (int, int) {}
  795. virtual void paint() {}
  796. virtual bool getEmbeddedViewSize (int& w, int& h)
  797. {
  798. if (embeddedView == 0)
  799. return false;
  800. HIRect bounds;
  801. HIViewGetBounds (embeddedView, &bounds);
  802. w = jmax (1, roundToInt (bounds.size.width));
  803. h = jmax (1, roundToInt (bounds.size.height));
  804. return true;
  805. }
  806. void createWindow()
  807. {
  808. if (wrapperWindow == 0)
  809. {
  810. Rect r;
  811. r.left = getScreenX();
  812. r.top = getScreenY();
  813. r.right = r.left + getWidth();
  814. r.bottom = r.top + getHeight();
  815. CreateNewWindow (kDocumentWindowClass,
  816. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  817. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  818. &r, &wrapperWindow);
  819. jassert (wrapperWindow != 0);
  820. if (wrapperWindow == 0)
  821. return;
  822. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  823. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  824. [ownerWindow addChildWindow: carbonWindow
  825. ordered: NSWindowAbove];
  826. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  827. EventTypeSpec windowEventTypes[] =
  828. {
  829. { kEventClassWindow, kEventWindowGetClickActivation },
  830. { kEventClassWindow, kEventWindowHandleDeactivate },
  831. { kEventClassWindow, kEventWindowBoundsChanging },
  832. { kEventClassMouse, kEventMouseDown },
  833. { kEventClassMouse, kEventMouseMoved },
  834. { kEventClassMouse, kEventMouseDragged },
  835. { kEventClassMouse, kEventMouseUp},
  836. { kEventClassWindow, kEventWindowDrawContent },
  837. { kEventClassWindow, kEventWindowShown },
  838. { kEventClassWindow, kEventWindowHidden }
  839. };
  840. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  841. InstallWindowEventHandler (wrapperWindow, upp,
  842. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  843. windowEventTypes, this, &eventHandlerRef);
  844. setOurSizeToEmbeddedViewSize();
  845. setEmbeddedWindowToOurSize();
  846. creationTime = Time::getCurrentTime();
  847. }
  848. }
  849. void deleteWindow()
  850. {
  851. removeView (embeddedView);
  852. embeddedView = 0;
  853. if (wrapperWindow != 0)
  854. {
  855. RemoveEventHandler (eventHandlerRef);
  856. DisposeWindow (wrapperWindow);
  857. wrapperWindow = 0;
  858. }
  859. }
  860. void setOurSizeToEmbeddedViewSize()
  861. {
  862. int w, h;
  863. if (getEmbeddedViewSize (w, h))
  864. {
  865. if (w != getWidth() || h != getHeight())
  866. {
  867. startTimer (50);
  868. setSize (w, h);
  869. if (getParentComponent() != 0)
  870. getParentComponent()->setSize (w, h);
  871. }
  872. else
  873. {
  874. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  875. }
  876. }
  877. else
  878. {
  879. stopTimer();
  880. }
  881. }
  882. void setEmbeddedWindowToOurSize()
  883. {
  884. if (! recursiveResize)
  885. {
  886. recursiveResize = true;
  887. if (embeddedView != 0)
  888. {
  889. HIRect r;
  890. r.origin.x = 0;
  891. r.origin.y = 0;
  892. r.size.width = (float) getWidth();
  893. r.size.height = (float) getHeight();
  894. HIViewSetFrame (embeddedView, &r);
  895. }
  896. if (wrapperWindow != 0)
  897. {
  898. Rect wr;
  899. wr.left = getScreenX();
  900. wr.top = getScreenY();
  901. wr.right = wr.left + getWidth();
  902. wr.bottom = wr.top + getHeight();
  903. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  904. ShowWindow (wrapperWindow);
  905. }
  906. recursiveResize = false;
  907. }
  908. }
  909. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  910. {
  911. setEmbeddedWindowToOurSize();
  912. }
  913. void componentPeerChanged()
  914. {
  915. deleteWindow();
  916. createWindow();
  917. }
  918. void componentVisibilityChanged (Component&)
  919. {
  920. if (isShowing())
  921. createWindow();
  922. else
  923. deleteWindow();
  924. setEmbeddedWindowToOurSize();
  925. }
  926. static void recursiveHIViewRepaint (HIViewRef view)
  927. {
  928. HIViewSetNeedsDisplay (view, true);
  929. HIViewRef child = HIViewGetFirstSubview (view);
  930. while (child != 0)
  931. {
  932. recursiveHIViewRepaint (child);
  933. child = HIViewGetNextView (child);
  934. }
  935. }
  936. void timerCallback()
  937. {
  938. setOurSizeToEmbeddedViewSize();
  939. // To avoid strange overpainting problems when the UI is first opened, we'll
  940. // repaint it a few times during the first second that it's on-screen..
  941. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  942. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  943. }
  944. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  945. {
  946. switch (GetEventKind (event))
  947. {
  948. case kEventWindowHandleDeactivate:
  949. ActivateWindow (wrapperWindow, TRUE);
  950. return noErr;
  951. case kEventWindowGetClickActivation:
  952. {
  953. getTopLevelComponent()->toFront (false);
  954. [carbonWindow makeKeyAndOrderFront: nil];
  955. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  956. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  957. sizeof (ClickActivationResult), &howToHandleClick);
  958. HIViewSetNeedsDisplay (embeddedView, true);
  959. return noErr;
  960. }
  961. }
  962. return eventNotHandledErr;
  963. }
  964. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  965. {
  966. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  967. }
  968. protected:
  969. WindowRef wrapperWindow;
  970. NSWindow* carbonWindow;
  971. HIViewRef embeddedView;
  972. bool recursiveResize;
  973. Time creationTime;
  974. EventHandlerRef eventHandlerRef;
  975. };
  976. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  977. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  978. END_JUCE_NAMESPACE
  979. #endif
  980. #define JUCE_AMALGAMATED_TEMPLATE 1
  981. //==============================================================================
  982. #if JUCE_BUILD_CORE
  983. /*** Start of inlined file: juce_FileLogger.cpp ***/
  984. BEGIN_JUCE_NAMESPACE
  985. FileLogger::FileLogger (const File& logFile_,
  986. const String& welcomeMessage,
  987. const int maxInitialFileSizeBytes)
  988. : logFile (logFile_)
  989. {
  990. if (maxInitialFileSizeBytes >= 0)
  991. trimFileSize (maxInitialFileSizeBytes);
  992. if (! logFile_.exists())
  993. {
  994. // do this so that the parent directories get created..
  995. logFile_.create();
  996. }
  997. String welcome;
  998. welcome << "\r\n**********************************************************\r\n"
  999. << welcomeMessage
  1000. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  1001. << "\r\n";
  1002. logMessage (welcome);
  1003. }
  1004. FileLogger::~FileLogger()
  1005. {
  1006. }
  1007. void FileLogger::logMessage (const String& message)
  1008. {
  1009. DBG (message);
  1010. const ScopedLock sl (logLock);
  1011. FileOutputStream out (logFile, 256);
  1012. out << message << "\r\n";
  1013. }
  1014. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1015. {
  1016. if (maxFileSizeBytes <= 0)
  1017. {
  1018. logFile.deleteFile();
  1019. }
  1020. else
  1021. {
  1022. const int64 fileSize = logFile.getSize();
  1023. if (fileSize > maxFileSizeBytes)
  1024. {
  1025. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1026. jassert (in != 0);
  1027. if (in != 0)
  1028. {
  1029. in->setPosition (fileSize - maxFileSizeBytes);
  1030. String content;
  1031. {
  1032. MemoryBlock contentToSave;
  1033. contentToSave.setSize (maxFileSizeBytes + 4);
  1034. contentToSave.fillWith (0);
  1035. in->read (contentToSave.getData(), maxFileSizeBytes);
  1036. in = 0;
  1037. content = contentToSave.toString();
  1038. }
  1039. int newStart = 0;
  1040. while (newStart < fileSize
  1041. && content[newStart] != '\n'
  1042. && content[newStart] != '\r')
  1043. ++newStart;
  1044. logFile.deleteFile();
  1045. logFile.appendText (content.substring (newStart), false, false);
  1046. }
  1047. }
  1048. }
  1049. }
  1050. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1051. const String& logFileName,
  1052. const String& welcomeMessage,
  1053. const int maxInitialFileSizeBytes)
  1054. {
  1055. #if JUCE_MAC
  1056. File logFile ("~/Library/Logs");
  1057. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1058. .getChildFile (logFileName);
  1059. #else
  1060. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1061. if (logFile.isDirectory())
  1062. {
  1063. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1064. .getChildFile (logFileName);
  1065. }
  1066. #endif
  1067. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1068. }
  1069. END_JUCE_NAMESPACE
  1070. /*** End of inlined file: juce_FileLogger.cpp ***/
  1071. /*** Start of inlined file: juce_Logger.cpp ***/
  1072. BEGIN_JUCE_NAMESPACE
  1073. Logger::Logger()
  1074. {
  1075. }
  1076. Logger::~Logger()
  1077. {
  1078. }
  1079. Logger* Logger::currentLogger = 0;
  1080. void Logger::setCurrentLogger (Logger* const newLogger,
  1081. const bool deleteOldLogger)
  1082. {
  1083. Logger* const oldLogger = currentLogger;
  1084. currentLogger = newLogger;
  1085. if (deleteOldLogger)
  1086. delete oldLogger;
  1087. }
  1088. void Logger::writeToLog (const String& message)
  1089. {
  1090. if (currentLogger != 0)
  1091. currentLogger->logMessage (message);
  1092. else
  1093. outputDebugString (message);
  1094. }
  1095. #if JUCE_LOG_ASSERTIONS
  1096. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1097. {
  1098. String m ("JUCE Assertion failure in ");
  1099. m << filename << ", line " << lineNum;
  1100. Logger::writeToLog (m);
  1101. }
  1102. #endif
  1103. END_JUCE_NAMESPACE
  1104. /*** End of inlined file: juce_Logger.cpp ***/
  1105. /*** Start of inlined file: juce_Random.cpp ***/
  1106. BEGIN_JUCE_NAMESPACE
  1107. Random::Random (const int64 seedValue) throw()
  1108. : seed (seedValue)
  1109. {
  1110. }
  1111. Random::~Random() throw()
  1112. {
  1113. }
  1114. void Random::setSeed (const int64 newSeed) throw()
  1115. {
  1116. seed = newSeed;
  1117. }
  1118. void Random::combineSeed (const int64 seedValue) throw()
  1119. {
  1120. seed ^= nextInt64() ^ seedValue;
  1121. }
  1122. void Random::setSeedRandomly()
  1123. {
  1124. combineSeed ((int64) (pointer_sized_int) this);
  1125. combineSeed (Time::getMillisecondCounter());
  1126. combineSeed (Time::getHighResolutionTicks());
  1127. combineSeed (Time::getHighResolutionTicksPerSecond());
  1128. combineSeed (Time::currentTimeMillis());
  1129. }
  1130. int Random::nextInt() throw()
  1131. {
  1132. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1133. return (int) (seed >> 16);
  1134. }
  1135. int Random::nextInt (const int maxValue) throw()
  1136. {
  1137. jassert (maxValue > 0);
  1138. return (nextInt() & 0x7fffffff) % maxValue;
  1139. }
  1140. int64 Random::nextInt64() throw()
  1141. {
  1142. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1143. }
  1144. bool Random::nextBool() throw()
  1145. {
  1146. return (nextInt() & 0x80000000) != 0;
  1147. }
  1148. float Random::nextFloat() throw()
  1149. {
  1150. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1151. }
  1152. double Random::nextDouble() throw()
  1153. {
  1154. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1155. }
  1156. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1157. {
  1158. BigInteger n;
  1159. do
  1160. {
  1161. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1162. }
  1163. while (n >= maximumValue);
  1164. return n;
  1165. }
  1166. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1167. {
  1168. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1169. while ((startBit & 31) != 0 && numBits > 0)
  1170. {
  1171. arrayToChange.setBit (startBit++, nextBool());
  1172. --numBits;
  1173. }
  1174. while (numBits >= 32)
  1175. {
  1176. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1177. startBit += 32;
  1178. numBits -= 32;
  1179. }
  1180. while (--numBits >= 0)
  1181. arrayToChange.setBit (startBit + numBits, nextBool());
  1182. }
  1183. Random& Random::getSystemRandom() throw()
  1184. {
  1185. static Random sysRand (1);
  1186. return sysRand;
  1187. }
  1188. END_JUCE_NAMESPACE
  1189. /*** End of inlined file: juce_Random.cpp ***/
  1190. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1191. BEGIN_JUCE_NAMESPACE
  1192. RelativeTime::RelativeTime (const double seconds_) throw()
  1193. : seconds (seconds_)
  1194. {
  1195. }
  1196. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1197. : seconds (other.seconds)
  1198. {
  1199. }
  1200. RelativeTime::~RelativeTime() throw()
  1201. {
  1202. }
  1203. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1204. {
  1205. return RelativeTime (milliseconds * 0.001);
  1206. }
  1207. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1208. {
  1209. return RelativeTime (milliseconds * 0.001);
  1210. }
  1211. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1212. {
  1213. return RelativeTime (numberOfMinutes * 60.0);
  1214. }
  1215. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1216. {
  1217. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1218. }
  1219. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1220. {
  1221. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1222. }
  1223. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1224. {
  1225. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1226. }
  1227. int64 RelativeTime::inMilliseconds() const throw()
  1228. {
  1229. return (int64) (seconds * 1000.0);
  1230. }
  1231. double RelativeTime::inMinutes() const throw()
  1232. {
  1233. return seconds / 60.0;
  1234. }
  1235. double RelativeTime::inHours() const throw()
  1236. {
  1237. return seconds / (60.0 * 60.0);
  1238. }
  1239. double RelativeTime::inDays() const throw()
  1240. {
  1241. return seconds / (60.0 * 60.0 * 24.0);
  1242. }
  1243. double RelativeTime::inWeeks() const throw()
  1244. {
  1245. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1246. }
  1247. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1248. {
  1249. if (seconds < 0.001 && seconds > -0.001)
  1250. return returnValueForZeroTime;
  1251. String result;
  1252. if (seconds < 0)
  1253. result = "-";
  1254. int fieldsShown = 0;
  1255. int n = abs ((int) inWeeks());
  1256. if (n > 0)
  1257. {
  1258. result << n << ((n == 1) ? TRANS(" week ")
  1259. : TRANS(" weeks "));
  1260. ++fieldsShown;
  1261. }
  1262. n = abs ((int) inDays()) % 7;
  1263. if (n > 0)
  1264. {
  1265. result << n << ((n == 1) ? TRANS(" day ")
  1266. : TRANS(" days "));
  1267. ++fieldsShown;
  1268. }
  1269. if (fieldsShown < 2)
  1270. {
  1271. n = abs ((int) inHours()) % 24;
  1272. if (n > 0)
  1273. {
  1274. result << n << ((n == 1) ? TRANS(" hr ")
  1275. : TRANS(" hrs "));
  1276. ++fieldsShown;
  1277. }
  1278. if (fieldsShown < 2)
  1279. {
  1280. n = abs ((int) inMinutes()) % 60;
  1281. if (n > 0)
  1282. {
  1283. result << n << ((n == 1) ? TRANS(" min ")
  1284. : TRANS(" mins "));
  1285. ++fieldsShown;
  1286. }
  1287. if (fieldsShown < 2)
  1288. {
  1289. n = abs ((int) inSeconds()) % 60;
  1290. if (n > 0)
  1291. {
  1292. result << n << ((n == 1) ? TRANS(" sec ")
  1293. : TRANS(" secs "));
  1294. ++fieldsShown;
  1295. }
  1296. if (fieldsShown < 1)
  1297. {
  1298. n = abs ((int) inMilliseconds()) % 1000;
  1299. if (n > 0)
  1300. {
  1301. result << n << TRANS(" ms");
  1302. ++fieldsShown;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. return result.trimEnd();
  1309. }
  1310. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1311. {
  1312. seconds = other.seconds;
  1313. return *this;
  1314. }
  1315. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1316. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1317. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1318. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1319. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1320. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1321. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1322. {
  1323. return RelativeTime (seconds + timeToAdd.seconds);
  1324. }
  1325. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1326. {
  1327. return RelativeTime (seconds - timeToSubtract.seconds);
  1328. }
  1329. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1330. {
  1331. return RelativeTime (seconds + secondsToAdd);
  1332. }
  1333. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1334. {
  1335. return RelativeTime (seconds - secondsToSubtract);
  1336. }
  1337. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1338. {
  1339. seconds += timeToAdd.seconds;
  1340. return *this;
  1341. }
  1342. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1343. {
  1344. seconds -= timeToSubtract.seconds;
  1345. return *this;
  1346. }
  1347. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1348. {
  1349. seconds += secondsToAdd;
  1350. return *this;
  1351. }
  1352. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1353. {
  1354. seconds -= secondsToSubtract;
  1355. return *this;
  1356. }
  1357. END_JUCE_NAMESPACE
  1358. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1359. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1360. BEGIN_JUCE_NAMESPACE
  1361. SystemStats::CPUFlags SystemStats::cpuFlags;
  1362. const String SystemStats::getJUCEVersion()
  1363. {
  1364. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1365. + "." + String (JUCE_MINOR_VERSION)
  1366. + "." + String (JUCE_BUILDNUMBER);
  1367. }
  1368. #ifdef JUCE_DLL
  1369. void* juce_Malloc (int size) { return malloc (size); }
  1370. void* juce_Calloc (int size) { return calloc (1, size); }
  1371. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1372. void juce_Free (void* block) { free (block); }
  1373. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1374. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1375. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1376. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1377. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1378. #endif
  1379. #endif
  1380. END_JUCE_NAMESPACE
  1381. /*** End of inlined file: juce_SystemStats.cpp ***/
  1382. /*** Start of inlined file: juce_Time.cpp ***/
  1383. #if JUCE_MSVC
  1384. #pragma warning (push)
  1385. #pragma warning (disable: 4514)
  1386. #endif
  1387. #ifndef JUCE_WINDOWS
  1388. #include <sys/time.h>
  1389. #else
  1390. #include <ctime>
  1391. #endif
  1392. #include <sys/timeb.h>
  1393. #if JUCE_MSVC
  1394. #pragma warning (pop)
  1395. #ifdef _INC_TIME_INL
  1396. #define USE_NEW_SECURE_TIME_FNS
  1397. #endif
  1398. #endif
  1399. BEGIN_JUCE_NAMESPACE
  1400. namespace TimeHelpers
  1401. {
  1402. static struct tm millisToLocal (const int64 millis) throw()
  1403. {
  1404. struct tm result;
  1405. const int64 seconds = millis / 1000;
  1406. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1407. {
  1408. // use extended maths for dates beyond 1970 to 2037..
  1409. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1410. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1411. const int days = (int) (jdm / literal64bit (86400));
  1412. const int a = 32044 + days;
  1413. const int b = (4 * a + 3) / 146097;
  1414. const int c = a - (b * 146097) / 4;
  1415. const int d = (4 * c + 3) / 1461;
  1416. const int e = c - (d * 1461) / 4;
  1417. const int m = (5 * e + 2) / 153;
  1418. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1419. result.tm_mon = m + 2 - 12 * (m / 10);
  1420. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1421. result.tm_wday = (days + 1) % 7;
  1422. result.tm_yday = -1;
  1423. int t = (int) (jdm % literal64bit (86400));
  1424. result.tm_hour = t / 3600;
  1425. t %= 3600;
  1426. result.tm_min = t / 60;
  1427. result.tm_sec = t % 60;
  1428. result.tm_isdst = -1;
  1429. }
  1430. else
  1431. {
  1432. time_t now = static_cast <time_t> (seconds);
  1433. #if JUCE_WINDOWS
  1434. #ifdef USE_NEW_SECURE_TIME_FNS
  1435. if (now >= 0 && now <= 0x793406fff)
  1436. localtime_s (&result, &now);
  1437. else
  1438. zeromem (&result, sizeof (result));
  1439. #else
  1440. result = *localtime (&now);
  1441. #endif
  1442. #else
  1443. // more thread-safe
  1444. localtime_r (&now, &result);
  1445. #endif
  1446. }
  1447. return result;
  1448. }
  1449. static int extendedModulo (const int64 value, const int modulo) throw()
  1450. {
  1451. return (int) (value >= 0 ? (value % modulo)
  1452. : (value - ((value / modulo) + 1) * modulo));
  1453. }
  1454. static uint32 lastMSCounterValue = 0;
  1455. }
  1456. Time::Time() throw()
  1457. : millisSinceEpoch (0)
  1458. {
  1459. }
  1460. Time::Time (const Time& other) throw()
  1461. : millisSinceEpoch (other.millisSinceEpoch)
  1462. {
  1463. }
  1464. Time::Time (const int64 ms) throw()
  1465. : millisSinceEpoch (ms)
  1466. {
  1467. }
  1468. Time::Time (const int year,
  1469. const int month,
  1470. const int day,
  1471. const int hours,
  1472. const int minutes,
  1473. const int seconds,
  1474. const int milliseconds,
  1475. const bool useLocalTime) throw()
  1476. {
  1477. jassert (year > 100); // year must be a 4-digit version
  1478. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1479. {
  1480. // use extended maths for dates beyond 1970 to 2037..
  1481. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1482. : 0;
  1483. const int a = (13 - month) / 12;
  1484. const int y = year + 4800 - a;
  1485. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1486. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1487. - 32045;
  1488. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1489. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1490. + milliseconds;
  1491. }
  1492. else
  1493. {
  1494. struct tm t;
  1495. t.tm_year = year - 1900;
  1496. t.tm_mon = month;
  1497. t.tm_mday = day;
  1498. t.tm_hour = hours;
  1499. t.tm_min = minutes;
  1500. t.tm_sec = seconds;
  1501. t.tm_isdst = -1;
  1502. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1503. if (millisSinceEpoch < 0)
  1504. millisSinceEpoch = 0;
  1505. else
  1506. millisSinceEpoch += milliseconds;
  1507. }
  1508. }
  1509. Time::~Time() throw()
  1510. {
  1511. }
  1512. Time& Time::operator= (const Time& other) throw()
  1513. {
  1514. millisSinceEpoch = other.millisSinceEpoch;
  1515. return *this;
  1516. }
  1517. int64 Time::currentTimeMillis() throw()
  1518. {
  1519. static uint32 lastCounterResult = 0xffffffff;
  1520. static int64 correction = 0;
  1521. const uint32 now = getMillisecondCounter();
  1522. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1523. if (now < lastCounterResult)
  1524. {
  1525. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1526. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1527. {
  1528. // get the time once using normal library calls, and store the difference needed to
  1529. // turn the millisecond counter into a real time.
  1530. #if JUCE_WINDOWS
  1531. struct _timeb t;
  1532. #ifdef USE_NEW_SECURE_TIME_FNS
  1533. _ftime_s (&t);
  1534. #else
  1535. _ftime (&t);
  1536. #endif
  1537. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1538. #else
  1539. struct timeval tv;
  1540. struct timezone tz;
  1541. gettimeofday (&tv, &tz);
  1542. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1543. #endif
  1544. }
  1545. }
  1546. lastCounterResult = now;
  1547. return correction + now;
  1548. }
  1549. uint32 juce_millisecondsSinceStartup() throw();
  1550. uint32 Time::getMillisecondCounter() throw()
  1551. {
  1552. const uint32 now = juce_millisecondsSinceStartup();
  1553. if (now < TimeHelpers::lastMSCounterValue)
  1554. {
  1555. // in multi-threaded apps this might be called concurrently, so
  1556. // make sure that our last counter value only increases and doesn't
  1557. // go backwards..
  1558. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1559. TimeHelpers::lastMSCounterValue = now;
  1560. }
  1561. else
  1562. {
  1563. TimeHelpers::lastMSCounterValue = now;
  1564. }
  1565. return now;
  1566. }
  1567. uint32 Time::getApproximateMillisecondCounter() throw()
  1568. {
  1569. jassert (TimeHelpers::lastMSCounterValue != 0);
  1570. return TimeHelpers::lastMSCounterValue;
  1571. }
  1572. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1573. {
  1574. for (;;)
  1575. {
  1576. const uint32 now = getMillisecondCounter();
  1577. if (now >= targetTime)
  1578. break;
  1579. const int toWait = targetTime - now;
  1580. if (toWait > 2)
  1581. {
  1582. Thread::sleep (jmin (20, toWait >> 1));
  1583. }
  1584. else
  1585. {
  1586. // xxx should consider using mutex_pause on the mac as it apparently
  1587. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1588. for (int i = 10; --i >= 0;)
  1589. Thread::yield();
  1590. }
  1591. }
  1592. }
  1593. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1594. {
  1595. return ticks / (double) getHighResolutionTicksPerSecond();
  1596. }
  1597. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1598. {
  1599. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1600. }
  1601. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1602. {
  1603. return Time (currentTimeMillis());
  1604. }
  1605. const String Time::toString (const bool includeDate,
  1606. const bool includeTime,
  1607. const bool includeSeconds,
  1608. const bool use24HourClock) const throw()
  1609. {
  1610. String result;
  1611. if (includeDate)
  1612. {
  1613. result << getDayOfMonth() << ' '
  1614. << getMonthName (true) << ' '
  1615. << getYear();
  1616. if (includeTime)
  1617. result << ' ';
  1618. }
  1619. if (includeTime)
  1620. {
  1621. const int mins = getMinutes();
  1622. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1623. << (mins < 10 ? ":0" : ":") << mins;
  1624. if (includeSeconds)
  1625. {
  1626. const int secs = getSeconds();
  1627. result << (secs < 10 ? ":0" : ":") << secs;
  1628. }
  1629. if (! use24HourClock)
  1630. result << (isAfternoon() ? "pm" : "am");
  1631. }
  1632. return result.trimEnd();
  1633. }
  1634. const String Time::formatted (const String& format) const
  1635. {
  1636. String buffer;
  1637. int bufferSize = 128;
  1638. buffer.preallocateStorage (bufferSize);
  1639. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1640. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1641. {
  1642. bufferSize += 128;
  1643. buffer.preallocateStorage (bufferSize);
  1644. }
  1645. return buffer;
  1646. }
  1647. int Time::getYear() const throw()
  1648. {
  1649. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1650. }
  1651. int Time::getMonth() const throw()
  1652. {
  1653. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1654. }
  1655. int Time::getDayOfMonth() const throw()
  1656. {
  1657. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1658. }
  1659. int Time::getDayOfWeek() const throw()
  1660. {
  1661. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1662. }
  1663. int Time::getHours() const throw()
  1664. {
  1665. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1666. }
  1667. int Time::getHoursInAmPmFormat() const throw()
  1668. {
  1669. const int hours = getHours();
  1670. if (hours == 0)
  1671. return 12;
  1672. else if (hours <= 12)
  1673. return hours;
  1674. else
  1675. return hours - 12;
  1676. }
  1677. bool Time::isAfternoon() const throw()
  1678. {
  1679. return getHours() >= 12;
  1680. }
  1681. int Time::getMinutes() const throw()
  1682. {
  1683. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1684. }
  1685. int Time::getSeconds() const throw()
  1686. {
  1687. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1688. }
  1689. int Time::getMilliseconds() const throw()
  1690. {
  1691. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1692. }
  1693. bool Time::isDaylightSavingTime() const throw()
  1694. {
  1695. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1696. }
  1697. const String Time::getTimeZone() const throw()
  1698. {
  1699. String zone[2];
  1700. #if JUCE_WINDOWS
  1701. _tzset();
  1702. #ifdef USE_NEW_SECURE_TIME_FNS
  1703. {
  1704. char name [128];
  1705. size_t length;
  1706. for (int i = 0; i < 2; ++i)
  1707. {
  1708. zeromem (name, sizeof (name));
  1709. _get_tzname (&length, name, 127, i);
  1710. zone[i] = name;
  1711. }
  1712. }
  1713. #else
  1714. const char** const zonePtr = (const char**) _tzname;
  1715. zone[0] = zonePtr[0];
  1716. zone[1] = zonePtr[1];
  1717. #endif
  1718. #else
  1719. tzset();
  1720. const char** const zonePtr = (const char**) tzname;
  1721. zone[0] = zonePtr[0];
  1722. zone[1] = zonePtr[1];
  1723. #endif
  1724. if (isDaylightSavingTime())
  1725. {
  1726. zone[0] = zone[1];
  1727. if (zone[0].length() > 3
  1728. && zone[0].containsIgnoreCase ("daylight")
  1729. && zone[0].contains ("GMT"))
  1730. zone[0] = "BST";
  1731. }
  1732. return zone[0].substring (0, 3);
  1733. }
  1734. const String Time::getMonthName (const bool threeLetterVersion) const
  1735. {
  1736. return getMonthName (getMonth(), threeLetterVersion);
  1737. }
  1738. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1739. {
  1740. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1741. }
  1742. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1743. {
  1744. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1745. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1746. monthNumber %= 12;
  1747. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1748. : longMonthNames [monthNumber]);
  1749. }
  1750. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1751. {
  1752. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1753. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1754. day %= 7;
  1755. return TRANS (threeLetterVersion ? shortDayNames [day]
  1756. : longDayNames [day]);
  1757. }
  1758. END_JUCE_NAMESPACE
  1759. /*** End of inlined file: juce_Time.cpp ***/
  1760. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1761. BEGIN_JUCE_NAMESPACE
  1762. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1763. #endif
  1764. #if JUCE_WINDOWS
  1765. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1766. #endif
  1767. #if JUCE_DEBUG
  1768. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1769. #endif
  1770. static bool juceInitialisedNonGUI = false;
  1771. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1772. {
  1773. if (! juceInitialisedNonGUI)
  1774. {
  1775. juceInitialisedNonGUI = true;
  1776. JUCE_AUTORELEASEPOOL
  1777. DBG (SystemStats::getJUCEVersion());
  1778. SystemStats::initialiseStats();
  1779. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1780. }
  1781. // Some basic tests, to keep an eye on things and make sure these types work ok
  1782. // on all platforms. Let me know if any of these assertions fail on your system!
  1783. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1784. static_jassert (sizeof (int8) == 1);
  1785. static_jassert (sizeof (uint8) == 1);
  1786. static_jassert (sizeof (int16) == 2);
  1787. static_jassert (sizeof (uint16) == 2);
  1788. static_jassert (sizeof (int32) == 4);
  1789. static_jassert (sizeof (uint32) == 4);
  1790. static_jassert (sizeof (int64) == 8);
  1791. static_jassert (sizeof (uint64) == 8);
  1792. }
  1793. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1794. {
  1795. if (juceInitialisedNonGUI)
  1796. {
  1797. juceInitialisedNonGUI = false;
  1798. JUCE_AUTORELEASEPOOL
  1799. LocalisedStrings::setCurrentMappings (0);
  1800. Thread::stopAllThreads (3000);
  1801. #if JUCE_WINDOWS
  1802. juce_shutdownWin32Sockets();
  1803. #endif
  1804. #if JUCE_DEBUG
  1805. juce_CheckForDanglingStreams();
  1806. #endif
  1807. }
  1808. }
  1809. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1810. static bool juceInitialisedGUI = false;
  1811. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1812. {
  1813. if (! juceInitialisedGUI)
  1814. {
  1815. juceInitialisedGUI = true;
  1816. JUCE_AUTORELEASEPOOL
  1817. initialiseJuce_NonGUI();
  1818. MessageManager::getInstance();
  1819. LookAndFeel::setDefaultLookAndFeel (0);
  1820. #if JUCE_DEBUG
  1821. try // This section is just a safety-net for catching builds without RTTI enabled..
  1822. {
  1823. MemoryOutputStream mo;
  1824. OutputStream* o = &mo;
  1825. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1826. o = dynamic_cast <MemoryOutputStream*> (o);
  1827. jassert (o != 0);
  1828. }
  1829. catch (...)
  1830. {
  1831. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1832. jassertfalse;
  1833. }
  1834. #endif
  1835. }
  1836. }
  1837. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1838. {
  1839. if (juceInitialisedGUI)
  1840. {
  1841. juceInitialisedGUI = false;
  1842. JUCE_AUTORELEASEPOOL
  1843. DeletedAtShutdown::deleteAll();
  1844. LookAndFeel::clearDefaultLookAndFeel();
  1845. delete MessageManager::getInstance();
  1846. shutdownJuce_NonGUI();
  1847. }
  1848. }
  1849. #endif
  1850. #if JUCE_UNIT_TESTS
  1851. class AtomicTests : public UnitTest
  1852. {
  1853. public:
  1854. AtomicTests() : UnitTest ("Atomics") {}
  1855. void runTest()
  1856. {
  1857. beginTest ("Misc");
  1858. char a1[7];
  1859. expect (numElementsInArray(a1) == 7);
  1860. int a2[3];
  1861. expect (numElementsInArray(a2) == 3);
  1862. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1863. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1864. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1865. beginTest ("Atomic types");
  1866. AtomicTester <int>::testInteger (*this);
  1867. AtomicTester <unsigned int>::testInteger (*this);
  1868. AtomicTester <int32>::testInteger (*this);
  1869. AtomicTester <uint32>::testInteger (*this);
  1870. AtomicTester <long>::testInteger (*this);
  1871. AtomicTester <void*>::testInteger (*this);
  1872. AtomicTester <int*>::testInteger (*this);
  1873. AtomicTester <float>::testFloat (*this);
  1874. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1875. AtomicTester <int64>::testInteger (*this);
  1876. AtomicTester <uint64>::testInteger (*this);
  1877. AtomicTester <double>::testFloat (*this);
  1878. #endif
  1879. }
  1880. template <typename Type>
  1881. class AtomicTester
  1882. {
  1883. public:
  1884. AtomicTester() {}
  1885. static void testInteger (UnitTest& test)
  1886. {
  1887. Atomic<Type> a, b;
  1888. a.set ((Type) 10);
  1889. a += (Type) 15;
  1890. a.memoryBarrier();
  1891. a -= (Type) 5;
  1892. ++a; ++a; --a;
  1893. a.memoryBarrier();
  1894. testFloat (test);
  1895. }
  1896. static void testFloat (UnitTest& test)
  1897. {
  1898. Atomic<Type> a, b;
  1899. a = (Type) 21;
  1900. a.memoryBarrier();
  1901. /* These are some simple test cases to check the atomics - let me know
  1902. if any of these assertions fail on your system!
  1903. */
  1904. test.expect (a.get() == (Type) 21);
  1905. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1906. test.expect (a.get() == (Type) 21);
  1907. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1908. test.expect (a.get() == (Type) 101);
  1909. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1910. test.expect (a.get() == (Type) 101);
  1911. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1912. test.expect (a.get() == (Type) 200);
  1913. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1914. test.expect (a.get() == (Type) 300);
  1915. b = a;
  1916. test.expect (b.get() == a.get());
  1917. }
  1918. };
  1919. };
  1920. static AtomicTests atomicUnitTests;
  1921. #endif
  1922. END_JUCE_NAMESPACE
  1923. /*** End of inlined file: juce_Initialisation.cpp ***/
  1924. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1925. BEGIN_JUCE_NAMESPACE
  1926. AbstractFifo::AbstractFifo (const int capacity) throw()
  1927. : bufferSize (capacity)
  1928. {
  1929. jassert (bufferSize > 0);
  1930. }
  1931. AbstractFifo::~AbstractFifo() {}
  1932. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1933. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1934. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1935. void AbstractFifo::reset() throw()
  1936. {
  1937. validEnd = 0;
  1938. validStart = 0;
  1939. }
  1940. void AbstractFifo::setTotalSize (int newSize) throw()
  1941. {
  1942. jassert (newSize > 0);
  1943. reset();
  1944. bufferSize = newSize;
  1945. }
  1946. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1947. {
  1948. const int vs = validStart.get();
  1949. const int ve = validEnd.get();
  1950. const int freeSpace = bufferSize - (ve - vs);
  1951. numToWrite = jmin (numToWrite, freeSpace);
  1952. if (numToWrite <= 0)
  1953. {
  1954. startIndex1 = 0;
  1955. startIndex2 = 0;
  1956. blockSize1 = 0;
  1957. blockSize2 = 0;
  1958. }
  1959. else
  1960. {
  1961. startIndex1 = (int) (ve % bufferSize);
  1962. startIndex2 = 0;
  1963. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1964. numToWrite -= blockSize1;
  1965. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1966. }
  1967. }
  1968. void AbstractFifo::finishedWrite (int numWritten) throw()
  1969. {
  1970. jassert (numWritten >= 0 && numWritten < bufferSize);
  1971. validEnd += numWritten;
  1972. }
  1973. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1974. {
  1975. const int vs = validStart.get();
  1976. const int ve = validEnd.get();
  1977. const int numReady = ve - vs;
  1978. numWanted = jmin (numWanted, numReady);
  1979. if (numWanted <= 0)
  1980. {
  1981. startIndex1 = 0;
  1982. startIndex2 = 0;
  1983. blockSize1 = 0;
  1984. blockSize2 = 0;
  1985. }
  1986. else
  1987. {
  1988. startIndex1 = (int) (vs % bufferSize);
  1989. startIndex2 = 0;
  1990. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1991. numWanted -= blockSize1;
  1992. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1993. }
  1994. }
  1995. void AbstractFifo::finishedRead (int numRead) throw()
  1996. {
  1997. jassert (numRead >= 0 && numRead < bufferSize);
  1998. validStart += numRead;
  1999. }
  2000. END_JUCE_NAMESPACE
  2001. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2002. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2003. BEGIN_JUCE_NAMESPACE
  2004. BigInteger::BigInteger()
  2005. : numValues (4),
  2006. highestBit (-1),
  2007. negative (false)
  2008. {
  2009. values.calloc (numValues + 1);
  2010. }
  2011. BigInteger::BigInteger (const int32 value)
  2012. : numValues (4),
  2013. highestBit (31),
  2014. negative (value < 0)
  2015. {
  2016. values.calloc (numValues + 1);
  2017. values[0] = abs (value);
  2018. highestBit = getHighestBit();
  2019. }
  2020. BigInteger::BigInteger (const uint32 value)
  2021. : numValues (4),
  2022. highestBit (31),
  2023. negative (false)
  2024. {
  2025. values.calloc (numValues + 1);
  2026. values[0] = value;
  2027. highestBit = getHighestBit();
  2028. }
  2029. BigInteger::BigInteger (int64 value)
  2030. : numValues (4),
  2031. highestBit (63),
  2032. negative (value < 0)
  2033. {
  2034. values.calloc (numValues + 1);
  2035. if (value < 0)
  2036. value = -value;
  2037. values[0] = (uint32) value;
  2038. values[1] = (uint32) (value >> 32);
  2039. highestBit = getHighestBit();
  2040. }
  2041. BigInteger::BigInteger (const BigInteger& other)
  2042. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2043. highestBit (other.getHighestBit()),
  2044. negative (other.negative)
  2045. {
  2046. values.malloc (numValues + 1);
  2047. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2048. }
  2049. BigInteger::~BigInteger()
  2050. {
  2051. }
  2052. void BigInteger::swapWith (BigInteger& other) throw()
  2053. {
  2054. values.swapWith (other.values);
  2055. swapVariables (numValues, other.numValues);
  2056. swapVariables (highestBit, other.highestBit);
  2057. swapVariables (negative, other.negative);
  2058. }
  2059. BigInteger& BigInteger::operator= (const BigInteger& other)
  2060. {
  2061. if (this != &other)
  2062. {
  2063. highestBit = other.getHighestBit();
  2064. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2065. negative = other.negative;
  2066. values.malloc (numValues + 1);
  2067. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2068. }
  2069. return *this;
  2070. }
  2071. void BigInteger::ensureSize (const int numVals)
  2072. {
  2073. if (numVals + 2 >= numValues)
  2074. {
  2075. int oldSize = numValues;
  2076. numValues = ((numVals + 2) * 3) / 2;
  2077. values.realloc (numValues + 1);
  2078. while (oldSize < numValues)
  2079. values [oldSize++] = 0;
  2080. }
  2081. }
  2082. bool BigInteger::operator[] (const int bit) const throw()
  2083. {
  2084. return bit <= highestBit && bit >= 0
  2085. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2086. }
  2087. int BigInteger::toInteger() const throw()
  2088. {
  2089. const int n = (int) (values[0] & 0x7fffffff);
  2090. return negative ? -n : n;
  2091. }
  2092. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2093. {
  2094. BigInteger r;
  2095. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2096. r.ensureSize (bitToIndex (numBits));
  2097. r.highestBit = numBits;
  2098. int i = 0;
  2099. while (numBits > 0)
  2100. {
  2101. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2102. numBits -= 32;
  2103. startBit += 32;
  2104. }
  2105. r.highestBit = r.getHighestBit();
  2106. return r;
  2107. }
  2108. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2109. {
  2110. if (numBits > 32)
  2111. {
  2112. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2113. numBits = 32;
  2114. }
  2115. numBits = jmin (numBits, highestBit + 1 - startBit);
  2116. if (numBits <= 0)
  2117. return 0;
  2118. const int pos = bitToIndex (startBit);
  2119. const int offset = startBit & 31;
  2120. const int endSpace = 32 - numBits;
  2121. uint32 n = ((uint32) values [pos]) >> offset;
  2122. if (offset > endSpace)
  2123. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2124. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2125. }
  2126. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2127. {
  2128. if (numBits > 32)
  2129. {
  2130. jassertfalse;
  2131. numBits = 32;
  2132. }
  2133. for (int i = 0; i < numBits; ++i)
  2134. {
  2135. setBit (startBit + i, (valueToSet & 1) != 0);
  2136. valueToSet >>= 1;
  2137. }
  2138. }
  2139. void BigInteger::clear()
  2140. {
  2141. if (numValues > 16)
  2142. {
  2143. numValues = 4;
  2144. values.calloc (numValues + 1);
  2145. }
  2146. else
  2147. {
  2148. zeromem (values, sizeof (uint32) * (numValues + 1));
  2149. }
  2150. highestBit = -1;
  2151. negative = false;
  2152. }
  2153. void BigInteger::setBit (const int bit)
  2154. {
  2155. if (bit >= 0)
  2156. {
  2157. if (bit > highestBit)
  2158. {
  2159. ensureSize (bitToIndex (bit));
  2160. highestBit = bit;
  2161. }
  2162. values [bitToIndex (bit)] |= bitToMask (bit);
  2163. }
  2164. }
  2165. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2166. {
  2167. if (shouldBeSet)
  2168. setBit (bit);
  2169. else
  2170. clearBit (bit);
  2171. }
  2172. void BigInteger::clearBit (const int bit) throw()
  2173. {
  2174. if (bit >= 0 && bit <= highestBit)
  2175. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2176. }
  2177. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2178. {
  2179. while (--numBits >= 0)
  2180. setBit (startBit++, shouldBeSet);
  2181. }
  2182. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2183. {
  2184. if (bit >= 0)
  2185. shiftBits (1, bit);
  2186. setBit (bit, shouldBeSet);
  2187. }
  2188. bool BigInteger::isZero() const throw()
  2189. {
  2190. return getHighestBit() < 0;
  2191. }
  2192. bool BigInteger::isOne() const throw()
  2193. {
  2194. return getHighestBit() == 0 && ! negative;
  2195. }
  2196. bool BigInteger::isNegative() const throw()
  2197. {
  2198. return negative && ! isZero();
  2199. }
  2200. void BigInteger::setNegative (const bool neg) throw()
  2201. {
  2202. negative = neg;
  2203. }
  2204. void BigInteger::negate() throw()
  2205. {
  2206. negative = (! negative) && ! isZero();
  2207. }
  2208. #if JUCE_USE_INTRINSICS
  2209. #pragma intrinsic (_BitScanReverse)
  2210. #endif
  2211. namespace BitFunctions
  2212. {
  2213. inline int countBitsInInt32 (uint32 n) throw()
  2214. {
  2215. n -= ((n >> 1) & 0x55555555);
  2216. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2217. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2218. n += (n >> 8);
  2219. n += (n >> 16);
  2220. return n & 0x3f;
  2221. }
  2222. inline int highestBitInInt (uint32 n) throw()
  2223. {
  2224. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2225. #if JUCE_GCC
  2226. return 31 - __builtin_clz (n);
  2227. #elif JUCE_USE_INTRINSICS
  2228. unsigned long highest;
  2229. _BitScanReverse (&highest, n);
  2230. return (int) highest;
  2231. #else
  2232. n |= (n >> 1);
  2233. n |= (n >> 2);
  2234. n |= (n >> 4);
  2235. n |= (n >> 8);
  2236. n |= (n >> 16);
  2237. return countBitsInInt32 (n >> 1);
  2238. #endif
  2239. }
  2240. }
  2241. int BigInteger::countNumberOfSetBits() const throw()
  2242. {
  2243. int total = 0;
  2244. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2245. total += BitFunctions::countBitsInInt32 (values[i]);
  2246. return total;
  2247. }
  2248. int BigInteger::getHighestBit() const throw()
  2249. {
  2250. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2251. {
  2252. const uint32 n = values[i];
  2253. if (n != 0)
  2254. return BitFunctions::highestBitInInt (n) + (i << 5);
  2255. }
  2256. return -1;
  2257. }
  2258. int BigInteger::findNextSetBit (int i) const throw()
  2259. {
  2260. for (; i <= highestBit; ++i)
  2261. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2262. return i;
  2263. return -1;
  2264. }
  2265. int BigInteger::findNextClearBit (int i) const throw()
  2266. {
  2267. for (; i <= highestBit; ++i)
  2268. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2269. break;
  2270. return i;
  2271. }
  2272. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2273. {
  2274. if (other.isNegative())
  2275. return operator-= (-other);
  2276. if (isNegative())
  2277. {
  2278. if (compareAbsolute (other) < 0)
  2279. {
  2280. BigInteger temp (*this);
  2281. temp.negate();
  2282. *this = other;
  2283. operator-= (temp);
  2284. }
  2285. else
  2286. {
  2287. negate();
  2288. operator-= (other);
  2289. negate();
  2290. }
  2291. }
  2292. else
  2293. {
  2294. if (other.highestBit > highestBit)
  2295. highestBit = other.highestBit;
  2296. ++highestBit;
  2297. const int numInts = bitToIndex (highestBit) + 1;
  2298. ensureSize (numInts);
  2299. int64 remainder = 0;
  2300. for (int i = 0; i <= numInts; ++i)
  2301. {
  2302. if (i < numValues)
  2303. remainder += values[i];
  2304. if (i < other.numValues)
  2305. remainder += other.values[i];
  2306. values[i] = (uint32) remainder;
  2307. remainder >>= 32;
  2308. }
  2309. jassert (remainder == 0);
  2310. highestBit = getHighestBit();
  2311. }
  2312. return *this;
  2313. }
  2314. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2315. {
  2316. if (other.isNegative())
  2317. return operator+= (-other);
  2318. if (! isNegative())
  2319. {
  2320. if (compareAbsolute (other) < 0)
  2321. {
  2322. BigInteger temp (other);
  2323. swapWith (temp);
  2324. operator-= (temp);
  2325. negate();
  2326. return *this;
  2327. }
  2328. }
  2329. else
  2330. {
  2331. negate();
  2332. operator+= (other);
  2333. negate();
  2334. return *this;
  2335. }
  2336. const int numInts = bitToIndex (highestBit) + 1;
  2337. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2338. int64 amountToSubtract = 0;
  2339. for (int i = 0; i <= numInts; ++i)
  2340. {
  2341. if (i <= maxOtherInts)
  2342. amountToSubtract += (int64) other.values[i];
  2343. if (values[i] >= amountToSubtract)
  2344. {
  2345. values[i] = (uint32) (values[i] - amountToSubtract);
  2346. amountToSubtract = 0;
  2347. }
  2348. else
  2349. {
  2350. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2351. values[i] = (uint32) n;
  2352. amountToSubtract = 1;
  2353. }
  2354. }
  2355. return *this;
  2356. }
  2357. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2358. {
  2359. BigInteger total;
  2360. highestBit = getHighestBit();
  2361. const bool wasNegative = isNegative();
  2362. setNegative (false);
  2363. for (int i = 0; i <= highestBit; ++i)
  2364. {
  2365. if (operator[](i))
  2366. {
  2367. BigInteger n (other);
  2368. n.setNegative (false);
  2369. n <<= i;
  2370. total += n;
  2371. }
  2372. }
  2373. total.setNegative (wasNegative ^ other.isNegative());
  2374. swapWith (total);
  2375. return *this;
  2376. }
  2377. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2378. {
  2379. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2380. const int divHB = divisor.getHighestBit();
  2381. const int ourHB = getHighestBit();
  2382. if (divHB < 0 || ourHB < 0)
  2383. {
  2384. // division by zero
  2385. remainder.clear();
  2386. clear();
  2387. }
  2388. else
  2389. {
  2390. const bool wasNegative = isNegative();
  2391. swapWith (remainder);
  2392. remainder.setNegative (false);
  2393. clear();
  2394. BigInteger temp (divisor);
  2395. temp.setNegative (false);
  2396. int leftShift = ourHB - divHB;
  2397. temp <<= leftShift;
  2398. while (leftShift >= 0)
  2399. {
  2400. if (remainder.compareAbsolute (temp) >= 0)
  2401. {
  2402. remainder -= temp;
  2403. setBit (leftShift);
  2404. }
  2405. if (--leftShift >= 0)
  2406. temp >>= 1;
  2407. }
  2408. negative = wasNegative ^ divisor.isNegative();
  2409. remainder.setNegative (wasNegative);
  2410. }
  2411. }
  2412. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2413. {
  2414. BigInteger remainder;
  2415. divideBy (other, remainder);
  2416. return *this;
  2417. }
  2418. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2419. {
  2420. // this operation doesn't take into account negative values..
  2421. jassert (isNegative() == other.isNegative());
  2422. if (other.highestBit >= 0)
  2423. {
  2424. ensureSize (bitToIndex (other.highestBit));
  2425. int n = bitToIndex (other.highestBit) + 1;
  2426. while (--n >= 0)
  2427. values[n] |= other.values[n];
  2428. if (other.highestBit > highestBit)
  2429. highestBit = other.highestBit;
  2430. highestBit = getHighestBit();
  2431. }
  2432. return *this;
  2433. }
  2434. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2435. {
  2436. // this operation doesn't take into account negative values..
  2437. jassert (isNegative() == other.isNegative());
  2438. int n = numValues;
  2439. while (n > other.numValues)
  2440. values[--n] = 0;
  2441. while (--n >= 0)
  2442. values[n] &= other.values[n];
  2443. if (other.highestBit < highestBit)
  2444. highestBit = other.highestBit;
  2445. highestBit = getHighestBit();
  2446. return *this;
  2447. }
  2448. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2449. {
  2450. // this operation will only work with the absolute values
  2451. jassert (isNegative() == other.isNegative());
  2452. if (other.highestBit >= 0)
  2453. {
  2454. ensureSize (bitToIndex (other.highestBit));
  2455. int n = bitToIndex (other.highestBit) + 1;
  2456. while (--n >= 0)
  2457. values[n] ^= other.values[n];
  2458. if (other.highestBit > highestBit)
  2459. highestBit = other.highestBit;
  2460. highestBit = getHighestBit();
  2461. }
  2462. return *this;
  2463. }
  2464. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2465. {
  2466. BigInteger remainder;
  2467. divideBy (divisor, remainder);
  2468. swapWith (remainder);
  2469. return *this;
  2470. }
  2471. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2472. {
  2473. shiftBits (numBitsToShift, 0);
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2477. {
  2478. return operator<<= (-numBitsToShift);
  2479. }
  2480. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2481. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2482. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2483. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2484. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2485. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2486. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2487. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2488. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2489. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2490. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2491. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2492. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2493. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2494. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2495. int BigInteger::compare (const BigInteger& other) const throw()
  2496. {
  2497. if (isNegative() == other.isNegative())
  2498. {
  2499. const int absComp = compareAbsolute (other);
  2500. return isNegative() ? -absComp : absComp;
  2501. }
  2502. else
  2503. {
  2504. return isNegative() ? -1 : 1;
  2505. }
  2506. }
  2507. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2508. {
  2509. const int h1 = getHighestBit();
  2510. const int h2 = other.getHighestBit();
  2511. if (h1 > h2)
  2512. return 1;
  2513. else if (h1 < h2)
  2514. return -1;
  2515. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2516. if (values[i] != other.values[i])
  2517. return (values[i] > other.values[i]) ? 1 : -1;
  2518. return 0;
  2519. }
  2520. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2521. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2522. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2523. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2524. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2525. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2526. void BigInteger::shiftBits (int bits, const int startBit)
  2527. {
  2528. if (highestBit < 0)
  2529. return;
  2530. if (startBit > 0)
  2531. {
  2532. if (bits < 0)
  2533. {
  2534. // right shift
  2535. for (int i = startBit; i <= highestBit; ++i)
  2536. setBit (i, operator[] (i - bits));
  2537. highestBit = getHighestBit();
  2538. }
  2539. else if (bits > 0)
  2540. {
  2541. // left shift
  2542. for (int i = highestBit + 1; --i >= startBit;)
  2543. setBit (i + bits, operator[] (i));
  2544. while (--bits >= 0)
  2545. clearBit (bits + startBit);
  2546. }
  2547. }
  2548. else
  2549. {
  2550. if (bits < 0)
  2551. {
  2552. // right shift
  2553. bits = -bits;
  2554. if (bits > highestBit)
  2555. {
  2556. clear();
  2557. }
  2558. else
  2559. {
  2560. const int wordsToMove = bitToIndex (bits);
  2561. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2562. highestBit -= bits;
  2563. if (wordsToMove > 0)
  2564. {
  2565. int i;
  2566. for (i = 0; i < top; ++i)
  2567. values [i] = values [i + wordsToMove];
  2568. for (i = 0; i < wordsToMove; ++i)
  2569. values [top + i] = 0;
  2570. bits &= 31;
  2571. }
  2572. if (bits != 0)
  2573. {
  2574. const int invBits = 32 - bits;
  2575. --top;
  2576. for (int i = 0; i < top; ++i)
  2577. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2578. values[top] = (values[top] >> bits);
  2579. }
  2580. highestBit = getHighestBit();
  2581. }
  2582. }
  2583. else if (bits > 0)
  2584. {
  2585. // left shift
  2586. ensureSize (bitToIndex (highestBit + bits) + 1);
  2587. const int wordsToMove = bitToIndex (bits);
  2588. int top = 1 + bitToIndex (highestBit);
  2589. highestBit += bits;
  2590. if (wordsToMove > 0)
  2591. {
  2592. int i;
  2593. for (i = top; --i >= 0;)
  2594. values [i + wordsToMove] = values [i];
  2595. for (i = 0; i < wordsToMove; ++i)
  2596. values [i] = 0;
  2597. bits &= 31;
  2598. }
  2599. if (bits != 0)
  2600. {
  2601. const int invBits = 32 - bits;
  2602. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2603. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2604. values [wordsToMove] = values [wordsToMove] << bits;
  2605. }
  2606. highestBit = getHighestBit();
  2607. }
  2608. }
  2609. }
  2610. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2611. {
  2612. while (! m->isZero())
  2613. {
  2614. if (n->compareAbsolute (*m) > 0)
  2615. swapVariables (m, n);
  2616. *m -= *n;
  2617. }
  2618. return *n;
  2619. }
  2620. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2621. {
  2622. BigInteger m (*this);
  2623. while (! n.isZero())
  2624. {
  2625. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2626. return simpleGCD (&m, &n);
  2627. BigInteger temp1 (m), temp2;
  2628. temp1.divideBy (n, temp2);
  2629. m = n;
  2630. n = temp2;
  2631. }
  2632. return m;
  2633. }
  2634. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2635. {
  2636. BigInteger exp (exponent);
  2637. exp %= modulus;
  2638. BigInteger value (1);
  2639. swapWith (value);
  2640. value %= modulus;
  2641. while (! exp.isZero())
  2642. {
  2643. if (exp [0])
  2644. {
  2645. operator*= (value);
  2646. operator%= (modulus);
  2647. }
  2648. value *= value;
  2649. value %= modulus;
  2650. exp >>= 1;
  2651. }
  2652. }
  2653. void BigInteger::inverseModulo (const BigInteger& modulus)
  2654. {
  2655. if (modulus.isOne() || modulus.isNegative())
  2656. {
  2657. clear();
  2658. return;
  2659. }
  2660. if (isNegative() || compareAbsolute (modulus) >= 0)
  2661. operator%= (modulus);
  2662. if (isOne())
  2663. return;
  2664. if (! (*this)[0])
  2665. {
  2666. // not invertible
  2667. clear();
  2668. return;
  2669. }
  2670. BigInteger a1 (modulus);
  2671. BigInteger a2 (*this);
  2672. BigInteger b1 (modulus);
  2673. BigInteger b2 (1);
  2674. while (! a2.isOne())
  2675. {
  2676. BigInteger temp1, temp2, multiplier (a1);
  2677. multiplier.divideBy (a2, temp1);
  2678. temp1 = a2;
  2679. temp1 *= multiplier;
  2680. temp2 = a1;
  2681. temp2 -= temp1;
  2682. a1 = a2;
  2683. a2 = temp2;
  2684. temp1 = b2;
  2685. temp1 *= multiplier;
  2686. temp2 = b1;
  2687. temp2 -= temp1;
  2688. b1 = b2;
  2689. b2 = temp2;
  2690. }
  2691. while (b2.isNegative())
  2692. b2 += modulus;
  2693. b2 %= modulus;
  2694. swapWith (b2);
  2695. }
  2696. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2697. {
  2698. return stream << value.toString (10);
  2699. }
  2700. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2701. {
  2702. String s;
  2703. BigInteger v (*this);
  2704. if (base == 2 || base == 8 || base == 16)
  2705. {
  2706. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2707. static const char* const hexDigits = "0123456789abcdef";
  2708. for (;;)
  2709. {
  2710. const int remainder = v.getBitRangeAsInt (0, bits);
  2711. v >>= bits;
  2712. if (remainder == 0 && v.isZero())
  2713. break;
  2714. s = String::charToString (hexDigits [remainder]) + s;
  2715. }
  2716. }
  2717. else if (base == 10)
  2718. {
  2719. const BigInteger ten (10);
  2720. BigInteger remainder;
  2721. for (;;)
  2722. {
  2723. v.divideBy (ten, remainder);
  2724. if (remainder.isZero() && v.isZero())
  2725. break;
  2726. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2727. }
  2728. }
  2729. else
  2730. {
  2731. jassertfalse; // can't do the specified base!
  2732. return String::empty;
  2733. }
  2734. s = s.paddedLeft ('0', minimumNumCharacters);
  2735. return isNegative() ? "-" + s : s;
  2736. }
  2737. void BigInteger::parseString (const String& text, const int base)
  2738. {
  2739. clear();
  2740. const juce_wchar* t = text;
  2741. if (base == 2 || base == 8 || base == 16)
  2742. {
  2743. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2744. for (;;)
  2745. {
  2746. const juce_wchar c = *t++;
  2747. const int digit = CharacterFunctions::getHexDigitValue (c);
  2748. if (((uint32) digit) < (uint32) base)
  2749. {
  2750. operator<<= (bits);
  2751. operator+= (digit);
  2752. }
  2753. else if (c == 0)
  2754. {
  2755. break;
  2756. }
  2757. }
  2758. }
  2759. else if (base == 10)
  2760. {
  2761. const BigInteger ten ((uint32) 10);
  2762. for (;;)
  2763. {
  2764. const juce_wchar c = *t++;
  2765. if (c >= '0' && c <= '9')
  2766. {
  2767. operator*= (ten);
  2768. operator+= ((int) (c - '0'));
  2769. }
  2770. else if (c == 0)
  2771. {
  2772. break;
  2773. }
  2774. }
  2775. }
  2776. setNegative (text.trimStart().startsWithChar ('-'));
  2777. }
  2778. const MemoryBlock BigInteger::toMemoryBlock() const
  2779. {
  2780. const int numBytes = (getHighestBit() + 8) >> 3;
  2781. MemoryBlock mb ((size_t) numBytes);
  2782. for (int i = 0; i < numBytes; ++i)
  2783. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2784. return mb;
  2785. }
  2786. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2787. {
  2788. clear();
  2789. for (int i = (int) data.getSize(); --i >= 0;)
  2790. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2791. }
  2792. END_JUCE_NAMESPACE
  2793. /*** End of inlined file: juce_BigInteger.cpp ***/
  2794. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2795. BEGIN_JUCE_NAMESPACE
  2796. MemoryBlock::MemoryBlock() throw()
  2797. : size (0)
  2798. {
  2799. }
  2800. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2801. {
  2802. if (initialSize > 0)
  2803. {
  2804. size = initialSize;
  2805. data.allocate (initialSize, initialiseToZero);
  2806. }
  2807. else
  2808. {
  2809. size = 0;
  2810. }
  2811. }
  2812. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2813. : size (other.size)
  2814. {
  2815. if (size > 0)
  2816. {
  2817. jassert (other.data != 0);
  2818. data.malloc (size);
  2819. memcpy (data, other.data, size);
  2820. }
  2821. }
  2822. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2823. : size (jmax ((size_t) 0, sizeInBytes))
  2824. {
  2825. jassert (sizeInBytes >= 0);
  2826. if (size > 0)
  2827. {
  2828. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2829. data.malloc (size);
  2830. if (dataToInitialiseFrom != 0)
  2831. memcpy (data, dataToInitialiseFrom, size);
  2832. }
  2833. }
  2834. MemoryBlock::~MemoryBlock() throw()
  2835. {
  2836. jassert (size >= 0); // should never happen
  2837. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2838. }
  2839. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2840. {
  2841. if (this != &other)
  2842. {
  2843. setSize (other.size, false);
  2844. memcpy (data, other.data, size);
  2845. }
  2846. return *this;
  2847. }
  2848. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2849. {
  2850. return matches (other.data, other.size);
  2851. }
  2852. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2853. {
  2854. return ! operator== (other);
  2855. }
  2856. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2857. {
  2858. return size == dataSize
  2859. && memcmp (data, dataToCompare, size) == 0;
  2860. }
  2861. // this will resize the block to this size
  2862. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2863. {
  2864. if (size != newSize)
  2865. {
  2866. if (newSize <= 0)
  2867. {
  2868. data.free();
  2869. size = 0;
  2870. }
  2871. else
  2872. {
  2873. if (data != 0)
  2874. {
  2875. data.realloc (newSize);
  2876. if (initialiseToZero && (newSize > size))
  2877. zeromem (data + size, newSize - size);
  2878. }
  2879. else
  2880. {
  2881. data.allocate (newSize, initialiseToZero);
  2882. }
  2883. size = newSize;
  2884. }
  2885. }
  2886. }
  2887. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2888. {
  2889. if (size < minimumSize)
  2890. setSize (minimumSize, initialiseToZero);
  2891. }
  2892. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2893. {
  2894. swapVariables (size, other.size);
  2895. data.swapWith (other.data);
  2896. }
  2897. void MemoryBlock::fillWith (const uint8 value) throw()
  2898. {
  2899. memset (data, (int) value, size);
  2900. }
  2901. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2902. {
  2903. if (numBytes > 0)
  2904. {
  2905. const size_t oldSize = size;
  2906. setSize (size + numBytes);
  2907. memcpy (data + oldSize, srcData, numBytes);
  2908. }
  2909. }
  2910. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2911. {
  2912. const char* d = static_cast<const char*> (src);
  2913. if (offset < 0)
  2914. {
  2915. d -= offset;
  2916. num -= offset;
  2917. offset = 0;
  2918. }
  2919. if (offset + num > size)
  2920. num = size - offset;
  2921. if (num > 0)
  2922. memcpy (data + offset, d, num);
  2923. }
  2924. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2925. {
  2926. char* d = static_cast<char*> (dst);
  2927. if (offset < 0)
  2928. {
  2929. zeromem (d, -offset);
  2930. d -= offset;
  2931. num += offset;
  2932. offset = 0;
  2933. }
  2934. if (offset + num > size)
  2935. {
  2936. const size_t newNum = size - offset;
  2937. zeromem (d + newNum, num - newNum);
  2938. num = newNum;
  2939. }
  2940. if (num > 0)
  2941. memcpy (d, data + offset, num);
  2942. }
  2943. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2944. {
  2945. if (startByte < 0)
  2946. {
  2947. numBytesToRemove += startByte;
  2948. startByte = 0;
  2949. }
  2950. if (startByte + numBytesToRemove >= size)
  2951. {
  2952. setSize (startByte);
  2953. }
  2954. else if (numBytesToRemove > 0)
  2955. {
  2956. memmove (data + startByte,
  2957. data + startByte + numBytesToRemove,
  2958. size - (startByte + numBytesToRemove));
  2959. setSize (size - numBytesToRemove);
  2960. }
  2961. }
  2962. const String MemoryBlock::toString() const
  2963. {
  2964. return String (static_cast <const char*> (getData()), size);
  2965. }
  2966. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2967. {
  2968. int res = 0;
  2969. size_t byte = bitRangeStart >> 3;
  2970. int offsetInByte = (int) bitRangeStart & 7;
  2971. size_t bitsSoFar = 0;
  2972. while (numBits > 0 && (size_t) byte < size)
  2973. {
  2974. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2975. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2976. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2977. bitsSoFar += bitsThisTime;
  2978. numBits -= bitsThisTime;
  2979. ++byte;
  2980. offsetInByte = 0;
  2981. }
  2982. return res;
  2983. }
  2984. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2985. {
  2986. size_t byte = bitRangeStart >> 3;
  2987. int offsetInByte = (int) bitRangeStart & 7;
  2988. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2989. while (numBits > 0 && (size_t) byte < size)
  2990. {
  2991. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2992. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2993. const unsigned int tempBits = bitsToSet << offsetInByte;
  2994. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2995. ++byte;
  2996. numBits -= bitsThisTime;
  2997. bitsToSet >>= bitsThisTime;
  2998. mask >>= bitsThisTime;
  2999. offsetInByte = 0;
  3000. }
  3001. }
  3002. void MemoryBlock::loadFromHexString (const String& hex)
  3003. {
  3004. ensureSize (hex.length() >> 1);
  3005. char* dest = data;
  3006. int i = 0;
  3007. for (;;)
  3008. {
  3009. int byte = 0;
  3010. for (int loop = 2; --loop >= 0;)
  3011. {
  3012. byte <<= 4;
  3013. for (;;)
  3014. {
  3015. const juce_wchar c = hex [i++];
  3016. if (c >= '0' && c <= '9')
  3017. {
  3018. byte |= c - '0';
  3019. break;
  3020. }
  3021. else if (c >= 'a' && c <= 'z')
  3022. {
  3023. byte |= c - ('a' - 10);
  3024. break;
  3025. }
  3026. else if (c >= 'A' && c <= 'Z')
  3027. {
  3028. byte |= c - ('A' - 10);
  3029. break;
  3030. }
  3031. else if (c == 0)
  3032. {
  3033. setSize (static_cast <size_t> (dest - data));
  3034. return;
  3035. }
  3036. }
  3037. }
  3038. *dest++ = (char) byte;
  3039. }
  3040. }
  3041. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3042. const String MemoryBlock::toBase64Encoding() const
  3043. {
  3044. const size_t numChars = ((size << 3) + 5) / 6;
  3045. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3046. const int initialLen = destString.length();
  3047. destString.preallocateStorage (initialLen + 2 + numChars);
  3048. juce_wchar* d = destString;
  3049. d += initialLen;
  3050. *d++ = '.';
  3051. for (size_t i = 0; i < numChars; ++i)
  3052. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3053. *d++ = 0;
  3054. return destString;
  3055. }
  3056. bool MemoryBlock::fromBase64Encoding (const String& s)
  3057. {
  3058. const int startPos = s.indexOfChar ('.') + 1;
  3059. if (startPos <= 0)
  3060. return false;
  3061. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3062. setSize (numBytesNeeded, true);
  3063. const int numChars = s.length() - startPos;
  3064. const juce_wchar* srcChars = s;
  3065. srcChars += startPos;
  3066. int pos = 0;
  3067. for (int i = 0; i < numChars; ++i)
  3068. {
  3069. const char c = (char) srcChars[i];
  3070. for (int j = 0; j < 64; ++j)
  3071. {
  3072. if (encodingTable[j] == c)
  3073. {
  3074. setBitRange (pos, 6, j);
  3075. pos += 6;
  3076. break;
  3077. }
  3078. }
  3079. }
  3080. return true;
  3081. }
  3082. END_JUCE_NAMESPACE
  3083. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3084. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3085. BEGIN_JUCE_NAMESPACE
  3086. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3087. : properties (ignoreCaseOfKeyNames),
  3088. fallbackProperties (0),
  3089. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3090. {
  3091. }
  3092. PropertySet::PropertySet (const PropertySet& other)
  3093. : properties (other.properties),
  3094. fallbackProperties (other.fallbackProperties),
  3095. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3096. {
  3097. }
  3098. PropertySet& PropertySet::operator= (const PropertySet& other)
  3099. {
  3100. properties = other.properties;
  3101. fallbackProperties = other.fallbackProperties;
  3102. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3103. propertyChanged();
  3104. return *this;
  3105. }
  3106. PropertySet::~PropertySet()
  3107. {
  3108. }
  3109. void PropertySet::clear()
  3110. {
  3111. const ScopedLock sl (lock);
  3112. if (properties.size() > 0)
  3113. {
  3114. properties.clear();
  3115. propertyChanged();
  3116. }
  3117. }
  3118. const String PropertySet::getValue (const String& keyName,
  3119. const String& defaultValue) const throw()
  3120. {
  3121. const ScopedLock sl (lock);
  3122. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3123. if (index >= 0)
  3124. return properties.getAllValues() [index];
  3125. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3126. : defaultValue;
  3127. }
  3128. int PropertySet::getIntValue (const String& keyName,
  3129. const int defaultValue) const throw()
  3130. {
  3131. const ScopedLock sl (lock);
  3132. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3133. if (index >= 0)
  3134. return properties.getAllValues() [index].getIntValue();
  3135. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3136. : defaultValue;
  3137. }
  3138. double PropertySet::getDoubleValue (const String& keyName,
  3139. const double defaultValue) const throw()
  3140. {
  3141. const ScopedLock sl (lock);
  3142. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3143. if (index >= 0)
  3144. return properties.getAllValues()[index].getDoubleValue();
  3145. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3146. : defaultValue;
  3147. }
  3148. bool PropertySet::getBoolValue (const String& keyName,
  3149. const bool defaultValue) const throw()
  3150. {
  3151. const ScopedLock sl (lock);
  3152. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3153. if (index >= 0)
  3154. return properties.getAllValues() [index].getIntValue() != 0;
  3155. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3156. : defaultValue;
  3157. }
  3158. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3159. {
  3160. return XmlDocument::parse (getValue (keyName));
  3161. }
  3162. void PropertySet::setValue (const String& keyName, const var& v)
  3163. {
  3164. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3165. if (keyName.isNotEmpty())
  3166. {
  3167. const String value (v.toString());
  3168. const ScopedLock sl (lock);
  3169. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3170. if (index < 0 || properties.getAllValues() [index] != value)
  3171. {
  3172. properties.set (keyName, value);
  3173. propertyChanged();
  3174. }
  3175. }
  3176. }
  3177. void PropertySet::removeValue (const String& keyName)
  3178. {
  3179. if (keyName.isNotEmpty())
  3180. {
  3181. const ScopedLock sl (lock);
  3182. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3183. if (index >= 0)
  3184. {
  3185. properties.remove (keyName);
  3186. propertyChanged();
  3187. }
  3188. }
  3189. }
  3190. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3191. {
  3192. setValue (keyName, xml == 0 ? var::null
  3193. : var (xml->createDocument (String::empty, true)));
  3194. }
  3195. bool PropertySet::containsKey (const String& keyName) const throw()
  3196. {
  3197. const ScopedLock sl (lock);
  3198. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3199. }
  3200. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3201. {
  3202. const ScopedLock sl (lock);
  3203. fallbackProperties = fallbackProperties_;
  3204. }
  3205. XmlElement* PropertySet::createXml (const String& nodeName) const
  3206. {
  3207. const ScopedLock sl (lock);
  3208. XmlElement* const xml = new XmlElement (nodeName);
  3209. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3210. {
  3211. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3212. e->setAttribute ("name", properties.getAllKeys()[i]);
  3213. e->setAttribute ("val", properties.getAllValues()[i]);
  3214. }
  3215. return xml;
  3216. }
  3217. void PropertySet::restoreFromXml (const XmlElement& xml)
  3218. {
  3219. const ScopedLock sl (lock);
  3220. clear();
  3221. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3222. {
  3223. if (e->hasAttribute ("name")
  3224. && e->hasAttribute ("val"))
  3225. {
  3226. properties.set (e->getStringAttribute ("name"),
  3227. e->getStringAttribute ("val"));
  3228. }
  3229. }
  3230. if (properties.size() > 0)
  3231. propertyChanged();
  3232. }
  3233. void PropertySet::propertyChanged()
  3234. {
  3235. }
  3236. END_JUCE_NAMESPACE
  3237. /*** End of inlined file: juce_PropertySet.cpp ***/
  3238. /*** Start of inlined file: juce_Identifier.cpp ***/
  3239. BEGIN_JUCE_NAMESPACE
  3240. StringPool& Identifier::getPool()
  3241. {
  3242. static StringPool pool;
  3243. return pool;
  3244. }
  3245. Identifier::Identifier() throw()
  3246. : name (0)
  3247. {
  3248. }
  3249. Identifier::Identifier (const Identifier& other) throw()
  3250. : name (other.name)
  3251. {
  3252. }
  3253. Identifier& Identifier::operator= (const Identifier& other) throw()
  3254. {
  3255. name = other.name;
  3256. return *this;
  3257. }
  3258. Identifier::Identifier (const String& name_)
  3259. : name (Identifier::getPool().getPooledString (name_))
  3260. {
  3261. /* An Identifier string must be suitable for use as a script variable or XML
  3262. attribute, so it can only contain this limited set of characters.. */
  3263. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3264. }
  3265. Identifier::Identifier (const char* const name_)
  3266. : name (Identifier::getPool().getPooledString (name_))
  3267. {
  3268. /* An Identifier string must be suitable for use as a script variable or XML
  3269. attribute, so it can only contain this limited set of characters.. */
  3270. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3271. }
  3272. Identifier::~Identifier()
  3273. {
  3274. }
  3275. END_JUCE_NAMESPACE
  3276. /*** End of inlined file: juce_Identifier.cpp ***/
  3277. /*** Start of inlined file: juce_Variant.cpp ***/
  3278. BEGIN_JUCE_NAMESPACE
  3279. class var::VariantType
  3280. {
  3281. public:
  3282. VariantType() {}
  3283. virtual ~VariantType() {}
  3284. virtual int toInt (const ValueUnion&) const { return 0; }
  3285. virtual double toDouble (const ValueUnion&) const { return 0; }
  3286. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3287. virtual bool toBool (const ValueUnion&) const { return false; }
  3288. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3289. virtual bool isVoid() const throw() { return false; }
  3290. virtual bool isInt() const throw() { return false; }
  3291. virtual bool isBool() const throw() { return false; }
  3292. virtual bool isDouble() const throw() { return false; }
  3293. virtual bool isString() const throw() { return false; }
  3294. virtual bool isObject() const throw() { return false; }
  3295. virtual bool isMethod() const throw() { return false; }
  3296. virtual void cleanUp (ValueUnion&) const throw() {}
  3297. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3298. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3299. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3300. };
  3301. class var::VariantType_Void : public var::VariantType
  3302. {
  3303. public:
  3304. VariantType_Void() {}
  3305. static const VariantType_Void instance;
  3306. bool isVoid() const throw() { return true; }
  3307. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3308. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3309. };
  3310. class var::VariantType_Int : public var::VariantType
  3311. {
  3312. public:
  3313. VariantType_Int() {}
  3314. static const VariantType_Int instance;
  3315. int toInt (const ValueUnion& data) const { return data.intValue; };
  3316. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3317. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3318. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3319. bool isInt() const throw() { return true; }
  3320. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3321. {
  3322. return otherType.toInt (otherData) == data.intValue;
  3323. }
  3324. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3325. {
  3326. output.writeCompressedInt (5);
  3327. output.writeByte (1);
  3328. output.writeInt (data.intValue);
  3329. }
  3330. };
  3331. class var::VariantType_Double : public var::VariantType
  3332. {
  3333. public:
  3334. VariantType_Double() {}
  3335. static const VariantType_Double instance;
  3336. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3337. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3338. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3339. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3340. bool isDouble() const throw() { return true; }
  3341. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3342. {
  3343. return otherType.toDouble (otherData) == data.doubleValue;
  3344. }
  3345. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3346. {
  3347. output.writeCompressedInt (9);
  3348. output.writeByte (4);
  3349. output.writeDouble (data.doubleValue);
  3350. }
  3351. };
  3352. class var::VariantType_Bool : public var::VariantType
  3353. {
  3354. public:
  3355. VariantType_Bool() {}
  3356. static const VariantType_Bool instance;
  3357. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3358. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3359. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3360. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3361. bool isBool() const throw() { return true; }
  3362. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3363. {
  3364. return otherType.toBool (otherData) == data.boolValue;
  3365. }
  3366. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3367. {
  3368. output.writeCompressedInt (1);
  3369. output.writeByte (data.boolValue ? 2 : 3);
  3370. }
  3371. };
  3372. class var::VariantType_String : public var::VariantType
  3373. {
  3374. public:
  3375. VariantType_String() {}
  3376. static const VariantType_String instance;
  3377. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3378. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3379. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3380. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3381. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3382. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3383. || data.stringValue->trim().equalsIgnoreCase ("true")
  3384. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3385. bool isString() const throw() { return true; }
  3386. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3387. {
  3388. return otherType.toString (otherData) == *data.stringValue;
  3389. }
  3390. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3391. {
  3392. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3393. output.writeCompressedInt (len + 1);
  3394. output.writeByte (5);
  3395. HeapBlock<char> temp (len);
  3396. data.stringValue->copyToUTF8 (temp, len);
  3397. output.write (temp, len);
  3398. }
  3399. };
  3400. class var::VariantType_Object : public var::VariantType
  3401. {
  3402. public:
  3403. VariantType_Object() {}
  3404. static const VariantType_Object instance;
  3405. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3406. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3407. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3408. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3409. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3410. bool isObject() const throw() { return true; }
  3411. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3412. {
  3413. return otherType.toObject (otherData) == data.objectValue;
  3414. }
  3415. void writeToStream (const ValueUnion&, OutputStream& output) const
  3416. {
  3417. jassertfalse; // Can't write an object to a stream!
  3418. output.writeCompressedInt (0);
  3419. }
  3420. };
  3421. class var::VariantType_Method : public var::VariantType
  3422. {
  3423. public:
  3424. VariantType_Method() {}
  3425. static const VariantType_Method instance;
  3426. const String toString (const ValueUnion&) const { return "Method"; }
  3427. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3428. bool isMethod() const throw() { return true; }
  3429. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3430. {
  3431. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3432. }
  3433. void writeToStream (const ValueUnion&, OutputStream& output) const
  3434. {
  3435. jassertfalse; // Can't write a method to a stream!
  3436. output.writeCompressedInt (0);
  3437. }
  3438. };
  3439. const var::VariantType_Void var::VariantType_Void::instance;
  3440. const var::VariantType_Int var::VariantType_Int::instance;
  3441. const var::VariantType_Bool var::VariantType_Bool::instance;
  3442. const var::VariantType_Double var::VariantType_Double::instance;
  3443. const var::VariantType_String var::VariantType_String::instance;
  3444. const var::VariantType_Object var::VariantType_Object::instance;
  3445. const var::VariantType_Method var::VariantType_Method::instance;
  3446. var::var() throw() : type (&VariantType_Void::instance)
  3447. {
  3448. }
  3449. var::~var() throw()
  3450. {
  3451. type->cleanUp (value);
  3452. }
  3453. const var var::null;
  3454. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3455. {
  3456. type->createCopy (value, valueToCopy.value);
  3457. }
  3458. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3459. {
  3460. value.intValue = value_;
  3461. }
  3462. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3463. {
  3464. value.boolValue = value_;
  3465. }
  3466. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3467. {
  3468. value.doubleValue = value_;
  3469. }
  3470. var::var (const String& value_) : type (&VariantType_String::instance)
  3471. {
  3472. value.stringValue = new String (value_);
  3473. }
  3474. var::var (const char* const value_) : type (&VariantType_String::instance)
  3475. {
  3476. value.stringValue = new String (value_);
  3477. }
  3478. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3479. {
  3480. value.stringValue = new String (value_);
  3481. }
  3482. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3483. {
  3484. value.objectValue = object;
  3485. if (object != 0)
  3486. object->incReferenceCount();
  3487. }
  3488. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3489. {
  3490. value.methodValue = method_;
  3491. }
  3492. bool var::isVoid() const throw() { return type->isVoid(); }
  3493. bool var::isInt() const throw() { return type->isInt(); }
  3494. bool var::isBool() const throw() { return type->isBool(); }
  3495. bool var::isDouble() const throw() { return type->isDouble(); }
  3496. bool var::isString() const throw() { return type->isString(); }
  3497. bool var::isObject() const throw() { return type->isObject(); }
  3498. bool var::isMethod() const throw() { return type->isMethod(); }
  3499. var::operator int() const { return type->toInt (value); }
  3500. var::operator bool() const { return type->toBool (value); }
  3501. var::operator float() const { return (float) type->toDouble (value); }
  3502. var::operator double() const { return type->toDouble (value); }
  3503. const String var::toString() const { return type->toString (value); }
  3504. var::operator const String() const { return type->toString (value); }
  3505. DynamicObject* var::getObject() const { return type->toObject (value); }
  3506. void var::swapWith (var& other) throw()
  3507. {
  3508. swapVariables (type, other.type);
  3509. swapVariables (value, other.value);
  3510. }
  3511. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3512. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3513. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3514. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3515. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3516. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3517. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3518. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3519. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3520. bool var::equals (const var& other) const throw()
  3521. {
  3522. return type->equals (value, other.value, *other.type);
  3523. }
  3524. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3525. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3526. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3527. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3528. void var::writeToStream (OutputStream& output) const
  3529. {
  3530. type->writeToStream (value, output);
  3531. }
  3532. const var var::readFromStream (InputStream& input)
  3533. {
  3534. const int numBytes = input.readCompressedInt();
  3535. if (numBytes > 0)
  3536. {
  3537. switch (input.readByte())
  3538. {
  3539. case 1: return var (input.readInt());
  3540. case 2: return var (true);
  3541. case 3: return var (false);
  3542. case 4: return var (input.readDouble());
  3543. case 5:
  3544. {
  3545. MemoryOutputStream mo;
  3546. mo.writeFromInputStream (input, numBytes - 1);
  3547. return var (mo.toUTF8());
  3548. }
  3549. default: input.skipNextBytes (numBytes - 1); break;
  3550. }
  3551. }
  3552. return var::null;
  3553. }
  3554. const var var::operator[] (const Identifier& propertyName) const
  3555. {
  3556. DynamicObject* const o = getObject();
  3557. return o != 0 ? o->getProperty (propertyName) : var::null;
  3558. }
  3559. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3560. {
  3561. DynamicObject* const o = getObject();
  3562. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3563. }
  3564. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3565. {
  3566. if (isMethod())
  3567. {
  3568. DynamicObject* const target = targetObject.getObject();
  3569. if (target != 0)
  3570. return (target->*(value.methodValue)) (arguments, numArguments);
  3571. }
  3572. return var::null;
  3573. }
  3574. const var var::call (const Identifier& method) const
  3575. {
  3576. return invoke (method, 0, 0);
  3577. }
  3578. const var var::call (const Identifier& method, const var& arg1) const
  3579. {
  3580. return invoke (method, &arg1, 1);
  3581. }
  3582. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3583. {
  3584. var args[] = { arg1, arg2 };
  3585. return invoke (method, args, 2);
  3586. }
  3587. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3588. {
  3589. var args[] = { arg1, arg2, arg3 };
  3590. return invoke (method, args, 3);
  3591. }
  3592. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3593. {
  3594. var args[] = { arg1, arg2, arg3, arg4 };
  3595. return invoke (method, args, 4);
  3596. }
  3597. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3598. {
  3599. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3600. return invoke (method, args, 5);
  3601. }
  3602. END_JUCE_NAMESPACE
  3603. /*** End of inlined file: juce_Variant.cpp ***/
  3604. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3605. BEGIN_JUCE_NAMESPACE
  3606. NamedValueSet::NamedValue::NamedValue() throw()
  3607. {
  3608. }
  3609. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3610. : name (name_), value (value_)
  3611. {
  3612. }
  3613. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3614. {
  3615. return name == other.name && value == other.value;
  3616. }
  3617. NamedValueSet::NamedValueSet() throw()
  3618. {
  3619. }
  3620. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3621. : values (other.values)
  3622. {
  3623. }
  3624. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3625. {
  3626. values = other.values;
  3627. return *this;
  3628. }
  3629. NamedValueSet::~NamedValueSet()
  3630. {
  3631. }
  3632. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3633. {
  3634. return values == other.values;
  3635. }
  3636. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3637. {
  3638. return ! operator== (other);
  3639. }
  3640. int NamedValueSet::size() const throw()
  3641. {
  3642. return values.size();
  3643. }
  3644. const var& NamedValueSet::operator[] (const Identifier& name) const
  3645. {
  3646. for (int i = values.size(); --i >= 0;)
  3647. {
  3648. const NamedValue& v = values.getReference(i);
  3649. if (v.name == name)
  3650. return v.value;
  3651. }
  3652. return var::null;
  3653. }
  3654. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3655. {
  3656. const var* v = getVarPointer (name);
  3657. return v != 0 ? *v : defaultReturnValue;
  3658. }
  3659. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3660. {
  3661. for (int i = values.size(); --i >= 0;)
  3662. {
  3663. NamedValue& v = values.getReference(i);
  3664. if (v.name == name)
  3665. return &(v.value);
  3666. }
  3667. return 0;
  3668. }
  3669. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3670. {
  3671. for (int i = values.size(); --i >= 0;)
  3672. {
  3673. NamedValue& v = values.getReference(i);
  3674. if (v.name == name)
  3675. {
  3676. if (v.value == newValue)
  3677. return false;
  3678. v.value = newValue;
  3679. return true;
  3680. }
  3681. }
  3682. values.add (NamedValue (name, newValue));
  3683. return true;
  3684. }
  3685. bool NamedValueSet::contains (const Identifier& name) const
  3686. {
  3687. return getVarPointer (name) != 0;
  3688. }
  3689. bool NamedValueSet::remove (const Identifier& name)
  3690. {
  3691. for (int i = values.size(); --i >= 0;)
  3692. {
  3693. if (values.getReference(i).name == name)
  3694. {
  3695. values.remove (i);
  3696. return true;
  3697. }
  3698. }
  3699. return false;
  3700. }
  3701. const Identifier NamedValueSet::getName (const int index) const
  3702. {
  3703. jassert (isPositiveAndBelow (index, values.size()));
  3704. return values [index].name;
  3705. }
  3706. const var NamedValueSet::getValueAt (const int index) const
  3707. {
  3708. jassert (isPositiveAndBelow (index, values.size()));
  3709. return values [index].value;
  3710. }
  3711. void NamedValueSet::clear()
  3712. {
  3713. values.clear();
  3714. }
  3715. END_JUCE_NAMESPACE
  3716. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3717. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3718. BEGIN_JUCE_NAMESPACE
  3719. DynamicObject::DynamicObject()
  3720. {
  3721. }
  3722. DynamicObject::~DynamicObject()
  3723. {
  3724. }
  3725. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3726. {
  3727. var* const v = properties.getVarPointer (propertyName);
  3728. return v != 0 && ! v->isMethod();
  3729. }
  3730. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3731. {
  3732. return properties [propertyName];
  3733. }
  3734. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3735. {
  3736. properties.set (propertyName, newValue);
  3737. }
  3738. void DynamicObject::removeProperty (const Identifier& propertyName)
  3739. {
  3740. properties.remove (propertyName);
  3741. }
  3742. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3743. {
  3744. return getProperty (methodName).isMethod();
  3745. }
  3746. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3747. const var* parameters,
  3748. int numParameters)
  3749. {
  3750. return properties [methodName].invoke (var (this), parameters, numParameters);
  3751. }
  3752. void DynamicObject::setMethod (const Identifier& name,
  3753. var::MethodFunction methodFunction)
  3754. {
  3755. properties.set (name, var (methodFunction));
  3756. }
  3757. void DynamicObject::clear()
  3758. {
  3759. properties.clear();
  3760. }
  3761. END_JUCE_NAMESPACE
  3762. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3763. /*** Start of inlined file: juce_Expression.cpp ***/
  3764. BEGIN_JUCE_NAMESPACE
  3765. class Expression::Helpers
  3766. {
  3767. public:
  3768. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3769. // This helper function is needed to work around VC6 scoping bugs
  3770. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3771. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3772. class Constant : public Term
  3773. {
  3774. public:
  3775. Constant (const double value_, bool isResolutionTarget_)
  3776. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3777. Type getType() const throw() { return constantType; }
  3778. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3779. double evaluate (const EvaluationContext&, int) const { return value; }
  3780. int getNumInputs() const { return 0; }
  3781. Term* getInput (int) const { return 0; }
  3782. const TermPtr negated()
  3783. {
  3784. return new Constant (-value, isResolutionTarget);
  3785. }
  3786. const String toString() const
  3787. {
  3788. if (isResolutionTarget)
  3789. return "@" + String (value);
  3790. return String (value);
  3791. }
  3792. double value;
  3793. bool isResolutionTarget;
  3794. };
  3795. class Symbol : public Term
  3796. {
  3797. public:
  3798. explicit Symbol (const String& symbol_)
  3799. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3800. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3801. {}
  3802. Symbol (const String& symbol_, const String& member_)
  3803. : mainSymbol (symbol_),
  3804. member (member_)
  3805. {}
  3806. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3807. {
  3808. if (++recursionDepth > 256)
  3809. throw EvaluationError ("Recursive symbol references");
  3810. try
  3811. {
  3812. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3813. }
  3814. catch (...)
  3815. {}
  3816. return 0;
  3817. }
  3818. Type getType() const throw() { return symbolType; }
  3819. Term* clone() const { return new Symbol (mainSymbol, member); }
  3820. int getNumInputs() const { return 0; }
  3821. Term* getInput (int) const { return 0; }
  3822. const String getSymbolName() const { return toString(); }
  3823. const String toString() const
  3824. {
  3825. return member.isEmpty() ? mainSymbol
  3826. : mainSymbol + "." + member;
  3827. }
  3828. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3829. {
  3830. if (s == mainSymbol)
  3831. return true;
  3832. if (++recursionDepth > 256)
  3833. throw EvaluationError ("Recursive symbol references");
  3834. try
  3835. {
  3836. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3837. }
  3838. catch (EvaluationError&)
  3839. {
  3840. return false;
  3841. }
  3842. }
  3843. String mainSymbol, member;
  3844. };
  3845. class Function : public Term
  3846. {
  3847. public:
  3848. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3849. : functionName (functionName_), parameters (parameters_)
  3850. {}
  3851. Term* clone() const { return new Function (functionName, parameters); }
  3852. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3853. {
  3854. HeapBlock <double> params (parameters.size());
  3855. for (int i = 0; i < parameters.size(); ++i)
  3856. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3857. return c.evaluateFunction (functionName, params, parameters.size());
  3858. }
  3859. Type getType() const throw() { return functionType; }
  3860. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3861. int getNumInputs() const { return parameters.size(); }
  3862. Term* getInput (int i) const { return parameters [i]; }
  3863. const String getFunctionName() const { return functionName; }
  3864. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3865. {
  3866. for (int i = 0; i < parameters.size(); ++i)
  3867. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3868. return true;
  3869. return false;
  3870. }
  3871. const String toString() const
  3872. {
  3873. if (parameters.size() == 0)
  3874. return functionName + "()";
  3875. String s (functionName + " (");
  3876. for (int i = 0; i < parameters.size(); ++i)
  3877. {
  3878. s << parameters.getUnchecked(i)->toString();
  3879. if (i < parameters.size() - 1)
  3880. s << ", ";
  3881. }
  3882. s << ')';
  3883. return s;
  3884. }
  3885. const String functionName;
  3886. ReferenceCountedArray<Term> parameters;
  3887. };
  3888. class Negate : public Term
  3889. {
  3890. public:
  3891. Negate (const TermPtr& input_) : input (input_)
  3892. {
  3893. jassert (input_ != 0);
  3894. }
  3895. Type getType() const throw() { return operatorType; }
  3896. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3897. int getNumInputs() const { return 1; }
  3898. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3899. Term* clone() const { return new Negate (input->clone()); }
  3900. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3901. const String getFunctionName() const { return "-"; }
  3902. const TermPtr negated()
  3903. {
  3904. return input;
  3905. }
  3906. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3907. {
  3908. (void) input_;
  3909. jassert (input_ == input);
  3910. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3911. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3912. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3913. }
  3914. const String toString() const
  3915. {
  3916. if (input->getOperatorPrecedence() > 0)
  3917. return "-(" + input->toString() + ")";
  3918. else
  3919. return "-" + input->toString();
  3920. }
  3921. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3922. {
  3923. return input->referencesSymbol (s, c, recursionDepth);
  3924. }
  3925. private:
  3926. const TermPtr input;
  3927. };
  3928. class BinaryTerm : public Term
  3929. {
  3930. public:
  3931. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3932. {
  3933. jassert (left_ != 0 && right_ != 0);
  3934. }
  3935. int getInputIndexFor (const Term* possibleInput) const
  3936. {
  3937. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3938. }
  3939. Type getType() const throw() { return operatorType; }
  3940. int getNumInputs() const { return 2; }
  3941. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3942. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3943. {
  3944. return left->referencesSymbol (s, c, recursionDepth)
  3945. || right->referencesSymbol (s, c, recursionDepth);
  3946. }
  3947. const String toString() const
  3948. {
  3949. String s;
  3950. const int ourPrecendence = getOperatorPrecedence();
  3951. if (left->getOperatorPrecedence() > ourPrecendence)
  3952. s << '(' << left->toString() << ')';
  3953. else
  3954. s = left->toString();
  3955. s << ' ' << getFunctionName() << ' ';
  3956. if (right->getOperatorPrecedence() >= ourPrecendence)
  3957. s << '(' << right->toString() << ')';
  3958. else
  3959. s << right->toString();
  3960. return s;
  3961. }
  3962. protected:
  3963. const TermPtr left, right;
  3964. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3965. {
  3966. jassert (input == left || input == right);
  3967. if (input != left && input != right)
  3968. return 0;
  3969. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3970. if (dest == 0)
  3971. return new Constant (overallTarget, false);
  3972. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3973. }
  3974. };
  3975. class Add : public BinaryTerm
  3976. {
  3977. public:
  3978. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3979. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3980. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3981. int getOperatorPrecedence() const { return 2; }
  3982. const String getFunctionName() const { return "+"; }
  3983. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3984. {
  3985. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3986. if (newDest == 0)
  3987. return 0;
  3988. return new Subtract (newDest, (input == left ? right : left)->clone());
  3989. }
  3990. private:
  3991. JUCE_DECLARE_NON_COPYABLE (Add);
  3992. };
  3993. class Subtract : public BinaryTerm
  3994. {
  3995. public:
  3996. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3997. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3998. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3999. int getOperatorPrecedence() const { return 2; }
  4000. const String getFunctionName() const { return "-"; }
  4001. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4002. {
  4003. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4004. if (newDest == 0)
  4005. return 0;
  4006. if (input == left)
  4007. return new Add (newDest, right->clone());
  4008. else
  4009. return new Subtract (left->clone(), newDest);
  4010. }
  4011. private:
  4012. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4013. };
  4014. class Multiply : public BinaryTerm
  4015. {
  4016. public:
  4017. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4018. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4019. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4020. const String getFunctionName() const { return "*"; }
  4021. int getOperatorPrecedence() const { return 1; }
  4022. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4023. {
  4024. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4025. if (newDest == 0)
  4026. return 0;
  4027. return new Divide (newDest, (input == left ? right : left)->clone());
  4028. }
  4029. private:
  4030. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4031. };
  4032. class Divide : public BinaryTerm
  4033. {
  4034. public:
  4035. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4036. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4037. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4038. const String getFunctionName() const { return "/"; }
  4039. int getOperatorPrecedence() const { return 1; }
  4040. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4041. {
  4042. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4043. if (newDest == 0)
  4044. return 0;
  4045. if (input == left)
  4046. return new Multiply (newDest, right->clone());
  4047. else
  4048. return new Divide (left->clone(), newDest);
  4049. }
  4050. private:
  4051. JUCE_DECLARE_NON_COPYABLE (Divide);
  4052. };
  4053. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4054. {
  4055. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4056. if (inputIndex >= 0)
  4057. return topLevel;
  4058. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4059. {
  4060. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4061. if (t != 0)
  4062. return t;
  4063. }
  4064. return 0;
  4065. }
  4066. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4067. {
  4068. Constant* c = dynamic_cast<Constant*> (term);
  4069. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4070. return c;
  4071. if (dynamic_cast<Function*> (term) != 0)
  4072. return 0;
  4073. int i;
  4074. const int numIns = term->getNumInputs();
  4075. for (i = 0; i < numIns; ++i)
  4076. {
  4077. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4078. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4079. return c;
  4080. }
  4081. for (i = 0; i < numIns; ++i)
  4082. {
  4083. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4084. if (c != 0)
  4085. return c;
  4086. }
  4087. return 0;
  4088. }
  4089. static bool containsAnySymbols (const Term* const t)
  4090. {
  4091. if (dynamic_cast <const Symbol*> (t) != 0)
  4092. return true;
  4093. for (int i = t->getNumInputs(); --i >= 0;)
  4094. if (containsAnySymbols (t->getInput (i)))
  4095. return true;
  4096. return false;
  4097. }
  4098. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4099. {
  4100. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4101. if (sym != 0 && sym->mainSymbol == oldName)
  4102. {
  4103. sym->mainSymbol = newName;
  4104. return true;
  4105. }
  4106. bool anyChanged = false;
  4107. for (int i = t->getNumInputs(); --i >= 0;)
  4108. if (renameSymbol (t->getInput (i), oldName, newName))
  4109. anyChanged = true;
  4110. return anyChanged;
  4111. }
  4112. class Parser
  4113. {
  4114. public:
  4115. Parser (const String& stringToParse, int& textIndex_)
  4116. : textString (stringToParse), textIndex (textIndex_)
  4117. {
  4118. text = textString;
  4119. }
  4120. const TermPtr readExpression()
  4121. {
  4122. TermPtr lhs (readMultiplyOrDivideExpression());
  4123. char opType;
  4124. while (lhs != 0 && readOperator ("+-", &opType))
  4125. {
  4126. TermPtr rhs (readMultiplyOrDivideExpression());
  4127. if (rhs == 0)
  4128. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4129. if (opType == '+')
  4130. lhs = new Add (lhs, rhs);
  4131. else
  4132. lhs = new Subtract (lhs, rhs);
  4133. }
  4134. return lhs;
  4135. }
  4136. private:
  4137. const String textString;
  4138. const juce_wchar* text;
  4139. int& textIndex;
  4140. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4141. {
  4142. return c >= '0' && c <= '9';
  4143. }
  4144. void skipWhitespace (int& i)
  4145. {
  4146. while (CharacterFunctions::isWhitespace (text [i]))
  4147. ++i;
  4148. }
  4149. bool readChar (const juce_wchar required)
  4150. {
  4151. if (text[textIndex] == required)
  4152. {
  4153. ++textIndex;
  4154. return true;
  4155. }
  4156. return false;
  4157. }
  4158. bool readOperator (const char* ops, char* const opType = 0)
  4159. {
  4160. skipWhitespace (textIndex);
  4161. while (*ops != 0)
  4162. {
  4163. if (readChar (*ops))
  4164. {
  4165. if (opType != 0)
  4166. *opType = *ops;
  4167. return true;
  4168. }
  4169. ++ops;
  4170. }
  4171. return false;
  4172. }
  4173. bool readIdentifier (String& identifier)
  4174. {
  4175. skipWhitespace (textIndex);
  4176. int i = textIndex;
  4177. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4178. {
  4179. ++i;
  4180. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4181. ++i;
  4182. }
  4183. if (i > textIndex)
  4184. {
  4185. identifier = String (text + textIndex, i - textIndex);
  4186. textIndex = i;
  4187. return true;
  4188. }
  4189. return false;
  4190. }
  4191. Term* readNumber()
  4192. {
  4193. skipWhitespace (textIndex);
  4194. int i = textIndex;
  4195. const bool isResolutionTarget = (text[i] == '@');
  4196. if (isResolutionTarget)
  4197. {
  4198. ++i;
  4199. skipWhitespace (i);
  4200. textIndex = i;
  4201. }
  4202. if (text[i] == '-')
  4203. {
  4204. ++i;
  4205. skipWhitespace (i);
  4206. }
  4207. int numDigits = 0;
  4208. while (isDecimalDigit (text[i]))
  4209. {
  4210. ++i;
  4211. ++numDigits;
  4212. }
  4213. const bool hasPoint = (text[i] == '.');
  4214. if (hasPoint)
  4215. {
  4216. ++i;
  4217. while (isDecimalDigit (text[i]))
  4218. {
  4219. ++i;
  4220. ++numDigits;
  4221. }
  4222. }
  4223. if (numDigits == 0)
  4224. return 0;
  4225. juce_wchar c = text[i];
  4226. const bool hasExponent = (c == 'e' || c == 'E');
  4227. if (hasExponent)
  4228. {
  4229. ++i;
  4230. c = text[i];
  4231. if (c == '+' || c == '-')
  4232. ++i;
  4233. int numExpDigits = 0;
  4234. while (isDecimalDigit (text[i]))
  4235. {
  4236. ++i;
  4237. ++numExpDigits;
  4238. }
  4239. if (numExpDigits == 0)
  4240. return 0;
  4241. }
  4242. const int start = textIndex;
  4243. textIndex = i;
  4244. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4245. }
  4246. const TermPtr readMultiplyOrDivideExpression()
  4247. {
  4248. TermPtr lhs (readUnaryExpression());
  4249. char opType;
  4250. while (lhs != 0 && readOperator ("*/", &opType))
  4251. {
  4252. TermPtr rhs (readUnaryExpression());
  4253. if (rhs == 0)
  4254. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4255. if (opType == '*')
  4256. lhs = new Multiply (lhs, rhs);
  4257. else
  4258. lhs = new Divide (lhs, rhs);
  4259. }
  4260. return lhs;
  4261. }
  4262. const TermPtr readUnaryExpression()
  4263. {
  4264. char opType;
  4265. if (readOperator ("+-", &opType))
  4266. {
  4267. TermPtr term (readUnaryExpression());
  4268. if (term == 0)
  4269. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4270. if (opType == '-')
  4271. term = term->negated();
  4272. return term;
  4273. }
  4274. return readPrimaryExpression();
  4275. }
  4276. const TermPtr readPrimaryExpression()
  4277. {
  4278. TermPtr e (readParenthesisedExpression());
  4279. if (e != 0)
  4280. return e;
  4281. e = readNumber();
  4282. if (e != 0)
  4283. return e;
  4284. String identifier;
  4285. if (readIdentifier (identifier))
  4286. {
  4287. if (readOperator ("(")) // method call...
  4288. {
  4289. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4290. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4291. TermPtr param (readExpression());
  4292. if (param == 0)
  4293. {
  4294. if (readOperator (")"))
  4295. return func.release();
  4296. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4297. }
  4298. f->parameters.add (param);
  4299. while (readOperator (","))
  4300. {
  4301. param = readExpression();
  4302. if (param == 0)
  4303. throw ParseError ("Expected expression after \",\"");
  4304. f->parameters.add (param);
  4305. }
  4306. if (readOperator (")"))
  4307. return func.release();
  4308. throw ParseError ("Expected \")\"");
  4309. }
  4310. else // just a symbol..
  4311. {
  4312. return new Symbol (identifier);
  4313. }
  4314. }
  4315. return 0;
  4316. }
  4317. const TermPtr readParenthesisedExpression()
  4318. {
  4319. if (! readOperator ("("))
  4320. return 0;
  4321. const TermPtr e (readExpression());
  4322. if (e == 0 || ! readOperator (")"))
  4323. return 0;
  4324. return e;
  4325. }
  4326. JUCE_DECLARE_NON_COPYABLE (Parser);
  4327. };
  4328. };
  4329. Expression::Expression()
  4330. : term (new Expression::Helpers::Constant (0, false))
  4331. {
  4332. }
  4333. Expression::~Expression()
  4334. {
  4335. }
  4336. Expression::Expression (Term* const term_)
  4337. : term (term_)
  4338. {
  4339. jassert (term != 0);
  4340. }
  4341. Expression::Expression (const double constant)
  4342. : term (new Expression::Helpers::Constant (constant, false))
  4343. {
  4344. }
  4345. Expression::Expression (const Expression& other)
  4346. : term (other.term)
  4347. {
  4348. }
  4349. Expression& Expression::operator= (const Expression& other)
  4350. {
  4351. term = other.term;
  4352. return *this;
  4353. }
  4354. Expression::Expression (const String& stringToParse)
  4355. {
  4356. int i = 0;
  4357. Helpers::Parser parser (stringToParse, i);
  4358. term = parser.readExpression();
  4359. if (term == 0)
  4360. term = new Helpers::Constant (0, false);
  4361. }
  4362. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4363. {
  4364. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4365. const Helpers::TermPtr term (parser.readExpression());
  4366. if (term != 0)
  4367. return Expression (term);
  4368. return Expression();
  4369. }
  4370. double Expression::evaluate() const
  4371. {
  4372. return evaluate (Expression::EvaluationContext());
  4373. }
  4374. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4375. {
  4376. return term->evaluate (context, 0);
  4377. }
  4378. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4379. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4380. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4381. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4382. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4383. const String Expression::toString() const
  4384. {
  4385. return term->toString();
  4386. }
  4387. const Expression Expression::symbol (const String& symbol)
  4388. {
  4389. return Expression (new Helpers::Symbol (symbol));
  4390. }
  4391. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4392. {
  4393. ReferenceCountedArray<Term> params;
  4394. for (int i = 0; i < parameters.size(); ++i)
  4395. params.add (parameters.getReference(i).term);
  4396. return Expression (new Helpers::Function (functionName, params));
  4397. }
  4398. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4399. const Expression::EvaluationContext& context) const
  4400. {
  4401. ScopedPointer<Term> newTerm (term->clone());
  4402. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4403. if (termToAdjust == 0)
  4404. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4405. if (termToAdjust == 0)
  4406. {
  4407. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4408. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4409. }
  4410. jassert (termToAdjust != 0);
  4411. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4412. if (parent == 0)
  4413. {
  4414. termToAdjust->value = targetValue;
  4415. }
  4416. else
  4417. {
  4418. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4419. if (reverseTerm == 0)
  4420. return Expression (targetValue);
  4421. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4422. }
  4423. return Expression (newTerm.release());
  4424. }
  4425. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4426. {
  4427. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  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. return term->getSymbolName();
  4447. }
  4448. const String Expression::getFunction() const
  4449. {
  4450. return term->getFunctionName();
  4451. }
  4452. const String Expression::getOperator() const
  4453. {
  4454. return term->getFunctionName();
  4455. }
  4456. int Expression::getNumInputs() const
  4457. {
  4458. return term->getNumInputs();
  4459. }
  4460. const Expression Expression::getInput (int index) const
  4461. {
  4462. return Expression (term->getInput (index));
  4463. }
  4464. int Expression::Term::getOperatorPrecedence() const
  4465. {
  4466. return 0;
  4467. }
  4468. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4469. {
  4470. return false;
  4471. }
  4472. int Expression::Term::getInputIndexFor (const Term*) const
  4473. {
  4474. return -1;
  4475. }
  4476. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4477. {
  4478. jassertfalse;
  4479. return 0;
  4480. }
  4481. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4482. {
  4483. return new Helpers::Negate (this);
  4484. }
  4485. const String Expression::Term::getSymbolName() const
  4486. {
  4487. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4488. return String::empty;
  4489. }
  4490. const String Expression::Term::getFunctionName() const
  4491. {
  4492. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4493. return String::empty;
  4494. }
  4495. Expression::ParseError::ParseError (const String& message)
  4496. : description (message)
  4497. {
  4498. DBG ("Expression::ParseError: " + message);
  4499. }
  4500. Expression::EvaluationError::EvaluationError (const String& message)
  4501. : description (message)
  4502. {
  4503. DBG ("Expression::EvaluationError: " + description);
  4504. }
  4505. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4506. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4507. {
  4508. DBG ("Expression::EvaluationError: " + description);
  4509. }
  4510. Expression::EvaluationContext::EvaluationContext() {}
  4511. Expression::EvaluationContext::~EvaluationContext() {}
  4512. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4513. {
  4514. throw EvaluationError (symbol, member);
  4515. }
  4516. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4517. {
  4518. if (numParams > 0)
  4519. {
  4520. if (functionName == "min")
  4521. {
  4522. double v = parameters[0];
  4523. for (int i = 1; i < numParams; ++i)
  4524. v = jmin (v, parameters[i]);
  4525. return v;
  4526. }
  4527. else if (functionName == "max")
  4528. {
  4529. double v = parameters[0];
  4530. for (int i = 1; i < numParams; ++i)
  4531. v = jmax (v, parameters[i]);
  4532. return v;
  4533. }
  4534. else if (numParams == 1)
  4535. {
  4536. if (functionName == "sin") return sin (parameters[0]);
  4537. else if (functionName == "cos") return cos (parameters[0]);
  4538. else if (functionName == "tan") return tan (parameters[0]);
  4539. else if (functionName == "abs") return std::abs (parameters[0]);
  4540. }
  4541. }
  4542. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4543. }
  4544. END_JUCE_NAMESPACE
  4545. /*** End of inlined file: juce_Expression.cpp ***/
  4546. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4547. BEGIN_JUCE_NAMESPACE
  4548. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4549. {
  4550. jassert (keyData != 0);
  4551. jassert (keyBytes > 0);
  4552. static const uint32 initialPValues [18] =
  4553. {
  4554. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4555. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4556. 0x9216d5d9, 0x8979fb1b
  4557. };
  4558. static const uint32 initialSValues [4 * 256] =
  4559. {
  4560. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4561. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4562. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4563. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4564. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4565. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4566. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4567. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4568. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4569. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4570. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4571. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4572. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4573. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4574. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4575. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4576. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4577. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4578. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4579. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4580. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4581. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4582. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4583. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4584. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4585. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4586. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4587. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4588. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4589. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4590. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4591. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4592. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4593. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4594. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4595. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4596. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4597. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4598. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4599. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4600. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4601. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4602. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4603. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4604. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4605. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4606. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4607. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4608. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4609. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4610. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4611. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4612. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4613. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4614. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4615. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4616. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4617. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4618. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4619. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4620. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4621. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4622. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4623. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4624. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4625. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4626. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4627. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4628. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4629. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4630. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4631. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4632. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4633. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4634. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4635. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4636. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4637. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4638. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4639. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4640. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4641. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4642. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4643. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4644. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4645. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4646. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4647. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4648. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4649. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4650. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4651. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4652. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4653. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4654. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4655. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4656. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4657. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4658. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4659. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4660. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4661. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4662. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4663. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4664. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4665. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4666. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4667. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4668. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4669. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4670. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4671. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4672. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4673. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4674. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4675. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4676. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4677. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4678. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4679. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4680. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4681. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4682. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4683. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4684. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4685. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4686. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4687. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4688. };
  4689. memcpy (p, initialPValues, sizeof (p));
  4690. int i, j = 0;
  4691. for (i = 4; --i >= 0;)
  4692. {
  4693. s[i].malloc (256);
  4694. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4695. }
  4696. for (i = 0; i < 18; ++i)
  4697. {
  4698. uint32 d = 0;
  4699. for (int k = 0; k < 4; ++k)
  4700. {
  4701. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4702. if (++j >= keyBytes)
  4703. j = 0;
  4704. }
  4705. p[i] = initialPValues[i] ^ d;
  4706. }
  4707. uint32 l = 0, r = 0;
  4708. for (i = 0; i < 18; i += 2)
  4709. {
  4710. encrypt (l, r);
  4711. p[i] = l;
  4712. p[i + 1] = r;
  4713. }
  4714. for (i = 0; i < 4; ++i)
  4715. {
  4716. for (j = 0; j < 256; j += 2)
  4717. {
  4718. encrypt (l, r);
  4719. s[i][j] = l;
  4720. s[i][j + 1] = r;
  4721. }
  4722. }
  4723. }
  4724. BlowFish::BlowFish (const BlowFish& other)
  4725. {
  4726. for (int i = 4; --i >= 0;)
  4727. s[i].malloc (256);
  4728. operator= (other);
  4729. }
  4730. BlowFish& BlowFish::operator= (const BlowFish& other)
  4731. {
  4732. memcpy (p, other.p, sizeof (p));
  4733. for (int i = 4; --i >= 0;)
  4734. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4735. return *this;
  4736. }
  4737. BlowFish::~BlowFish()
  4738. {
  4739. }
  4740. uint32 BlowFish::F (const uint32 x) const throw()
  4741. {
  4742. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4743. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4744. }
  4745. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4746. {
  4747. uint32 l = data1;
  4748. uint32 r = data2;
  4749. for (int i = 0; i < 16; ++i)
  4750. {
  4751. l ^= p[i];
  4752. r ^= F(l);
  4753. swapVariables (l, r);
  4754. }
  4755. data1 = r ^ p[17];
  4756. data2 = l ^ p[16];
  4757. }
  4758. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4759. {
  4760. uint32 l = data1;
  4761. uint32 r = data2;
  4762. for (int i = 17; i > 1; --i)
  4763. {
  4764. l ^= p[i];
  4765. r ^= F(l);
  4766. swapVariables (l, r);
  4767. }
  4768. data1 = r ^ p[0];
  4769. data2 = l ^ p[1];
  4770. }
  4771. END_JUCE_NAMESPACE
  4772. /*** End of inlined file: juce_BlowFish.cpp ***/
  4773. /*** Start of inlined file: juce_MD5.cpp ***/
  4774. BEGIN_JUCE_NAMESPACE
  4775. MD5::MD5()
  4776. {
  4777. zerostruct (result);
  4778. }
  4779. MD5::MD5 (const MD5& other)
  4780. {
  4781. memcpy (result, other.result, sizeof (result));
  4782. }
  4783. MD5& MD5::operator= (const MD5& other)
  4784. {
  4785. memcpy (result, other.result, sizeof (result));
  4786. return *this;
  4787. }
  4788. MD5::MD5 (const MemoryBlock& data)
  4789. {
  4790. ProcessContext context;
  4791. context.processBlock (data.getData(), data.getSize());
  4792. context.finish (result);
  4793. }
  4794. MD5::MD5 (const void* data, const size_t numBytes)
  4795. {
  4796. ProcessContext context;
  4797. context.processBlock (data, numBytes);
  4798. context.finish (result);
  4799. }
  4800. MD5::MD5 (const String& text)
  4801. {
  4802. ProcessContext context;
  4803. const int len = text.length();
  4804. const juce_wchar* const t = text;
  4805. for (int i = 0; i < len; ++i)
  4806. {
  4807. // force the string into integer-sized unicode characters, to try to make it
  4808. // get the same results on all platforms + compilers.
  4809. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4810. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4811. }
  4812. context.finish (result);
  4813. }
  4814. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4815. {
  4816. ProcessContext context;
  4817. if (numBytesToRead < 0)
  4818. numBytesToRead = std::numeric_limits<int64>::max();
  4819. while (numBytesToRead > 0)
  4820. {
  4821. uint8 tempBuffer [512];
  4822. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4823. if (bytesRead <= 0)
  4824. break;
  4825. numBytesToRead -= bytesRead;
  4826. context.processBlock (tempBuffer, bytesRead);
  4827. }
  4828. context.finish (result);
  4829. }
  4830. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4831. {
  4832. processStream (input, numBytesToRead);
  4833. }
  4834. MD5::MD5 (const File& file)
  4835. {
  4836. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4837. if (fin != 0)
  4838. processStream (*fin, -1);
  4839. else
  4840. zerostruct (result);
  4841. }
  4842. MD5::~MD5()
  4843. {
  4844. }
  4845. namespace MD5Functions
  4846. {
  4847. void encode (void* const output, const void* const input, const int numBytes) throw()
  4848. {
  4849. for (int i = 0; i < (numBytes >> 2); ++i)
  4850. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4851. }
  4852. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4853. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4854. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4855. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4856. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4857. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4858. {
  4859. a += F (b, c, d) + x + ac;
  4860. a = rotateLeft (a, s) + b;
  4861. }
  4862. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4863. {
  4864. a += G (b, c, d) + x + ac;
  4865. a = rotateLeft (a, s) + b;
  4866. }
  4867. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += H (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += I (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. }
  4878. MD5::ProcessContext::ProcessContext()
  4879. {
  4880. state[0] = 0x67452301;
  4881. state[1] = 0xefcdab89;
  4882. state[2] = 0x98badcfe;
  4883. state[3] = 0x10325476;
  4884. count[0] = 0;
  4885. count[1] = 0;
  4886. }
  4887. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4888. {
  4889. int bufferPos = ((count[0] >> 3) & 0x3F);
  4890. count[0] += (uint32) (dataSize << 3);
  4891. if (count[0] < ((uint32) dataSize << 3))
  4892. count[1]++;
  4893. count[1] += (uint32) (dataSize >> 29);
  4894. const size_t spaceLeft = 64 - bufferPos;
  4895. size_t i = 0;
  4896. if (dataSize >= spaceLeft)
  4897. {
  4898. memcpy (buffer + bufferPos, data, spaceLeft);
  4899. transform (buffer);
  4900. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4901. transform (static_cast <const char*> (data) + i);
  4902. bufferPos = 0;
  4903. }
  4904. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4905. }
  4906. void MD5::ProcessContext::finish (void* const result)
  4907. {
  4908. unsigned char encodedLength[8];
  4909. MD5Functions::encode (encodedLength, count, 8);
  4910. // Pad out to 56 mod 64.
  4911. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4912. const int paddingLength = (index < 56) ? (56 - index)
  4913. : (120 - index);
  4914. uint8 paddingBuffer [64];
  4915. zeromem (paddingBuffer, paddingLength);
  4916. paddingBuffer [0] = 0x80;
  4917. processBlock (paddingBuffer, paddingLength);
  4918. processBlock (encodedLength, 8);
  4919. MD5Functions::encode (result, state, 16);
  4920. zerostruct (buffer);
  4921. }
  4922. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4923. {
  4924. using namespace MD5Functions;
  4925. uint32 a = state[0];
  4926. uint32 b = state[1];
  4927. uint32 c = state[2];
  4928. uint32 d = state[3];
  4929. uint32 x[16];
  4930. encode (x, bufferToTransform, 64);
  4931. enum Constants
  4932. {
  4933. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4934. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4935. };
  4936. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4937. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4938. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4939. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4940. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4941. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4942. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4943. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4944. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4945. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4946. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4947. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4948. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4949. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4950. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4951. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4952. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4953. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4954. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4955. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4956. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4957. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4958. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4959. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4960. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4961. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4962. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4963. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4964. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4965. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4966. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4967. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4968. state[0] += a;
  4969. state[1] += b;
  4970. state[2] += c;
  4971. state[3] += d;
  4972. zerostruct (x);
  4973. }
  4974. const MemoryBlock MD5::getRawChecksumData() const
  4975. {
  4976. return MemoryBlock (result, sizeof (result));
  4977. }
  4978. const String MD5::toHexString() const
  4979. {
  4980. return String::toHexString (result, sizeof (result), 0);
  4981. }
  4982. bool MD5::operator== (const MD5& other) const
  4983. {
  4984. return memcmp (result, other.result, sizeof (result)) == 0;
  4985. }
  4986. bool MD5::operator!= (const MD5& other) const
  4987. {
  4988. return ! operator== (other);
  4989. }
  4990. END_JUCE_NAMESPACE
  4991. /*** End of inlined file: juce_MD5.cpp ***/
  4992. /*** Start of inlined file: juce_Primes.cpp ***/
  4993. BEGIN_JUCE_NAMESPACE
  4994. namespace PrimesHelpers
  4995. {
  4996. void createSmallSieve (const int numBits, BigInteger& result)
  4997. {
  4998. result.setBit (numBits);
  4999. result.clearBit (numBits); // to enlarge the array
  5000. result.setBit (0);
  5001. int n = 2;
  5002. do
  5003. {
  5004. for (int i = n + n; i < numBits; i += n)
  5005. result.setBit (i);
  5006. n = result.findNextClearBit (n + 1);
  5007. }
  5008. while (n <= (numBits >> 1));
  5009. }
  5010. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5011. const BigInteger& smallSieve, const int smallSieveSize)
  5012. {
  5013. jassert (! base[0]); // must be even!
  5014. result.setBit (numBits);
  5015. result.clearBit (numBits); // to enlarge the array
  5016. int index = smallSieve.findNextClearBit (0);
  5017. do
  5018. {
  5019. const int prime = (index << 1) + 1;
  5020. BigInteger r (base), remainder;
  5021. r.divideBy (prime, remainder);
  5022. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5023. if (r.isZero())
  5024. i += prime;
  5025. if ((i & 1) == 0)
  5026. i += prime;
  5027. i = (i - 1) >> 1;
  5028. while (i < numBits)
  5029. {
  5030. result.setBit (i);
  5031. i += prime;
  5032. }
  5033. index = smallSieve.findNextClearBit (index + 1);
  5034. }
  5035. while (index < smallSieveSize);
  5036. }
  5037. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5038. const int numBits, BigInteger& result, const int certainty)
  5039. {
  5040. for (int i = 0; i < numBits; ++i)
  5041. {
  5042. if (! sieve[i])
  5043. {
  5044. result = base + (unsigned int) ((i << 1) + 1);
  5045. if (Primes::isProbablyPrime (result, certainty))
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. }
  5051. bool passesMillerRabin (const BigInteger& n, int iterations)
  5052. {
  5053. const BigInteger one (1), two (2);
  5054. const BigInteger nMinusOne (n - one);
  5055. BigInteger d (nMinusOne);
  5056. const int s = d.findNextSetBit (0);
  5057. d >>= s;
  5058. BigInteger smallPrimes;
  5059. int numBitsInSmallPrimes = 0;
  5060. for (;;)
  5061. {
  5062. numBitsInSmallPrimes += 256;
  5063. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5064. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5065. if (numPrimesFound > iterations + 1)
  5066. break;
  5067. }
  5068. int smallPrime = 2;
  5069. while (--iterations >= 0)
  5070. {
  5071. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5072. BigInteger r (smallPrime);
  5073. r.exponentModulo (d, n);
  5074. if (r != one && r != nMinusOne)
  5075. {
  5076. for (int j = 0; j < s; ++j)
  5077. {
  5078. r.exponentModulo (two, n);
  5079. if (r == nMinusOne)
  5080. break;
  5081. }
  5082. if (r != nMinusOne)
  5083. return false;
  5084. }
  5085. }
  5086. return true;
  5087. }
  5088. }
  5089. const BigInteger Primes::createProbablePrime (const int bitLength,
  5090. const int certainty,
  5091. const int* randomSeeds,
  5092. int numRandomSeeds)
  5093. {
  5094. using namespace PrimesHelpers;
  5095. int defaultSeeds [16];
  5096. if (numRandomSeeds <= 0)
  5097. {
  5098. randomSeeds = defaultSeeds;
  5099. numRandomSeeds = numElementsInArray (defaultSeeds);
  5100. Random r (0);
  5101. for (int j = 10; --j >= 0;)
  5102. {
  5103. r.setSeedRandomly();
  5104. for (int i = numRandomSeeds; --i >= 0;)
  5105. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5106. }
  5107. }
  5108. BigInteger smallSieve;
  5109. const int smallSieveSize = 15000;
  5110. createSmallSieve (smallSieveSize, smallSieve);
  5111. BigInteger p;
  5112. for (int i = numRandomSeeds; --i >= 0;)
  5113. {
  5114. BigInteger p2;
  5115. Random r (randomSeeds[i]);
  5116. r.fillBitsRandomly (p2, 0, bitLength);
  5117. p ^= p2;
  5118. }
  5119. p.setBit (bitLength - 1);
  5120. p.clearBit (0);
  5121. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5122. while (p.getHighestBit() < bitLength)
  5123. {
  5124. p += 2 * searchLen;
  5125. BigInteger sieve;
  5126. bigSieve (p, searchLen, sieve,
  5127. smallSieve, smallSieveSize);
  5128. BigInteger candidate;
  5129. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5130. return candidate;
  5131. }
  5132. jassertfalse;
  5133. return BigInteger();
  5134. }
  5135. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5136. {
  5137. using namespace PrimesHelpers;
  5138. if (! number[0])
  5139. return false;
  5140. if (number.getHighestBit() <= 10)
  5141. {
  5142. const int num = number.getBitRangeAsInt (0, 10);
  5143. for (int i = num / 2; --i > 1;)
  5144. if (num % i == 0)
  5145. return false;
  5146. return true;
  5147. }
  5148. else
  5149. {
  5150. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5151. return false;
  5152. return passesMillerRabin (number, certainty);
  5153. }
  5154. }
  5155. END_JUCE_NAMESPACE
  5156. /*** End of inlined file: juce_Primes.cpp ***/
  5157. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5158. BEGIN_JUCE_NAMESPACE
  5159. RSAKey::RSAKey()
  5160. {
  5161. }
  5162. RSAKey::RSAKey (const String& s)
  5163. {
  5164. if (s.containsChar (','))
  5165. {
  5166. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5167. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5168. }
  5169. else
  5170. {
  5171. // the string needs to be two hex numbers, comma-separated..
  5172. jassertfalse;
  5173. }
  5174. }
  5175. RSAKey::~RSAKey()
  5176. {
  5177. }
  5178. bool RSAKey::operator== (const RSAKey& other) const throw()
  5179. {
  5180. return part1 == other.part1 && part2 == other.part2;
  5181. }
  5182. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5183. {
  5184. return ! operator== (other);
  5185. }
  5186. const String RSAKey::toString() const
  5187. {
  5188. return part1.toString (16) + "," + part2.toString (16);
  5189. }
  5190. bool RSAKey::applyToValue (BigInteger& value) const
  5191. {
  5192. if (part1.isZero() || part2.isZero() || value <= 0)
  5193. {
  5194. jassertfalse; // using an uninitialised key
  5195. value.clear();
  5196. return false;
  5197. }
  5198. BigInteger result;
  5199. while (! value.isZero())
  5200. {
  5201. result *= part2;
  5202. BigInteger remainder;
  5203. value.divideBy (part2, remainder);
  5204. remainder.exponentModulo (part1, part2);
  5205. result += remainder;
  5206. }
  5207. value.swapWith (result);
  5208. return true;
  5209. }
  5210. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5211. {
  5212. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5213. // are fast to divide + multiply
  5214. for (int i = 2; i <= 65536; i *= 2)
  5215. {
  5216. const BigInteger e (1 + i);
  5217. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5218. return e;
  5219. }
  5220. BigInteger e (4);
  5221. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5222. ++e;
  5223. return e;
  5224. }
  5225. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5226. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5227. {
  5228. jassert (numBits > 16); // not much point using less than this..
  5229. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5230. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5231. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5232. const BigInteger n (p * q);
  5233. const BigInteger m (--p * --q);
  5234. const BigInteger e (findBestCommonDivisor (p, q));
  5235. BigInteger d (e);
  5236. d.inverseModulo (m);
  5237. publicKey.part1 = e;
  5238. publicKey.part2 = n;
  5239. privateKey.part1 = d;
  5240. privateKey.part2 = n;
  5241. }
  5242. END_JUCE_NAMESPACE
  5243. /*** End of inlined file: juce_RSAKey.cpp ***/
  5244. /*** Start of inlined file: juce_InputStream.cpp ***/
  5245. BEGIN_JUCE_NAMESPACE
  5246. char InputStream::readByte()
  5247. {
  5248. char temp = 0;
  5249. read (&temp, 1);
  5250. return temp;
  5251. }
  5252. bool InputStream::readBool()
  5253. {
  5254. return readByte() != 0;
  5255. }
  5256. short InputStream::readShort()
  5257. {
  5258. char temp[2];
  5259. if (read (temp, 2) == 2)
  5260. return (short) ByteOrder::littleEndianShort (temp);
  5261. return 0;
  5262. }
  5263. short InputStream::readShortBigEndian()
  5264. {
  5265. char temp[2];
  5266. if (read (temp, 2) == 2)
  5267. return (short) ByteOrder::bigEndianShort (temp);
  5268. return 0;
  5269. }
  5270. int InputStream::readInt()
  5271. {
  5272. char temp[4];
  5273. if (read (temp, 4) == 4)
  5274. return (int) ByteOrder::littleEndianInt (temp);
  5275. return 0;
  5276. }
  5277. int InputStream::readIntBigEndian()
  5278. {
  5279. char temp[4];
  5280. if (read (temp, 4) == 4)
  5281. return (int) ByteOrder::bigEndianInt (temp);
  5282. return 0;
  5283. }
  5284. int InputStream::readCompressedInt()
  5285. {
  5286. const unsigned char sizeByte = readByte();
  5287. if (sizeByte == 0)
  5288. return 0;
  5289. const int numBytes = (sizeByte & 0x7f);
  5290. if (numBytes > 4)
  5291. {
  5292. jassertfalse; // trying to read corrupt data - this method must only be used
  5293. // to read data that was written by OutputStream::writeCompressedInt()
  5294. return 0;
  5295. }
  5296. char bytes[4] = { 0, 0, 0, 0 };
  5297. if (read (bytes, numBytes) != numBytes)
  5298. return 0;
  5299. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5300. return (sizeByte >> 7) ? -num : num;
  5301. }
  5302. int64 InputStream::readInt64()
  5303. {
  5304. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5305. if (read (n.asBytes, 8) == 8)
  5306. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5307. return 0;
  5308. }
  5309. int64 InputStream::readInt64BigEndian()
  5310. {
  5311. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5312. if (read (n.asBytes, 8) == 8)
  5313. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5314. return 0;
  5315. }
  5316. float InputStream::readFloat()
  5317. {
  5318. // the union below relies on these types being the same size...
  5319. static_jassert (sizeof (int32) == sizeof (float));
  5320. union { int32 asInt; float asFloat; } n;
  5321. n.asInt = (int32) readInt();
  5322. return n.asFloat;
  5323. }
  5324. float InputStream::readFloatBigEndian()
  5325. {
  5326. union { int32 asInt; float asFloat; } n;
  5327. n.asInt = (int32) readIntBigEndian();
  5328. return n.asFloat;
  5329. }
  5330. double InputStream::readDouble()
  5331. {
  5332. union { int64 asInt; double asDouble; } n;
  5333. n.asInt = readInt64();
  5334. return n.asDouble;
  5335. }
  5336. double InputStream::readDoubleBigEndian()
  5337. {
  5338. union { int64 asInt; double asDouble; } n;
  5339. n.asInt = readInt64BigEndian();
  5340. return n.asDouble;
  5341. }
  5342. const String InputStream::readString()
  5343. {
  5344. MemoryBlock buffer (256);
  5345. char* data = static_cast<char*> (buffer.getData());
  5346. size_t i = 0;
  5347. while ((data[i] = readByte()) != 0)
  5348. {
  5349. if (++i >= buffer.getSize())
  5350. {
  5351. buffer.setSize (buffer.getSize() + 512);
  5352. data = static_cast<char*> (buffer.getData());
  5353. }
  5354. }
  5355. return String::fromUTF8 (data, (int) i);
  5356. }
  5357. const String InputStream::readNextLine()
  5358. {
  5359. MemoryBlock buffer (256);
  5360. char* data = static_cast<char*> (buffer.getData());
  5361. size_t i = 0;
  5362. while ((data[i] = readByte()) != 0)
  5363. {
  5364. if (data[i] == '\n')
  5365. break;
  5366. if (data[i] == '\r')
  5367. {
  5368. const int64 lastPos = getPosition();
  5369. if (readByte() != '\n')
  5370. setPosition (lastPos);
  5371. break;
  5372. }
  5373. if (++i >= buffer.getSize())
  5374. {
  5375. buffer.setSize (buffer.getSize() + 512);
  5376. data = static_cast<char*> (buffer.getData());
  5377. }
  5378. }
  5379. return String::fromUTF8 (data, (int) i);
  5380. }
  5381. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5382. {
  5383. MemoryOutputStream mo (block, true);
  5384. return mo.writeFromInputStream (*this, numBytes);
  5385. }
  5386. const String InputStream::readEntireStreamAsString()
  5387. {
  5388. MemoryOutputStream mo;
  5389. mo.writeFromInputStream (*this, -1);
  5390. return mo.toString();
  5391. }
  5392. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5393. {
  5394. if (numBytesToSkip > 0)
  5395. {
  5396. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5397. HeapBlock<char> temp (skipBufferSize);
  5398. while (numBytesToSkip > 0 && ! isExhausted())
  5399. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5400. }
  5401. }
  5402. END_JUCE_NAMESPACE
  5403. /*** End of inlined file: juce_InputStream.cpp ***/
  5404. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5405. BEGIN_JUCE_NAMESPACE
  5406. #if JUCE_DEBUG
  5407. static Array<void*, CriticalSection> activeStreams;
  5408. void juce_CheckForDanglingStreams()
  5409. {
  5410. /*
  5411. It's always a bad idea to leak any object, but if you're leaking output
  5412. streams, then there's a good chance that you're failing to flush a file
  5413. to disk properly, which could result in corrupted data and other similar
  5414. nastiness..
  5415. */
  5416. jassert (activeStreams.size() == 0);
  5417. };
  5418. #endif
  5419. OutputStream::OutputStream()
  5420. {
  5421. #if JUCE_DEBUG
  5422. activeStreams.add (this);
  5423. #endif
  5424. }
  5425. OutputStream::~OutputStream()
  5426. {
  5427. #if JUCE_DEBUG
  5428. activeStreams.removeValue (this);
  5429. #endif
  5430. }
  5431. void OutputStream::writeBool (const bool b)
  5432. {
  5433. writeByte (b ? (char) 1
  5434. : (char) 0);
  5435. }
  5436. void OutputStream::writeByte (char byte)
  5437. {
  5438. write (&byte, 1);
  5439. }
  5440. void OutputStream::writeShort (short value)
  5441. {
  5442. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5443. write (&v, 2);
  5444. }
  5445. void OutputStream::writeShortBigEndian (short value)
  5446. {
  5447. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5448. write (&v, 2);
  5449. }
  5450. void OutputStream::writeInt (int value)
  5451. {
  5452. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5453. write (&v, 4);
  5454. }
  5455. void OutputStream::writeIntBigEndian (int value)
  5456. {
  5457. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5458. write (&v, 4);
  5459. }
  5460. void OutputStream::writeCompressedInt (int value)
  5461. {
  5462. unsigned int un = (value < 0) ? (unsigned int) -value
  5463. : (unsigned int) value;
  5464. uint8 data[5];
  5465. int num = 0;
  5466. while (un > 0)
  5467. {
  5468. data[++num] = (uint8) un;
  5469. un >>= 8;
  5470. }
  5471. data[0] = (uint8) num;
  5472. if (value < 0)
  5473. data[0] |= 0x80;
  5474. write (data, num + 1);
  5475. }
  5476. void OutputStream::writeInt64 (int64 value)
  5477. {
  5478. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5479. write (&v, 8);
  5480. }
  5481. void OutputStream::writeInt64BigEndian (int64 value)
  5482. {
  5483. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5484. write (&v, 8);
  5485. }
  5486. void OutputStream::writeFloat (float value)
  5487. {
  5488. union { int asInt; float asFloat; } n;
  5489. n.asFloat = value;
  5490. writeInt (n.asInt);
  5491. }
  5492. void OutputStream::writeFloatBigEndian (float value)
  5493. {
  5494. union { int asInt; float asFloat; } n;
  5495. n.asFloat = value;
  5496. writeIntBigEndian (n.asInt);
  5497. }
  5498. void OutputStream::writeDouble (double value)
  5499. {
  5500. union { int64 asInt; double asDouble; } n;
  5501. n.asDouble = value;
  5502. writeInt64 (n.asInt);
  5503. }
  5504. void OutputStream::writeDoubleBigEndian (double value)
  5505. {
  5506. union { int64 asInt; double asDouble; } n;
  5507. n.asDouble = value;
  5508. writeInt64BigEndian (n.asInt);
  5509. }
  5510. void OutputStream::writeString (const String& text)
  5511. {
  5512. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5513. // if lots of large, persistent strings were to be written to streams).
  5514. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5515. HeapBlock<char> temp (numBytes);
  5516. text.copyToUTF8 (temp, numBytes);
  5517. write (temp, numBytes);
  5518. }
  5519. void OutputStream::writeText (const String& text, const bool asUnicode,
  5520. const bool writeUnicodeHeaderBytes)
  5521. {
  5522. if (asUnicode)
  5523. {
  5524. if (writeUnicodeHeaderBytes)
  5525. write ("\x0ff\x0fe", 2);
  5526. const juce_wchar* src = text;
  5527. bool lastCharWasReturn = false;
  5528. while (*src != 0)
  5529. {
  5530. if (*src == L'\n' && ! lastCharWasReturn)
  5531. writeShort ((short) L'\r');
  5532. lastCharWasReturn = (*src == L'\r');
  5533. writeShort ((short) *src++);
  5534. }
  5535. }
  5536. else
  5537. {
  5538. const char* src = text.toUTF8();
  5539. const char* t = src;
  5540. for (;;)
  5541. {
  5542. if (*t == '\n')
  5543. {
  5544. if (t > src)
  5545. write (src, (int) (t - src));
  5546. write ("\r\n", 2);
  5547. src = t + 1;
  5548. }
  5549. else if (*t == '\r')
  5550. {
  5551. if (t[1] == '\n')
  5552. ++t;
  5553. }
  5554. else if (*t == 0)
  5555. {
  5556. if (t > src)
  5557. write (src, (int) (t - src));
  5558. break;
  5559. }
  5560. ++t;
  5561. }
  5562. }
  5563. }
  5564. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5565. {
  5566. if (numBytesToWrite < 0)
  5567. numBytesToWrite = std::numeric_limits<int64>::max();
  5568. int numWritten = 0;
  5569. while (numBytesToWrite > 0 && ! source.isExhausted())
  5570. {
  5571. char buffer [8192];
  5572. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5573. if (num <= 0)
  5574. break;
  5575. write (buffer, num);
  5576. numBytesToWrite -= num;
  5577. numWritten += num;
  5578. }
  5579. return numWritten;
  5580. }
  5581. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5582. {
  5583. return stream << String (number);
  5584. }
  5585. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5586. {
  5587. return stream << String (number);
  5588. }
  5589. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5590. {
  5591. stream.writeByte (character);
  5592. return stream;
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5595. {
  5596. stream.write (text, (int) strlen (text));
  5597. return stream;
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5600. {
  5601. stream.write (data.getData(), (int) data.getSize());
  5602. return stream;
  5603. }
  5604. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5605. {
  5606. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5607. if (in != 0)
  5608. stream.writeFromInputStream (*in, -1);
  5609. return stream;
  5610. }
  5611. END_JUCE_NAMESPACE
  5612. /*** End of inlined file: juce_OutputStream.cpp ***/
  5613. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5614. BEGIN_JUCE_NAMESPACE
  5615. DirectoryIterator::DirectoryIterator (const File& directory,
  5616. bool isRecursive_,
  5617. const String& wildCard_,
  5618. const int whatToLookFor_)
  5619. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5620. wildCard (wildCard_),
  5621. path (File::addTrailingSeparator (directory.getFullPathName())),
  5622. index (-1),
  5623. totalNumFiles (-1),
  5624. whatToLookFor (whatToLookFor_),
  5625. isRecursive (isRecursive_),
  5626. hasBeenAdvanced (false)
  5627. {
  5628. // you have to specify the type of files you're looking for!
  5629. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5630. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5631. }
  5632. DirectoryIterator::~DirectoryIterator()
  5633. {
  5634. }
  5635. bool DirectoryIterator::next()
  5636. {
  5637. return next (0, 0, 0, 0, 0, 0);
  5638. }
  5639. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5640. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5641. {
  5642. hasBeenAdvanced = true;
  5643. if (subIterator != 0)
  5644. {
  5645. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5646. return true;
  5647. subIterator = 0;
  5648. }
  5649. String filename;
  5650. bool isDirectory, isHidden;
  5651. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5652. {
  5653. ++index;
  5654. if (! filename.containsOnly ("."))
  5655. {
  5656. const File fileFound (path + filename, 0);
  5657. bool matches = false;
  5658. if (isDirectory)
  5659. {
  5660. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5661. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5662. matches = (whatToLookFor & File::findDirectories) != 0;
  5663. }
  5664. else
  5665. {
  5666. matches = (whatToLookFor & File::findFiles) != 0;
  5667. }
  5668. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5669. if (matches && isRecursive)
  5670. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5671. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5672. matches = ! isHidden;
  5673. if (matches)
  5674. {
  5675. currentFile = fileFound;
  5676. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5677. if (isDirResult != 0) *isDirResult = isDirectory;
  5678. return true;
  5679. }
  5680. else if (subIterator != 0)
  5681. {
  5682. return next();
  5683. }
  5684. }
  5685. }
  5686. return false;
  5687. }
  5688. const File DirectoryIterator::getFile() const
  5689. {
  5690. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5691. return subIterator->getFile();
  5692. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5693. jassert (hasBeenAdvanced);
  5694. return currentFile;
  5695. }
  5696. float DirectoryIterator::getEstimatedProgress() const
  5697. {
  5698. if (totalNumFiles < 0)
  5699. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5700. if (totalNumFiles <= 0)
  5701. return 0.0f;
  5702. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5703. : (float) index;
  5704. return detailedIndex / totalNumFiles;
  5705. }
  5706. END_JUCE_NAMESPACE
  5707. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5708. /*** Start of inlined file: juce_File.cpp ***/
  5709. #if ! JUCE_WINDOWS
  5710. #include <pwd.h>
  5711. #endif
  5712. BEGIN_JUCE_NAMESPACE
  5713. File::File (const String& fullPathName)
  5714. : fullPath (parseAbsolutePath (fullPathName))
  5715. {
  5716. }
  5717. File::File (const String& path, int)
  5718. : fullPath (path)
  5719. {
  5720. }
  5721. const File File::createFileWithoutCheckingPath (const String& path)
  5722. {
  5723. return File (path, 0);
  5724. }
  5725. File::File (const File& other)
  5726. : fullPath (other.fullPath)
  5727. {
  5728. }
  5729. File& File::operator= (const String& newPath)
  5730. {
  5731. fullPath = parseAbsolutePath (newPath);
  5732. return *this;
  5733. }
  5734. File& File::operator= (const File& other)
  5735. {
  5736. fullPath = other.fullPath;
  5737. return *this;
  5738. }
  5739. const File File::nonexistent;
  5740. const String File::parseAbsolutePath (const String& p)
  5741. {
  5742. if (p.isEmpty())
  5743. return String::empty;
  5744. #if JUCE_WINDOWS
  5745. // Windows..
  5746. String path (p.replaceCharacter ('/', '\\'));
  5747. if (path.startsWithChar (File::separator))
  5748. {
  5749. if (path[1] != File::separator)
  5750. {
  5751. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5752. If you're trying to parse a string that may be either a relative path or an absolute path,
  5753. you MUST provide a context against which the partial path can be evaluated - you can do
  5754. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5755. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5756. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5757. */
  5758. jassertfalse;
  5759. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5760. }
  5761. }
  5762. else if (! path.containsChar (':'))
  5763. {
  5764. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5765. If you're trying to parse a string that may be either a relative path or an absolute path,
  5766. you MUST provide a context against which the partial path can be evaluated - you can do
  5767. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5768. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5769. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5770. */
  5771. jassertfalse;
  5772. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5773. }
  5774. #else
  5775. // Mac or Linux..
  5776. String path (p.replaceCharacter ('\\', '/'));
  5777. if (path.startsWithChar ('~'))
  5778. {
  5779. if (path[1] == File::separator || path[1] == 0)
  5780. {
  5781. // expand a name of the form "~/abc"
  5782. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5783. + path.substring (1);
  5784. }
  5785. else
  5786. {
  5787. // expand a name of type "~dave/abc"
  5788. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5789. struct passwd* const pw = getpwnam (userName.toUTF8());
  5790. if (pw != 0)
  5791. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5792. }
  5793. }
  5794. else if (! path.startsWithChar (File::separator))
  5795. {
  5796. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5797. If you're trying to parse a string that may be either a relative path or an absolute path,
  5798. you MUST provide a context against which the partial path can be evaluated - you can do
  5799. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5800. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5801. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5802. */
  5803. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5804. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5805. }
  5806. #endif
  5807. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5808. path = path.dropLastCharacters (1);
  5809. return path;
  5810. }
  5811. const String File::addTrailingSeparator (const String& path)
  5812. {
  5813. return path.endsWithChar (File::separator) ? path
  5814. : path + File::separator;
  5815. }
  5816. #if JUCE_LINUX
  5817. #define NAMES_ARE_CASE_SENSITIVE 1
  5818. #endif
  5819. bool File::areFileNamesCaseSensitive()
  5820. {
  5821. #if NAMES_ARE_CASE_SENSITIVE
  5822. return true;
  5823. #else
  5824. return false;
  5825. #endif
  5826. }
  5827. bool File::operator== (const File& other) const
  5828. {
  5829. #if NAMES_ARE_CASE_SENSITIVE
  5830. return fullPath == other.fullPath;
  5831. #else
  5832. return fullPath.equalsIgnoreCase (other.fullPath);
  5833. #endif
  5834. }
  5835. bool File::operator!= (const File& other) const
  5836. {
  5837. return ! operator== (other);
  5838. }
  5839. bool File::operator< (const File& other) const
  5840. {
  5841. #if NAMES_ARE_CASE_SENSITIVE
  5842. return fullPath < other.fullPath;
  5843. #else
  5844. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5845. #endif
  5846. }
  5847. bool File::operator> (const File& other) const
  5848. {
  5849. #if NAMES_ARE_CASE_SENSITIVE
  5850. return fullPath > other.fullPath;
  5851. #else
  5852. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5853. #endif
  5854. }
  5855. bool File::setReadOnly (const bool shouldBeReadOnly,
  5856. const bool applyRecursively) const
  5857. {
  5858. bool worked = true;
  5859. if (applyRecursively && isDirectory())
  5860. {
  5861. Array <File> subFiles;
  5862. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5863. for (int i = subFiles.size(); --i >= 0;)
  5864. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5865. }
  5866. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5867. }
  5868. bool File::deleteRecursively() const
  5869. {
  5870. bool worked = true;
  5871. if (isDirectory())
  5872. {
  5873. Array<File> subFiles;
  5874. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5875. for (int i = subFiles.size(); --i >= 0;)
  5876. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5877. }
  5878. return deleteFile() && worked;
  5879. }
  5880. bool File::moveFileTo (const File& newFile) const
  5881. {
  5882. if (newFile.fullPath == fullPath)
  5883. return true;
  5884. #if ! NAMES_ARE_CASE_SENSITIVE
  5885. if (*this != newFile)
  5886. #endif
  5887. if (! newFile.deleteFile())
  5888. return false;
  5889. return moveInternal (newFile);
  5890. }
  5891. bool File::copyFileTo (const File& newFile) const
  5892. {
  5893. return (*this == newFile)
  5894. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5895. }
  5896. bool File::copyDirectoryTo (const File& newDirectory) const
  5897. {
  5898. if (isDirectory() && newDirectory.createDirectory())
  5899. {
  5900. Array<File> subFiles;
  5901. findChildFiles (subFiles, File::findFiles, false);
  5902. int i;
  5903. for (i = 0; i < subFiles.size(); ++i)
  5904. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5905. return false;
  5906. subFiles.clear();
  5907. findChildFiles (subFiles, File::findDirectories, false);
  5908. for (i = 0; i < subFiles.size(); ++i)
  5909. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5910. return false;
  5911. return true;
  5912. }
  5913. return false;
  5914. }
  5915. const String File::getPathUpToLastSlash() const
  5916. {
  5917. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5918. if (lastSlash > 0)
  5919. return fullPath.substring (0, lastSlash);
  5920. else if (lastSlash == 0)
  5921. return separatorString;
  5922. else
  5923. return fullPath;
  5924. }
  5925. const File File::getParentDirectory() const
  5926. {
  5927. return File (getPathUpToLastSlash(), (int) 0);
  5928. }
  5929. const String File::getFileName() const
  5930. {
  5931. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5932. }
  5933. int File::hashCode() const
  5934. {
  5935. return fullPath.hashCode();
  5936. }
  5937. int64 File::hashCode64() const
  5938. {
  5939. return fullPath.hashCode64();
  5940. }
  5941. const String File::getFileNameWithoutExtension() const
  5942. {
  5943. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5944. const int lastDot = fullPath.lastIndexOfChar ('.');
  5945. if (lastDot > lastSlash)
  5946. return fullPath.substring (lastSlash, lastDot);
  5947. else
  5948. return fullPath.substring (lastSlash);
  5949. }
  5950. bool File::isAChildOf (const File& potentialParent) const
  5951. {
  5952. if (potentialParent == File::nonexistent)
  5953. return false;
  5954. const String ourPath (getPathUpToLastSlash());
  5955. #if NAMES_ARE_CASE_SENSITIVE
  5956. if (potentialParent.fullPath == ourPath)
  5957. #else
  5958. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5959. #endif
  5960. {
  5961. return true;
  5962. }
  5963. else if (potentialParent.fullPath.length() >= ourPath.length())
  5964. {
  5965. return false;
  5966. }
  5967. else
  5968. {
  5969. return getParentDirectory().isAChildOf (potentialParent);
  5970. }
  5971. }
  5972. bool File::isAbsolutePath (const String& path)
  5973. {
  5974. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5975. #if JUCE_WINDOWS
  5976. || (path.isNotEmpty() && path[1] == ':');
  5977. #else
  5978. || path.startsWithChar ('~');
  5979. #endif
  5980. }
  5981. const File File::getChildFile (String relativePath) const
  5982. {
  5983. if (isAbsolutePath (relativePath))
  5984. {
  5985. // the path is really absolute..
  5986. return File (relativePath);
  5987. }
  5988. else
  5989. {
  5990. // it's relative, so remove any ../ or ./ bits at the start.
  5991. String path (fullPath);
  5992. if (relativePath[0] == '.')
  5993. {
  5994. #if JUCE_WINDOWS
  5995. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5996. #else
  5997. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5998. #endif
  5999. while (relativePath[0] == '.')
  6000. {
  6001. if (relativePath[1] == '.')
  6002. {
  6003. if (relativePath [2] == 0 || relativePath[2] == separator)
  6004. {
  6005. const int lastSlash = path.lastIndexOfChar (separator);
  6006. if (lastSlash >= 0)
  6007. path = path.substring (0, lastSlash);
  6008. relativePath = relativePath.substring (3);
  6009. }
  6010. else
  6011. {
  6012. break;
  6013. }
  6014. }
  6015. else if (relativePath[1] == separator)
  6016. {
  6017. relativePath = relativePath.substring (2);
  6018. }
  6019. else
  6020. {
  6021. break;
  6022. }
  6023. }
  6024. }
  6025. return File (addTrailingSeparator (path) + relativePath);
  6026. }
  6027. }
  6028. const File File::getSiblingFile (const String& fileName) const
  6029. {
  6030. return getParentDirectory().getChildFile (fileName);
  6031. }
  6032. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6033. {
  6034. if (bytes == 1)
  6035. {
  6036. return "1 byte";
  6037. }
  6038. else if (bytes < 1024)
  6039. {
  6040. return String ((int) bytes) + " bytes";
  6041. }
  6042. else if (bytes < 1024 * 1024)
  6043. {
  6044. return String (bytes / 1024.0, 1) + " KB";
  6045. }
  6046. else if (bytes < 1024 * 1024 * 1024)
  6047. {
  6048. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6049. }
  6050. else
  6051. {
  6052. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6053. }
  6054. }
  6055. bool File::create() const
  6056. {
  6057. if (exists())
  6058. return true;
  6059. {
  6060. const File parentDir (getParentDirectory());
  6061. if (parentDir == *this || ! parentDir.createDirectory())
  6062. return false;
  6063. FileOutputStream fo (*this, 8);
  6064. }
  6065. return exists();
  6066. }
  6067. bool File::createDirectory() const
  6068. {
  6069. if (! isDirectory())
  6070. {
  6071. const File parentDir (getParentDirectory());
  6072. if (parentDir == *this || ! parentDir.createDirectory())
  6073. return false;
  6074. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6075. return isDirectory();
  6076. }
  6077. return true;
  6078. }
  6079. const Time File::getCreationTime() const
  6080. {
  6081. int64 m, a, c;
  6082. getFileTimesInternal (m, a, c);
  6083. return Time (c);
  6084. }
  6085. const Time File::getLastModificationTime() const
  6086. {
  6087. int64 m, a, c;
  6088. getFileTimesInternal (m, a, c);
  6089. return Time (m);
  6090. }
  6091. const Time File::getLastAccessTime() const
  6092. {
  6093. int64 m, a, c;
  6094. getFileTimesInternal (m, a, c);
  6095. return Time (a);
  6096. }
  6097. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6098. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6099. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6100. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6101. {
  6102. if (! existsAsFile())
  6103. return false;
  6104. FileInputStream in (*this);
  6105. return getSize() == in.readIntoMemoryBlock (destBlock);
  6106. }
  6107. const String File::loadFileAsString() const
  6108. {
  6109. if (! existsAsFile())
  6110. return String::empty;
  6111. FileInputStream in (*this);
  6112. return in.readEntireStreamAsString();
  6113. }
  6114. int File::findChildFiles (Array<File>& results,
  6115. const int whatToLookFor,
  6116. const bool searchRecursively,
  6117. const String& wildCardPattern) const
  6118. {
  6119. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6120. int total = 0;
  6121. while (di.next())
  6122. {
  6123. results.add (di.getFile());
  6124. ++total;
  6125. }
  6126. return total;
  6127. }
  6128. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6129. {
  6130. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6131. int total = 0;
  6132. while (di.next())
  6133. ++total;
  6134. return total;
  6135. }
  6136. bool File::containsSubDirectories() const
  6137. {
  6138. if (isDirectory())
  6139. {
  6140. DirectoryIterator di (*this, false, "*", findDirectories);
  6141. return di.next();
  6142. }
  6143. return false;
  6144. }
  6145. const File File::getNonexistentChildFile (const String& prefix_,
  6146. const String& suffix,
  6147. bool putNumbersInBrackets) const
  6148. {
  6149. File f (getChildFile (prefix_ + suffix));
  6150. if (f.exists())
  6151. {
  6152. int num = 2;
  6153. String prefix (prefix_);
  6154. // remove any bracketed numbers that may already be on the end..
  6155. if (prefix.trim().endsWithChar (')'))
  6156. {
  6157. putNumbersInBrackets = true;
  6158. const int openBracks = prefix.lastIndexOfChar ('(');
  6159. const int closeBracks = prefix.lastIndexOfChar (')');
  6160. if (openBracks > 0
  6161. && closeBracks > openBracks
  6162. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6163. {
  6164. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6165. prefix = prefix.substring (0, openBracks);
  6166. }
  6167. }
  6168. // also use brackets if it ends in a digit.
  6169. putNumbersInBrackets = putNumbersInBrackets
  6170. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6171. do
  6172. {
  6173. if (putNumbersInBrackets)
  6174. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6175. else
  6176. f = getChildFile (prefix + String (num++) + suffix);
  6177. } while (f.exists());
  6178. }
  6179. return f;
  6180. }
  6181. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6182. {
  6183. if (exists())
  6184. {
  6185. return getParentDirectory()
  6186. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6187. getFileExtension(),
  6188. putNumbersInBrackets);
  6189. }
  6190. else
  6191. {
  6192. return *this;
  6193. }
  6194. }
  6195. const String File::getFileExtension() const
  6196. {
  6197. String ext;
  6198. if (! isDirectory())
  6199. {
  6200. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6201. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6202. ext = fullPath.substring (indexOfDot);
  6203. }
  6204. return ext;
  6205. }
  6206. bool File::hasFileExtension (const String& possibleSuffix) const
  6207. {
  6208. if (possibleSuffix.isEmpty())
  6209. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6210. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6211. if (semicolon >= 0)
  6212. {
  6213. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6214. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6215. }
  6216. else
  6217. {
  6218. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6219. {
  6220. if (possibleSuffix.startsWithChar ('.'))
  6221. return true;
  6222. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6223. if (dotPos >= 0)
  6224. return fullPath [dotPos] == '.';
  6225. }
  6226. }
  6227. return false;
  6228. }
  6229. const File File::withFileExtension (const String& newExtension) const
  6230. {
  6231. if (fullPath.isEmpty())
  6232. return File::nonexistent;
  6233. String filePart (getFileName());
  6234. int i = filePart.lastIndexOfChar ('.');
  6235. if (i >= 0)
  6236. filePart = filePart.substring (0, i);
  6237. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6238. filePart << '.';
  6239. return getSiblingFile (filePart + newExtension);
  6240. }
  6241. bool File::startAsProcess (const String& parameters) const
  6242. {
  6243. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6244. }
  6245. FileInputStream* File::createInputStream() const
  6246. {
  6247. if (existsAsFile())
  6248. return new FileInputStream (*this);
  6249. return 0;
  6250. }
  6251. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6252. {
  6253. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6254. if (out->failedToOpen())
  6255. return 0;
  6256. return out.release();
  6257. }
  6258. bool File::appendData (const void* const dataToAppend,
  6259. const int numberOfBytes) const
  6260. {
  6261. if (numberOfBytes > 0)
  6262. {
  6263. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6264. if (out == 0)
  6265. return false;
  6266. out->write (dataToAppend, numberOfBytes);
  6267. }
  6268. return true;
  6269. }
  6270. bool File::replaceWithData (const void* const dataToWrite,
  6271. const int numberOfBytes) const
  6272. {
  6273. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6274. if (numberOfBytes <= 0)
  6275. return deleteFile();
  6276. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6277. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6278. return tempFile.overwriteTargetFileWithTemporary();
  6279. }
  6280. bool File::appendText (const String& text,
  6281. const bool asUnicode,
  6282. const bool writeUnicodeHeaderBytes) const
  6283. {
  6284. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6285. if (out != 0)
  6286. {
  6287. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6288. return true;
  6289. }
  6290. return false;
  6291. }
  6292. bool File::replaceWithText (const String& textToWrite,
  6293. const bool asUnicode,
  6294. const bool writeUnicodeHeaderBytes) const
  6295. {
  6296. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6297. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6298. return tempFile.overwriteTargetFileWithTemporary();
  6299. }
  6300. bool File::hasIdenticalContentTo (const File& other) const
  6301. {
  6302. if (other == *this)
  6303. return true;
  6304. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6305. {
  6306. FileInputStream in1 (*this), in2 (other);
  6307. const int bufferSize = 4096;
  6308. HeapBlock <char> buffer1, buffer2;
  6309. buffer1.malloc (bufferSize);
  6310. buffer2.malloc (bufferSize);
  6311. for (;;)
  6312. {
  6313. const int num1 = in1.read (buffer1, bufferSize);
  6314. const int num2 = in2.read (buffer2, bufferSize);
  6315. if (num1 != num2)
  6316. break;
  6317. if (num1 <= 0)
  6318. return true;
  6319. if (memcmp (buffer1, buffer2, num1) != 0)
  6320. break;
  6321. }
  6322. }
  6323. return false;
  6324. }
  6325. const String File::createLegalPathName (const String& original)
  6326. {
  6327. String s (original);
  6328. String start;
  6329. if (s[1] == ':')
  6330. {
  6331. start = s.substring (0, 2);
  6332. s = s.substring (2);
  6333. }
  6334. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6335. .substring (0, 1024);
  6336. }
  6337. const String File::createLegalFileName (const String& original)
  6338. {
  6339. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6340. const int maxLength = 128; // only the length of the filename, not the whole path
  6341. const int len = s.length();
  6342. if (len > maxLength)
  6343. {
  6344. const int lastDot = s.lastIndexOfChar ('.');
  6345. if (lastDot > jmax (0, len - 12))
  6346. {
  6347. s = s.substring (0, maxLength - (len - lastDot))
  6348. + s.substring (lastDot);
  6349. }
  6350. else
  6351. {
  6352. s = s.substring (0, maxLength);
  6353. }
  6354. }
  6355. return s;
  6356. }
  6357. const String File::getRelativePathFrom (const File& dir) const
  6358. {
  6359. String thisPath (fullPath);
  6360. {
  6361. int len = thisPath.length();
  6362. while (--len >= 0 && thisPath [len] == File::separator)
  6363. thisPath [len] = 0;
  6364. }
  6365. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6366. : dir.fullPath));
  6367. const int len = jmin (thisPath.length(), dirPath.length());
  6368. int commonBitLength = 0;
  6369. for (int i = 0; i < len; ++i)
  6370. {
  6371. #if NAMES_ARE_CASE_SENSITIVE
  6372. if (thisPath[i] != dirPath[i])
  6373. #else
  6374. if (CharacterFunctions::toLowerCase (thisPath[i])
  6375. != CharacterFunctions::toLowerCase (dirPath[i]))
  6376. #endif
  6377. {
  6378. break;
  6379. }
  6380. ++commonBitLength;
  6381. }
  6382. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6383. --commonBitLength;
  6384. // if the only common bit is the root, then just return the full path..
  6385. if (commonBitLength <= 0
  6386. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6387. return fullPath;
  6388. thisPath = thisPath.substring (commonBitLength);
  6389. dirPath = dirPath.substring (commonBitLength);
  6390. while (dirPath.isNotEmpty())
  6391. {
  6392. #if JUCE_WINDOWS
  6393. thisPath = "..\\" + thisPath;
  6394. #else
  6395. thisPath = "../" + thisPath;
  6396. #endif
  6397. const int sep = dirPath.indexOfChar (separator);
  6398. if (sep >= 0)
  6399. dirPath = dirPath.substring (sep + 1);
  6400. else
  6401. dirPath = String::empty;
  6402. }
  6403. return thisPath;
  6404. }
  6405. const File File::createTempFile (const String& fileNameEnding)
  6406. {
  6407. const File tempFile (getSpecialLocation (tempDirectory)
  6408. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6409. .withFileExtension (fileNameEnding));
  6410. if (tempFile.exists())
  6411. return createTempFile (fileNameEnding);
  6412. else
  6413. return tempFile;
  6414. }
  6415. #if JUCE_UNIT_TESTS
  6416. class FileTests : public UnitTest
  6417. {
  6418. public:
  6419. FileTests() : UnitTest ("Files") {}
  6420. void runTest()
  6421. {
  6422. beginTest ("Reading");
  6423. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6424. const File temp (File::getSpecialLocation (File::tempDirectory));
  6425. expect (! File::nonexistent.exists());
  6426. expect (home.isDirectory());
  6427. expect (home.exists());
  6428. expect (! home.existsAsFile());
  6429. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6430. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6431. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6432. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6433. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6434. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6435. expect (home.getBytesFreeOnVolume() > 0);
  6436. expect (! home.isHidden());
  6437. expect (home.isOnHardDisk());
  6438. expect (! home.isOnCDRomDrive());
  6439. expect (File::getCurrentWorkingDirectory().exists());
  6440. expect (home.setAsCurrentWorkingDirectory());
  6441. expect (File::getCurrentWorkingDirectory() == home);
  6442. {
  6443. Array<File> roots;
  6444. File::findFileSystemRoots (roots);
  6445. expect (roots.size() > 0);
  6446. int numRootsExisting = 0;
  6447. for (int i = 0; i < roots.size(); ++i)
  6448. if (roots[i].exists())
  6449. ++numRootsExisting;
  6450. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6451. expect (numRootsExisting > 0);
  6452. }
  6453. beginTest ("Writing");
  6454. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6455. expect (demoFolder.deleteRecursively());
  6456. expect (demoFolder.createDirectory());
  6457. expect (demoFolder.isDirectory());
  6458. expect (demoFolder.getParentDirectory() == temp);
  6459. expect (temp.isDirectory());
  6460. {
  6461. Array<File> files;
  6462. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6463. expect (files.contains (demoFolder));
  6464. }
  6465. {
  6466. Array<File> files;
  6467. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6468. expect (files.contains (demoFolder));
  6469. }
  6470. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6471. expect (tempFile.getFileExtension() == ".txt");
  6472. expect (tempFile.hasFileExtension (".txt"));
  6473. expect (tempFile.hasFileExtension ("txt"));
  6474. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6475. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6476. expect (tempFile.hasWriteAccess());
  6477. {
  6478. FileOutputStream fo (tempFile);
  6479. fo.write ("0123456789", 10);
  6480. }
  6481. expect (tempFile.exists());
  6482. expect (tempFile.getSize() == 10);
  6483. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6484. expect (tempFile.loadFileAsString() == "0123456789");
  6485. expect (! demoFolder.containsSubDirectories());
  6486. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6487. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6488. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6489. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6490. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6491. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6492. expect (demoFolder.containsSubDirectories());
  6493. expect (tempFile.hasWriteAccess());
  6494. tempFile.setReadOnly (true);
  6495. expect (! tempFile.hasWriteAccess());
  6496. tempFile.setReadOnly (false);
  6497. expect (tempFile.hasWriteAccess());
  6498. Time t (Time::getCurrentTime());
  6499. tempFile.setLastModificationTime (t);
  6500. Time t2 = tempFile.getLastModificationTime();
  6501. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6502. {
  6503. MemoryBlock mb;
  6504. tempFile.loadFileAsData (mb);
  6505. expect (mb.getSize() == 10);
  6506. expect (mb[0] == '0');
  6507. }
  6508. expect (tempFile.appendData ("abcdefghij", 10));
  6509. expect (tempFile.getSize() == 20);
  6510. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6511. expect (tempFile.getSize() == 10);
  6512. File tempFile2 (tempFile.getNonexistentSibling (false));
  6513. expect (tempFile.copyFileTo (tempFile2));
  6514. expect (tempFile2.exists());
  6515. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6516. expect (tempFile.deleteFile());
  6517. expect (! tempFile.exists());
  6518. expect (tempFile2.moveFileTo (tempFile));
  6519. expect (tempFile.exists());
  6520. expect (! tempFile2.exists());
  6521. expect (demoFolder.deleteRecursively());
  6522. expect (! demoFolder.exists());
  6523. }
  6524. };
  6525. static FileTests fileUnitTests;
  6526. #endif
  6527. END_JUCE_NAMESPACE
  6528. /*** End of inlined file: juce_File.cpp ***/
  6529. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6530. BEGIN_JUCE_NAMESPACE
  6531. int64 juce_fileSetPosition (void* handle, int64 pos);
  6532. FileInputStream::FileInputStream (const File& f)
  6533. : file (f),
  6534. fileHandle (0),
  6535. currentPosition (0),
  6536. totalSize (0),
  6537. needToSeek (true)
  6538. {
  6539. openHandle();
  6540. }
  6541. FileInputStream::~FileInputStream()
  6542. {
  6543. closeHandle();
  6544. }
  6545. int64 FileInputStream::getTotalLength()
  6546. {
  6547. return totalSize;
  6548. }
  6549. int FileInputStream::read (void* buffer, int bytesToRead)
  6550. {
  6551. int num = 0;
  6552. if (needToSeek)
  6553. {
  6554. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6555. return 0;
  6556. needToSeek = false;
  6557. }
  6558. num = readInternal (buffer, bytesToRead);
  6559. currentPosition += num;
  6560. return num;
  6561. }
  6562. bool FileInputStream::isExhausted()
  6563. {
  6564. return currentPosition >= totalSize;
  6565. }
  6566. int64 FileInputStream::getPosition()
  6567. {
  6568. return currentPosition;
  6569. }
  6570. bool FileInputStream::setPosition (int64 pos)
  6571. {
  6572. pos = jlimit ((int64) 0, totalSize, pos);
  6573. needToSeek |= (currentPosition != pos);
  6574. currentPosition = pos;
  6575. return true;
  6576. }
  6577. END_JUCE_NAMESPACE
  6578. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6579. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6580. BEGIN_JUCE_NAMESPACE
  6581. int64 juce_fileSetPosition (void* handle, int64 pos);
  6582. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6583. : file (f),
  6584. fileHandle (0),
  6585. currentPosition (0),
  6586. bufferSize (bufferSize_),
  6587. bytesInBuffer (0),
  6588. buffer (jmax (bufferSize_, 16))
  6589. {
  6590. openHandle();
  6591. }
  6592. FileOutputStream::~FileOutputStream()
  6593. {
  6594. flush();
  6595. closeHandle();
  6596. }
  6597. int64 FileOutputStream::getPosition()
  6598. {
  6599. return currentPosition;
  6600. }
  6601. bool FileOutputStream::setPosition (int64 newPosition)
  6602. {
  6603. if (newPosition != currentPosition)
  6604. {
  6605. flush();
  6606. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6607. }
  6608. return newPosition == currentPosition;
  6609. }
  6610. void FileOutputStream::flush()
  6611. {
  6612. if (bytesInBuffer > 0)
  6613. {
  6614. writeInternal (buffer, bytesInBuffer);
  6615. bytesInBuffer = 0;
  6616. }
  6617. flushInternal();
  6618. }
  6619. bool FileOutputStream::write (const void* const src, const int numBytes)
  6620. {
  6621. if (bytesInBuffer + numBytes < bufferSize)
  6622. {
  6623. memcpy (buffer + bytesInBuffer, src, numBytes);
  6624. bytesInBuffer += numBytes;
  6625. currentPosition += numBytes;
  6626. }
  6627. else
  6628. {
  6629. if (bytesInBuffer > 0)
  6630. {
  6631. // flush the reservoir
  6632. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6633. bytesInBuffer = 0;
  6634. if (! wroteOk)
  6635. return false;
  6636. }
  6637. if (numBytes < bufferSize)
  6638. {
  6639. memcpy (buffer + bytesInBuffer, src, numBytes);
  6640. bytesInBuffer += numBytes;
  6641. currentPosition += numBytes;
  6642. }
  6643. else
  6644. {
  6645. const int bytesWritten = writeInternal (src, numBytes);
  6646. if (bytesWritten < 0)
  6647. return false;
  6648. currentPosition += bytesWritten;
  6649. return bytesWritten == numBytes;
  6650. }
  6651. }
  6652. return true;
  6653. }
  6654. END_JUCE_NAMESPACE
  6655. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6656. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6657. BEGIN_JUCE_NAMESPACE
  6658. FileSearchPath::FileSearchPath()
  6659. {
  6660. }
  6661. FileSearchPath::FileSearchPath (const String& path)
  6662. {
  6663. init (path);
  6664. }
  6665. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6666. : directories (other.directories)
  6667. {
  6668. }
  6669. FileSearchPath::~FileSearchPath()
  6670. {
  6671. }
  6672. FileSearchPath& FileSearchPath::operator= (const String& path)
  6673. {
  6674. init (path);
  6675. return *this;
  6676. }
  6677. void FileSearchPath::init (const String& path)
  6678. {
  6679. directories.clear();
  6680. directories.addTokens (path, ";", "\"");
  6681. directories.trim();
  6682. directories.removeEmptyStrings();
  6683. for (int i = directories.size(); --i >= 0;)
  6684. directories.set (i, directories[i].unquoted());
  6685. }
  6686. int FileSearchPath::getNumPaths() const
  6687. {
  6688. return directories.size();
  6689. }
  6690. const File FileSearchPath::operator[] (const int index) const
  6691. {
  6692. return File (directories [index]);
  6693. }
  6694. const String FileSearchPath::toString() const
  6695. {
  6696. StringArray directories2 (directories);
  6697. for (int i = directories2.size(); --i >= 0;)
  6698. if (directories2[i].containsChar (';'))
  6699. directories2.set (i, directories2[i].quoted());
  6700. return directories2.joinIntoString (";");
  6701. }
  6702. void FileSearchPath::add (const File& dir, const int insertIndex)
  6703. {
  6704. directories.insert (insertIndex, dir.getFullPathName());
  6705. }
  6706. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6707. {
  6708. for (int i = 0; i < directories.size(); ++i)
  6709. if (File (directories[i]) == dir)
  6710. return;
  6711. add (dir);
  6712. }
  6713. void FileSearchPath::remove (const int index)
  6714. {
  6715. directories.remove (index);
  6716. }
  6717. void FileSearchPath::addPath (const FileSearchPath& other)
  6718. {
  6719. for (int i = 0; i < other.getNumPaths(); ++i)
  6720. addIfNotAlreadyThere (other[i]);
  6721. }
  6722. void FileSearchPath::removeRedundantPaths()
  6723. {
  6724. for (int i = directories.size(); --i >= 0;)
  6725. {
  6726. const File d1 (directories[i]);
  6727. for (int j = directories.size(); --j >= 0;)
  6728. {
  6729. const File d2 (directories[j]);
  6730. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6731. {
  6732. directories.remove (i);
  6733. break;
  6734. }
  6735. }
  6736. }
  6737. }
  6738. void FileSearchPath::removeNonExistentPaths()
  6739. {
  6740. for (int i = directories.size(); --i >= 0;)
  6741. if (! File (directories[i]).isDirectory())
  6742. directories.remove (i);
  6743. }
  6744. int FileSearchPath::findChildFiles (Array<File>& results,
  6745. const int whatToLookFor,
  6746. const bool searchRecursively,
  6747. const String& wildCardPattern) const
  6748. {
  6749. int total = 0;
  6750. for (int i = 0; i < directories.size(); ++i)
  6751. total += operator[] (i).findChildFiles (results,
  6752. whatToLookFor,
  6753. searchRecursively,
  6754. wildCardPattern);
  6755. return total;
  6756. }
  6757. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6758. const bool checkRecursively) const
  6759. {
  6760. for (int i = directories.size(); --i >= 0;)
  6761. {
  6762. const File d (directories[i]);
  6763. if (checkRecursively)
  6764. {
  6765. if (fileToCheck.isAChildOf (d))
  6766. return true;
  6767. }
  6768. else
  6769. {
  6770. if (fileToCheck.getParentDirectory() == d)
  6771. return true;
  6772. }
  6773. }
  6774. return false;
  6775. }
  6776. END_JUCE_NAMESPACE
  6777. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6778. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6779. BEGIN_JUCE_NAMESPACE
  6780. NamedPipe::NamedPipe()
  6781. : internal (0)
  6782. {
  6783. }
  6784. NamedPipe::~NamedPipe()
  6785. {
  6786. close();
  6787. }
  6788. bool NamedPipe::openExisting (const String& pipeName)
  6789. {
  6790. currentPipeName = pipeName;
  6791. return openInternal (pipeName, false);
  6792. }
  6793. bool NamedPipe::createNewPipe (const String& pipeName)
  6794. {
  6795. currentPipeName = pipeName;
  6796. return openInternal (pipeName, true);
  6797. }
  6798. bool NamedPipe::isOpen() const
  6799. {
  6800. return internal != 0;
  6801. }
  6802. const String NamedPipe::getName() const
  6803. {
  6804. return currentPipeName;
  6805. }
  6806. // other methods for this class are implemented in the platform-specific files
  6807. END_JUCE_NAMESPACE
  6808. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6809. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6810. BEGIN_JUCE_NAMESPACE
  6811. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6812. {
  6813. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6814. "temp_" + String (Random::getSystemRandom().nextInt()),
  6815. suffix,
  6816. optionFlags);
  6817. }
  6818. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6819. : targetFile (targetFile_)
  6820. {
  6821. // If you use this constructor, you need to give it a valid target file!
  6822. jassert (targetFile != File::nonexistent);
  6823. createTempFile (targetFile.getParentDirectory(),
  6824. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6825. targetFile.getFileExtension(),
  6826. optionFlags);
  6827. }
  6828. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6829. const String& suffix, const int optionFlags)
  6830. {
  6831. if ((optionFlags & useHiddenFile) != 0)
  6832. name = "." + name;
  6833. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6834. }
  6835. TemporaryFile::~TemporaryFile()
  6836. {
  6837. if (! deleteTemporaryFile())
  6838. {
  6839. /* Failed to delete our temporary file! The most likely reason for this would be
  6840. that you've not closed an output stream that was being used to write to file.
  6841. If you find that something beyond your control is changing permissions on
  6842. your temporary files and preventing them from being deleted, you may want to
  6843. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6844. handle them appropriately.
  6845. */
  6846. jassertfalse;
  6847. }
  6848. }
  6849. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6850. {
  6851. // This method only works if you created this object with the constructor
  6852. // that takes a target file!
  6853. jassert (targetFile != File::nonexistent);
  6854. if (temporaryFile.exists())
  6855. {
  6856. // Have a few attempts at overwriting the file before giving up..
  6857. for (int i = 5; --i >= 0;)
  6858. {
  6859. if (temporaryFile.moveFileTo (targetFile))
  6860. return true;
  6861. Thread::sleep (100);
  6862. }
  6863. }
  6864. else
  6865. {
  6866. // There's no temporary file to use. If your write failed, you should
  6867. // probably check, and not bother calling this method.
  6868. jassertfalse;
  6869. }
  6870. return false;
  6871. }
  6872. bool TemporaryFile::deleteTemporaryFile() const
  6873. {
  6874. // Have a few attempts at deleting the file before giving up..
  6875. for (int i = 5; --i >= 0;)
  6876. {
  6877. if (temporaryFile.deleteFile())
  6878. return true;
  6879. Thread::sleep (50);
  6880. }
  6881. return false;
  6882. }
  6883. END_JUCE_NAMESPACE
  6884. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6885. /*** Start of inlined file: juce_Socket.cpp ***/
  6886. #if JUCE_WINDOWS
  6887. #include <winsock2.h>
  6888. #if JUCE_MSVC
  6889. #pragma warning (push)
  6890. #pragma warning (disable : 4127 4389 4018)
  6891. #endif
  6892. #else
  6893. #if JUCE_LINUX
  6894. #include <sys/types.h>
  6895. #include <sys/socket.h>
  6896. #include <sys/errno.h>
  6897. #include <unistd.h>
  6898. #include <netinet/in.h>
  6899. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6900. #include <CoreServices/CoreServices.h>
  6901. #endif
  6902. #include <fcntl.h>
  6903. #include <netdb.h>
  6904. #include <arpa/inet.h>
  6905. #include <netinet/tcp.h>
  6906. #endif
  6907. BEGIN_JUCE_NAMESPACE
  6908. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6909. typedef socklen_t juce_socklen_t;
  6910. #else
  6911. typedef int juce_socklen_t;
  6912. #endif
  6913. #if JUCE_WINDOWS
  6914. namespace SocketHelpers
  6915. {
  6916. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6917. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6918. void initWin32Sockets()
  6919. {
  6920. static CriticalSection lock;
  6921. const ScopedLock sl (lock);
  6922. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6923. {
  6924. WSADATA wsaData;
  6925. const WORD wVersionRequested = MAKEWORD (1, 1);
  6926. WSAStartup (wVersionRequested, &wsaData);
  6927. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6928. }
  6929. }
  6930. }
  6931. void juce_shutdownWin32Sockets()
  6932. {
  6933. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6934. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6935. }
  6936. #endif
  6937. namespace SocketHelpers
  6938. {
  6939. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6940. {
  6941. const int sndBufSize = 65536;
  6942. const int rcvBufSize = 65536;
  6943. const int one = 1;
  6944. return handle > 0
  6945. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6946. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6947. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6948. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6949. }
  6950. bool bindSocketToPort (const int handle, const int port) throw()
  6951. {
  6952. if (handle <= 0 || port <= 0)
  6953. return false;
  6954. struct sockaddr_in servTmpAddr;
  6955. zerostruct (servTmpAddr);
  6956. servTmpAddr.sin_family = PF_INET;
  6957. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6958. servTmpAddr.sin_port = htons ((uint16) port);
  6959. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6960. }
  6961. int readSocket (const int handle,
  6962. void* const destBuffer, const int maxBytesToRead,
  6963. bool volatile& connected,
  6964. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6965. {
  6966. int bytesRead = 0;
  6967. while (bytesRead < maxBytesToRead)
  6968. {
  6969. int bytesThisTime;
  6970. #if JUCE_WINDOWS
  6971. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6972. #else
  6973. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6974. && errno == EINTR
  6975. && connected)
  6976. {
  6977. }
  6978. #endif
  6979. if (bytesThisTime <= 0 || ! connected)
  6980. {
  6981. if (bytesRead == 0)
  6982. bytesRead = -1;
  6983. break;
  6984. }
  6985. bytesRead += bytesThisTime;
  6986. if (! blockUntilSpecifiedAmountHasArrived)
  6987. break;
  6988. }
  6989. return bytesRead;
  6990. }
  6991. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  6992. {
  6993. struct timeval timeout;
  6994. struct timeval* timeoutp;
  6995. if (timeoutMsecs >= 0)
  6996. {
  6997. timeout.tv_sec = timeoutMsecs / 1000;
  6998. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6999. timeoutp = &timeout;
  7000. }
  7001. else
  7002. {
  7003. timeoutp = 0;
  7004. }
  7005. fd_set rset, wset;
  7006. FD_ZERO (&rset);
  7007. FD_SET (handle, &rset);
  7008. FD_ZERO (&wset);
  7009. FD_SET (handle, &wset);
  7010. fd_set* const prset = forReading ? &rset : 0;
  7011. fd_set* const pwset = forReading ? 0 : &wset;
  7012. #if JUCE_WINDOWS
  7013. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7014. return -1;
  7015. #else
  7016. {
  7017. int result;
  7018. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7019. && errno == EINTR)
  7020. {
  7021. }
  7022. if (result < 0)
  7023. return -1;
  7024. }
  7025. #endif
  7026. {
  7027. int opt;
  7028. juce_socklen_t len = sizeof (opt);
  7029. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7030. || opt != 0)
  7031. return -1;
  7032. }
  7033. if ((forReading && FD_ISSET (handle, &rset))
  7034. || ((! forReading) && FD_ISSET (handle, &wset)))
  7035. return 1;
  7036. return 0;
  7037. }
  7038. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7039. {
  7040. #if JUCE_WINDOWS
  7041. u_long nonBlocking = shouldBlock ? 0 : 1;
  7042. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7043. return false;
  7044. #else
  7045. int socketFlags = fcntl (handle, F_GETFL, 0);
  7046. if (socketFlags == -1)
  7047. return false;
  7048. if (shouldBlock)
  7049. socketFlags &= ~O_NONBLOCK;
  7050. else
  7051. socketFlags |= O_NONBLOCK;
  7052. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7053. return false;
  7054. #endif
  7055. return true;
  7056. }
  7057. bool connectSocket (int volatile& handle,
  7058. const bool isDatagram,
  7059. void** serverAddress,
  7060. const String& hostName,
  7061. const int portNumber,
  7062. const int timeOutMillisecs) throw()
  7063. {
  7064. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7065. if (hostEnt == 0)
  7066. return false;
  7067. struct in_addr targetAddress;
  7068. memcpy (&targetAddress.s_addr,
  7069. *(hostEnt->h_addr_list),
  7070. sizeof (targetAddress.s_addr));
  7071. struct sockaddr_in servTmpAddr;
  7072. zerostruct (servTmpAddr);
  7073. servTmpAddr.sin_family = PF_INET;
  7074. servTmpAddr.sin_addr = targetAddress;
  7075. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7076. if (handle < 0)
  7077. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7078. if (handle < 0)
  7079. return false;
  7080. if (isDatagram)
  7081. {
  7082. *serverAddress = new struct sockaddr_in();
  7083. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7084. return true;
  7085. }
  7086. setSocketBlockingState (handle, false);
  7087. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7088. if (result < 0)
  7089. {
  7090. #if JUCE_WINDOWS
  7091. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7092. #else
  7093. if (errno == EINPROGRESS)
  7094. #endif
  7095. {
  7096. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7097. {
  7098. setSocketBlockingState (handle, true);
  7099. return false;
  7100. }
  7101. }
  7102. }
  7103. setSocketBlockingState (handle, true);
  7104. resetSocketOptions (handle, false, false);
  7105. return true;
  7106. }
  7107. }
  7108. StreamingSocket::StreamingSocket()
  7109. : portNumber (0),
  7110. handle (-1),
  7111. connected (false),
  7112. isListener (false)
  7113. {
  7114. #if JUCE_WINDOWS
  7115. SocketHelpers::initWin32Sockets();
  7116. #endif
  7117. }
  7118. StreamingSocket::StreamingSocket (const String& hostName_,
  7119. const int portNumber_,
  7120. const int handle_)
  7121. : hostName (hostName_),
  7122. portNumber (portNumber_),
  7123. handle (handle_),
  7124. connected (true),
  7125. isListener (false)
  7126. {
  7127. #if JUCE_WINDOWS
  7128. SocketHelpers::initWin32Sockets();
  7129. #endif
  7130. SocketHelpers::resetSocketOptions (handle_, false, false);
  7131. }
  7132. StreamingSocket::~StreamingSocket()
  7133. {
  7134. close();
  7135. }
  7136. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7137. {
  7138. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7139. : -1;
  7140. }
  7141. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7142. {
  7143. if (isListener || ! connected)
  7144. return -1;
  7145. #if JUCE_WINDOWS
  7146. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7147. #else
  7148. int result;
  7149. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7150. && errno == EINTR)
  7151. {
  7152. }
  7153. return result;
  7154. #endif
  7155. }
  7156. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7157. const int timeoutMsecs) const
  7158. {
  7159. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7160. : -1;
  7161. }
  7162. bool StreamingSocket::bindToPort (const int port)
  7163. {
  7164. return SocketHelpers::bindSocketToPort (handle, port);
  7165. }
  7166. bool StreamingSocket::connect (const String& remoteHostName,
  7167. const int remotePortNumber,
  7168. const int timeOutMillisecs)
  7169. {
  7170. if (isListener)
  7171. {
  7172. jassertfalse; // a listener socket can't connect to another one!
  7173. return false;
  7174. }
  7175. if (connected)
  7176. close();
  7177. hostName = remoteHostName;
  7178. portNumber = remotePortNumber;
  7179. isListener = false;
  7180. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7181. remotePortNumber, timeOutMillisecs);
  7182. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7183. {
  7184. close();
  7185. return false;
  7186. }
  7187. return true;
  7188. }
  7189. void StreamingSocket::close()
  7190. {
  7191. #if JUCE_WINDOWS
  7192. if (handle != SOCKET_ERROR || connected)
  7193. closesocket (handle);
  7194. connected = false;
  7195. #else
  7196. if (connected)
  7197. {
  7198. connected = false;
  7199. if (isListener)
  7200. {
  7201. // need to do this to interrupt the accept() function..
  7202. StreamingSocket temp;
  7203. temp.connect ("localhost", portNumber, 1000);
  7204. }
  7205. }
  7206. if (handle != -1)
  7207. ::close (handle);
  7208. #endif
  7209. hostName = String::empty;
  7210. portNumber = 0;
  7211. handle = -1;
  7212. isListener = false;
  7213. }
  7214. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7215. {
  7216. if (connected)
  7217. close();
  7218. hostName = "listener";
  7219. portNumber = newPortNumber;
  7220. isListener = true;
  7221. struct sockaddr_in servTmpAddr;
  7222. zerostruct (servTmpAddr);
  7223. servTmpAddr.sin_family = PF_INET;
  7224. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7225. if (localHostName.isNotEmpty())
  7226. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7227. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7228. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7229. if (handle < 0)
  7230. return false;
  7231. const int reuse = 1;
  7232. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7233. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7234. || listen (handle, SOMAXCONN) < 0)
  7235. {
  7236. close();
  7237. return false;
  7238. }
  7239. connected = true;
  7240. return true;
  7241. }
  7242. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7243. {
  7244. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7245. // prepare this socket as a listener.
  7246. if (connected && isListener)
  7247. {
  7248. struct sockaddr address;
  7249. juce_socklen_t len = sizeof (sockaddr);
  7250. const int newSocket = (int) accept (handle, &address, &len);
  7251. if (newSocket >= 0 && connected)
  7252. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7253. portNumber, newSocket);
  7254. }
  7255. return 0;
  7256. }
  7257. bool StreamingSocket::isLocal() const throw()
  7258. {
  7259. return hostName == "127.0.0.1";
  7260. }
  7261. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7262. : portNumber (0),
  7263. handle (-1),
  7264. connected (true),
  7265. allowBroadcast (allowBroadcast_),
  7266. serverAddress (0)
  7267. {
  7268. #if JUCE_WINDOWS
  7269. SocketHelpers::initWin32Sockets();
  7270. #endif
  7271. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7272. bindToPort (localPortNumber);
  7273. }
  7274. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7275. const int handle_, const int localPortNumber)
  7276. : hostName (hostName_),
  7277. portNumber (portNumber_),
  7278. handle (handle_),
  7279. connected (true),
  7280. allowBroadcast (false),
  7281. serverAddress (0)
  7282. {
  7283. #if JUCE_WINDOWS
  7284. SocketHelpers::initWin32Sockets();
  7285. #endif
  7286. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7287. bindToPort (localPortNumber);
  7288. }
  7289. DatagramSocket::~DatagramSocket()
  7290. {
  7291. close();
  7292. delete static_cast <struct sockaddr_in*> (serverAddress);
  7293. serverAddress = 0;
  7294. }
  7295. void DatagramSocket::close()
  7296. {
  7297. #if JUCE_WINDOWS
  7298. closesocket (handle);
  7299. connected = false;
  7300. #else
  7301. connected = false;
  7302. ::close (handle);
  7303. #endif
  7304. hostName = String::empty;
  7305. portNumber = 0;
  7306. handle = -1;
  7307. }
  7308. bool DatagramSocket::bindToPort (const int port)
  7309. {
  7310. return SocketHelpers::bindSocketToPort (handle, port);
  7311. }
  7312. bool DatagramSocket::connect (const String& remoteHostName,
  7313. const int remotePortNumber,
  7314. const int timeOutMillisecs)
  7315. {
  7316. if (connected)
  7317. close();
  7318. hostName = remoteHostName;
  7319. portNumber = remotePortNumber;
  7320. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7321. remoteHostName, remotePortNumber,
  7322. timeOutMillisecs);
  7323. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7324. {
  7325. close();
  7326. return false;
  7327. }
  7328. return true;
  7329. }
  7330. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7331. {
  7332. struct sockaddr address;
  7333. juce_socklen_t len = sizeof (sockaddr);
  7334. while (waitUntilReady (true, -1) == 1)
  7335. {
  7336. char buf[1];
  7337. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7338. {
  7339. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7340. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7341. -1, -1);
  7342. }
  7343. }
  7344. return 0;
  7345. }
  7346. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7347. const int timeoutMsecs) const
  7348. {
  7349. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7350. : -1;
  7351. }
  7352. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7353. {
  7354. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7355. : -1;
  7356. }
  7357. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7358. {
  7359. // You need to call connect() first to set the server address..
  7360. jassert (serverAddress != 0 && connected);
  7361. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7362. numBytesToWrite, 0,
  7363. (const struct sockaddr*) serverAddress,
  7364. sizeof (struct sockaddr_in))
  7365. : -1;
  7366. }
  7367. bool DatagramSocket::isLocal() const throw()
  7368. {
  7369. return hostName == "127.0.0.1";
  7370. }
  7371. #if JUCE_MSVC
  7372. #pragma warning (pop)
  7373. #endif
  7374. END_JUCE_NAMESPACE
  7375. /*** End of inlined file: juce_Socket.cpp ***/
  7376. /*** Start of inlined file: juce_URL.cpp ***/
  7377. BEGIN_JUCE_NAMESPACE
  7378. URL::URL()
  7379. {
  7380. }
  7381. URL::URL (const String& url_)
  7382. : url (url_)
  7383. {
  7384. int i = url.indexOfChar ('?');
  7385. if (i >= 0)
  7386. {
  7387. do
  7388. {
  7389. const int nextAmp = url.indexOfChar (i + 1, '&');
  7390. const int equalsPos = url.indexOfChar (i + 1, '=');
  7391. if (equalsPos > i + 1)
  7392. {
  7393. if (nextAmp < 0)
  7394. {
  7395. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7396. removeEscapeChars (url.substring (equalsPos + 1)));
  7397. }
  7398. else if (nextAmp > 0 && equalsPos < nextAmp)
  7399. {
  7400. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7401. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7402. }
  7403. }
  7404. i = nextAmp;
  7405. }
  7406. while (i >= 0);
  7407. url = url.upToFirstOccurrenceOf ("?", false, false);
  7408. }
  7409. }
  7410. URL::URL (const URL& other)
  7411. : url (other.url),
  7412. postData (other.postData),
  7413. parameters (other.parameters),
  7414. filesToUpload (other.filesToUpload),
  7415. mimeTypes (other.mimeTypes)
  7416. {
  7417. }
  7418. URL& URL::operator= (const URL& other)
  7419. {
  7420. url = other.url;
  7421. postData = other.postData;
  7422. parameters = other.parameters;
  7423. filesToUpload = other.filesToUpload;
  7424. mimeTypes = other.mimeTypes;
  7425. return *this;
  7426. }
  7427. URL::~URL()
  7428. {
  7429. }
  7430. namespace URLHelpers
  7431. {
  7432. const String getMangledParameters (const StringPairArray& parameters)
  7433. {
  7434. String p;
  7435. for (int i = 0; i < parameters.size(); ++i)
  7436. {
  7437. if (i > 0)
  7438. p << '&';
  7439. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7440. << '='
  7441. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7442. }
  7443. return p;
  7444. }
  7445. int findStartOfDomain (const String& url)
  7446. {
  7447. int i = 0;
  7448. while (CharacterFunctions::isLetterOrDigit (url[i])
  7449. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7450. ++i;
  7451. return url[i] == ':' ? i + 1 : 0;
  7452. }
  7453. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7454. {
  7455. MemoryOutputStream data (postData, false);
  7456. if (url.getFilesToUpload().size() > 0)
  7457. {
  7458. // need to upload some files, so do it as multi-part...
  7459. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7460. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7461. data << "--" << boundary;
  7462. int i;
  7463. for (i = 0; i < url.getParameters().size(); ++i)
  7464. {
  7465. data << "\r\nContent-Disposition: form-data; name=\""
  7466. << url.getParameters().getAllKeys() [i]
  7467. << "\"\r\n\r\n"
  7468. << url.getParameters().getAllValues() [i]
  7469. << "\r\n--"
  7470. << boundary;
  7471. }
  7472. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7473. {
  7474. const File file (url.getFilesToUpload().getAllValues() [i]);
  7475. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7476. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7477. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7478. const String mimeType (url.getMimeTypesOfUploadFiles()
  7479. .getValue (paramName, String::empty));
  7480. if (mimeType.isNotEmpty())
  7481. data << "Content-Type: " << mimeType << "\r\n";
  7482. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7483. << file << "\r\n--" << boundary;
  7484. }
  7485. data << "--\r\n";
  7486. data.flush();
  7487. }
  7488. else
  7489. {
  7490. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7491. data.flush();
  7492. // just a short text attachment, so use simple url encoding..
  7493. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7494. << postData.getSize() << "\r\n";
  7495. }
  7496. }
  7497. }
  7498. const String URL::toString (const bool includeGetParameters) const
  7499. {
  7500. if (includeGetParameters && parameters.size() > 0)
  7501. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7502. else
  7503. return url;
  7504. }
  7505. bool URL::isWellFormed() const
  7506. {
  7507. //xxx TODO
  7508. return url.isNotEmpty();
  7509. }
  7510. const String URL::getDomain() const
  7511. {
  7512. int start = URLHelpers::findStartOfDomain (url);
  7513. while (url[start] == '/')
  7514. ++start;
  7515. const int end1 = url.indexOfChar (start, '/');
  7516. const int end2 = url.indexOfChar (start, ':');
  7517. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7518. : jmin (end1, end2);
  7519. return url.substring (start, end);
  7520. }
  7521. const String URL::getSubPath() const
  7522. {
  7523. int start = URLHelpers::findStartOfDomain (url);
  7524. while (url[start] == '/')
  7525. ++start;
  7526. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7527. return startOfPath <= 0 ? String::empty
  7528. : url.substring (startOfPath);
  7529. }
  7530. const String URL::getScheme() const
  7531. {
  7532. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7533. }
  7534. const URL URL::withNewSubPath (const String& newPath) const
  7535. {
  7536. int start = URLHelpers::findStartOfDomain (url);
  7537. while (url[start] == '/')
  7538. ++start;
  7539. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7540. URL u (*this);
  7541. if (startOfPath > 0)
  7542. u.url = url.substring (0, startOfPath);
  7543. if (! u.url.endsWithChar ('/'))
  7544. u.url << '/';
  7545. if (newPath.startsWithChar ('/'))
  7546. u.url << newPath.substring (1);
  7547. else
  7548. u.url << newPath;
  7549. return u;
  7550. }
  7551. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7552. {
  7553. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7554. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7555. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7556. return true;
  7557. if (possibleURL.containsChar ('@')
  7558. || possibleURL.containsChar (' '))
  7559. return false;
  7560. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7561. .fromLastOccurrenceOf (".", false, false));
  7562. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7563. }
  7564. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7565. {
  7566. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7567. return atSign > 0
  7568. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7569. && (! possibleEmailAddress.endsWithChar ('.'));
  7570. }
  7571. InputStream* URL::createInputStream (const bool usePostCommand,
  7572. OpenStreamProgressCallback* const progressCallback,
  7573. void* const progressCallbackContext,
  7574. const String& extraHeaders,
  7575. const int timeOutMs,
  7576. StringPairArray* const responseHeaders) const
  7577. {
  7578. String headers;
  7579. MemoryBlock postData;
  7580. if (usePostCommand)
  7581. URLHelpers::createHeadersAndPostData (*this, headers, postData);
  7582. headers += extraHeaders;
  7583. if (! headers.endsWithChar ('\n'))
  7584. headers << "\r\n";
  7585. return createNativeStream (toString (! usePostCommand), usePostCommand, postData,
  7586. progressCallback, progressCallbackContext,
  7587. headers, timeOutMs, responseHeaders);
  7588. }
  7589. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7590. const bool usePostCommand) const
  7591. {
  7592. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7593. if (in != 0)
  7594. {
  7595. in->readIntoMemoryBlock (destData);
  7596. return true;
  7597. }
  7598. return false;
  7599. }
  7600. const String URL::readEntireTextStream (const bool usePostCommand) const
  7601. {
  7602. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7603. if (in != 0)
  7604. return in->readEntireStreamAsString();
  7605. return String::empty;
  7606. }
  7607. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7608. {
  7609. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7610. }
  7611. const URL URL::withParameter (const String& parameterName,
  7612. const String& parameterValue) const
  7613. {
  7614. URL u (*this);
  7615. u.parameters.set (parameterName, parameterValue);
  7616. return u;
  7617. }
  7618. const URL URL::withFileToUpload (const String& parameterName,
  7619. const File& fileToUpload,
  7620. const String& mimeType) const
  7621. {
  7622. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7623. URL u (*this);
  7624. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7625. u.mimeTypes.set (parameterName, mimeType);
  7626. return u;
  7627. }
  7628. const URL URL::withPOSTData (const String& postData_) const
  7629. {
  7630. URL u (*this);
  7631. u.postData = postData_;
  7632. return u;
  7633. }
  7634. const StringPairArray& URL::getParameters() const
  7635. {
  7636. return parameters;
  7637. }
  7638. const StringPairArray& URL::getFilesToUpload() const
  7639. {
  7640. return filesToUpload;
  7641. }
  7642. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7643. {
  7644. return mimeTypes;
  7645. }
  7646. const String URL::removeEscapeChars (const String& s)
  7647. {
  7648. String result (s.replaceCharacter ('+', ' '));
  7649. if (! result.containsChar ('%'))
  7650. return result;
  7651. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7652. // after all the replacements have been made, so that multi-byte chars are handled.
  7653. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7654. for (int i = 0; i < utf8.size(); ++i)
  7655. {
  7656. if (utf8.getUnchecked(i) == '%')
  7657. {
  7658. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7659. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7660. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7661. {
  7662. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7663. utf8.removeRange (i + 1, 2);
  7664. }
  7665. }
  7666. }
  7667. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7668. }
  7669. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7670. {
  7671. const char* const legalChars = isParameter ? "_-.*!'()"
  7672. : ",$_-.*!'()";
  7673. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7674. for (int i = 0; i < utf8.size(); ++i)
  7675. {
  7676. const char c = utf8.getUnchecked(i);
  7677. if (! (CharacterFunctions::isLetterOrDigit (c)
  7678. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7679. {
  7680. if (c == ' ')
  7681. {
  7682. utf8.set (i, '+');
  7683. }
  7684. else
  7685. {
  7686. static const char* const hexDigits = "0123456789abcdef";
  7687. utf8.set (i, '%');
  7688. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7689. utf8.insert (++i, hexDigits [c & 15]);
  7690. }
  7691. }
  7692. }
  7693. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7694. }
  7695. bool URL::launchInDefaultBrowser() const
  7696. {
  7697. String u (toString (true));
  7698. if (u.containsChar ('@') && ! u.containsChar (':'))
  7699. u = "mailto:" + u;
  7700. return PlatformUtilities::openDocument (u, String::empty);
  7701. }
  7702. END_JUCE_NAMESPACE
  7703. /*** End of inlined file: juce_URL.cpp ***/
  7704. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7705. BEGIN_JUCE_NAMESPACE
  7706. MACAddress::MACAddress()
  7707. : asInt64 (0)
  7708. {
  7709. }
  7710. MACAddress::MACAddress (const MACAddress& other)
  7711. : asInt64 (other.asInt64)
  7712. {
  7713. }
  7714. MACAddress& MACAddress::operator= (const MACAddress& other)
  7715. {
  7716. asInt64 = other.asInt64;
  7717. return *this;
  7718. }
  7719. MACAddress::MACAddress (const uint8 bytes[6])
  7720. : asInt64 (0)
  7721. {
  7722. memcpy (asBytes, bytes, sizeof (asBytes));
  7723. }
  7724. const String MACAddress::toString() const
  7725. {
  7726. String s;
  7727. s.preallocateStorage (18);
  7728. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7729. {
  7730. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7731. if (i < numElementsInArray (asBytes) - 1)
  7732. s << '-';
  7733. }
  7734. return s;
  7735. }
  7736. int64 MACAddress::toInt64() const throw()
  7737. {
  7738. int64 n = 0;
  7739. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7740. n = (n << 8) | asBytes[i];
  7741. return n;
  7742. }
  7743. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7744. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7745. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7746. END_JUCE_NAMESPACE
  7747. /*** End of inlined file: juce_MACAddress.cpp ***/
  7748. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7749. BEGIN_JUCE_NAMESPACE
  7750. namespace
  7751. {
  7752. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7753. {
  7754. // You need to supply a real stream when creating a BufferedInputStream
  7755. jassert (source != 0);
  7756. requestedSize = jmax (256, requestedSize);
  7757. const int64 sourceSize = source->getTotalLength();
  7758. if (sourceSize >= 0 && sourceSize < requestedSize)
  7759. requestedSize = jmax (32, (int) sourceSize);
  7760. return requestedSize;
  7761. }
  7762. }
  7763. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7764. const bool deleteSourceWhenDestroyed)
  7765. : source (sourceStream),
  7766. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7767. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7768. position (sourceStream->getPosition()),
  7769. lastReadPos (0),
  7770. bufferStart (position),
  7771. bufferOverlap (128)
  7772. {
  7773. buffer.malloc (bufferSize);
  7774. }
  7775. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7776. : source (&sourceStream),
  7777. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7778. position (sourceStream.getPosition()),
  7779. lastReadPos (0),
  7780. bufferStart (position),
  7781. bufferOverlap (128)
  7782. {
  7783. buffer.malloc (bufferSize);
  7784. }
  7785. BufferedInputStream::~BufferedInputStream()
  7786. {
  7787. }
  7788. int64 BufferedInputStream::getTotalLength()
  7789. {
  7790. return source->getTotalLength();
  7791. }
  7792. int64 BufferedInputStream::getPosition()
  7793. {
  7794. return position;
  7795. }
  7796. bool BufferedInputStream::setPosition (int64 newPosition)
  7797. {
  7798. position = jmax ((int64) 0, newPosition);
  7799. return true;
  7800. }
  7801. bool BufferedInputStream::isExhausted()
  7802. {
  7803. return (position >= lastReadPos)
  7804. && source->isExhausted();
  7805. }
  7806. void BufferedInputStream::ensureBuffered()
  7807. {
  7808. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7809. if (position < bufferStart || position >= bufferEndOverlap)
  7810. {
  7811. int bytesRead;
  7812. if (position < lastReadPos
  7813. && position >= bufferEndOverlap
  7814. && position >= bufferStart)
  7815. {
  7816. const int bytesToKeep = (int) (lastReadPos - position);
  7817. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7818. bufferStart = position;
  7819. bytesRead = source->read (buffer + bytesToKeep,
  7820. bufferSize - bytesToKeep);
  7821. lastReadPos += bytesRead;
  7822. bytesRead += bytesToKeep;
  7823. }
  7824. else
  7825. {
  7826. bufferStart = position;
  7827. source->setPosition (bufferStart);
  7828. bytesRead = source->read (buffer, bufferSize);
  7829. lastReadPos = bufferStart + bytesRead;
  7830. }
  7831. while (bytesRead < bufferSize)
  7832. buffer [bytesRead++] = 0;
  7833. }
  7834. }
  7835. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7836. {
  7837. if (position >= bufferStart
  7838. && position + maxBytesToRead <= lastReadPos)
  7839. {
  7840. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7841. position += maxBytesToRead;
  7842. return maxBytesToRead;
  7843. }
  7844. else
  7845. {
  7846. if (position < bufferStart || position >= lastReadPos)
  7847. ensureBuffered();
  7848. int bytesRead = 0;
  7849. while (maxBytesToRead > 0)
  7850. {
  7851. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7852. if (bytesAvailable > 0)
  7853. {
  7854. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7855. maxBytesToRead -= bytesAvailable;
  7856. bytesRead += bytesAvailable;
  7857. position += bytesAvailable;
  7858. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7859. }
  7860. const int64 oldLastReadPos = lastReadPos;
  7861. ensureBuffered();
  7862. if (oldLastReadPos == lastReadPos)
  7863. break; // if ensureBuffered() failed to read any more data, bail out
  7864. if (isExhausted())
  7865. break;
  7866. }
  7867. return bytesRead;
  7868. }
  7869. }
  7870. const String BufferedInputStream::readString()
  7871. {
  7872. if (position >= bufferStart
  7873. && position < lastReadPos)
  7874. {
  7875. const int maxChars = (int) (lastReadPos - position);
  7876. const char* const src = buffer + (int) (position - bufferStart);
  7877. for (int i = 0; i < maxChars; ++i)
  7878. {
  7879. if (src[i] == 0)
  7880. {
  7881. position += i + 1;
  7882. return String::fromUTF8 (src, i);
  7883. }
  7884. }
  7885. }
  7886. return InputStream::readString();
  7887. }
  7888. END_JUCE_NAMESPACE
  7889. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7890. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7891. BEGIN_JUCE_NAMESPACE
  7892. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  7893. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  7894. {
  7895. }
  7896. FileInputSource::~FileInputSource()
  7897. {
  7898. }
  7899. InputStream* FileInputSource::createInputStream()
  7900. {
  7901. return file.createInputStream();
  7902. }
  7903. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7904. {
  7905. return file.getSiblingFile (relatedItemPath).createInputStream();
  7906. }
  7907. int64 FileInputSource::hashCode() const
  7908. {
  7909. int64 h = file.hashCode();
  7910. if (useFileTimeInHashGeneration)
  7911. h ^= file.getLastModificationTime().toMilliseconds();
  7912. return h;
  7913. }
  7914. END_JUCE_NAMESPACE
  7915. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7916. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7917. BEGIN_JUCE_NAMESPACE
  7918. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7919. const size_t sourceDataSize,
  7920. const bool keepInternalCopy)
  7921. : data (static_cast <const char*> (sourceData)),
  7922. dataSize (sourceDataSize),
  7923. position (0)
  7924. {
  7925. if (keepInternalCopy)
  7926. {
  7927. internalCopy.append (data, sourceDataSize);
  7928. data = static_cast <const char*> (internalCopy.getData());
  7929. }
  7930. }
  7931. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7932. const bool keepInternalCopy)
  7933. : data (static_cast <const char*> (sourceData.getData())),
  7934. dataSize (sourceData.getSize()),
  7935. position (0)
  7936. {
  7937. if (keepInternalCopy)
  7938. {
  7939. internalCopy = sourceData;
  7940. data = static_cast <const char*> (internalCopy.getData());
  7941. }
  7942. }
  7943. MemoryInputStream::~MemoryInputStream()
  7944. {
  7945. }
  7946. int64 MemoryInputStream::getTotalLength()
  7947. {
  7948. return dataSize;
  7949. }
  7950. int MemoryInputStream::read (void* const buffer, const int howMany)
  7951. {
  7952. jassert (howMany >= 0);
  7953. const int num = jmin (howMany, (int) (dataSize - position));
  7954. memcpy (buffer, data + position, num);
  7955. position += num;
  7956. return (int) num;
  7957. }
  7958. bool MemoryInputStream::isExhausted()
  7959. {
  7960. return (position >= dataSize);
  7961. }
  7962. bool MemoryInputStream::setPosition (const int64 pos)
  7963. {
  7964. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7965. return true;
  7966. }
  7967. int64 MemoryInputStream::getPosition()
  7968. {
  7969. return position;
  7970. }
  7971. #if JUCE_UNIT_TESTS
  7972. class MemoryStreamTests : public UnitTest
  7973. {
  7974. public:
  7975. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7976. void runTest()
  7977. {
  7978. beginTest ("Basics");
  7979. int randomInt = Random::getSystemRandom().nextInt();
  7980. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7981. double randomDouble = Random::getSystemRandom().nextDouble();
  7982. String randomString;
  7983. for (int i = 50; --i >= 0;)
  7984. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7985. MemoryOutputStream mo;
  7986. mo.writeInt (randomInt);
  7987. mo.writeIntBigEndian (randomInt);
  7988. mo.writeCompressedInt (randomInt);
  7989. mo.writeString (randomString);
  7990. mo.writeInt64 (randomInt64);
  7991. mo.writeInt64BigEndian (randomInt64);
  7992. mo.writeDouble (randomDouble);
  7993. mo.writeDoubleBigEndian (randomDouble);
  7994. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  7995. expect (mi.readInt() == randomInt);
  7996. expect (mi.readIntBigEndian() == randomInt);
  7997. expect (mi.readCompressedInt() == randomInt);
  7998. expect (mi.readString() == randomString);
  7999. expect (mi.readInt64() == randomInt64);
  8000. expect (mi.readInt64BigEndian() == randomInt64);
  8001. expect (mi.readDouble() == randomDouble);
  8002. expect (mi.readDoubleBigEndian() == randomDouble);
  8003. }
  8004. };
  8005. static MemoryStreamTests memoryInputStreamUnitTests;
  8006. #endif
  8007. END_JUCE_NAMESPACE
  8008. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8009. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8010. BEGIN_JUCE_NAMESPACE
  8011. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8012. : data (internalBlock),
  8013. position (0),
  8014. size (0)
  8015. {
  8016. internalBlock.setSize (initialSize, false);
  8017. }
  8018. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8019. const bool appendToExistingBlockContent)
  8020. : data (memoryBlockToWriteTo),
  8021. position (0),
  8022. size (0)
  8023. {
  8024. if (appendToExistingBlockContent)
  8025. position = size = memoryBlockToWriteTo.getSize();
  8026. }
  8027. MemoryOutputStream::~MemoryOutputStream()
  8028. {
  8029. flush();
  8030. }
  8031. void MemoryOutputStream::flush()
  8032. {
  8033. if (&data != &internalBlock)
  8034. data.setSize (size, false);
  8035. }
  8036. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8037. {
  8038. data.ensureSize (bytesToPreallocate + 1);
  8039. }
  8040. void MemoryOutputStream::reset() throw()
  8041. {
  8042. position = 0;
  8043. size = 0;
  8044. }
  8045. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8046. {
  8047. if (howMany > 0)
  8048. {
  8049. const size_t storageNeeded = position + howMany;
  8050. if (storageNeeded >= data.getSize())
  8051. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8052. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8053. position += howMany;
  8054. size = jmax (size, position);
  8055. }
  8056. return true;
  8057. }
  8058. const void* MemoryOutputStream::getData() const throw()
  8059. {
  8060. void* const d = data.getData();
  8061. if (data.getSize() > size)
  8062. static_cast <char*> (d) [size] = 0;
  8063. return d;
  8064. }
  8065. bool MemoryOutputStream::setPosition (int64 newPosition)
  8066. {
  8067. if (newPosition <= (int64) size)
  8068. {
  8069. // ok to seek backwards
  8070. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8071. return true;
  8072. }
  8073. else
  8074. {
  8075. // trying to make it bigger isn't a good thing to do..
  8076. return false;
  8077. }
  8078. }
  8079. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8080. {
  8081. // before writing from an input, see if we can preallocate to make it more efficient..
  8082. int64 availableData = source.getTotalLength() - source.getPosition();
  8083. if (availableData > 0)
  8084. {
  8085. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8086. availableData = maxNumBytesToWrite;
  8087. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8088. }
  8089. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8090. }
  8091. const String MemoryOutputStream::toUTF8() const
  8092. {
  8093. return String (static_cast <const char*> (getData()), getDataSize());
  8094. }
  8095. const String MemoryOutputStream::toString() const
  8096. {
  8097. return String::createStringFromData (getData(), getDataSize());
  8098. }
  8099. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8100. {
  8101. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8102. return stream;
  8103. }
  8104. END_JUCE_NAMESPACE
  8105. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8106. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8107. BEGIN_JUCE_NAMESPACE
  8108. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8109. const int64 startPositionInSourceStream_,
  8110. const int64 lengthOfSourceStream_,
  8111. const bool deleteSourceWhenDestroyed)
  8112. : source (sourceStream),
  8113. startPositionInSourceStream (startPositionInSourceStream_),
  8114. lengthOfSourceStream (lengthOfSourceStream_)
  8115. {
  8116. if (deleteSourceWhenDestroyed)
  8117. sourceToDelete = source;
  8118. setPosition (0);
  8119. }
  8120. SubregionStream::~SubregionStream()
  8121. {
  8122. }
  8123. int64 SubregionStream::getTotalLength()
  8124. {
  8125. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8126. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8127. : srcLen;
  8128. }
  8129. int64 SubregionStream::getPosition()
  8130. {
  8131. return source->getPosition() - startPositionInSourceStream;
  8132. }
  8133. bool SubregionStream::setPosition (int64 newPosition)
  8134. {
  8135. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8136. }
  8137. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8138. {
  8139. if (lengthOfSourceStream < 0)
  8140. {
  8141. return source->read (destBuffer, maxBytesToRead);
  8142. }
  8143. else
  8144. {
  8145. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8146. if (maxBytesToRead <= 0)
  8147. return 0;
  8148. return source->read (destBuffer, maxBytesToRead);
  8149. }
  8150. }
  8151. bool SubregionStream::isExhausted()
  8152. {
  8153. if (lengthOfSourceStream >= 0)
  8154. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8155. else
  8156. return source->isExhausted();
  8157. }
  8158. END_JUCE_NAMESPACE
  8159. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8160. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8161. BEGIN_JUCE_NAMESPACE
  8162. PerformanceCounter::PerformanceCounter (const String& name_,
  8163. int runsPerPrintout,
  8164. const File& loggingFile)
  8165. : name (name_),
  8166. numRuns (0),
  8167. runsPerPrint (runsPerPrintout),
  8168. totalTime (0),
  8169. outputFile (loggingFile)
  8170. {
  8171. if (outputFile != File::nonexistent)
  8172. {
  8173. String s ("**** Counter for \"");
  8174. s << name_ << "\" started at: "
  8175. << Time::getCurrentTime().toString (true, true)
  8176. << "\r\n";
  8177. outputFile.appendText (s, false, false);
  8178. }
  8179. }
  8180. PerformanceCounter::~PerformanceCounter()
  8181. {
  8182. printStatistics();
  8183. }
  8184. void PerformanceCounter::start()
  8185. {
  8186. started = Time::getHighResolutionTicks();
  8187. }
  8188. void PerformanceCounter::stop()
  8189. {
  8190. const int64 now = Time::getHighResolutionTicks();
  8191. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8192. if (++numRuns == runsPerPrint)
  8193. printStatistics();
  8194. }
  8195. void PerformanceCounter::printStatistics()
  8196. {
  8197. if (numRuns > 0)
  8198. {
  8199. String s ("Performance count for \"");
  8200. s << name << "\" - average over " << numRuns << " run(s) = ";
  8201. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8202. if (micros > 10000)
  8203. s << (micros/1000) << " millisecs";
  8204. else
  8205. s << micros << " microsecs";
  8206. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8207. Logger::outputDebugString (s);
  8208. s << "\r\n";
  8209. if (outputFile != File::nonexistent)
  8210. outputFile.appendText (s, false, false);
  8211. numRuns = 0;
  8212. totalTime = 0;
  8213. }
  8214. }
  8215. END_JUCE_NAMESPACE
  8216. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8217. /*** Start of inlined file: juce_Uuid.cpp ***/
  8218. BEGIN_JUCE_NAMESPACE
  8219. Uuid::Uuid()
  8220. {
  8221. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8222. // to make it very very unlikely that two UUIDs will ever be the same..
  8223. static int64 macAddresses[2];
  8224. static bool hasCheckedMacAddresses = false;
  8225. if (! hasCheckedMacAddresses)
  8226. {
  8227. hasCheckedMacAddresses = true;
  8228. Array<MACAddress> result;
  8229. MACAddress::findAllAddresses (result);
  8230. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8231. macAddresses[i] = result[i].toInt64();
  8232. }
  8233. value.asInt64[0] = macAddresses[0];
  8234. value.asInt64[1] = macAddresses[1];
  8235. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8236. // whose seed will carry over between calls to this method.
  8237. Random r (macAddresses[0] ^ macAddresses[1]
  8238. ^ Random::getSystemRandom().nextInt64());
  8239. for (int i = 4; --i >= 0;)
  8240. {
  8241. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8242. value.asInt[i] ^= r.nextInt();
  8243. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8244. }
  8245. }
  8246. Uuid::~Uuid() throw()
  8247. {
  8248. }
  8249. Uuid::Uuid (const Uuid& other)
  8250. : value (other.value)
  8251. {
  8252. }
  8253. Uuid& Uuid::operator= (const Uuid& other)
  8254. {
  8255. value = other.value;
  8256. return *this;
  8257. }
  8258. bool Uuid::operator== (const Uuid& other) const
  8259. {
  8260. return value.asInt64[0] == other.value.asInt64[0]
  8261. && value.asInt64[1] == other.value.asInt64[1];
  8262. }
  8263. bool Uuid::operator!= (const Uuid& other) const
  8264. {
  8265. return ! operator== (other);
  8266. }
  8267. bool Uuid::isNull() const throw()
  8268. {
  8269. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8270. }
  8271. const String Uuid::toString() const
  8272. {
  8273. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8274. }
  8275. Uuid::Uuid (const String& uuidString)
  8276. {
  8277. operator= (uuidString);
  8278. }
  8279. Uuid& Uuid::operator= (const String& uuidString)
  8280. {
  8281. MemoryBlock mb;
  8282. mb.loadFromHexString (uuidString);
  8283. mb.ensureSize (sizeof (value.asBytes), true);
  8284. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8285. return *this;
  8286. }
  8287. Uuid::Uuid (const uint8* const rawData)
  8288. {
  8289. operator= (rawData);
  8290. }
  8291. Uuid& Uuid::operator= (const uint8* const rawData)
  8292. {
  8293. if (rawData != 0)
  8294. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8295. else
  8296. zeromem (value.asBytes, sizeof (value.asBytes));
  8297. return *this;
  8298. }
  8299. END_JUCE_NAMESPACE
  8300. /*** End of inlined file: juce_Uuid.cpp ***/
  8301. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8302. BEGIN_JUCE_NAMESPACE
  8303. class ZipFile::ZipEntryInfo
  8304. {
  8305. public:
  8306. ZipFile::ZipEntry entry;
  8307. int streamOffset;
  8308. int compressedSize;
  8309. bool compressed;
  8310. };
  8311. class ZipFile::ZipInputStream : public InputStream
  8312. {
  8313. public:
  8314. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8315. : file (file_),
  8316. zipEntryInfo (zei),
  8317. pos (0),
  8318. headerSize (0),
  8319. inputStream (0)
  8320. {
  8321. inputStream = file_.inputStream;
  8322. if (file_.inputSource != 0)
  8323. {
  8324. inputStream = streamToDelete = file.inputSource->createInputStream();
  8325. }
  8326. else
  8327. {
  8328. #if JUCE_DEBUG
  8329. file_.numOpenStreams++;
  8330. #endif
  8331. }
  8332. char buffer [30];
  8333. if (inputStream != 0
  8334. && inputStream->setPosition (zei.streamOffset)
  8335. && inputStream->read (buffer, 30) == 30
  8336. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8337. {
  8338. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8339. + ByteOrder::littleEndianShort (buffer + 28);
  8340. }
  8341. }
  8342. ~ZipInputStream()
  8343. {
  8344. #if JUCE_DEBUG
  8345. if (inputStream != 0 && inputStream == file.inputStream)
  8346. file.numOpenStreams--;
  8347. #endif
  8348. }
  8349. int64 getTotalLength()
  8350. {
  8351. return zipEntryInfo.compressedSize;
  8352. }
  8353. int read (void* buffer, int howMany)
  8354. {
  8355. if (headerSize <= 0)
  8356. return 0;
  8357. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8358. if (inputStream == 0)
  8359. return 0;
  8360. int num;
  8361. if (inputStream == file.inputStream)
  8362. {
  8363. const ScopedLock sl (file.lock);
  8364. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8365. num = inputStream->read (buffer, howMany);
  8366. }
  8367. else
  8368. {
  8369. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8370. num = inputStream->read (buffer, howMany);
  8371. }
  8372. pos += num;
  8373. return num;
  8374. }
  8375. bool isExhausted()
  8376. {
  8377. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8378. }
  8379. int64 getPosition()
  8380. {
  8381. return pos;
  8382. }
  8383. bool setPosition (int64 newPos)
  8384. {
  8385. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8386. return true;
  8387. }
  8388. private:
  8389. ZipFile& file;
  8390. ZipEntryInfo zipEntryInfo;
  8391. int64 pos;
  8392. int headerSize;
  8393. InputStream* inputStream;
  8394. ScopedPointer<InputStream> streamToDelete;
  8395. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8396. };
  8397. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8398. : inputStream (source_)
  8399. #if JUCE_DEBUG
  8400. , numOpenStreams (0)
  8401. #endif
  8402. {
  8403. if (deleteStreamWhenDestroyed)
  8404. streamToDelete = inputStream;
  8405. init();
  8406. }
  8407. ZipFile::ZipFile (const File& file)
  8408. : inputStream (0)
  8409. #if JUCE_DEBUG
  8410. , numOpenStreams (0)
  8411. #endif
  8412. {
  8413. inputSource = new FileInputSource (file);
  8414. init();
  8415. }
  8416. ZipFile::ZipFile (InputSource* const inputSource_)
  8417. : inputStream (0),
  8418. inputSource (inputSource_)
  8419. #if JUCE_DEBUG
  8420. , numOpenStreams (0)
  8421. #endif
  8422. {
  8423. init();
  8424. }
  8425. ZipFile::~ZipFile()
  8426. {
  8427. #if JUCE_DEBUG
  8428. entries.clear();
  8429. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8430. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8431. Streams can't be kept open after the file is deleted because they need to share the input
  8432. stream that the file uses to read itself.
  8433. */
  8434. jassert (numOpenStreams == 0);
  8435. #endif
  8436. }
  8437. int ZipFile::getNumEntries() const throw()
  8438. {
  8439. return entries.size();
  8440. }
  8441. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8442. {
  8443. ZipEntryInfo* const zei = entries [index];
  8444. return zei != 0 ? &(zei->entry) : 0;
  8445. }
  8446. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8447. {
  8448. for (int i = 0; i < entries.size(); ++i)
  8449. if (entries.getUnchecked (i)->entry.filename == fileName)
  8450. return i;
  8451. return -1;
  8452. }
  8453. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8454. {
  8455. return getEntry (getIndexOfFileName (fileName));
  8456. }
  8457. InputStream* ZipFile::createStreamForEntry (const int index)
  8458. {
  8459. ZipEntryInfo* const zei = entries[index];
  8460. InputStream* stream = 0;
  8461. if (zei != 0)
  8462. {
  8463. stream = new ZipInputStream (*this, *zei);
  8464. if (zei->compressed)
  8465. {
  8466. stream = new GZIPDecompressorInputStream (stream, true, true,
  8467. zei->entry.uncompressedSize);
  8468. // (much faster to unzip in big blocks using a buffer..)
  8469. stream = new BufferedInputStream (stream, 32768, true);
  8470. }
  8471. }
  8472. return stream;
  8473. }
  8474. class ZipFile::ZipFilenameComparator
  8475. {
  8476. public:
  8477. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8478. {
  8479. return first->entry.filename.compare (second->entry.filename);
  8480. }
  8481. };
  8482. void ZipFile::sortEntriesByFilename()
  8483. {
  8484. ZipFilenameComparator sorter;
  8485. entries.sort (sorter);
  8486. }
  8487. void ZipFile::init()
  8488. {
  8489. ScopedPointer <InputStream> toDelete;
  8490. InputStream* in = inputStream;
  8491. if (inputSource != 0)
  8492. {
  8493. in = inputSource->createInputStream();
  8494. toDelete = in;
  8495. }
  8496. if (in != 0)
  8497. {
  8498. int numEntries = 0;
  8499. int pos = findEndOfZipEntryTable (*in, numEntries);
  8500. if (pos >= 0 && pos < in->getTotalLength())
  8501. {
  8502. const int size = (int) (in->getTotalLength() - pos);
  8503. in->setPosition (pos);
  8504. MemoryBlock headerData;
  8505. if (in->readIntoMemoryBlock (headerData, size) == size)
  8506. {
  8507. pos = 0;
  8508. for (int i = 0; i < numEntries; ++i)
  8509. {
  8510. if (pos + 46 > size)
  8511. break;
  8512. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8513. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8514. if (pos + 46 + fileNameLen > size)
  8515. break;
  8516. ZipEntryInfo* const zei = new ZipEntryInfo();
  8517. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8518. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8519. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8520. const int year = 1980 + (date >> 9);
  8521. const int month = ((date >> 5) & 15) - 1;
  8522. const int day = date & 31;
  8523. const int hours = time >> 11;
  8524. const int minutes = (time >> 5) & 63;
  8525. const int seconds = (time & 31) << 1;
  8526. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8527. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8528. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8529. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8530. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8531. entries.add (zei);
  8532. pos += 46 + fileNameLen
  8533. + ByteOrder::littleEndianShort (buffer + 30)
  8534. + ByteOrder::littleEndianShort (buffer + 32);
  8535. }
  8536. }
  8537. }
  8538. }
  8539. }
  8540. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8541. {
  8542. BufferedInputStream in (input, 8192);
  8543. in.setPosition (in.getTotalLength());
  8544. int64 pos = in.getPosition();
  8545. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8546. char buffer [32];
  8547. zeromem (buffer, sizeof (buffer));
  8548. while (pos > lowestPos)
  8549. {
  8550. in.setPosition (pos - 22);
  8551. pos = in.getPosition();
  8552. memcpy (buffer + 22, buffer, 4);
  8553. if (in.read (buffer, 22) != 22)
  8554. return 0;
  8555. for (int i = 0; i < 22; ++i)
  8556. {
  8557. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8558. {
  8559. in.setPosition (pos + i);
  8560. in.read (buffer, 22);
  8561. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8562. return ByteOrder::littleEndianInt (buffer + 16);
  8563. }
  8564. }
  8565. }
  8566. return 0;
  8567. }
  8568. bool ZipFile::uncompressTo (const File& targetDirectory,
  8569. const bool shouldOverwriteFiles)
  8570. {
  8571. for (int i = 0; i < entries.size(); ++i)
  8572. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8573. return false;
  8574. return true;
  8575. }
  8576. bool ZipFile::uncompressEntry (const int index,
  8577. const File& targetDirectory,
  8578. bool shouldOverwriteFiles)
  8579. {
  8580. const ZipEntryInfo* zei = entries [index];
  8581. if (zei != 0)
  8582. {
  8583. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8584. if (zei->entry.filename.endsWithChar ('/'))
  8585. {
  8586. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8587. }
  8588. else
  8589. {
  8590. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8591. if (in != 0)
  8592. {
  8593. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8594. return false;
  8595. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8596. {
  8597. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8598. if (out != 0)
  8599. {
  8600. out->writeFromInputStream (*in, -1);
  8601. out = 0;
  8602. targetFile.setCreationTime (zei->entry.fileTime);
  8603. targetFile.setLastModificationTime (zei->entry.fileTime);
  8604. targetFile.setLastAccessTime (zei->entry.fileTime);
  8605. return true;
  8606. }
  8607. }
  8608. }
  8609. }
  8610. }
  8611. return false;
  8612. }
  8613. END_JUCE_NAMESPACE
  8614. /*** End of inlined file: juce_ZipFile.cpp ***/
  8615. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8616. #if JUCE_MSVC
  8617. #pragma warning (push)
  8618. #pragma warning (disable: 4514 4996)
  8619. #endif
  8620. #include <cwctype>
  8621. #include <cctype>
  8622. #include <ctime>
  8623. BEGIN_JUCE_NAMESPACE
  8624. int CharacterFunctions::length (const char* const s) throw()
  8625. {
  8626. return (int) strlen (s);
  8627. }
  8628. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8629. {
  8630. return (int) wcslen (s);
  8631. }
  8632. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8633. {
  8634. strncpy (dest, src, maxChars);
  8635. }
  8636. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8637. {
  8638. wcsncpy (dest, src, maxChars);
  8639. }
  8640. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8641. {
  8642. mbstowcs (dest, src, maxChars);
  8643. }
  8644. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8645. {
  8646. wcstombs (dest, src, maxChars);
  8647. }
  8648. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8649. {
  8650. return (int) wcstombs (0, src, 0);
  8651. }
  8652. void CharacterFunctions::append (char* dest, const char* src) throw()
  8653. {
  8654. strcat (dest, src);
  8655. }
  8656. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8657. {
  8658. wcscat (dest, src);
  8659. }
  8660. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8661. {
  8662. return strcmp (s1, s2);
  8663. }
  8664. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8665. {
  8666. jassert (s1 != 0 && s2 != 0);
  8667. return wcscmp (s1, s2);
  8668. }
  8669. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8670. {
  8671. jassert (s1 != 0 && s2 != 0);
  8672. return strncmp (s1, s2, maxChars);
  8673. }
  8674. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8675. {
  8676. jassert (s1 != 0 && s2 != 0);
  8677. return wcsncmp (s1, s2, maxChars);
  8678. }
  8679. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8680. {
  8681. jassert (s1 != 0 && s2 != 0);
  8682. for (;;)
  8683. {
  8684. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8685. if (diff != 0)
  8686. return diff;
  8687. else if (*s1 == 0)
  8688. break;
  8689. ++s1;
  8690. ++s2;
  8691. }
  8692. return 0;
  8693. }
  8694. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8695. {
  8696. return -compare (s2, s1);
  8697. }
  8698. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8699. {
  8700. jassert (s1 != 0 && s2 != 0);
  8701. #if JUCE_WINDOWS
  8702. return stricmp (s1, s2);
  8703. #else
  8704. return strcasecmp (s1, s2);
  8705. #endif
  8706. }
  8707. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8708. {
  8709. jassert (s1 != 0 && s2 != 0);
  8710. #if JUCE_WINDOWS
  8711. return _wcsicmp (s1, s2);
  8712. #else
  8713. for (;;)
  8714. {
  8715. if (*s1 != *s2)
  8716. {
  8717. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8718. if (diff != 0)
  8719. return diff < 0 ? -1 : 1;
  8720. }
  8721. else if (*s1 == 0)
  8722. break;
  8723. ++s1;
  8724. ++s2;
  8725. }
  8726. return 0;
  8727. #endif
  8728. }
  8729. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8730. {
  8731. jassert (s1 != 0 && s2 != 0);
  8732. for (;;)
  8733. {
  8734. if (*s1 != *s2)
  8735. {
  8736. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8737. if (diff != 0)
  8738. return diff < 0 ? -1 : 1;
  8739. }
  8740. else if (*s1 == 0)
  8741. break;
  8742. ++s1;
  8743. ++s2;
  8744. }
  8745. return 0;
  8746. }
  8747. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8748. {
  8749. jassert (s1 != 0 && s2 != 0);
  8750. #if JUCE_WINDOWS
  8751. return strnicmp (s1, s2, maxChars);
  8752. #else
  8753. return strncasecmp (s1, s2, maxChars);
  8754. #endif
  8755. }
  8756. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8757. {
  8758. jassert (s1 != 0 && s2 != 0);
  8759. #if JUCE_WINDOWS
  8760. return _wcsnicmp (s1, s2, maxChars);
  8761. #else
  8762. while (--maxChars >= 0)
  8763. {
  8764. if (*s1 != *s2)
  8765. {
  8766. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8767. if (diff != 0)
  8768. return diff < 0 ? -1 : 1;
  8769. }
  8770. else if (*s1 == 0)
  8771. break;
  8772. ++s1;
  8773. ++s2;
  8774. }
  8775. return 0;
  8776. #endif
  8777. }
  8778. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8779. {
  8780. return strstr (haystack, needle);
  8781. }
  8782. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8783. {
  8784. return wcsstr (haystack, needle);
  8785. }
  8786. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8787. {
  8788. if (haystack != 0)
  8789. {
  8790. int i = 0;
  8791. if (ignoreCase)
  8792. {
  8793. const char n1 = toLowerCase (needle);
  8794. const char n2 = toUpperCase (needle);
  8795. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8796. {
  8797. while (haystack[i] != 0)
  8798. {
  8799. if (haystack[i] == n1 || haystack[i] == n2)
  8800. return i;
  8801. ++i;
  8802. }
  8803. return -1;
  8804. }
  8805. jassert (n1 == needle);
  8806. }
  8807. while (haystack[i] != 0)
  8808. {
  8809. if (haystack[i] == needle)
  8810. return i;
  8811. ++i;
  8812. }
  8813. }
  8814. return -1;
  8815. }
  8816. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8817. {
  8818. if (haystack != 0)
  8819. {
  8820. int i = 0;
  8821. if (ignoreCase)
  8822. {
  8823. const juce_wchar n1 = toLowerCase (needle);
  8824. const juce_wchar n2 = toUpperCase (needle);
  8825. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8826. {
  8827. while (haystack[i] != 0)
  8828. {
  8829. if (haystack[i] == n1 || haystack[i] == n2)
  8830. return i;
  8831. ++i;
  8832. }
  8833. return -1;
  8834. }
  8835. jassert (n1 == needle);
  8836. }
  8837. while (haystack[i] != 0)
  8838. {
  8839. if (haystack[i] == needle)
  8840. return i;
  8841. ++i;
  8842. }
  8843. }
  8844. return -1;
  8845. }
  8846. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8847. {
  8848. jassert (haystack != 0);
  8849. int i = 0;
  8850. while (haystack[i] != 0)
  8851. {
  8852. if (haystack[i] == needle)
  8853. return i;
  8854. ++i;
  8855. }
  8856. return -1;
  8857. }
  8858. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8859. {
  8860. jassert (haystack != 0);
  8861. int i = 0;
  8862. while (haystack[i] != 0)
  8863. {
  8864. if (haystack[i] == needle)
  8865. return i;
  8866. ++i;
  8867. }
  8868. return -1;
  8869. }
  8870. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8871. {
  8872. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8873. }
  8874. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8875. {
  8876. if (allowedChars == 0)
  8877. return 0;
  8878. int i = 0;
  8879. for (;;)
  8880. {
  8881. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8882. break;
  8883. ++i;
  8884. }
  8885. return i;
  8886. }
  8887. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8888. {
  8889. return (int) strftime (dest, maxChars, format, tm);
  8890. }
  8891. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8892. {
  8893. return (int) wcsftime (dest, maxChars, format, tm);
  8894. }
  8895. int CharacterFunctions::getIntValue (const char* const s) throw()
  8896. {
  8897. return atoi (s);
  8898. }
  8899. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8900. {
  8901. #if JUCE_WINDOWS
  8902. return _wtoi (s);
  8903. #else
  8904. int v = 0;
  8905. while (isWhitespace (*s))
  8906. ++s;
  8907. const bool isNeg = *s == '-';
  8908. if (isNeg)
  8909. ++s;
  8910. for (;;)
  8911. {
  8912. const wchar_t c = *s++;
  8913. if (c >= '0' && c <= '9')
  8914. v = v * 10 + (int) (c - '0');
  8915. else
  8916. break;
  8917. }
  8918. return isNeg ? -v : v;
  8919. #endif
  8920. }
  8921. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8922. {
  8923. #if JUCE_LINUX
  8924. return atoll (s);
  8925. #elif JUCE_WINDOWS
  8926. return _atoi64 (s);
  8927. #else
  8928. int64 v = 0;
  8929. while (isWhitespace (*s))
  8930. ++s;
  8931. const bool isNeg = *s == '-';
  8932. if (isNeg)
  8933. ++s;
  8934. for (;;)
  8935. {
  8936. const char c = *s++;
  8937. if (c >= '0' && c <= '9')
  8938. v = v * 10 + (int64) (c - '0');
  8939. else
  8940. break;
  8941. }
  8942. return isNeg ? -v : v;
  8943. #endif
  8944. }
  8945. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8946. {
  8947. #if JUCE_WINDOWS
  8948. return _wtoi64 (s);
  8949. #else
  8950. int64 v = 0;
  8951. while (isWhitespace (*s))
  8952. ++s;
  8953. const bool isNeg = *s == '-';
  8954. if (isNeg)
  8955. ++s;
  8956. for (;;)
  8957. {
  8958. const juce_wchar c = *s++;
  8959. if (c >= '0' && c <= '9')
  8960. v = v * 10 + (int64) (c - '0');
  8961. else
  8962. break;
  8963. }
  8964. return isNeg ? -v : v;
  8965. #endif
  8966. }
  8967. namespace
  8968. {
  8969. double juce_mulexp10 (const double value, int exponent) throw()
  8970. {
  8971. if (exponent == 0)
  8972. return value;
  8973. if (value == 0)
  8974. return 0;
  8975. const bool negative = (exponent < 0);
  8976. if (negative)
  8977. exponent = -exponent;
  8978. double result = 1.0, power = 10.0;
  8979. for (int bit = 1; exponent != 0; bit <<= 1)
  8980. {
  8981. if ((exponent & bit) != 0)
  8982. {
  8983. exponent ^= bit;
  8984. result *= power;
  8985. if (exponent == 0)
  8986. break;
  8987. }
  8988. power *= power;
  8989. }
  8990. return negative ? (value / result) : (value * result);
  8991. }
  8992. template <class CharType>
  8993. double juce_atof (const CharType* const original) throw()
  8994. {
  8995. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8996. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8997. int exponent = 0, decPointIndex = 0, digit = 0;
  8998. int lastDigit = 0, numSignificantDigits = 0;
  8999. bool isNegative = false, digitsFound = false;
  9000. const int maxSignificantDigits = 15 + 2;
  9001. const CharType* s = original;
  9002. while (CharacterFunctions::isWhitespace (*s))
  9003. ++s;
  9004. switch (*s)
  9005. {
  9006. case '-': isNegative = true; // fall-through..
  9007. case '+': ++s;
  9008. }
  9009. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9010. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9011. for (;;)
  9012. {
  9013. if (CharacterFunctions::isDigit (*s))
  9014. {
  9015. lastDigit = digit;
  9016. digit = *s++ - '0';
  9017. digitsFound = true;
  9018. if (decPointIndex != 0)
  9019. exponentAdjustment[1]++;
  9020. if (numSignificantDigits == 0 && digit == 0)
  9021. continue;
  9022. if (++numSignificantDigits > maxSignificantDigits)
  9023. {
  9024. if (digit > 5)
  9025. ++accumulator [decPointIndex];
  9026. else if (digit == 5 && (lastDigit & 1) != 0)
  9027. ++accumulator [decPointIndex];
  9028. if (decPointIndex > 0)
  9029. exponentAdjustment[1]--;
  9030. else
  9031. exponentAdjustment[0]++;
  9032. while (CharacterFunctions::isDigit (*s))
  9033. {
  9034. ++s;
  9035. if (decPointIndex == 0)
  9036. exponentAdjustment[0]++;
  9037. }
  9038. }
  9039. else
  9040. {
  9041. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9042. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9043. {
  9044. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9045. + accumulator [decPointIndex];
  9046. accumulator [decPointIndex] = 0;
  9047. exponentAccumulator [decPointIndex] = 0;
  9048. }
  9049. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9050. exponentAccumulator [decPointIndex]++;
  9051. }
  9052. }
  9053. else if (decPointIndex == 0 && *s == '.')
  9054. {
  9055. ++s;
  9056. decPointIndex = 1;
  9057. if (numSignificantDigits > maxSignificantDigits)
  9058. {
  9059. while (CharacterFunctions::isDigit (*s))
  9060. ++s;
  9061. break;
  9062. }
  9063. }
  9064. else
  9065. {
  9066. break;
  9067. }
  9068. }
  9069. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9070. if (decPointIndex != 0)
  9071. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9072. if ((*s == 'e' || *s == 'E') && digitsFound)
  9073. {
  9074. bool negativeExponent = false;
  9075. switch (*++s)
  9076. {
  9077. case '-': negativeExponent = true; // fall-through..
  9078. case '+': ++s;
  9079. }
  9080. while (CharacterFunctions::isDigit (*s))
  9081. exponent = (exponent * 10) + (*s++ - '0');
  9082. if (negativeExponent)
  9083. exponent = -exponent;
  9084. }
  9085. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9086. if (decPointIndex != 0)
  9087. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9088. return isNegative ? -r : r;
  9089. }
  9090. }
  9091. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9092. {
  9093. return juce_atof <char> (s);
  9094. }
  9095. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9096. {
  9097. return juce_atof <juce_wchar> (s);
  9098. }
  9099. char CharacterFunctions::toUpperCase (const char character) throw()
  9100. {
  9101. return (char) toupper (character);
  9102. }
  9103. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9104. {
  9105. return towupper (character);
  9106. }
  9107. void CharacterFunctions::toUpperCase (char* s) throw()
  9108. {
  9109. #if JUCE_WINDOWS
  9110. strupr (s);
  9111. #else
  9112. while (*s != 0)
  9113. {
  9114. *s = toUpperCase (*s);
  9115. ++s;
  9116. }
  9117. #endif
  9118. }
  9119. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9120. {
  9121. #if JUCE_WINDOWS
  9122. _wcsupr (s);
  9123. #else
  9124. while (*s != 0)
  9125. {
  9126. *s = toUpperCase (*s);
  9127. ++s;
  9128. }
  9129. #endif
  9130. }
  9131. bool CharacterFunctions::isUpperCase (const char character) throw()
  9132. {
  9133. return isupper (character) != 0;
  9134. }
  9135. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9136. {
  9137. #if JUCE_WINDOWS
  9138. return iswupper (character) != 0;
  9139. #else
  9140. return toLowerCase (character) != character;
  9141. #endif
  9142. }
  9143. char CharacterFunctions::toLowerCase (const char character) throw()
  9144. {
  9145. return (char) tolower (character);
  9146. }
  9147. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9148. {
  9149. return towlower (character);
  9150. }
  9151. void CharacterFunctions::toLowerCase (char* s) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. strlwr (s);
  9155. #else
  9156. while (*s != 0)
  9157. {
  9158. *s = toLowerCase (*s);
  9159. ++s;
  9160. }
  9161. #endif
  9162. }
  9163. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9164. {
  9165. #if JUCE_WINDOWS
  9166. _wcslwr (s);
  9167. #else
  9168. while (*s != 0)
  9169. {
  9170. *s = toLowerCase (*s);
  9171. ++s;
  9172. }
  9173. #endif
  9174. }
  9175. bool CharacterFunctions::isLowerCase (const char character) throw()
  9176. {
  9177. return islower (character) != 0;
  9178. }
  9179. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9180. {
  9181. #if JUCE_WINDOWS
  9182. return iswlower (character) != 0;
  9183. #else
  9184. return toUpperCase (character) != character;
  9185. #endif
  9186. }
  9187. bool CharacterFunctions::isWhitespace (const char character) throw()
  9188. {
  9189. return character == ' ' || (character <= 13 && character >= 9);
  9190. }
  9191. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9192. {
  9193. return iswspace (character) != 0;
  9194. }
  9195. bool CharacterFunctions::isDigit (const char character) throw()
  9196. {
  9197. return (character >= '0' && character <= '9');
  9198. }
  9199. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9200. {
  9201. return iswdigit (character) != 0;
  9202. }
  9203. bool CharacterFunctions::isLetter (const char character) throw()
  9204. {
  9205. return (character >= 'a' && character <= 'z')
  9206. || (character >= 'A' && character <= 'Z');
  9207. }
  9208. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9209. {
  9210. return iswalpha (character) != 0;
  9211. }
  9212. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9213. {
  9214. return (character >= 'a' && character <= 'z')
  9215. || (character >= 'A' && character <= 'Z')
  9216. || (character >= '0' && character <= '9');
  9217. }
  9218. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9219. {
  9220. return iswalnum (character) != 0;
  9221. }
  9222. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9223. {
  9224. unsigned int d = digit - '0';
  9225. if (d < (unsigned int) 10)
  9226. return (int) d;
  9227. d += (unsigned int) ('0' - 'a');
  9228. if (d < (unsigned int) 6)
  9229. return (int) d + 10;
  9230. d += (unsigned int) ('a' - 'A');
  9231. if (d < (unsigned int) 6)
  9232. return (int) d + 10;
  9233. return -1;
  9234. }
  9235. #if JUCE_MSVC
  9236. #pragma warning (pop)
  9237. #endif
  9238. END_JUCE_NAMESPACE
  9239. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9240. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9241. BEGIN_JUCE_NAMESPACE
  9242. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9243. {
  9244. loadFromText (fileContents);
  9245. }
  9246. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9247. {
  9248. loadFromText (fileToLoad.loadFileAsString());
  9249. }
  9250. LocalisedStrings::~LocalisedStrings()
  9251. {
  9252. }
  9253. const String LocalisedStrings::translate (const String& text) const
  9254. {
  9255. return translations.getValue (text, text);
  9256. }
  9257. namespace
  9258. {
  9259. CriticalSection currentMappingsLock;
  9260. LocalisedStrings* currentMappings = 0;
  9261. int findCloseQuote (const String& text, int startPos)
  9262. {
  9263. juce_wchar lastChar = 0;
  9264. for (;;)
  9265. {
  9266. const juce_wchar c = text [startPos];
  9267. if (c == 0 || (c == '"' && lastChar != '\\'))
  9268. break;
  9269. lastChar = c;
  9270. ++startPos;
  9271. }
  9272. return startPos;
  9273. }
  9274. const String unescapeString (const String& s)
  9275. {
  9276. return s.replace ("\\\"", "\"")
  9277. .replace ("\\\'", "\'")
  9278. .replace ("\\t", "\t")
  9279. .replace ("\\r", "\r")
  9280. .replace ("\\n", "\n");
  9281. }
  9282. }
  9283. void LocalisedStrings::loadFromText (const String& fileContents)
  9284. {
  9285. StringArray lines;
  9286. lines.addLines (fileContents);
  9287. for (int i = 0; i < lines.size(); ++i)
  9288. {
  9289. String line (lines[i].trim());
  9290. if (line.startsWithChar ('"'))
  9291. {
  9292. int closeQuote = findCloseQuote (line, 1);
  9293. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9294. if (originalText.isNotEmpty())
  9295. {
  9296. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9297. closeQuote = findCloseQuote (line, openingQuote + 1);
  9298. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9299. if (newText.isNotEmpty())
  9300. translations.set (originalText, newText);
  9301. }
  9302. }
  9303. else if (line.startsWithIgnoreCase ("language:"))
  9304. {
  9305. languageName = line.substring (9).trim();
  9306. }
  9307. else if (line.startsWithIgnoreCase ("countries:"))
  9308. {
  9309. countryCodes.addTokens (line.substring (10).trim(), true);
  9310. countryCodes.trim();
  9311. countryCodes.removeEmptyStrings();
  9312. }
  9313. }
  9314. }
  9315. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9316. {
  9317. translations.setIgnoresCase (shouldIgnoreCase);
  9318. }
  9319. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9320. {
  9321. const ScopedLock sl (currentMappingsLock);
  9322. delete currentMappings;
  9323. currentMappings = newTranslations;
  9324. }
  9325. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9326. {
  9327. return currentMappings;
  9328. }
  9329. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9330. {
  9331. const ScopedLock sl (currentMappingsLock);
  9332. if (currentMappings != 0)
  9333. return currentMappings->translate (text);
  9334. return text;
  9335. }
  9336. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9337. {
  9338. return translateWithCurrentMappings (String (text));
  9339. }
  9340. END_JUCE_NAMESPACE
  9341. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9342. /*** Start of inlined file: juce_String.cpp ***/
  9343. #if JUCE_MSVC
  9344. #pragma warning (push)
  9345. #pragma warning (disable: 4514)
  9346. #endif
  9347. #include <locale>
  9348. BEGIN_JUCE_NAMESPACE
  9349. #if JUCE_MSVC
  9350. #pragma warning (pop)
  9351. #endif
  9352. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9353. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9354. #endif
  9355. class StringHolder
  9356. {
  9357. public:
  9358. StringHolder()
  9359. : refCount (0x3fffffff), allocatedNumChars (0)
  9360. {
  9361. text[0] = 0;
  9362. }
  9363. static juce_wchar* createUninitialised (const size_t numChars)
  9364. {
  9365. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9366. s->refCount.value = 0;
  9367. s->allocatedNumChars = numChars;
  9368. return &(s->text[0]);
  9369. }
  9370. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9371. {
  9372. juce_wchar* const dest = createUninitialised (numChars);
  9373. copyChars (dest, src, numChars);
  9374. return dest;
  9375. }
  9376. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9377. {
  9378. juce_wchar* const dest = createUninitialised (numChars);
  9379. CharacterFunctions::copy (dest, src, (int) numChars);
  9380. dest [numChars] = 0;
  9381. return dest;
  9382. }
  9383. static inline juce_wchar* getEmpty() throw()
  9384. {
  9385. return &(empty.text[0]);
  9386. }
  9387. static void retain (juce_wchar* const text) throw()
  9388. {
  9389. ++(bufferFromText (text)->refCount);
  9390. }
  9391. static inline void release (StringHolder* const b) throw()
  9392. {
  9393. if (--(b->refCount) == -1 && b != &empty)
  9394. delete[] reinterpret_cast <char*> (b);
  9395. }
  9396. static void release (juce_wchar* const text) throw()
  9397. {
  9398. release (bufferFromText (text));
  9399. }
  9400. static juce_wchar* makeUnique (juce_wchar* const text)
  9401. {
  9402. StringHolder* const b = bufferFromText (text);
  9403. if (b->refCount.get() <= 0)
  9404. return text;
  9405. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9406. release (b);
  9407. return newText;
  9408. }
  9409. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9410. {
  9411. StringHolder* const b = bufferFromText (text);
  9412. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9413. return text;
  9414. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9415. copyChars (newText, text, b->allocatedNumChars);
  9416. release (b);
  9417. return newText;
  9418. }
  9419. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9420. {
  9421. return bufferFromText (text)->allocatedNumChars;
  9422. }
  9423. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9424. {
  9425. jassert (src != 0 && dest != 0);
  9426. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9427. dest [numChars] = 0;
  9428. }
  9429. Atomic<int> refCount;
  9430. size_t allocatedNumChars;
  9431. juce_wchar text[1];
  9432. static StringHolder empty;
  9433. private:
  9434. static inline StringHolder* bufferFromText (void* const text) throw()
  9435. {
  9436. // (Can't use offsetof() here because of warnings about this not being a POD)
  9437. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9438. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9439. }
  9440. };
  9441. StringHolder StringHolder::empty;
  9442. const String String::empty;
  9443. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9444. {
  9445. jassert (t[numChars] == 0); // must have a null terminator
  9446. text = StringHolder::createCopy (t, numChars);
  9447. }
  9448. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9449. {
  9450. if (numExtraChars > 0)
  9451. {
  9452. const int oldLen = length();
  9453. const int newTotalLen = oldLen + numExtraChars;
  9454. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9455. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9456. }
  9457. }
  9458. void String::preallocateStorage (const size_t numChars)
  9459. {
  9460. text = StringHolder::makeUniqueWithSize (text, numChars);
  9461. }
  9462. String::String() throw()
  9463. : text (StringHolder::getEmpty())
  9464. {
  9465. }
  9466. String::~String() throw()
  9467. {
  9468. StringHolder::release (text);
  9469. }
  9470. String::String (const String& other) throw()
  9471. : text (other.text)
  9472. {
  9473. StringHolder::retain (text);
  9474. }
  9475. void String::swapWith (String& other) throw()
  9476. {
  9477. swapVariables (text, other.text);
  9478. }
  9479. String& String::operator= (const String& other) throw()
  9480. {
  9481. juce_wchar* const newText = other.text;
  9482. StringHolder::retain (newText);
  9483. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>&> (text).exchange (newText));
  9484. return *this;
  9485. }
  9486. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9487. String::String (const Preallocation& preallocationSize)
  9488. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9489. {
  9490. }
  9491. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9492. {
  9493. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9494. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9495. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9496. }
  9497. String::String (const char* const t)
  9498. {
  9499. if (t != 0 && *t != 0)
  9500. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9501. else
  9502. text = StringHolder::getEmpty();
  9503. }
  9504. String::String (const juce_wchar* const t)
  9505. {
  9506. if (t != 0 && *t != 0)
  9507. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9508. else
  9509. text = StringHolder::getEmpty();
  9510. }
  9511. String::String (const char* const t, const size_t maxChars)
  9512. {
  9513. int i;
  9514. for (i = 0; (size_t) i < maxChars; ++i)
  9515. if (t[i] == 0)
  9516. break;
  9517. if (i > 0)
  9518. text = StringHolder::createCopy (t, i);
  9519. else
  9520. text = StringHolder::getEmpty();
  9521. }
  9522. String::String (const juce_wchar* const t, const size_t maxChars)
  9523. {
  9524. int i;
  9525. for (i = 0; (size_t) i < maxChars; ++i)
  9526. if (t[i] == 0)
  9527. break;
  9528. if (i > 0)
  9529. text = StringHolder::createCopy (t, i);
  9530. else
  9531. text = StringHolder::getEmpty();
  9532. }
  9533. const String String::charToString (const juce_wchar character)
  9534. {
  9535. String result (Preallocation (1));
  9536. result.text[0] = character;
  9537. result.text[1] = 0;
  9538. return result;
  9539. }
  9540. namespace NumberToStringConverters
  9541. {
  9542. // pass in a pointer to the END of a buffer..
  9543. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9544. {
  9545. *--t = 0;
  9546. int64 v = (n >= 0) ? n : -n;
  9547. do
  9548. {
  9549. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9550. v /= 10;
  9551. } while (v > 0);
  9552. if (n < 0)
  9553. *--t = '-';
  9554. return t;
  9555. }
  9556. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9557. {
  9558. *--t = 0;
  9559. do
  9560. {
  9561. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9562. v /= 10;
  9563. } while (v > 0);
  9564. return t;
  9565. }
  9566. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9567. {
  9568. if (n == (int) 0x80000000) // (would cause an overflow)
  9569. return int64ToString (t, n);
  9570. *--t = 0;
  9571. int v = abs (n);
  9572. do
  9573. {
  9574. *--t = (juce_wchar) ('0' + (v % 10));
  9575. v /= 10;
  9576. } while (v > 0);
  9577. if (n < 0)
  9578. *--t = '-';
  9579. return t;
  9580. }
  9581. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9582. {
  9583. *--t = 0;
  9584. do
  9585. {
  9586. *--t = (juce_wchar) ('0' + (v % 10));
  9587. v /= 10;
  9588. } while (v > 0);
  9589. return t;
  9590. }
  9591. juce_wchar getDecimalPoint()
  9592. {
  9593. #if JUCE_VC7_OR_EARLIER
  9594. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9595. #else
  9596. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9597. #endif
  9598. return dp;
  9599. }
  9600. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9601. {
  9602. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9603. {
  9604. juce_wchar* const end = buffer + numChars;
  9605. juce_wchar* t = end;
  9606. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9607. *--t = (juce_wchar) 0;
  9608. while (numDecPlaces >= 0 || v > 0)
  9609. {
  9610. if (numDecPlaces == 0)
  9611. *--t = getDecimalPoint();
  9612. *--t = (juce_wchar) ('0' + (v % 10));
  9613. v /= 10;
  9614. --numDecPlaces;
  9615. }
  9616. if (n < 0)
  9617. *--t = '-';
  9618. len = end - t - 1;
  9619. return t;
  9620. }
  9621. else
  9622. {
  9623. #if JUCE_WINDOWS
  9624. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9625. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9626. #else
  9627. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9628. #endif
  9629. #else
  9630. len = swprintf (buffer, numChars, L"%.9g", n);
  9631. #endif
  9632. return buffer;
  9633. }
  9634. }
  9635. }
  9636. String::String (const int number)
  9637. {
  9638. juce_wchar buffer [16];
  9639. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9640. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9641. createInternal (start, end - start - 1);
  9642. }
  9643. String::String (const unsigned int number)
  9644. {
  9645. juce_wchar buffer [16];
  9646. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9647. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9648. createInternal (start, end - start - 1);
  9649. }
  9650. String::String (const short number)
  9651. {
  9652. juce_wchar buffer [16];
  9653. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9654. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9655. createInternal (start, end - start - 1);
  9656. }
  9657. String::String (const unsigned short number)
  9658. {
  9659. juce_wchar buffer [16];
  9660. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9661. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9662. createInternal (start, end - start - 1);
  9663. }
  9664. String::String (const int64 number)
  9665. {
  9666. juce_wchar buffer [32];
  9667. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9668. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9669. createInternal (start, end - start - 1);
  9670. }
  9671. String::String (const uint64 number)
  9672. {
  9673. juce_wchar buffer [32];
  9674. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9675. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9676. createInternal (start, end - start - 1);
  9677. }
  9678. String::String (const float number, const int numberOfDecimalPlaces)
  9679. {
  9680. juce_wchar buffer [48];
  9681. size_t len;
  9682. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9683. createInternal (start, len);
  9684. }
  9685. String::String (const double number, const int numberOfDecimalPlaces)
  9686. {
  9687. juce_wchar buffer [48];
  9688. size_t len;
  9689. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9690. createInternal (start, len);
  9691. }
  9692. int String::length() const throw()
  9693. {
  9694. return CharacterFunctions::length (text);
  9695. }
  9696. int String::hashCode() const throw()
  9697. {
  9698. const juce_wchar* t = text;
  9699. int result = 0;
  9700. while (*t != (juce_wchar) 0)
  9701. result = 31 * result + *t++;
  9702. return result;
  9703. }
  9704. int64 String::hashCode64() const throw()
  9705. {
  9706. const juce_wchar* t = text;
  9707. int64 result = 0;
  9708. while (*t != (juce_wchar) 0)
  9709. result = 101 * result + *t++;
  9710. return result;
  9711. }
  9712. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9713. {
  9714. return string1.compare (string2) == 0;
  9715. }
  9716. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9717. {
  9718. return string1.compare (string2) == 0;
  9719. }
  9720. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9721. {
  9722. return string1.compare (string2) == 0;
  9723. }
  9724. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9725. {
  9726. return string1.compare (string2) != 0;
  9727. }
  9728. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9729. {
  9730. return string1.compare (string2) != 0;
  9731. }
  9732. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9733. {
  9734. return string1.compare (string2) != 0;
  9735. }
  9736. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9737. {
  9738. return string1.compare (string2) > 0;
  9739. }
  9740. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9741. {
  9742. return string1.compare (string2) < 0;
  9743. }
  9744. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9745. {
  9746. return string1.compare (string2) >= 0;
  9747. }
  9748. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9749. {
  9750. return string1.compare (string2) <= 0;
  9751. }
  9752. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9753. {
  9754. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9755. : isEmpty();
  9756. }
  9757. bool String::equalsIgnoreCase (const char* t) const throw()
  9758. {
  9759. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9760. : isEmpty();
  9761. }
  9762. bool String::equalsIgnoreCase (const String& other) const throw()
  9763. {
  9764. return text == other.text
  9765. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9766. }
  9767. int String::compare (const String& other) const throw()
  9768. {
  9769. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9770. }
  9771. int String::compare (const char* other) const throw()
  9772. {
  9773. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9774. }
  9775. int String::compare (const juce_wchar* other) const throw()
  9776. {
  9777. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9778. }
  9779. int String::compareIgnoreCase (const String& other) const throw()
  9780. {
  9781. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9782. }
  9783. int String::compareLexicographically (const String& other) const throw()
  9784. {
  9785. const juce_wchar* s1 = text;
  9786. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9787. ++s1;
  9788. const juce_wchar* s2 = other.text;
  9789. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9790. ++s2;
  9791. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9792. }
  9793. String& String::operator+= (const juce_wchar* const t)
  9794. {
  9795. if (t != 0)
  9796. appendInternal (t, CharacterFunctions::length (t));
  9797. return *this;
  9798. }
  9799. String& String::operator+= (const String& other)
  9800. {
  9801. if (isEmpty())
  9802. operator= (other);
  9803. else
  9804. appendInternal (other.text, other.length());
  9805. return *this;
  9806. }
  9807. String& String::operator+= (const char ch)
  9808. {
  9809. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9810. return operator+= (static_cast <const juce_wchar*> (asString));
  9811. }
  9812. String& String::operator+= (const juce_wchar ch)
  9813. {
  9814. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9815. return operator+= (static_cast <const juce_wchar*> (asString));
  9816. }
  9817. String& String::operator+= (const int number)
  9818. {
  9819. juce_wchar buffer [16];
  9820. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9821. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9822. appendInternal (start, (int) (end - start));
  9823. return *this;
  9824. }
  9825. String& String::operator+= (const unsigned int number)
  9826. {
  9827. juce_wchar buffer [16];
  9828. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9829. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9830. appendInternal (start, (int) (end - start));
  9831. return *this;
  9832. }
  9833. void String::append (const juce_wchar* const other, const int howMany)
  9834. {
  9835. if (howMany > 0)
  9836. {
  9837. int i;
  9838. for (i = 0; i < howMany; ++i)
  9839. if (other[i] == 0)
  9840. break;
  9841. appendInternal (other, i);
  9842. }
  9843. }
  9844. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9845. {
  9846. String s (string1);
  9847. return s += string2;
  9848. }
  9849. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9850. {
  9851. String s (string1);
  9852. return s += string2;
  9853. }
  9854. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9855. {
  9856. return String::charToString (string1) + string2;
  9857. }
  9858. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9859. {
  9860. return String::charToString (string1) + string2;
  9861. }
  9862. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9863. {
  9864. return string1 += string2;
  9865. }
  9866. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9867. {
  9868. return string1 += string2;
  9869. }
  9870. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9871. {
  9872. return string1 += string2;
  9873. }
  9874. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9875. {
  9876. return string1 += string2;
  9877. }
  9878. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9879. {
  9880. return string1 += string2;
  9881. }
  9882. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9883. {
  9884. return string1 += characterToAppend;
  9885. }
  9886. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9887. {
  9888. return string1 += characterToAppend;
  9889. }
  9890. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9891. {
  9892. return string1 += string2;
  9893. }
  9894. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9895. {
  9896. return string1 += string2;
  9897. }
  9898. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9899. {
  9900. return string1 += string2;
  9901. }
  9902. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9903. {
  9904. return string1 += (int) number;
  9905. }
  9906. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9907. {
  9908. return string1 += number;
  9909. }
  9910. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9911. {
  9912. return string1 += number;
  9913. }
  9914. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9915. {
  9916. return string1 += (int) number;
  9917. }
  9918. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9919. {
  9920. return string1 += (unsigned int) number;
  9921. }
  9922. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9923. {
  9924. return string1 += String (number);
  9925. }
  9926. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9927. {
  9928. return string1 += String (number);
  9929. }
  9930. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9931. {
  9932. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9933. // if lots of large, persistent strings were to be written to streams).
  9934. const int numBytes = text.getNumBytesAsUTF8();
  9935. HeapBlock<char> temp (numBytes + 1);
  9936. text.copyToUTF8 (temp, numBytes + 1);
  9937. stream.write (temp, numBytes);
  9938. return stream;
  9939. }
  9940. int String::indexOfChar (const juce_wchar character) const throw()
  9941. {
  9942. const juce_wchar* t = text;
  9943. for (;;)
  9944. {
  9945. if (*t == character)
  9946. return (int) (t - text);
  9947. if (*t++ == 0)
  9948. return -1;
  9949. }
  9950. }
  9951. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9952. {
  9953. for (int i = length(); --i >= 0;)
  9954. if (text[i] == character)
  9955. return i;
  9956. return -1;
  9957. }
  9958. int String::indexOf (const String& t) const throw()
  9959. {
  9960. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9961. return r == 0 ? -1 : (int) (r - text);
  9962. }
  9963. int String::indexOfChar (const int startIndex,
  9964. const juce_wchar character) const throw()
  9965. {
  9966. if (startIndex > 0 && startIndex >= length())
  9967. return -1;
  9968. const juce_wchar* t = text + jmax (0, startIndex);
  9969. for (;;)
  9970. {
  9971. if (*t == character)
  9972. return (int) (t - text);
  9973. if (*t == 0)
  9974. return -1;
  9975. ++t;
  9976. }
  9977. }
  9978. int String::indexOfAnyOf (const String& charactersToLookFor,
  9979. const int startIndex,
  9980. const bool ignoreCase) const throw()
  9981. {
  9982. if (startIndex > 0 && startIndex >= length())
  9983. return -1;
  9984. const juce_wchar* t = text + jmax (0, startIndex);
  9985. while (*t != 0)
  9986. {
  9987. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9988. return (int) (t - text);
  9989. ++t;
  9990. }
  9991. return -1;
  9992. }
  9993. int String::indexOf (const int startIndex, const String& other) const throw()
  9994. {
  9995. if (startIndex > 0 && startIndex >= length())
  9996. return -1;
  9997. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9998. return found == 0 ? -1 : (int) (found - text);
  9999. }
  10000. int String::indexOfIgnoreCase (const String& other) const throw()
  10001. {
  10002. if (other.isNotEmpty())
  10003. {
  10004. const int len = other.length();
  10005. const int end = length() - len;
  10006. for (int i = 0; i <= end; ++i)
  10007. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10008. return i;
  10009. }
  10010. return -1;
  10011. }
  10012. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10013. {
  10014. if (other.isNotEmpty())
  10015. {
  10016. const int len = other.length();
  10017. const int end = length() - len;
  10018. for (int i = jmax (0, startIndex); i <= end; ++i)
  10019. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10020. return i;
  10021. }
  10022. return -1;
  10023. }
  10024. int String::lastIndexOf (const String& other) const throw()
  10025. {
  10026. if (other.isNotEmpty())
  10027. {
  10028. const int len = other.length();
  10029. int i = length() - len;
  10030. if (i >= 0)
  10031. {
  10032. const juce_wchar* n = text + i;
  10033. while (i >= 0)
  10034. {
  10035. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10036. return i;
  10037. --i;
  10038. }
  10039. }
  10040. }
  10041. return -1;
  10042. }
  10043. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10044. {
  10045. if (other.isNotEmpty())
  10046. {
  10047. const int len = other.length();
  10048. int i = length() - len;
  10049. if (i >= 0)
  10050. {
  10051. const juce_wchar* n = text + i;
  10052. while (i >= 0)
  10053. {
  10054. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10055. return i;
  10056. --i;
  10057. }
  10058. }
  10059. }
  10060. return -1;
  10061. }
  10062. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10063. {
  10064. for (int i = length(); --i >= 0;)
  10065. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10066. return i;
  10067. return -1;
  10068. }
  10069. bool String::contains (const String& other) const throw()
  10070. {
  10071. return indexOf (other) >= 0;
  10072. }
  10073. bool String::containsChar (const juce_wchar character) const throw()
  10074. {
  10075. const juce_wchar* t = text;
  10076. for (;;)
  10077. {
  10078. if (*t == 0)
  10079. return false;
  10080. if (*t == character)
  10081. return true;
  10082. ++t;
  10083. }
  10084. }
  10085. bool String::containsIgnoreCase (const String& t) const throw()
  10086. {
  10087. return indexOfIgnoreCase (t) >= 0;
  10088. }
  10089. int String::indexOfWholeWord (const String& word) const throw()
  10090. {
  10091. if (word.isNotEmpty())
  10092. {
  10093. const int wordLen = word.length();
  10094. const int end = length() - wordLen;
  10095. const juce_wchar* t = text;
  10096. for (int i = 0; i <= end; ++i)
  10097. {
  10098. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10099. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10100. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10101. {
  10102. return i;
  10103. }
  10104. ++t;
  10105. }
  10106. }
  10107. return -1;
  10108. }
  10109. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10110. {
  10111. if (word.isNotEmpty())
  10112. {
  10113. const int wordLen = word.length();
  10114. const int end = length() - wordLen;
  10115. const juce_wchar* t = text;
  10116. for (int i = 0; i <= end; ++i)
  10117. {
  10118. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10119. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10120. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10121. {
  10122. return i;
  10123. }
  10124. ++t;
  10125. }
  10126. }
  10127. return -1;
  10128. }
  10129. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10130. {
  10131. return indexOfWholeWord (wordToLookFor) >= 0;
  10132. }
  10133. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10134. {
  10135. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10136. }
  10137. namespace WildCardHelpers
  10138. {
  10139. int indexOfMatch (const juce_wchar* const wildcard,
  10140. const juce_wchar* const test,
  10141. const bool ignoreCase) throw()
  10142. {
  10143. int start = 0;
  10144. while (test [start] != 0)
  10145. {
  10146. int i = 0;
  10147. for (;;)
  10148. {
  10149. const juce_wchar wc = wildcard [i];
  10150. const juce_wchar c = test [i + start];
  10151. if (wc == c
  10152. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10153. || (wc == '?' && c != 0))
  10154. {
  10155. if (wc == 0)
  10156. return start;
  10157. ++i;
  10158. }
  10159. else
  10160. {
  10161. if (wc == '*' && (wildcard [i + 1] == 0
  10162. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10163. {
  10164. return start;
  10165. }
  10166. break;
  10167. }
  10168. }
  10169. ++start;
  10170. }
  10171. return -1;
  10172. }
  10173. }
  10174. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10175. {
  10176. int i = 0;
  10177. for (;;)
  10178. {
  10179. const juce_wchar wc = wildcard.text [i];
  10180. const juce_wchar c = text [i];
  10181. if (wc == c
  10182. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10183. || (wc == '?' && c != 0))
  10184. {
  10185. if (wc == 0)
  10186. return true;
  10187. ++i;
  10188. }
  10189. else
  10190. {
  10191. return wc == '*' && (wildcard [i + 1] == 0
  10192. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10193. }
  10194. }
  10195. }
  10196. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10197. {
  10198. const int len = stringToRepeat.length();
  10199. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10200. juce_wchar* n = result.text;
  10201. *n = 0;
  10202. while (--numberOfTimesToRepeat >= 0)
  10203. {
  10204. StringHolder::copyChars (n, stringToRepeat.text, len);
  10205. n += len;
  10206. }
  10207. return result;
  10208. }
  10209. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10210. {
  10211. jassert (padCharacter != 0);
  10212. const int len = length();
  10213. if (len >= minimumLength || padCharacter == 0)
  10214. return *this;
  10215. String result (Preallocation (minimumLength + 1));
  10216. juce_wchar* n = result.text;
  10217. minimumLength -= len;
  10218. while (--minimumLength >= 0)
  10219. *n++ = padCharacter;
  10220. StringHolder::copyChars (n, text, len);
  10221. return result;
  10222. }
  10223. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10224. {
  10225. jassert (padCharacter != 0);
  10226. const int len = length();
  10227. if (len >= minimumLength || padCharacter == 0)
  10228. return *this;
  10229. String result (*this, (size_t) minimumLength);
  10230. juce_wchar* n = result.text + len;
  10231. minimumLength -= len;
  10232. while (--minimumLength >= 0)
  10233. *n++ = padCharacter;
  10234. *n = 0;
  10235. return result;
  10236. }
  10237. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10238. {
  10239. if (index < 0)
  10240. {
  10241. // a negative index to replace from?
  10242. jassertfalse;
  10243. index = 0;
  10244. }
  10245. if (numCharsToReplace < 0)
  10246. {
  10247. // replacing a negative number of characters?
  10248. numCharsToReplace = 0;
  10249. jassertfalse;
  10250. }
  10251. const int len = length();
  10252. if (index + numCharsToReplace > len)
  10253. {
  10254. if (index > len)
  10255. {
  10256. // replacing beyond the end of the string?
  10257. index = len;
  10258. jassertfalse;
  10259. }
  10260. numCharsToReplace = len - index;
  10261. }
  10262. const int newStringLen = stringToInsert.length();
  10263. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10264. if (newTotalLen <= 0)
  10265. return String::empty;
  10266. String result (Preallocation ((size_t) newTotalLen));
  10267. StringHolder::copyChars (result.text, text, index);
  10268. if (newStringLen > 0)
  10269. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10270. const int endStringLen = newTotalLen - (index + newStringLen);
  10271. if (endStringLen > 0)
  10272. StringHolder::copyChars (result.text + (index + newStringLen),
  10273. text + (index + numCharsToReplace),
  10274. endStringLen);
  10275. return result;
  10276. }
  10277. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10278. {
  10279. const int stringToReplaceLen = stringToReplace.length();
  10280. const int stringToInsertLen = stringToInsert.length();
  10281. int i = 0;
  10282. String result (*this);
  10283. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10284. : result.indexOf (i, stringToReplace))) >= 0)
  10285. {
  10286. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10287. i += stringToInsertLen;
  10288. }
  10289. return result;
  10290. }
  10291. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10292. {
  10293. const int index = indexOfChar (charToReplace);
  10294. if (index < 0)
  10295. return *this;
  10296. String result (*this, size_t());
  10297. juce_wchar* t = result.text + index;
  10298. while (*t != 0)
  10299. {
  10300. if (*t == charToReplace)
  10301. *t = charToInsert;
  10302. ++t;
  10303. }
  10304. return result;
  10305. }
  10306. const String String::replaceCharacters (const String& charactersToReplace,
  10307. const String& charactersToInsertInstead) const
  10308. {
  10309. String result (*this, size_t());
  10310. juce_wchar* t = result.text;
  10311. const int len2 = charactersToInsertInstead.length();
  10312. // the two strings passed in are supposed to be the same length!
  10313. jassert (len2 == charactersToReplace.length());
  10314. while (*t != 0)
  10315. {
  10316. const int index = charactersToReplace.indexOfChar (*t);
  10317. if (isPositiveAndBelow (index, len2))
  10318. *t = charactersToInsertInstead [index];
  10319. ++t;
  10320. }
  10321. return result;
  10322. }
  10323. bool String::startsWith (const String& other) const throw()
  10324. {
  10325. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10326. }
  10327. bool String::startsWithIgnoreCase (const String& other) const throw()
  10328. {
  10329. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10330. }
  10331. bool String::startsWithChar (const juce_wchar character) const throw()
  10332. {
  10333. jassert (character != 0); // strings can't contain a null character!
  10334. return text[0] == character;
  10335. }
  10336. bool String::endsWithChar (const juce_wchar character) const throw()
  10337. {
  10338. jassert (character != 0); // strings can't contain a null character!
  10339. return text[0] != 0
  10340. && text [length() - 1] == character;
  10341. }
  10342. bool String::endsWith (const String& other) const throw()
  10343. {
  10344. const int thisLen = length();
  10345. const int otherLen = other.length();
  10346. return thisLen >= otherLen
  10347. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10348. }
  10349. bool String::endsWithIgnoreCase (const String& other) const throw()
  10350. {
  10351. const int thisLen = length();
  10352. const int otherLen = other.length();
  10353. return thisLen >= otherLen
  10354. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10355. }
  10356. const String String::toUpperCase() const
  10357. {
  10358. String result (*this, size_t());
  10359. CharacterFunctions::toUpperCase (result.text);
  10360. return result;
  10361. }
  10362. const String String::toLowerCase() const
  10363. {
  10364. String result (*this, size_t());
  10365. CharacterFunctions::toLowerCase (result.text);
  10366. return result;
  10367. }
  10368. juce_wchar& String::operator[] (const int index)
  10369. {
  10370. jassert (isPositiveAndNotGreaterThan (index, length()));
  10371. text = StringHolder::makeUnique (text);
  10372. return text [index];
  10373. }
  10374. juce_wchar String::getLastCharacter() const throw()
  10375. {
  10376. return isEmpty() ? juce_wchar() : text [length() - 1];
  10377. }
  10378. const String String::substring (int start, int end) const
  10379. {
  10380. if (start < 0)
  10381. start = 0;
  10382. else if (end <= start)
  10383. return empty;
  10384. int len = 0;
  10385. while (len <= end && text [len] != 0)
  10386. ++len;
  10387. if (end >= len)
  10388. {
  10389. if (start == 0)
  10390. return *this;
  10391. end = len;
  10392. }
  10393. return String (text + start, end - start);
  10394. }
  10395. const String String::substring (const int start) const
  10396. {
  10397. if (start <= 0)
  10398. return *this;
  10399. const int len = length();
  10400. if (start >= len)
  10401. return empty;
  10402. return String (text + start, len - start);
  10403. }
  10404. const String String::dropLastCharacters (const int numberToDrop) const
  10405. {
  10406. return String (text, jmax (0, length() - numberToDrop));
  10407. }
  10408. const String String::getLastCharacters (const int numCharacters) const
  10409. {
  10410. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10411. }
  10412. const String String::fromFirstOccurrenceOf (const String& sub,
  10413. const bool includeSubString,
  10414. const bool ignoreCase) const
  10415. {
  10416. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10417. : indexOf (sub);
  10418. if (i < 0)
  10419. return empty;
  10420. return substring (includeSubString ? i : i + sub.length());
  10421. }
  10422. const String String::fromLastOccurrenceOf (const String& sub,
  10423. const bool includeSubString,
  10424. const bool ignoreCase) const
  10425. {
  10426. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10427. : lastIndexOf (sub);
  10428. if (i < 0)
  10429. return *this;
  10430. return substring (includeSubString ? i : i + sub.length());
  10431. }
  10432. const String String::upToFirstOccurrenceOf (const String& sub,
  10433. const bool includeSubString,
  10434. const bool ignoreCase) const
  10435. {
  10436. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10437. : indexOf (sub);
  10438. if (i < 0)
  10439. return *this;
  10440. return substring (0, includeSubString ? i + sub.length() : i);
  10441. }
  10442. const String String::upToLastOccurrenceOf (const String& sub,
  10443. const bool includeSubString,
  10444. const bool ignoreCase) const
  10445. {
  10446. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10447. : lastIndexOf (sub);
  10448. if (i < 0)
  10449. return *this;
  10450. return substring (0, includeSubString ? i + sub.length() : i);
  10451. }
  10452. bool String::isQuotedString() const
  10453. {
  10454. const String trimmed (trimStart());
  10455. return trimmed[0] == '"'
  10456. || trimmed[0] == '\'';
  10457. }
  10458. const String String::unquoted() const
  10459. {
  10460. String s (*this);
  10461. if (s.text[0] == '"' || s.text[0] == '\'')
  10462. s = s.substring (1);
  10463. const int lastCharIndex = s.length() - 1;
  10464. if (lastCharIndex >= 0
  10465. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10466. s [lastCharIndex] = 0;
  10467. return s;
  10468. }
  10469. const String String::quoted (const juce_wchar quoteCharacter) const
  10470. {
  10471. if (isEmpty())
  10472. return charToString (quoteCharacter) + quoteCharacter;
  10473. String t (*this);
  10474. if (! t.startsWithChar (quoteCharacter))
  10475. t = charToString (quoteCharacter) + t;
  10476. if (! t.endsWithChar (quoteCharacter))
  10477. t += quoteCharacter;
  10478. return t;
  10479. }
  10480. const String String::trim() const
  10481. {
  10482. if (isEmpty())
  10483. return empty;
  10484. int start = 0;
  10485. while (CharacterFunctions::isWhitespace (text [start]))
  10486. ++start;
  10487. const int len = length();
  10488. int end = len - 1;
  10489. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10490. --end;
  10491. ++end;
  10492. if (end <= start)
  10493. return empty;
  10494. else if (start > 0 || end < len)
  10495. return String (text + start, end - start);
  10496. return *this;
  10497. }
  10498. const String String::trimStart() const
  10499. {
  10500. if (isEmpty())
  10501. return empty;
  10502. const juce_wchar* t = text;
  10503. while (CharacterFunctions::isWhitespace (*t))
  10504. ++t;
  10505. if (t == text)
  10506. return *this;
  10507. return String (t);
  10508. }
  10509. const String String::trimEnd() const
  10510. {
  10511. if (isEmpty())
  10512. return empty;
  10513. const juce_wchar* endT = text + (length() - 1);
  10514. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10515. --endT;
  10516. return String (text, (int) (++endT - text));
  10517. }
  10518. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10519. {
  10520. const juce_wchar* t = text;
  10521. while (charactersToTrim.containsChar (*t))
  10522. ++t;
  10523. return t == text ? *this : String (t);
  10524. }
  10525. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10526. {
  10527. if (isEmpty())
  10528. return empty;
  10529. const int len = length();
  10530. const juce_wchar* endT = text + (len - 1);
  10531. int numToRemove = 0;
  10532. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10533. {
  10534. ++numToRemove;
  10535. --endT;
  10536. }
  10537. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10538. }
  10539. const String String::retainCharacters (const String& charactersToRetain) const
  10540. {
  10541. if (isEmpty())
  10542. return empty;
  10543. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10544. juce_wchar* dst = result.text;
  10545. const juce_wchar* src = text;
  10546. while (*src != 0)
  10547. {
  10548. if (charactersToRetain.containsChar (*src))
  10549. *dst++ = *src;
  10550. ++src;
  10551. }
  10552. *dst = 0;
  10553. return result;
  10554. }
  10555. const String String::removeCharacters (const String& charactersToRemove) const
  10556. {
  10557. if (isEmpty())
  10558. return empty;
  10559. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10560. juce_wchar* dst = result.text;
  10561. const juce_wchar* src = text;
  10562. while (*src != 0)
  10563. {
  10564. if (! charactersToRemove.containsChar (*src))
  10565. *dst++ = *src;
  10566. ++src;
  10567. }
  10568. *dst = 0;
  10569. return result;
  10570. }
  10571. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10572. {
  10573. int i = 0;
  10574. for (;;)
  10575. {
  10576. if (! permittedCharacters.containsChar (text[i]))
  10577. break;
  10578. ++i;
  10579. }
  10580. return substring (0, i);
  10581. }
  10582. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10583. {
  10584. const juce_wchar* const t = text;
  10585. int i = 0;
  10586. while (t[i] != 0)
  10587. {
  10588. if (charactersToStopAt.containsChar (t[i]))
  10589. return String (text, i);
  10590. ++i;
  10591. }
  10592. return empty;
  10593. }
  10594. bool String::containsOnly (const String& chars) const throw()
  10595. {
  10596. const juce_wchar* t = text;
  10597. while (*t != 0)
  10598. if (! chars.containsChar (*t++))
  10599. return false;
  10600. return true;
  10601. }
  10602. bool String::containsAnyOf (const String& chars) const throw()
  10603. {
  10604. const juce_wchar* t = text;
  10605. while (*t != 0)
  10606. if (chars.containsChar (*t++))
  10607. return true;
  10608. return false;
  10609. }
  10610. bool String::containsNonWhitespaceChars() const throw()
  10611. {
  10612. const juce_wchar* t = text;
  10613. while (*t != 0)
  10614. if (! CharacterFunctions::isWhitespace (*t++))
  10615. return true;
  10616. return false;
  10617. }
  10618. const String String::formatted (const juce_wchar* const pf, ... )
  10619. {
  10620. jassert (pf != 0);
  10621. va_list args;
  10622. va_start (args, pf);
  10623. size_t bufferSize = 256;
  10624. String result (Preallocation ((size_t) bufferSize));
  10625. result.text[0] = 0;
  10626. for (;;)
  10627. {
  10628. #if JUCE_LINUX && JUCE_64BIT
  10629. va_list tempArgs;
  10630. va_copy (tempArgs, args);
  10631. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10632. va_end (tempArgs);
  10633. #elif JUCE_WINDOWS
  10634. #if JUCE_MSVC
  10635. #pragma warning (push)
  10636. #pragma warning (disable: 4996)
  10637. #endif
  10638. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10639. #if JUCE_MSVC
  10640. #pragma warning (pop)
  10641. #endif
  10642. #else
  10643. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10644. #endif
  10645. if (num > 0)
  10646. return result;
  10647. bufferSize += 256;
  10648. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10649. break; // returns -1 because of an error rather than because it needs more space.
  10650. result.preallocateStorage (bufferSize);
  10651. }
  10652. return empty;
  10653. }
  10654. int String::getIntValue() const throw()
  10655. {
  10656. return CharacterFunctions::getIntValue (text);
  10657. }
  10658. int String::getTrailingIntValue() const throw()
  10659. {
  10660. int n = 0;
  10661. int mult = 1;
  10662. const juce_wchar* t = text + length();
  10663. while (--t >= text)
  10664. {
  10665. const juce_wchar c = *t;
  10666. if (! CharacterFunctions::isDigit (c))
  10667. {
  10668. if (c == '-')
  10669. n = -n;
  10670. break;
  10671. }
  10672. n += mult * (c - '0');
  10673. mult *= 10;
  10674. }
  10675. return n;
  10676. }
  10677. int64 String::getLargeIntValue() const throw()
  10678. {
  10679. return CharacterFunctions::getInt64Value (text);
  10680. }
  10681. float String::getFloatValue() const throw()
  10682. {
  10683. return (float) CharacterFunctions::getDoubleValue (text);
  10684. }
  10685. double String::getDoubleValue() const throw()
  10686. {
  10687. return CharacterFunctions::getDoubleValue (text);
  10688. }
  10689. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10690. const String String::toHexString (const int number)
  10691. {
  10692. juce_wchar buffer[32];
  10693. juce_wchar* const end = buffer + 32;
  10694. juce_wchar* t = end;
  10695. *--t = 0;
  10696. unsigned int v = (unsigned int) number;
  10697. do
  10698. {
  10699. *--t = hexDigits [v & 15];
  10700. v >>= 4;
  10701. } while (v != 0);
  10702. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10703. }
  10704. const String String::toHexString (const int64 number)
  10705. {
  10706. juce_wchar buffer[32];
  10707. juce_wchar* const end = buffer + 32;
  10708. juce_wchar* t = end;
  10709. *--t = 0;
  10710. uint64 v = (uint64) number;
  10711. do
  10712. {
  10713. *--t = hexDigits [(int) (v & 15)];
  10714. v >>= 4;
  10715. } while (v != 0);
  10716. return String (t, (int) (((char*) end) - (char*) t));
  10717. }
  10718. const String String::toHexString (const short number)
  10719. {
  10720. return toHexString ((int) (unsigned short) number);
  10721. }
  10722. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10723. {
  10724. if (size <= 0)
  10725. return empty;
  10726. int numChars = (size * 2) + 2;
  10727. if (groupSize > 0)
  10728. numChars += size / groupSize;
  10729. String s (Preallocation ((size_t) numChars));
  10730. juce_wchar* d = s.text;
  10731. for (int i = 0; i < size; ++i)
  10732. {
  10733. *d++ = hexDigits [(*data) >> 4];
  10734. *d++ = hexDigits [(*data) & 0xf];
  10735. ++data;
  10736. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10737. *d++ = ' ';
  10738. }
  10739. *d = 0;
  10740. return s;
  10741. }
  10742. int String::getHexValue32() const throw()
  10743. {
  10744. int result = 0;
  10745. const juce_wchar* c = text;
  10746. for (;;)
  10747. {
  10748. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10749. if (hexValue >= 0)
  10750. result = (result << 4) | hexValue;
  10751. else if (*c == 0)
  10752. break;
  10753. ++c;
  10754. }
  10755. return result;
  10756. }
  10757. int64 String::getHexValue64() const throw()
  10758. {
  10759. int64 result = 0;
  10760. const juce_wchar* c = text;
  10761. for (;;)
  10762. {
  10763. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10764. if (hexValue >= 0)
  10765. result = (result << 4) | hexValue;
  10766. else if (*c == 0)
  10767. break;
  10768. ++c;
  10769. }
  10770. return result;
  10771. }
  10772. const String String::createStringFromData (const void* const data_, const int size)
  10773. {
  10774. const char* const data = static_cast <const char*> (data_);
  10775. if (size <= 0 || data == 0)
  10776. {
  10777. return empty;
  10778. }
  10779. else if (size < 2)
  10780. {
  10781. return charToString (data[0]);
  10782. }
  10783. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10784. || (data[0] == (char)-1 && data[1] == (char)-2))
  10785. {
  10786. // assume it's 16-bit unicode
  10787. const bool bigEndian = (data[0] == (char)-2);
  10788. const int numChars = size / 2 - 1;
  10789. String result;
  10790. result.preallocateStorage (numChars + 2);
  10791. const uint16* const src = (const uint16*) (data + 2);
  10792. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10793. if (bigEndian)
  10794. {
  10795. for (int i = 0; i < numChars; ++i)
  10796. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10797. }
  10798. else
  10799. {
  10800. for (int i = 0; i < numChars; ++i)
  10801. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10802. }
  10803. dst [numChars] = 0;
  10804. return result;
  10805. }
  10806. else
  10807. {
  10808. return String::fromUTF8 (data, size);
  10809. }
  10810. }
  10811. const char* String::toUTF8() const
  10812. {
  10813. if (isEmpty())
  10814. {
  10815. return reinterpret_cast <const char*> (text);
  10816. }
  10817. else
  10818. {
  10819. const int currentLen = length() + 1;
  10820. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10821. String* const mutableThis = const_cast <String*> (this);
  10822. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10823. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10824. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10825. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10826. #endif
  10827. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10828. return otherCopy;
  10829. }
  10830. }
  10831. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10832. {
  10833. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10834. int num = 0, index = 0;
  10835. for (;;)
  10836. {
  10837. const uint32 c = (uint32) text [index++];
  10838. if (c >= 0x80)
  10839. {
  10840. int numExtraBytes = 1;
  10841. if (c >= 0x800)
  10842. {
  10843. ++numExtraBytes;
  10844. if (c >= 0x10000)
  10845. {
  10846. ++numExtraBytes;
  10847. if (c >= 0x200000)
  10848. {
  10849. ++numExtraBytes;
  10850. if (c >= 0x4000000)
  10851. ++numExtraBytes;
  10852. }
  10853. }
  10854. }
  10855. if (buffer != 0)
  10856. {
  10857. if (num + numExtraBytes >= maxBufferSizeBytes)
  10858. {
  10859. buffer [num++] = 0;
  10860. break;
  10861. }
  10862. else
  10863. {
  10864. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10865. while (--numExtraBytes >= 0)
  10866. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10867. }
  10868. }
  10869. else
  10870. {
  10871. num += numExtraBytes + 1;
  10872. }
  10873. }
  10874. else
  10875. {
  10876. if (buffer != 0)
  10877. {
  10878. if (num + 1 >= maxBufferSizeBytes)
  10879. {
  10880. buffer [num++] = 0;
  10881. break;
  10882. }
  10883. buffer [num] = (uint8) c;
  10884. }
  10885. ++num;
  10886. }
  10887. if (c == 0)
  10888. break;
  10889. }
  10890. return num;
  10891. }
  10892. int String::getNumBytesAsUTF8() const throw()
  10893. {
  10894. int num = 0;
  10895. const juce_wchar* t = text;
  10896. for (;;)
  10897. {
  10898. const uint32 c = (uint32) *t;
  10899. if (c >= 0x80)
  10900. {
  10901. ++num;
  10902. if (c >= 0x800)
  10903. {
  10904. ++num;
  10905. if (c >= 0x10000)
  10906. {
  10907. ++num;
  10908. if (c >= 0x200000)
  10909. {
  10910. ++num;
  10911. if (c >= 0x4000000)
  10912. ++num;
  10913. }
  10914. }
  10915. }
  10916. }
  10917. else if (c == 0)
  10918. break;
  10919. ++num;
  10920. ++t;
  10921. }
  10922. return num;
  10923. }
  10924. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10925. {
  10926. if (buffer == 0)
  10927. return empty;
  10928. if (bufferSizeBytes < 0)
  10929. bufferSizeBytes = std::numeric_limits<int>::max();
  10930. size_t numBytes;
  10931. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10932. if (buffer [numBytes] == 0)
  10933. break;
  10934. String result (Preallocation (numBytes + 1));
  10935. juce_wchar* dest = result.text;
  10936. size_t i = 0;
  10937. while (i < numBytes)
  10938. {
  10939. const char c = buffer [i++];
  10940. if (c < 0)
  10941. {
  10942. unsigned int mask = 0x7f;
  10943. int bit = 0x40;
  10944. int numExtraValues = 0;
  10945. while (bit != 0 && (c & bit) != 0)
  10946. {
  10947. bit >>= 1;
  10948. mask >>= 1;
  10949. ++numExtraValues;
  10950. }
  10951. int n = (mask & (unsigned char) c);
  10952. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10953. {
  10954. const char nextByte = buffer[i];
  10955. if ((nextByte & 0xc0) != 0x80)
  10956. break;
  10957. n <<= 6;
  10958. n |= (nextByte & 0x3f);
  10959. ++i;
  10960. }
  10961. *dest++ = (juce_wchar) n;
  10962. }
  10963. else
  10964. {
  10965. *dest++ = (juce_wchar) c;
  10966. }
  10967. }
  10968. *dest = 0;
  10969. return result;
  10970. }
  10971. const char* String::toCString() const
  10972. {
  10973. if (isEmpty())
  10974. {
  10975. return reinterpret_cast <const char*> (text);
  10976. }
  10977. else
  10978. {
  10979. const int len = length();
  10980. String* const mutableThis = const_cast <String*> (this);
  10981. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10982. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10983. CharacterFunctions::copy (otherCopy, text, len);
  10984. otherCopy [len] = 0;
  10985. return otherCopy;
  10986. }
  10987. }
  10988. #if JUCE_MSVC
  10989. #pragma warning (push)
  10990. #pragma warning (disable: 4514 4996)
  10991. #endif
  10992. int String::getNumBytesAsCString() const throw()
  10993. {
  10994. return (int) wcstombs (0, text, 0);
  10995. }
  10996. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10997. {
  10998. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10999. if (destBuffer != 0 && numBytes >= 0)
  11000. destBuffer [numBytes] = 0;
  11001. return numBytes;
  11002. }
  11003. #if JUCE_MSVC
  11004. #pragma warning (pop)
  11005. #endif
  11006. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11007. {
  11008. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11009. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11010. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11011. }
  11012. String::Concatenator::Concatenator (String& stringToAppendTo)
  11013. : result (stringToAppendTo),
  11014. nextIndex (stringToAppendTo.length())
  11015. {
  11016. }
  11017. String::Concatenator::~Concatenator()
  11018. {
  11019. }
  11020. void String::Concatenator::append (const String& s)
  11021. {
  11022. const int len = s.length();
  11023. if (len > 0)
  11024. {
  11025. result.preallocateStorage (nextIndex + len);
  11026. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11027. nextIndex += len;
  11028. }
  11029. }
  11030. #if JUCE_UNIT_TESTS
  11031. class StringTests : public UnitTest
  11032. {
  11033. public:
  11034. StringTests() : UnitTest ("String class") {}
  11035. void runTest()
  11036. {
  11037. {
  11038. beginTest ("Basics");
  11039. expect (String().length() == 0);
  11040. expect (String() == String::empty);
  11041. String s1, s2 ("abcd");
  11042. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11043. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11044. expect (s2.length() == 4);
  11045. s1 = "abcd";
  11046. expect (s2 == s1 && s1 == s2);
  11047. expect (s1 == "abcd" && s1 == L"abcd");
  11048. expect (String ("abcd") == String (L"abcd"));
  11049. expect (String ("abcdefg", 4) == L"abcd");
  11050. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11051. expect (String::charToString ('x') == "x");
  11052. expect (String::charToString (0) == String::empty);
  11053. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11054. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11055. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11056. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11057. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11058. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11059. expect (s1.indexOf (String::empty) == 0);
  11060. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11061. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11062. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11063. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11064. }
  11065. {
  11066. beginTest ("Operations");
  11067. String s ("012345678");
  11068. expect (s.hashCode() != 0);
  11069. expect (s.hashCode64() != 0);
  11070. expect (s.hashCode() != (s + s).hashCode());
  11071. expect (s.hashCode64() != (s + s).hashCode64());
  11072. expect (s.compare (String ("012345678")) == 0);
  11073. expect (s.compare (String ("012345679")) < 0);
  11074. expect (s.compare (String ("012345676")) > 0);
  11075. expect (s.substring (2, 3) == String::charToString (s[2]));
  11076. expect (s.substring (0, 1) == String::charToString (s[0]));
  11077. expect (s.getLastCharacter() == s [s.length() - 1]);
  11078. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11079. expect (s.substring (0, 3) == L"012");
  11080. expect (s.substring (0, 100) == s);
  11081. expect (s.substring (-1, 100) == s);
  11082. expect (s.substring (3) == "345678");
  11083. expect (s.indexOf (L"45") == 4);
  11084. expect (String ("444445").indexOf ("45") == 4);
  11085. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11086. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11087. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11088. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11089. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11090. expect (s.indexOfChar (L'4') == 4);
  11091. expect (s + s == "012345678012345678");
  11092. expect (s.startsWith (s));
  11093. expect (s.startsWith (s.substring (0, 4)));
  11094. expect (s.startsWith (s.dropLastCharacters (4)));
  11095. expect (s.endsWith (s.substring (5)));
  11096. expect (s.endsWith (s));
  11097. expect (s.contains (s.substring (3, 6)));
  11098. expect (s.contains (s.substring (3)));
  11099. expect (s.startsWithChar (s[0]));
  11100. expect (s.endsWithChar (s.getLastCharacter()));
  11101. expect (s [s.length()] == 0);
  11102. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11103. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11104. String s2 ("123");
  11105. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11106. s2 += "xyz";
  11107. expect (s2 == "1234567890xyz");
  11108. beginTest ("Numeric conversions");
  11109. expect (String::empty.getIntValue() == 0);
  11110. expect (String::empty.getDoubleValue() == 0.0);
  11111. expect (String::empty.getFloatValue() == 0.0f);
  11112. expect (s.getIntValue() == 12345678);
  11113. expect (s.getLargeIntValue() == (int64) 12345678);
  11114. expect (s.getDoubleValue() == 12345678.0);
  11115. expect (s.getFloatValue() == 12345678.0f);
  11116. expect (String (-1234).getIntValue() == -1234);
  11117. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11118. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11119. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11120. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11121. expect (s.getHexValue32() == 0x12345678);
  11122. expect (s.getHexValue64() == (int64) 0x12345678);
  11123. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11124. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11125. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11126. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11127. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11128. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11129. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11130. beginTest ("Subsections");
  11131. String s3;
  11132. s3 = "abcdeFGHIJ";
  11133. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11134. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11135. expect (s3.containsIgnoreCase (s3.substring (3)));
  11136. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11137. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11138. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11139. expect (s3.containsAnyOf (L"zzzFs"));
  11140. expect (s3.startsWith ("abcd"));
  11141. expect (s3.startsWithIgnoreCase (L"abCD"));
  11142. expect (s3.startsWith (String::empty));
  11143. expect (s3.startsWithChar ('a'));
  11144. expect (s3.endsWith (String ("HIJ")));
  11145. expect (s3.endsWithIgnoreCase (L"Hij"));
  11146. expect (s3.endsWith (String::empty));
  11147. expect (s3.endsWithChar (L'J'));
  11148. expect (s3.indexOf ("HIJ") == 7);
  11149. expect (s3.indexOf (L"HIJK") == -1);
  11150. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11151. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11152. String s4 (s3);
  11153. s4.append (String ("xyz123"), 3);
  11154. expect (s4 == s3 + "xyz");
  11155. expect (String (1234) < String (1235));
  11156. expect (String (1235) > String (1234));
  11157. expect (String (1234) >= String (1234));
  11158. expect (String (1234) <= String (1234));
  11159. expect (String (1235) >= String (1234));
  11160. expect (String (1234) <= String (1235));
  11161. String s5 ("word word2 word3");
  11162. expect (s5.containsWholeWord (String ("word2")));
  11163. expect (s5.indexOfWholeWord ("word2") == 5);
  11164. expect (s5.containsWholeWord (L"word"));
  11165. expect (s5.containsWholeWord ("word3"));
  11166. expect (s5.containsWholeWord (s5));
  11167. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11168. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11169. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11170. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11171. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11172. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11173. expect (s5.containsNonWhitespaceChars());
  11174. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11175. expect (s5.matchesWildcard (L"wor*", false));
  11176. expect (s5.matchesWildcard ("wOr*", true));
  11177. expect (s5.matchesWildcard (L"*word3", true));
  11178. expect (s5.matchesWildcard ("*word?", true));
  11179. expect (s5.matchesWildcard (L"Word*3", true));
  11180. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11181. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11182. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11183. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11184. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11185. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11186. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11187. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11188. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11189. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11190. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11191. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11192. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11193. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11194. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11195. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11196. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11197. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11198. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11199. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11200. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11201. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11202. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11203. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11204. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11205. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11206. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11207. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11208. expect (s5.replace ("Word", "", true) == " 2 3");
  11209. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11210. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11211. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11212. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11213. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11214. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11215. expect (s5.retainCharacters (String::empty).isEmpty());
  11216. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11217. expect (s5.removeCharacters (String::empty) == s5);
  11218. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11219. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11220. expect (! s5.isQuotedString());
  11221. expect (s5.quoted().isQuotedString());
  11222. expect (! s5.quoted().unquoted().isQuotedString());
  11223. expect (! String ("x'").isQuotedString());
  11224. expect (String ("'x").isQuotedString());
  11225. String s6 (" \t xyz \t\r\n");
  11226. expect (s6.trim() == String ("xyz"));
  11227. expect (s6.trim().trim() == "xyz");
  11228. expect (s5.trim() == s5);
  11229. expect (s6.trimStart().trimEnd() == s6.trim());
  11230. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11231. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11232. expect (s6.trimStart() != s6.trimEnd());
  11233. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11234. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11235. }
  11236. {
  11237. beginTest ("UTF8");
  11238. String s ("word word2 word3");
  11239. {
  11240. char buffer [100];
  11241. memset (buffer, 0xff, sizeof (buffer));
  11242. s.copyToUTF8 (buffer, 100);
  11243. expect (String::fromUTF8 (buffer, 100) == s);
  11244. juce_wchar bufferUnicode [100];
  11245. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11246. s.copyToUnicode (bufferUnicode, 100);
  11247. expect (String (bufferUnicode, 100) == s);
  11248. }
  11249. {
  11250. juce_wchar wideBuffer [50];
  11251. zerostruct (wideBuffer);
  11252. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11253. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11254. String wide (wideBuffer);
  11255. expect (wide == (const juce_wchar*) wideBuffer);
  11256. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11257. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11258. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11259. }
  11260. }
  11261. }
  11262. };
  11263. static StringTests stringUnitTests;
  11264. #endif
  11265. END_JUCE_NAMESPACE
  11266. /*** End of inlined file: juce_String.cpp ***/
  11267. /*** Start of inlined file: juce_StringArray.cpp ***/
  11268. BEGIN_JUCE_NAMESPACE
  11269. StringArray::StringArray() throw()
  11270. {
  11271. }
  11272. StringArray::StringArray (const StringArray& other)
  11273. : strings (other.strings)
  11274. {
  11275. }
  11276. StringArray::StringArray (const String& firstValue)
  11277. {
  11278. strings.add (firstValue);
  11279. }
  11280. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11281. const int numberOfStrings)
  11282. {
  11283. for (int i = 0; i < numberOfStrings; ++i)
  11284. strings.add (initialStrings [i]);
  11285. }
  11286. StringArray::StringArray (const char* const* const initialStrings,
  11287. const int numberOfStrings)
  11288. {
  11289. for (int i = 0; i < numberOfStrings; ++i)
  11290. strings.add (initialStrings [i]);
  11291. }
  11292. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11293. {
  11294. int i = 0;
  11295. while (initialStrings[i] != 0)
  11296. strings.add (initialStrings [i++]);
  11297. }
  11298. StringArray::StringArray (const char* const* const initialStrings)
  11299. {
  11300. int i = 0;
  11301. while (initialStrings[i] != 0)
  11302. strings.add (initialStrings [i++]);
  11303. }
  11304. StringArray& StringArray::operator= (const StringArray& other)
  11305. {
  11306. strings = other.strings;
  11307. return *this;
  11308. }
  11309. StringArray::~StringArray()
  11310. {
  11311. }
  11312. bool StringArray::operator== (const StringArray& other) const throw()
  11313. {
  11314. if (other.size() != size())
  11315. return false;
  11316. for (int i = size(); --i >= 0;)
  11317. if (other.strings.getReference(i) != strings.getReference(i))
  11318. return false;
  11319. return true;
  11320. }
  11321. bool StringArray::operator!= (const StringArray& other) const throw()
  11322. {
  11323. return ! operator== (other);
  11324. }
  11325. void StringArray::clear()
  11326. {
  11327. strings.clear();
  11328. }
  11329. const String& StringArray::operator[] (const int index) const throw()
  11330. {
  11331. if (isPositiveAndBelow (index, strings.size()))
  11332. return strings.getReference (index);
  11333. return String::empty;
  11334. }
  11335. String& StringArray::getReference (const int index) throw()
  11336. {
  11337. jassert (isPositiveAndBelow (index, strings.size()));
  11338. return strings.getReference (index);
  11339. }
  11340. void StringArray::add (const String& newString)
  11341. {
  11342. strings.add (newString);
  11343. }
  11344. void StringArray::insert (const int index, const String& newString)
  11345. {
  11346. strings.insert (index, newString);
  11347. }
  11348. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11349. {
  11350. if (! contains (newString, ignoreCase))
  11351. add (newString);
  11352. }
  11353. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11354. {
  11355. if (startIndex < 0)
  11356. {
  11357. jassertfalse;
  11358. startIndex = 0;
  11359. }
  11360. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11361. numElementsToAdd = otherArray.size() - startIndex;
  11362. while (--numElementsToAdd >= 0)
  11363. strings.add (otherArray.strings.getReference (startIndex++));
  11364. }
  11365. void StringArray::set (const int index, const String& newString)
  11366. {
  11367. strings.set (index, newString);
  11368. }
  11369. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11370. {
  11371. if (ignoreCase)
  11372. {
  11373. for (int i = size(); --i >= 0;)
  11374. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11375. return true;
  11376. }
  11377. else
  11378. {
  11379. for (int i = size(); --i >= 0;)
  11380. if (stringToLookFor == strings.getReference(i))
  11381. return true;
  11382. }
  11383. return false;
  11384. }
  11385. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11386. {
  11387. if (i < 0)
  11388. i = 0;
  11389. const int numElements = size();
  11390. if (ignoreCase)
  11391. {
  11392. while (i < numElements)
  11393. {
  11394. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11395. return i;
  11396. ++i;
  11397. }
  11398. }
  11399. else
  11400. {
  11401. while (i < numElements)
  11402. {
  11403. if (stringToLookFor == strings.getReference (i))
  11404. return i;
  11405. ++i;
  11406. }
  11407. }
  11408. return -1;
  11409. }
  11410. void StringArray::remove (const int index)
  11411. {
  11412. strings.remove (index);
  11413. }
  11414. void StringArray::removeString (const String& stringToRemove,
  11415. const bool ignoreCase)
  11416. {
  11417. if (ignoreCase)
  11418. {
  11419. for (int i = size(); --i >= 0;)
  11420. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11421. strings.remove (i);
  11422. }
  11423. else
  11424. {
  11425. for (int i = size(); --i >= 0;)
  11426. if (stringToRemove == strings.getReference (i))
  11427. strings.remove (i);
  11428. }
  11429. }
  11430. void StringArray::removeRange (int startIndex, int numberToRemove)
  11431. {
  11432. strings.removeRange (startIndex, numberToRemove);
  11433. }
  11434. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11435. {
  11436. if (removeWhitespaceStrings)
  11437. {
  11438. for (int i = size(); --i >= 0;)
  11439. if (! strings.getReference(i).containsNonWhitespaceChars())
  11440. strings.remove (i);
  11441. }
  11442. else
  11443. {
  11444. for (int i = size(); --i >= 0;)
  11445. if (strings.getReference(i).isEmpty())
  11446. strings.remove (i);
  11447. }
  11448. }
  11449. void StringArray::trim()
  11450. {
  11451. for (int i = size(); --i >= 0;)
  11452. {
  11453. String& s = strings.getReference(i);
  11454. s = s.trim();
  11455. }
  11456. }
  11457. class InternalStringArrayComparator_CaseSensitive
  11458. {
  11459. public:
  11460. static int compareElements (String& first, String& second) { return first.compare (second); }
  11461. };
  11462. class InternalStringArrayComparator_CaseInsensitive
  11463. {
  11464. public:
  11465. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11466. };
  11467. void StringArray::sort (const bool ignoreCase)
  11468. {
  11469. if (ignoreCase)
  11470. {
  11471. InternalStringArrayComparator_CaseInsensitive comp;
  11472. strings.sort (comp);
  11473. }
  11474. else
  11475. {
  11476. InternalStringArrayComparator_CaseSensitive comp;
  11477. strings.sort (comp);
  11478. }
  11479. }
  11480. void StringArray::move (const int currentIndex, int newIndex) throw()
  11481. {
  11482. strings.move (currentIndex, newIndex);
  11483. }
  11484. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11485. {
  11486. const int last = (numberToJoin < 0) ? size()
  11487. : jmin (size(), start + numberToJoin);
  11488. if (start < 0)
  11489. start = 0;
  11490. if (start >= last)
  11491. return String::empty;
  11492. if (start == last - 1)
  11493. return strings.getReference (start);
  11494. const int separatorLen = separator.length();
  11495. int charsNeeded = separatorLen * (last - start - 1);
  11496. for (int i = start; i < last; ++i)
  11497. charsNeeded += strings.getReference(i).length();
  11498. String result;
  11499. result.preallocateStorage (charsNeeded);
  11500. juce_wchar* dest = result;
  11501. while (start < last)
  11502. {
  11503. const String& s = strings.getReference (start);
  11504. const int len = s.length();
  11505. if (len > 0)
  11506. {
  11507. s.copyToUnicode (dest, len);
  11508. dest += len;
  11509. }
  11510. if (++start < last && separatorLen > 0)
  11511. {
  11512. separator.copyToUnicode (dest, separatorLen);
  11513. dest += separatorLen;
  11514. }
  11515. }
  11516. *dest = 0;
  11517. return result;
  11518. }
  11519. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11520. {
  11521. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11522. }
  11523. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11524. {
  11525. int num = 0;
  11526. if (text.isNotEmpty())
  11527. {
  11528. bool insideQuotes = false;
  11529. juce_wchar currentQuoteChar = 0;
  11530. int i = 0;
  11531. int tokenStart = 0;
  11532. for (;;)
  11533. {
  11534. const juce_wchar c = text[i];
  11535. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11536. if (! isBreak)
  11537. {
  11538. if (quoteCharacters.containsChar (c))
  11539. {
  11540. if (insideQuotes)
  11541. {
  11542. // only break out of quotes-mode if we find a matching quote to the
  11543. // one that we opened with..
  11544. if (currentQuoteChar == c)
  11545. insideQuotes = false;
  11546. }
  11547. else
  11548. {
  11549. insideQuotes = true;
  11550. currentQuoteChar = c;
  11551. }
  11552. }
  11553. }
  11554. else
  11555. {
  11556. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11557. ++num;
  11558. tokenStart = i + 1;
  11559. }
  11560. if (c == 0)
  11561. break;
  11562. ++i;
  11563. }
  11564. }
  11565. return num;
  11566. }
  11567. int StringArray::addLines (const String& sourceText)
  11568. {
  11569. int numLines = 0;
  11570. const juce_wchar* text = sourceText;
  11571. while (*text != 0)
  11572. {
  11573. const juce_wchar* const startOfLine = text;
  11574. while (*text != 0)
  11575. {
  11576. if (*text == '\r')
  11577. {
  11578. ++text;
  11579. if (*text == '\n')
  11580. ++text;
  11581. break;
  11582. }
  11583. if (*text == '\n')
  11584. {
  11585. ++text;
  11586. break;
  11587. }
  11588. ++text;
  11589. }
  11590. const juce_wchar* endOfLine = text;
  11591. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11592. --endOfLine;
  11593. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11594. --endOfLine;
  11595. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11596. ++numLines;
  11597. }
  11598. return numLines;
  11599. }
  11600. void StringArray::removeDuplicates (const bool ignoreCase)
  11601. {
  11602. for (int i = 0; i < size() - 1; ++i)
  11603. {
  11604. const String s (strings.getReference(i));
  11605. int nextIndex = i + 1;
  11606. for (;;)
  11607. {
  11608. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11609. if (nextIndex < 0)
  11610. break;
  11611. strings.remove (nextIndex);
  11612. }
  11613. }
  11614. }
  11615. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11616. const bool appendNumberToFirstInstance,
  11617. const juce_wchar* preNumberString,
  11618. const juce_wchar* postNumberString)
  11619. {
  11620. if (preNumberString == 0)
  11621. preNumberString = L" (";
  11622. if (postNumberString == 0)
  11623. postNumberString = L")";
  11624. for (int i = 0; i < size() - 1; ++i)
  11625. {
  11626. String& s = strings.getReference(i);
  11627. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11628. if (nextIndex >= 0)
  11629. {
  11630. const String original (s);
  11631. int number = 0;
  11632. if (appendNumberToFirstInstance)
  11633. s = original + preNumberString + String (++number) + postNumberString;
  11634. else
  11635. ++number;
  11636. while (nextIndex >= 0)
  11637. {
  11638. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11639. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11640. }
  11641. }
  11642. }
  11643. }
  11644. void StringArray::minimiseStorageOverheads()
  11645. {
  11646. strings.minimiseStorageOverheads();
  11647. }
  11648. END_JUCE_NAMESPACE
  11649. /*** End of inlined file: juce_StringArray.cpp ***/
  11650. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11651. BEGIN_JUCE_NAMESPACE
  11652. StringPairArray::StringPairArray (const bool ignoreCase_)
  11653. : ignoreCase (ignoreCase_)
  11654. {
  11655. }
  11656. StringPairArray::StringPairArray (const StringPairArray& other)
  11657. : keys (other.keys),
  11658. values (other.values),
  11659. ignoreCase (other.ignoreCase)
  11660. {
  11661. }
  11662. StringPairArray::~StringPairArray()
  11663. {
  11664. }
  11665. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11666. {
  11667. keys = other.keys;
  11668. values = other.values;
  11669. return *this;
  11670. }
  11671. bool StringPairArray::operator== (const StringPairArray& other) const
  11672. {
  11673. for (int i = keys.size(); --i >= 0;)
  11674. if (other [keys[i]] != values[i])
  11675. return false;
  11676. return true;
  11677. }
  11678. bool StringPairArray::operator!= (const StringPairArray& other) const
  11679. {
  11680. return ! operator== (other);
  11681. }
  11682. const String& StringPairArray::operator[] (const String& key) const
  11683. {
  11684. return values [keys.indexOf (key, ignoreCase)];
  11685. }
  11686. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11687. {
  11688. const int i = keys.indexOf (key, ignoreCase);
  11689. if (i >= 0)
  11690. return values[i];
  11691. return defaultReturnValue;
  11692. }
  11693. void StringPairArray::set (const String& key, const String& value)
  11694. {
  11695. const int i = keys.indexOf (key, ignoreCase);
  11696. if (i >= 0)
  11697. {
  11698. values.set (i, value);
  11699. }
  11700. else
  11701. {
  11702. keys.add (key);
  11703. values.add (value);
  11704. }
  11705. }
  11706. void StringPairArray::addArray (const StringPairArray& other)
  11707. {
  11708. for (int i = 0; i < other.size(); ++i)
  11709. set (other.keys[i], other.values[i]);
  11710. }
  11711. void StringPairArray::clear()
  11712. {
  11713. keys.clear();
  11714. values.clear();
  11715. }
  11716. void StringPairArray::remove (const String& key)
  11717. {
  11718. remove (keys.indexOf (key, ignoreCase));
  11719. }
  11720. void StringPairArray::remove (const int index)
  11721. {
  11722. keys.remove (index);
  11723. values.remove (index);
  11724. }
  11725. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11726. {
  11727. ignoreCase = shouldIgnoreCase;
  11728. }
  11729. const String StringPairArray::getDescription() const
  11730. {
  11731. String s;
  11732. for (int i = 0; i < keys.size(); ++i)
  11733. {
  11734. s << keys[i] << " = " << values[i];
  11735. if (i < keys.size())
  11736. s << ", ";
  11737. }
  11738. return s;
  11739. }
  11740. void StringPairArray::minimiseStorageOverheads()
  11741. {
  11742. keys.minimiseStorageOverheads();
  11743. values.minimiseStorageOverheads();
  11744. }
  11745. END_JUCE_NAMESPACE
  11746. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11747. /*** Start of inlined file: juce_StringPool.cpp ***/
  11748. BEGIN_JUCE_NAMESPACE
  11749. StringPool::StringPool() throw() {}
  11750. StringPool::~StringPool() {}
  11751. namespace StringPoolHelpers
  11752. {
  11753. template <class StringType>
  11754. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11755. {
  11756. int start = 0;
  11757. int end = strings.size();
  11758. for (;;)
  11759. {
  11760. if (start >= end)
  11761. {
  11762. jassert (start <= end);
  11763. strings.insert (start, newString);
  11764. return strings.getReference (start);
  11765. }
  11766. else
  11767. {
  11768. const String& startString = strings.getReference (start);
  11769. if (startString == newString)
  11770. return startString;
  11771. const int halfway = (start + end) >> 1;
  11772. if (halfway == start)
  11773. {
  11774. if (startString.compare (newString) < 0)
  11775. ++start;
  11776. strings.insert (start, newString);
  11777. return strings.getReference (start);
  11778. }
  11779. const int comp = strings.getReference (halfway).compare (newString);
  11780. if (comp == 0)
  11781. return strings.getReference (halfway);
  11782. else if (comp < 0)
  11783. start = halfway;
  11784. else
  11785. end = halfway;
  11786. }
  11787. }
  11788. }
  11789. }
  11790. const juce_wchar* StringPool::getPooledString (const String& s)
  11791. {
  11792. if (s.isEmpty())
  11793. return String::empty;
  11794. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11795. }
  11796. const juce_wchar* StringPool::getPooledString (const char* const s)
  11797. {
  11798. if (s == 0 || *s == 0)
  11799. return String::empty;
  11800. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11801. }
  11802. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11803. {
  11804. if (s == 0 || *s == 0)
  11805. return String::empty;
  11806. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11807. }
  11808. int StringPool::size() const throw()
  11809. {
  11810. return strings.size();
  11811. }
  11812. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11813. {
  11814. return strings [index];
  11815. }
  11816. END_JUCE_NAMESPACE
  11817. /*** End of inlined file: juce_StringPool.cpp ***/
  11818. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11819. BEGIN_JUCE_NAMESPACE
  11820. XmlDocument::XmlDocument (const String& documentText)
  11821. : originalText (documentText),
  11822. ignoreEmptyTextElements (true)
  11823. {
  11824. }
  11825. XmlDocument::XmlDocument (const File& file)
  11826. : ignoreEmptyTextElements (true),
  11827. inputSource (new FileInputSource (file))
  11828. {
  11829. }
  11830. XmlDocument::~XmlDocument()
  11831. {
  11832. }
  11833. XmlElement* XmlDocument::parse (const File& file)
  11834. {
  11835. XmlDocument doc (file);
  11836. return doc.getDocumentElement();
  11837. }
  11838. XmlElement* XmlDocument::parse (const String& xmlData)
  11839. {
  11840. XmlDocument doc (xmlData);
  11841. return doc.getDocumentElement();
  11842. }
  11843. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11844. {
  11845. inputSource = newSource;
  11846. }
  11847. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11848. {
  11849. ignoreEmptyTextElements = shouldBeIgnored;
  11850. }
  11851. namespace XmlIdentifierChars
  11852. {
  11853. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11854. {
  11855. return CharacterFunctions::isLetterOrDigit (c)
  11856. || c == '_' || c == '-' || c == ':' || c == '.';
  11857. }
  11858. bool isIdentifierChar (const juce_wchar c) throw()
  11859. {
  11860. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11861. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11862. : isIdentifierCharSlow (c);
  11863. }
  11864. /*static void generateIdentifierCharConstants()
  11865. {
  11866. uint32 n[8];
  11867. zerostruct (n);
  11868. for (int i = 0; i < 256; ++i)
  11869. if (isIdentifierCharSlow (i))
  11870. n[i >> 5] |= (1 << (i & 31));
  11871. String s;
  11872. for (int i = 0; i < 8; ++i)
  11873. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11874. DBG (s);
  11875. }*/
  11876. }
  11877. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11878. {
  11879. String textToParse (originalText);
  11880. if (textToParse.isEmpty() && inputSource != 0)
  11881. {
  11882. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11883. if (in != 0)
  11884. {
  11885. MemoryOutputStream data;
  11886. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11887. textToParse = data.toString();
  11888. if (! onlyReadOuterDocumentElement)
  11889. originalText = textToParse;
  11890. }
  11891. }
  11892. input = textToParse;
  11893. lastError = String::empty;
  11894. errorOccurred = false;
  11895. outOfData = false;
  11896. needToLoadDTD = true;
  11897. if (textToParse.isEmpty())
  11898. {
  11899. lastError = "not enough input";
  11900. }
  11901. else
  11902. {
  11903. skipHeader();
  11904. if (input != 0)
  11905. {
  11906. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11907. if (! errorOccurred)
  11908. return result.release();
  11909. }
  11910. else
  11911. {
  11912. lastError = "incorrect xml header";
  11913. }
  11914. }
  11915. return 0;
  11916. }
  11917. const String& XmlDocument::getLastParseError() const throw()
  11918. {
  11919. return lastError;
  11920. }
  11921. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11922. {
  11923. lastError = desc;
  11924. errorOccurred = ! carryOn;
  11925. }
  11926. const String XmlDocument::getFileContents (const String& filename) const
  11927. {
  11928. if (inputSource != 0)
  11929. {
  11930. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11931. if (in != 0)
  11932. return in->readEntireStreamAsString();
  11933. }
  11934. return String::empty;
  11935. }
  11936. juce_wchar XmlDocument::readNextChar() throw()
  11937. {
  11938. if (*input != 0)
  11939. return *input++;
  11940. outOfData = true;
  11941. return 0;
  11942. }
  11943. int XmlDocument::findNextTokenLength() throw()
  11944. {
  11945. int len = 0;
  11946. juce_wchar c = *input;
  11947. while (XmlIdentifierChars::isIdentifierChar (c))
  11948. c = input [++len];
  11949. return len;
  11950. }
  11951. void XmlDocument::skipHeader()
  11952. {
  11953. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11954. if (found != 0)
  11955. {
  11956. input = found;
  11957. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11958. if (input == 0)
  11959. return;
  11960. #if JUCE_DEBUG
  11961. const String header (found, input - found);
  11962. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11963. .fromFirstOccurrenceOf ("=", false, false)
  11964. .fromFirstOccurrenceOf ("\"", false, false)
  11965. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11966. /* If you load an XML document with a non-UTF encoding type, it may have been
  11967. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11968. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11969. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11970. read, use your own code to convert them to a unicode String, and pass that to the
  11971. XML parser.
  11972. */
  11973. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11974. #endif
  11975. input += 2;
  11976. }
  11977. skipNextWhiteSpace();
  11978. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11979. if (docType == 0)
  11980. return;
  11981. input = docType + 9;
  11982. int n = 1;
  11983. while (n > 0)
  11984. {
  11985. const juce_wchar c = readNextChar();
  11986. if (outOfData)
  11987. return;
  11988. if (c == '<')
  11989. ++n;
  11990. else if (c == '>')
  11991. --n;
  11992. }
  11993. docType += 9;
  11994. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11995. }
  11996. void XmlDocument::skipNextWhiteSpace()
  11997. {
  11998. for (;;)
  11999. {
  12000. juce_wchar c = *input;
  12001. while (CharacterFunctions::isWhitespace (c))
  12002. c = *++input;
  12003. if (c == 0)
  12004. {
  12005. outOfData = true;
  12006. break;
  12007. }
  12008. else if (c == '<')
  12009. {
  12010. if (input[1] == '!'
  12011. && input[2] == '-'
  12012. && input[3] == '-')
  12013. {
  12014. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12015. if (closeComment == 0)
  12016. {
  12017. outOfData = true;
  12018. break;
  12019. }
  12020. input = closeComment + 3;
  12021. continue;
  12022. }
  12023. else if (input[1] == '?')
  12024. {
  12025. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12026. if (closeBracket == 0)
  12027. {
  12028. outOfData = true;
  12029. break;
  12030. }
  12031. input = closeBracket + 2;
  12032. continue;
  12033. }
  12034. }
  12035. break;
  12036. }
  12037. }
  12038. void XmlDocument::readQuotedString (String& result)
  12039. {
  12040. const juce_wchar quote = readNextChar();
  12041. while (! outOfData)
  12042. {
  12043. const juce_wchar c = readNextChar();
  12044. if (c == quote)
  12045. break;
  12046. if (c == '&')
  12047. {
  12048. --input;
  12049. readEntity (result);
  12050. }
  12051. else
  12052. {
  12053. --input;
  12054. const juce_wchar* const start = input;
  12055. for (;;)
  12056. {
  12057. const juce_wchar character = *input;
  12058. if (character == quote)
  12059. {
  12060. result.append (start, (int) (input - start));
  12061. ++input;
  12062. return;
  12063. }
  12064. else if (character == '&')
  12065. {
  12066. result.append (start, (int) (input - start));
  12067. break;
  12068. }
  12069. else if (character == 0)
  12070. {
  12071. outOfData = true;
  12072. setLastError ("unmatched quotes", false);
  12073. break;
  12074. }
  12075. ++input;
  12076. }
  12077. }
  12078. }
  12079. }
  12080. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12081. {
  12082. XmlElement* node = 0;
  12083. skipNextWhiteSpace();
  12084. if (outOfData)
  12085. return 0;
  12086. input = CharacterFunctions::find (input, JUCE_T("<"));
  12087. if (input != 0)
  12088. {
  12089. ++input;
  12090. int tagLen = findNextTokenLength();
  12091. if (tagLen == 0)
  12092. {
  12093. // no tag name - but allow for a gap after the '<' before giving an error
  12094. skipNextWhiteSpace();
  12095. tagLen = findNextTokenLength();
  12096. if (tagLen == 0)
  12097. {
  12098. setLastError ("tag name missing", false);
  12099. return node;
  12100. }
  12101. }
  12102. node = new XmlElement (String (input, tagLen));
  12103. input += tagLen;
  12104. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12105. // look for attributes
  12106. for (;;)
  12107. {
  12108. skipNextWhiteSpace();
  12109. const juce_wchar c = *input;
  12110. // empty tag..
  12111. if (c == '/' && input[1] == '>')
  12112. {
  12113. input += 2;
  12114. break;
  12115. }
  12116. // parse the guts of the element..
  12117. if (c == '>')
  12118. {
  12119. ++input;
  12120. if (alsoParseSubElements)
  12121. readChildElements (node);
  12122. break;
  12123. }
  12124. // get an attribute..
  12125. if (XmlIdentifierChars::isIdentifierChar (c))
  12126. {
  12127. const int attNameLen = findNextTokenLength();
  12128. if (attNameLen > 0)
  12129. {
  12130. const juce_wchar* attNameStart = input;
  12131. input += attNameLen;
  12132. skipNextWhiteSpace();
  12133. if (readNextChar() == '=')
  12134. {
  12135. skipNextWhiteSpace();
  12136. const juce_wchar nextChar = *input;
  12137. if (nextChar == '"' || nextChar == '\'')
  12138. {
  12139. XmlElement::XmlAttributeNode* const newAtt
  12140. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12141. String::empty);
  12142. readQuotedString (newAtt->value);
  12143. if (lastAttribute == 0)
  12144. node->attributes = newAtt;
  12145. else
  12146. lastAttribute->next = newAtt;
  12147. lastAttribute = newAtt;
  12148. continue;
  12149. }
  12150. }
  12151. }
  12152. }
  12153. else
  12154. {
  12155. if (! outOfData)
  12156. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12157. }
  12158. break;
  12159. }
  12160. }
  12161. return node;
  12162. }
  12163. void XmlDocument::readChildElements (XmlElement* parent)
  12164. {
  12165. XmlElement* lastChildNode = 0;
  12166. for (;;)
  12167. {
  12168. const juce_wchar* const preWhitespaceInput = input;
  12169. skipNextWhiteSpace();
  12170. if (outOfData)
  12171. {
  12172. setLastError ("unmatched tags", false);
  12173. break;
  12174. }
  12175. if (*input == '<')
  12176. {
  12177. if (input[1] == '/')
  12178. {
  12179. // our close tag..
  12180. input = CharacterFunctions::find (input, JUCE_T(">"));
  12181. ++input;
  12182. break;
  12183. }
  12184. else if (input[1] == '!'
  12185. && input[2] == '['
  12186. && input[3] == 'C'
  12187. && input[4] == 'D'
  12188. && input[5] == 'A'
  12189. && input[6] == 'T'
  12190. && input[7] == 'A'
  12191. && input[8] == '[')
  12192. {
  12193. input += 9;
  12194. const juce_wchar* const inputStart = input;
  12195. int len = 0;
  12196. for (;;)
  12197. {
  12198. if (*input == 0)
  12199. {
  12200. setLastError ("unterminated CDATA section", false);
  12201. outOfData = true;
  12202. break;
  12203. }
  12204. else if (input[0] == ']'
  12205. && input[1] == ']'
  12206. && input[2] == '>')
  12207. {
  12208. input += 3;
  12209. break;
  12210. }
  12211. ++input;
  12212. ++len;
  12213. }
  12214. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12215. if (lastChildNode != 0)
  12216. lastChildNode->nextElement = e;
  12217. else
  12218. parent->addChildElement (e);
  12219. lastChildNode = e;
  12220. }
  12221. else
  12222. {
  12223. // this is some other element, so parse and add it..
  12224. XmlElement* const n = readNextElement (true);
  12225. if (n != 0)
  12226. {
  12227. if (lastChildNode == 0)
  12228. parent->addChildElement (n);
  12229. else
  12230. lastChildNode->nextElement = n;
  12231. lastChildNode = n;
  12232. }
  12233. else
  12234. {
  12235. return;
  12236. }
  12237. }
  12238. }
  12239. else // must be a character block
  12240. {
  12241. input = preWhitespaceInput; // roll back to include the leading whitespace
  12242. String textElementContent;
  12243. for (;;)
  12244. {
  12245. const juce_wchar c = *input;
  12246. if (c == '<')
  12247. break;
  12248. if (c == 0)
  12249. {
  12250. setLastError ("unmatched tags", false);
  12251. outOfData = true;
  12252. return;
  12253. }
  12254. if (c == '&')
  12255. {
  12256. String entity;
  12257. readEntity (entity);
  12258. if (entity.startsWithChar ('<') && entity [1] != 0)
  12259. {
  12260. const juce_wchar* const oldInput = input;
  12261. const bool oldOutOfData = outOfData;
  12262. input = entity;
  12263. outOfData = false;
  12264. for (;;)
  12265. {
  12266. XmlElement* const n = readNextElement (true);
  12267. if (n == 0)
  12268. break;
  12269. if (lastChildNode == 0)
  12270. parent->addChildElement (n);
  12271. else
  12272. lastChildNode->nextElement = n;
  12273. lastChildNode = n;
  12274. }
  12275. input = oldInput;
  12276. outOfData = oldOutOfData;
  12277. }
  12278. else
  12279. {
  12280. textElementContent += entity;
  12281. }
  12282. }
  12283. else
  12284. {
  12285. const juce_wchar* start = input;
  12286. int len = 0;
  12287. for (;;)
  12288. {
  12289. const juce_wchar nextChar = *input;
  12290. if (nextChar == '<' || nextChar == '&')
  12291. {
  12292. break;
  12293. }
  12294. else if (nextChar == 0)
  12295. {
  12296. setLastError ("unmatched tags", false);
  12297. outOfData = true;
  12298. return;
  12299. }
  12300. ++input;
  12301. ++len;
  12302. }
  12303. textElementContent.append (start, len);
  12304. }
  12305. }
  12306. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12307. {
  12308. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12309. if (lastChildNode != 0)
  12310. lastChildNode->nextElement = textElement;
  12311. else
  12312. parent->addChildElement (textElement);
  12313. lastChildNode = textElement;
  12314. }
  12315. }
  12316. }
  12317. }
  12318. void XmlDocument::readEntity (String& result)
  12319. {
  12320. // skip over the ampersand
  12321. ++input;
  12322. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12323. {
  12324. input += 4;
  12325. result += '&';
  12326. }
  12327. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12328. {
  12329. input += 5;
  12330. result += '"';
  12331. }
  12332. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12333. {
  12334. input += 5;
  12335. result += '\'';
  12336. }
  12337. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12338. {
  12339. input += 3;
  12340. result += '<';
  12341. }
  12342. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12343. {
  12344. input += 3;
  12345. result += '>';
  12346. }
  12347. else if (*input == '#')
  12348. {
  12349. int charCode = 0;
  12350. ++input;
  12351. if (*input == 'x' || *input == 'X')
  12352. {
  12353. ++input;
  12354. int numChars = 0;
  12355. while (input[0] != ';')
  12356. {
  12357. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12358. if (hexValue < 0 || ++numChars > 8)
  12359. {
  12360. setLastError ("illegal escape sequence", true);
  12361. break;
  12362. }
  12363. charCode = (charCode << 4) | hexValue;
  12364. ++input;
  12365. }
  12366. ++input;
  12367. }
  12368. else if (input[0] >= '0' && input[0] <= '9')
  12369. {
  12370. int numChars = 0;
  12371. while (input[0] != ';')
  12372. {
  12373. if (++numChars > 12)
  12374. {
  12375. setLastError ("illegal escape sequence", true);
  12376. break;
  12377. }
  12378. charCode = charCode * 10 + (input[0] - '0');
  12379. ++input;
  12380. }
  12381. ++input;
  12382. }
  12383. else
  12384. {
  12385. setLastError ("illegal escape sequence", true);
  12386. result += '&';
  12387. return;
  12388. }
  12389. result << (juce_wchar) charCode;
  12390. }
  12391. else
  12392. {
  12393. const juce_wchar* const entityNameStart = input;
  12394. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12395. if (closingSemiColon == 0)
  12396. {
  12397. outOfData = true;
  12398. result += '&';
  12399. }
  12400. else
  12401. {
  12402. input = closingSemiColon + 1;
  12403. result += expandExternalEntity (String (entityNameStart,
  12404. (int) (closingSemiColon - entityNameStart)));
  12405. }
  12406. }
  12407. }
  12408. const String XmlDocument::expandEntity (const String& ent)
  12409. {
  12410. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12411. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12412. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12413. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12414. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12415. if (ent[0] == '#')
  12416. {
  12417. if (ent[1] == 'x' || ent[1] == 'X')
  12418. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12419. if (ent[1] >= '0' && ent[1] <= '9')
  12420. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12421. setLastError ("illegal escape sequence", false);
  12422. return String::charToString ('&');
  12423. }
  12424. return expandExternalEntity (ent);
  12425. }
  12426. const String XmlDocument::expandExternalEntity (const String& entity)
  12427. {
  12428. if (needToLoadDTD)
  12429. {
  12430. if (dtdText.isNotEmpty())
  12431. {
  12432. dtdText = dtdText.trimCharactersAtEnd (">");
  12433. tokenisedDTD.addTokens (dtdText, true);
  12434. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12435. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12436. {
  12437. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12438. tokenisedDTD.clear();
  12439. tokenisedDTD.addTokens (getFileContents (fn), true);
  12440. }
  12441. else
  12442. {
  12443. tokenisedDTD.clear();
  12444. const int openBracket = dtdText.indexOfChar ('[');
  12445. if (openBracket > 0)
  12446. {
  12447. const int closeBracket = dtdText.lastIndexOfChar (']');
  12448. if (closeBracket > openBracket)
  12449. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12450. closeBracket), true);
  12451. }
  12452. }
  12453. for (int i = tokenisedDTD.size(); --i >= 0;)
  12454. {
  12455. if (tokenisedDTD[i].startsWithChar ('%')
  12456. && tokenisedDTD[i].endsWithChar (';'))
  12457. {
  12458. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12459. StringArray newToks;
  12460. newToks.addTokens (parsed, true);
  12461. tokenisedDTD.remove (i);
  12462. for (int j = newToks.size(); --j >= 0;)
  12463. tokenisedDTD.insert (i, newToks[j]);
  12464. }
  12465. }
  12466. }
  12467. needToLoadDTD = false;
  12468. }
  12469. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12470. {
  12471. if (tokenisedDTD[i] == entity)
  12472. {
  12473. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12474. {
  12475. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12476. // check for sub-entities..
  12477. int ampersand = ent.indexOfChar ('&');
  12478. while (ampersand >= 0)
  12479. {
  12480. const int semiColon = ent.indexOf (i + 1, ";");
  12481. if (semiColon < 0)
  12482. {
  12483. setLastError ("entity without terminating semi-colon", false);
  12484. break;
  12485. }
  12486. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12487. ent = ent.substring (0, ampersand)
  12488. + resolved
  12489. + ent.substring (semiColon + 1);
  12490. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12491. }
  12492. return ent;
  12493. }
  12494. }
  12495. }
  12496. setLastError ("unknown entity", true);
  12497. return entity;
  12498. }
  12499. const String XmlDocument::getParameterEntity (const String& entity)
  12500. {
  12501. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12502. {
  12503. if (tokenisedDTD[i] == entity)
  12504. {
  12505. if (tokenisedDTD [i - 1] == "%"
  12506. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12507. {
  12508. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12509. if (ent.equalsIgnoreCase ("system"))
  12510. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12511. else
  12512. return ent.trim().unquoted();
  12513. }
  12514. }
  12515. }
  12516. return entity;
  12517. }
  12518. END_JUCE_NAMESPACE
  12519. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12520. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12521. BEGIN_JUCE_NAMESPACE
  12522. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12523. : name (other.name),
  12524. value (other.value),
  12525. next (0)
  12526. {
  12527. }
  12528. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12529. : name (name_),
  12530. value (value_),
  12531. next (0)
  12532. {
  12533. #if JUCE_DEBUG
  12534. // this checks whether the attribute name string contains any illegals characters..
  12535. for (const juce_wchar* t = name; *t != 0; ++t)
  12536. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12537. #endif
  12538. }
  12539. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12540. {
  12541. return name.equalsIgnoreCase (nameToMatch);
  12542. }
  12543. XmlElement::XmlElement (const String& tagName_) throw()
  12544. : tagName (tagName_),
  12545. firstChildElement (0),
  12546. nextElement (0),
  12547. attributes (0)
  12548. {
  12549. // the tag name mustn't be empty, or it'll look like a text element!
  12550. jassert (tagName_.containsNonWhitespaceChars())
  12551. // The tag can't contain spaces or other characters that would create invalid XML!
  12552. jassert (! tagName_.containsAnyOf (" <>/&"));
  12553. }
  12554. XmlElement::XmlElement (int /*dummy*/) throw()
  12555. : firstChildElement (0),
  12556. nextElement (0),
  12557. attributes (0)
  12558. {
  12559. }
  12560. XmlElement::XmlElement (const XmlElement& other)
  12561. : tagName (other.tagName),
  12562. firstChildElement (0),
  12563. nextElement (0),
  12564. attributes (0)
  12565. {
  12566. copyChildrenAndAttributesFrom (other);
  12567. }
  12568. XmlElement& XmlElement::operator= (const XmlElement& other)
  12569. {
  12570. if (this != &other)
  12571. {
  12572. removeAllAttributes();
  12573. deleteAllChildElements();
  12574. tagName = other.tagName;
  12575. copyChildrenAndAttributesFrom (other);
  12576. }
  12577. return *this;
  12578. }
  12579. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12580. {
  12581. XmlElement* child = other.firstChildElement;
  12582. XmlElement* lastChild = 0;
  12583. while (child != 0)
  12584. {
  12585. XmlElement* const copiedChild = new XmlElement (*child);
  12586. if (lastChild != 0)
  12587. lastChild->nextElement = copiedChild;
  12588. else
  12589. firstChildElement = copiedChild;
  12590. lastChild = copiedChild;
  12591. child = child->nextElement;
  12592. }
  12593. const XmlAttributeNode* att = other.attributes;
  12594. XmlAttributeNode* lastAtt = 0;
  12595. while (att != 0)
  12596. {
  12597. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12598. if (lastAtt != 0)
  12599. lastAtt->next = newAtt;
  12600. else
  12601. attributes = newAtt;
  12602. lastAtt = newAtt;
  12603. att = att->next;
  12604. }
  12605. }
  12606. XmlElement::~XmlElement() throw()
  12607. {
  12608. XmlElement* child = firstChildElement;
  12609. while (child != 0)
  12610. {
  12611. XmlElement* const nextChild = child->nextElement;
  12612. delete child;
  12613. child = nextChild;
  12614. }
  12615. XmlAttributeNode* att = attributes;
  12616. while (att != 0)
  12617. {
  12618. XmlAttributeNode* const nextAtt = att->next;
  12619. delete att;
  12620. att = nextAtt;
  12621. }
  12622. }
  12623. namespace XmlOutputFunctions
  12624. {
  12625. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12626. {
  12627. if ((character >= 'a' && character <= 'z')
  12628. || (character >= 'A' && character <= 'Z')
  12629. || (character >= '0' && character <= '9'))
  12630. return true;
  12631. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12632. do
  12633. {
  12634. if (((juce_wchar) (uint8) *t) == character)
  12635. return true;
  12636. }
  12637. while (*++t != 0);
  12638. return false;
  12639. }
  12640. void generateLegalCharConstants()
  12641. {
  12642. uint8 n[32];
  12643. zerostruct (n);
  12644. for (int i = 0; i < 256; ++i)
  12645. if (isLegalXmlCharSlow (i))
  12646. n[i >> 3] |= (1 << (i & 7));
  12647. String s;
  12648. for (int i = 0; i < 32; ++i)
  12649. s << (int) n[i] << ", ";
  12650. DBG (s);
  12651. }*/
  12652. bool isLegalXmlChar (const uint32 c) throw()
  12653. {
  12654. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12655. return c < sizeof (legalChars) * 8
  12656. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12657. }
  12658. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12659. {
  12660. const juce_wchar* t = text;
  12661. for (;;)
  12662. {
  12663. const juce_wchar character = *t++;
  12664. if (character == 0)
  12665. break;
  12666. if (isLegalXmlChar ((uint32) character))
  12667. {
  12668. outputStream << (char) character;
  12669. }
  12670. else
  12671. {
  12672. switch (character)
  12673. {
  12674. case '&': outputStream << "&amp;"; break;
  12675. case '"': outputStream << "&quot;"; break;
  12676. case '>': outputStream << "&gt;"; break;
  12677. case '<': outputStream << "&lt;"; break;
  12678. case '\n':
  12679. case '\r':
  12680. if (! changeNewLines)
  12681. {
  12682. outputStream << (char) character;
  12683. break;
  12684. }
  12685. // Note: deliberate fall-through here!
  12686. default:
  12687. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12688. break;
  12689. }
  12690. }
  12691. }
  12692. }
  12693. void writeSpaces (OutputStream& out, int numSpaces)
  12694. {
  12695. if (numSpaces > 0)
  12696. {
  12697. const char blanks[] = " ";
  12698. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12699. while (numSpaces > blankSize)
  12700. {
  12701. out.write (blanks, blankSize);
  12702. numSpaces -= blankSize;
  12703. }
  12704. out.write (blanks, numSpaces);
  12705. }
  12706. }
  12707. void writeNewLine (OutputStream& out)
  12708. {
  12709. out.write ("\r\n", 2);
  12710. }
  12711. }
  12712. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12713. const int indentationLevel,
  12714. const int lineWrapLength) const
  12715. {
  12716. using namespace XmlOutputFunctions;
  12717. writeSpaces (outputStream, indentationLevel);
  12718. if (! isTextElement())
  12719. {
  12720. outputStream.writeByte ('<');
  12721. outputStream << tagName;
  12722. {
  12723. const int attIndent = indentationLevel + tagName.length() + 1;
  12724. int lineLen = 0;
  12725. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12726. {
  12727. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12728. {
  12729. writeNewLine (outputStream);
  12730. writeSpaces (outputStream, attIndent);
  12731. lineLen = 0;
  12732. }
  12733. const int64 startPos = outputStream.getPosition();
  12734. outputStream.writeByte (' ');
  12735. outputStream << att->name;
  12736. outputStream.write ("=\"", 2);
  12737. escapeIllegalXmlChars (outputStream, att->value, true);
  12738. outputStream.writeByte ('"');
  12739. lineLen += (int) (outputStream.getPosition() - startPos);
  12740. }
  12741. }
  12742. if (firstChildElement != 0)
  12743. {
  12744. outputStream.writeByte ('>');
  12745. XmlElement* child = firstChildElement;
  12746. bool lastWasTextNode = false;
  12747. while (child != 0)
  12748. {
  12749. if (child->isTextElement())
  12750. {
  12751. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12752. lastWasTextNode = true;
  12753. }
  12754. else
  12755. {
  12756. if (indentationLevel >= 0 && ! lastWasTextNode)
  12757. writeNewLine (outputStream);
  12758. child->writeElementAsText (outputStream,
  12759. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12760. lastWasTextNode = false;
  12761. }
  12762. child = child->nextElement;
  12763. }
  12764. if (indentationLevel >= 0 && ! lastWasTextNode)
  12765. {
  12766. writeNewLine (outputStream);
  12767. writeSpaces (outputStream, indentationLevel);
  12768. }
  12769. outputStream.write ("</", 2);
  12770. outputStream << tagName;
  12771. outputStream.writeByte ('>');
  12772. }
  12773. else
  12774. {
  12775. outputStream.write ("/>", 2);
  12776. }
  12777. }
  12778. else
  12779. {
  12780. escapeIllegalXmlChars (outputStream, getText(), false);
  12781. }
  12782. }
  12783. const String XmlElement::createDocument (const String& dtdToUse,
  12784. const bool allOnOneLine,
  12785. const bool includeXmlHeader,
  12786. const String& encodingType,
  12787. const int lineWrapLength) const
  12788. {
  12789. MemoryOutputStream mem (2048);
  12790. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12791. return mem.toUTF8();
  12792. }
  12793. void XmlElement::writeToStream (OutputStream& output,
  12794. const String& dtdToUse,
  12795. const bool allOnOneLine,
  12796. const bool includeXmlHeader,
  12797. const String& encodingType,
  12798. const int lineWrapLength) const
  12799. {
  12800. using namespace XmlOutputFunctions;
  12801. if (includeXmlHeader)
  12802. {
  12803. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12804. if (allOnOneLine)
  12805. {
  12806. output.writeByte (' ');
  12807. }
  12808. else
  12809. {
  12810. writeNewLine (output);
  12811. writeNewLine (output);
  12812. }
  12813. }
  12814. if (dtdToUse.isNotEmpty())
  12815. {
  12816. output << dtdToUse;
  12817. if (allOnOneLine)
  12818. output.writeByte (' ');
  12819. else
  12820. writeNewLine (output);
  12821. }
  12822. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12823. if (! allOnOneLine)
  12824. writeNewLine (output);
  12825. }
  12826. bool XmlElement::writeToFile (const File& file,
  12827. const String& dtdToUse,
  12828. const String& encodingType,
  12829. const int lineWrapLength) const
  12830. {
  12831. if (file.hasWriteAccess())
  12832. {
  12833. TemporaryFile tempFile (file);
  12834. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12835. if (out != 0)
  12836. {
  12837. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12838. out = 0;
  12839. return tempFile.overwriteTargetFileWithTemporary();
  12840. }
  12841. }
  12842. return false;
  12843. }
  12844. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12845. {
  12846. #if JUCE_DEBUG
  12847. // if debugging, check that the case is actually the same, because
  12848. // valid xml is case-sensitive, and although this lets it pass, it's
  12849. // better not to..
  12850. if (tagName.equalsIgnoreCase (tagNameWanted))
  12851. {
  12852. jassert (tagName == tagNameWanted);
  12853. return true;
  12854. }
  12855. else
  12856. {
  12857. return false;
  12858. }
  12859. #else
  12860. return tagName.equalsIgnoreCase (tagNameWanted);
  12861. #endif
  12862. }
  12863. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12864. {
  12865. XmlElement* e = nextElement;
  12866. while (e != 0 && ! e->hasTagName (requiredTagName))
  12867. e = e->nextElement;
  12868. return e;
  12869. }
  12870. int XmlElement::getNumAttributes() const throw()
  12871. {
  12872. int count = 0;
  12873. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12874. ++count;
  12875. return count;
  12876. }
  12877. const String& XmlElement::getAttributeName (const int index) const throw()
  12878. {
  12879. int count = 0;
  12880. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12881. {
  12882. if (count == index)
  12883. return att->name;
  12884. ++count;
  12885. }
  12886. return String::empty;
  12887. }
  12888. const String& XmlElement::getAttributeValue (const int index) const throw()
  12889. {
  12890. int count = 0;
  12891. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12892. {
  12893. if (count == index)
  12894. return att->value;
  12895. ++count;
  12896. }
  12897. return String::empty;
  12898. }
  12899. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12900. {
  12901. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12902. if (att->hasName (attributeName))
  12903. return true;
  12904. return false;
  12905. }
  12906. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12907. {
  12908. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12909. if (att->hasName (attributeName))
  12910. return att->value;
  12911. return String::empty;
  12912. }
  12913. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12914. {
  12915. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12916. if (att->hasName (attributeName))
  12917. return att->value;
  12918. return defaultReturnValue;
  12919. }
  12920. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12921. {
  12922. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12923. if (att->hasName (attributeName))
  12924. return att->value.getIntValue();
  12925. return defaultReturnValue;
  12926. }
  12927. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12928. {
  12929. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12930. if (att->hasName (attributeName))
  12931. return att->value.getDoubleValue();
  12932. return defaultReturnValue;
  12933. }
  12934. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12935. {
  12936. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12937. {
  12938. if (att->hasName (attributeName))
  12939. {
  12940. juce_wchar firstChar = att->value[0];
  12941. if (CharacterFunctions::isWhitespace (firstChar))
  12942. firstChar = att->value.trimStart() [0];
  12943. return firstChar == '1'
  12944. || firstChar == 't'
  12945. || firstChar == 'y'
  12946. || firstChar == 'T'
  12947. || firstChar == 'Y';
  12948. }
  12949. }
  12950. return defaultReturnValue;
  12951. }
  12952. bool XmlElement::compareAttribute (const String& attributeName,
  12953. const String& stringToCompareAgainst,
  12954. const bool ignoreCase) const throw()
  12955. {
  12956. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12957. if (att->hasName (attributeName))
  12958. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12959. : att->value == stringToCompareAgainst;
  12960. return false;
  12961. }
  12962. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12963. {
  12964. if (attributes == 0)
  12965. {
  12966. attributes = new XmlAttributeNode (attributeName, value);
  12967. }
  12968. else
  12969. {
  12970. XmlAttributeNode* att = attributes;
  12971. for (;;)
  12972. {
  12973. if (att->hasName (attributeName))
  12974. {
  12975. att->value = value;
  12976. break;
  12977. }
  12978. else if (att->next == 0)
  12979. {
  12980. att->next = new XmlAttributeNode (attributeName, value);
  12981. break;
  12982. }
  12983. att = att->next;
  12984. }
  12985. }
  12986. }
  12987. void XmlElement::setAttribute (const String& attributeName, const int number)
  12988. {
  12989. setAttribute (attributeName, String (number));
  12990. }
  12991. void XmlElement::setAttribute (const String& attributeName, const double number)
  12992. {
  12993. setAttribute (attributeName, String (number));
  12994. }
  12995. void XmlElement::removeAttribute (const String& attributeName) throw()
  12996. {
  12997. XmlAttributeNode* lastAtt = 0;
  12998. for (XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12999. {
  13000. if (att->hasName (attributeName))
  13001. {
  13002. if (lastAtt == 0)
  13003. attributes = att->next;
  13004. else
  13005. lastAtt->next = att->next;
  13006. delete att;
  13007. break;
  13008. }
  13009. lastAtt = att;
  13010. }
  13011. }
  13012. void XmlElement::removeAllAttributes() throw()
  13013. {
  13014. while (attributes != 0)
  13015. {
  13016. XmlAttributeNode* const nextAtt = attributes->next;
  13017. delete attributes;
  13018. attributes = nextAtt;
  13019. }
  13020. }
  13021. int XmlElement::getNumChildElements() const throw()
  13022. {
  13023. int count = 0;
  13024. const XmlElement* child = firstChildElement;
  13025. while (child != 0)
  13026. {
  13027. ++count;
  13028. child = child->nextElement;
  13029. }
  13030. return count;
  13031. }
  13032. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13033. {
  13034. int count = 0;
  13035. XmlElement* child = firstChildElement;
  13036. while (child != 0 && count < index)
  13037. {
  13038. child = child->nextElement;
  13039. ++count;
  13040. }
  13041. return child;
  13042. }
  13043. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13044. {
  13045. XmlElement* child = firstChildElement;
  13046. while (child != 0)
  13047. {
  13048. if (child->hasTagName (childName))
  13049. break;
  13050. child = child->nextElement;
  13051. }
  13052. return child;
  13053. }
  13054. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13055. {
  13056. if (newNode != 0)
  13057. {
  13058. if (firstChildElement == 0)
  13059. {
  13060. firstChildElement = newNode;
  13061. }
  13062. else
  13063. {
  13064. XmlElement* child = firstChildElement;
  13065. while (child->nextElement != 0)
  13066. child = child->nextElement;
  13067. child->nextElement = newNode;
  13068. // if this is non-zero, then something's probably
  13069. // gone wrong..
  13070. jassert (newNode->nextElement == 0);
  13071. }
  13072. }
  13073. }
  13074. void XmlElement::insertChildElement (XmlElement* const newNode,
  13075. int indexToInsertAt) throw()
  13076. {
  13077. if (newNode != 0)
  13078. {
  13079. removeChildElement (newNode, false);
  13080. if (indexToInsertAt == 0)
  13081. {
  13082. newNode->nextElement = firstChildElement;
  13083. firstChildElement = newNode;
  13084. }
  13085. else
  13086. {
  13087. if (firstChildElement == 0)
  13088. {
  13089. firstChildElement = newNode;
  13090. }
  13091. else
  13092. {
  13093. if (indexToInsertAt < 0)
  13094. indexToInsertAt = std::numeric_limits<int>::max();
  13095. XmlElement* child = firstChildElement;
  13096. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13097. child = child->nextElement;
  13098. newNode->nextElement = child->nextElement;
  13099. child->nextElement = newNode;
  13100. }
  13101. }
  13102. }
  13103. }
  13104. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13105. {
  13106. XmlElement* const newElement = new XmlElement (childTagName);
  13107. addChildElement (newElement);
  13108. return newElement;
  13109. }
  13110. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13111. XmlElement* const newNode) throw()
  13112. {
  13113. if (newNode != 0)
  13114. {
  13115. XmlElement* child = firstChildElement;
  13116. XmlElement* previousNode = 0;
  13117. while (child != 0)
  13118. {
  13119. if (child == currentChildElement)
  13120. {
  13121. if (child != newNode)
  13122. {
  13123. if (previousNode == 0)
  13124. firstChildElement = newNode;
  13125. else
  13126. previousNode->nextElement = newNode;
  13127. newNode->nextElement = child->nextElement;
  13128. delete child;
  13129. }
  13130. return true;
  13131. }
  13132. previousNode = child;
  13133. child = child->nextElement;
  13134. }
  13135. }
  13136. return false;
  13137. }
  13138. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13139. const bool shouldDeleteTheChild) throw()
  13140. {
  13141. if (childToRemove != 0)
  13142. {
  13143. if (firstChildElement == childToRemove)
  13144. {
  13145. firstChildElement = childToRemove->nextElement;
  13146. childToRemove->nextElement = 0;
  13147. }
  13148. else
  13149. {
  13150. XmlElement* child = firstChildElement;
  13151. XmlElement* last = 0;
  13152. while (child != 0)
  13153. {
  13154. if (child == childToRemove)
  13155. {
  13156. if (last == 0)
  13157. firstChildElement = child->nextElement;
  13158. else
  13159. last->nextElement = child->nextElement;
  13160. childToRemove->nextElement = 0;
  13161. break;
  13162. }
  13163. last = child;
  13164. child = child->nextElement;
  13165. }
  13166. }
  13167. if (shouldDeleteTheChild)
  13168. delete childToRemove;
  13169. }
  13170. }
  13171. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13172. const bool ignoreOrderOfAttributes) const throw()
  13173. {
  13174. if (this != other)
  13175. {
  13176. if (other == 0 || tagName != other->tagName)
  13177. return false;
  13178. if (ignoreOrderOfAttributes)
  13179. {
  13180. int totalAtts = 0;
  13181. const XmlAttributeNode* att = attributes;
  13182. while (att != 0)
  13183. {
  13184. if (! other->compareAttribute (att->name, att->value))
  13185. return false;
  13186. att = att->next;
  13187. ++totalAtts;
  13188. }
  13189. if (totalAtts != other->getNumAttributes())
  13190. return false;
  13191. }
  13192. else
  13193. {
  13194. const XmlAttributeNode* thisAtt = attributes;
  13195. const XmlAttributeNode* otherAtt = other->attributes;
  13196. for (;;)
  13197. {
  13198. if (thisAtt == 0 || otherAtt == 0)
  13199. {
  13200. if (thisAtt == otherAtt) // both 0, so it's a match
  13201. break;
  13202. return false;
  13203. }
  13204. if (thisAtt->name != otherAtt->name
  13205. || thisAtt->value != otherAtt->value)
  13206. {
  13207. return false;
  13208. }
  13209. thisAtt = thisAtt->next;
  13210. otherAtt = otherAtt->next;
  13211. }
  13212. }
  13213. const XmlElement* thisChild = firstChildElement;
  13214. const XmlElement* otherChild = other->firstChildElement;
  13215. for (;;)
  13216. {
  13217. if (thisChild == 0 || otherChild == 0)
  13218. {
  13219. if (thisChild == otherChild) // both 0, so it's a match
  13220. break;
  13221. return false;
  13222. }
  13223. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13224. return false;
  13225. thisChild = thisChild->nextElement;
  13226. otherChild = otherChild->nextElement;
  13227. }
  13228. }
  13229. return true;
  13230. }
  13231. void XmlElement::deleteAllChildElements() throw()
  13232. {
  13233. while (firstChildElement != 0)
  13234. {
  13235. XmlElement* const nextChild = firstChildElement->nextElement;
  13236. delete firstChildElement;
  13237. firstChildElement = nextChild;
  13238. }
  13239. }
  13240. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13241. {
  13242. XmlElement* child = firstChildElement;
  13243. while (child != 0)
  13244. {
  13245. if (child->hasTagName (name))
  13246. {
  13247. XmlElement* const nextChild = child->nextElement;
  13248. removeChildElement (child, true);
  13249. child = nextChild;
  13250. }
  13251. else
  13252. {
  13253. child = child->nextElement;
  13254. }
  13255. }
  13256. }
  13257. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13258. {
  13259. const XmlElement* child = firstChildElement;
  13260. while (child != 0)
  13261. {
  13262. if (child == possibleChild)
  13263. return true;
  13264. child = child->nextElement;
  13265. }
  13266. return false;
  13267. }
  13268. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13269. {
  13270. if (this == elementToLookFor || elementToLookFor == 0)
  13271. return 0;
  13272. XmlElement* child = firstChildElement;
  13273. while (child != 0)
  13274. {
  13275. if (elementToLookFor == child)
  13276. return this;
  13277. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13278. if (found != 0)
  13279. return found;
  13280. child = child->nextElement;
  13281. }
  13282. return 0;
  13283. }
  13284. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13285. {
  13286. XmlElement* e = firstChildElement;
  13287. while (e != 0)
  13288. {
  13289. *elems++ = e;
  13290. e = e->nextElement;
  13291. }
  13292. }
  13293. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13294. {
  13295. XmlElement* e = firstChildElement = elems[0];
  13296. for (int i = 1; i < num; ++i)
  13297. {
  13298. e->nextElement = elems[i];
  13299. e = e->nextElement;
  13300. }
  13301. e->nextElement = 0;
  13302. }
  13303. bool XmlElement::isTextElement() const throw()
  13304. {
  13305. return tagName.isEmpty();
  13306. }
  13307. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13308. const String& XmlElement::getText() const throw()
  13309. {
  13310. jassert (isTextElement()); // you're trying to get the text from an element that
  13311. // isn't actually a text element.. If this contains text sub-nodes, you
  13312. // probably want to use getAllSubText instead.
  13313. return getStringAttribute (juce_xmltextContentAttributeName);
  13314. }
  13315. void XmlElement::setText (const String& newText)
  13316. {
  13317. if (isTextElement())
  13318. setAttribute (juce_xmltextContentAttributeName, newText);
  13319. else
  13320. jassertfalse; // you can only change the text in a text element, not a normal one.
  13321. }
  13322. const String XmlElement::getAllSubText() const
  13323. {
  13324. if (isTextElement())
  13325. return getText();
  13326. String result;
  13327. String::Concatenator concatenator (result);
  13328. const XmlElement* child = firstChildElement;
  13329. while (child != 0)
  13330. {
  13331. concatenator.append (child->getAllSubText());
  13332. child = child->nextElement;
  13333. }
  13334. return result;
  13335. }
  13336. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13337. const String& defaultReturnValue) const
  13338. {
  13339. const XmlElement* const child = getChildByName (childTagName);
  13340. if (child != 0)
  13341. return child->getAllSubText();
  13342. return defaultReturnValue;
  13343. }
  13344. XmlElement* XmlElement::createTextElement (const String& text)
  13345. {
  13346. XmlElement* const e = new XmlElement ((int) 0);
  13347. e->setAttribute (juce_xmltextContentAttributeName, text);
  13348. return e;
  13349. }
  13350. void XmlElement::addTextElement (const String& text)
  13351. {
  13352. addChildElement (createTextElement (text));
  13353. }
  13354. void XmlElement::deleteAllTextElements() throw()
  13355. {
  13356. XmlElement* child = firstChildElement;
  13357. while (child != 0)
  13358. {
  13359. XmlElement* const next = child->nextElement;
  13360. if (child->isTextElement())
  13361. removeChildElement (child, true);
  13362. child = next;
  13363. }
  13364. }
  13365. END_JUCE_NAMESPACE
  13366. /*** End of inlined file: juce_XmlElement.cpp ***/
  13367. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13368. BEGIN_JUCE_NAMESPACE
  13369. ReadWriteLock::ReadWriteLock() throw()
  13370. : numWaitingWriters (0),
  13371. numWriters (0),
  13372. writerThreadId (0)
  13373. {
  13374. }
  13375. ReadWriteLock::~ReadWriteLock() throw()
  13376. {
  13377. jassert (readerThreads.size() == 0);
  13378. jassert (numWriters == 0);
  13379. }
  13380. void ReadWriteLock::enterRead() const throw()
  13381. {
  13382. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13383. const ScopedLock sl (accessLock);
  13384. for (;;)
  13385. {
  13386. jassert (readerThreads.size() % 2 == 0);
  13387. int i;
  13388. for (i = 0; i < readerThreads.size(); i += 2)
  13389. if (readerThreads.getUnchecked(i) == threadId)
  13390. break;
  13391. if (i < readerThreads.size()
  13392. || numWriters + numWaitingWriters == 0
  13393. || (threadId == writerThreadId && numWriters > 0))
  13394. {
  13395. if (i < readerThreads.size())
  13396. {
  13397. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13398. }
  13399. else
  13400. {
  13401. readerThreads.add (threadId);
  13402. readerThreads.add ((Thread::ThreadID) 1);
  13403. }
  13404. return;
  13405. }
  13406. const ScopedUnlock ul (accessLock);
  13407. waitEvent.wait (100);
  13408. }
  13409. }
  13410. void ReadWriteLock::exitRead() const throw()
  13411. {
  13412. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13413. const ScopedLock sl (accessLock);
  13414. for (int i = 0; i < readerThreads.size(); i += 2)
  13415. {
  13416. if (readerThreads.getUnchecked(i) == threadId)
  13417. {
  13418. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13419. if (newCount == 0)
  13420. {
  13421. readerThreads.removeRange (i, 2);
  13422. waitEvent.signal();
  13423. }
  13424. else
  13425. {
  13426. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13427. }
  13428. return;
  13429. }
  13430. }
  13431. jassertfalse; // unlocking a lock that wasn't locked..
  13432. }
  13433. void ReadWriteLock::enterWrite() const throw()
  13434. {
  13435. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13436. const ScopedLock sl (accessLock);
  13437. for (;;)
  13438. {
  13439. if (readerThreads.size() + numWriters == 0
  13440. || threadId == writerThreadId
  13441. || (readerThreads.size() == 2
  13442. && readerThreads.getUnchecked(0) == threadId))
  13443. {
  13444. writerThreadId = threadId;
  13445. ++numWriters;
  13446. break;
  13447. }
  13448. ++numWaitingWriters;
  13449. accessLock.exit();
  13450. waitEvent.wait (100);
  13451. accessLock.enter();
  13452. --numWaitingWriters;
  13453. }
  13454. }
  13455. bool ReadWriteLock::tryEnterWrite() const throw()
  13456. {
  13457. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13458. const ScopedLock sl (accessLock);
  13459. if (readerThreads.size() + numWriters == 0
  13460. || threadId == writerThreadId
  13461. || (readerThreads.size() == 2
  13462. && readerThreads.getUnchecked(0) == threadId))
  13463. {
  13464. writerThreadId = threadId;
  13465. ++numWriters;
  13466. return true;
  13467. }
  13468. return false;
  13469. }
  13470. void ReadWriteLock::exitWrite() const throw()
  13471. {
  13472. const ScopedLock sl (accessLock);
  13473. // check this thread actually had the lock..
  13474. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13475. if (--numWriters == 0)
  13476. {
  13477. writerThreadId = 0;
  13478. waitEvent.signal();
  13479. }
  13480. }
  13481. END_JUCE_NAMESPACE
  13482. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13483. /*** Start of inlined file: juce_Thread.cpp ***/
  13484. BEGIN_JUCE_NAMESPACE
  13485. class RunningThreadsList
  13486. {
  13487. public:
  13488. RunningThreadsList()
  13489. {
  13490. }
  13491. void add (Thread* const thread)
  13492. {
  13493. const ScopedLock sl (lock);
  13494. jassert (! threads.contains (thread));
  13495. threads.add (thread);
  13496. }
  13497. void remove (Thread* const thread)
  13498. {
  13499. const ScopedLock sl (lock);
  13500. jassert (threads.contains (thread));
  13501. threads.removeValue (thread);
  13502. }
  13503. int size() const throw()
  13504. {
  13505. return threads.size();
  13506. }
  13507. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13508. {
  13509. const ScopedLock sl (lock);
  13510. for (int i = threads.size(); --i >= 0;)
  13511. {
  13512. Thread* const t = threads.getUnchecked(i);
  13513. if (t->getThreadId() == targetID)
  13514. return t;
  13515. }
  13516. return 0;
  13517. }
  13518. void stopAll (const int timeOutMilliseconds)
  13519. {
  13520. signalAllThreadsToStop();
  13521. for (;;)
  13522. {
  13523. Thread* firstThread = getFirstThread();
  13524. if (firstThread != 0)
  13525. firstThread->stopThread (timeOutMilliseconds);
  13526. else
  13527. break;
  13528. }
  13529. }
  13530. static RunningThreadsList& getInstance()
  13531. {
  13532. static RunningThreadsList runningThreads;
  13533. return runningThreads;
  13534. }
  13535. private:
  13536. Array<Thread*> threads;
  13537. CriticalSection lock;
  13538. void signalAllThreadsToStop()
  13539. {
  13540. const ScopedLock sl (lock);
  13541. for (int i = threads.size(); --i >= 0;)
  13542. threads.getUnchecked(i)->signalThreadShouldExit();
  13543. }
  13544. Thread* getFirstThread() const
  13545. {
  13546. const ScopedLock sl (lock);
  13547. return threads.getFirst();
  13548. }
  13549. };
  13550. void Thread::threadEntryPoint()
  13551. {
  13552. RunningThreadsList::getInstance().add (this);
  13553. JUCE_TRY
  13554. {
  13555. if (threadName_.isNotEmpty())
  13556. setCurrentThreadName (threadName_);
  13557. if (startSuspensionEvent_.wait (10000))
  13558. {
  13559. jassert (getCurrentThreadId() == threadId_);
  13560. if (affinityMask_ != 0)
  13561. setCurrentThreadAffinityMask (affinityMask_);
  13562. run();
  13563. }
  13564. }
  13565. JUCE_CATCH_ALL_ASSERT
  13566. RunningThreadsList::getInstance().remove (this);
  13567. closeThreadHandle();
  13568. }
  13569. // used to wrap the incoming call from the platform-specific code
  13570. void JUCE_API juce_threadEntryPoint (void* userData)
  13571. {
  13572. static_cast <Thread*> (userData)->threadEntryPoint();
  13573. }
  13574. Thread::Thread (const String& threadName)
  13575. : threadName_ (threadName),
  13576. threadHandle_ (0),
  13577. threadId_ (0),
  13578. threadPriority_ (5),
  13579. affinityMask_ (0),
  13580. threadShouldExit_ (false)
  13581. {
  13582. }
  13583. Thread::~Thread()
  13584. {
  13585. /* If your thread class's destructor has been called without first stopping the thread, that
  13586. means that this partially destructed object is still performing some work - and that's
  13587. probably a Bad Thing!
  13588. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13589. your subclass's destructor.
  13590. */
  13591. jassert (! isThreadRunning());
  13592. stopThread (100);
  13593. }
  13594. void Thread::startThread()
  13595. {
  13596. const ScopedLock sl (startStopLock);
  13597. threadShouldExit_ = false;
  13598. if (threadHandle_ == 0)
  13599. {
  13600. launchThread();
  13601. setThreadPriority (threadHandle_, threadPriority_);
  13602. startSuspensionEvent_.signal();
  13603. }
  13604. }
  13605. void Thread::startThread (const int priority)
  13606. {
  13607. const ScopedLock sl (startStopLock);
  13608. if (threadHandle_ == 0)
  13609. {
  13610. threadPriority_ = priority;
  13611. startThread();
  13612. }
  13613. else
  13614. {
  13615. setPriority (priority);
  13616. }
  13617. }
  13618. bool Thread::isThreadRunning() const
  13619. {
  13620. return threadHandle_ != 0;
  13621. }
  13622. void Thread::signalThreadShouldExit()
  13623. {
  13624. threadShouldExit_ = true;
  13625. }
  13626. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13627. {
  13628. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13629. jassert (getThreadId() != getCurrentThreadId());
  13630. const int sleepMsPerIteration = 5;
  13631. int count = timeOutMilliseconds / sleepMsPerIteration;
  13632. while (isThreadRunning())
  13633. {
  13634. if (timeOutMilliseconds > 0 && --count < 0)
  13635. return false;
  13636. sleep (sleepMsPerIteration);
  13637. }
  13638. return true;
  13639. }
  13640. void Thread::stopThread (const int timeOutMilliseconds)
  13641. {
  13642. // agh! You can't stop the thread that's calling this method! How on earth
  13643. // would that work??
  13644. jassert (getCurrentThreadId() != getThreadId());
  13645. const ScopedLock sl (startStopLock);
  13646. if (isThreadRunning())
  13647. {
  13648. signalThreadShouldExit();
  13649. notify();
  13650. if (timeOutMilliseconds != 0)
  13651. waitForThreadToExit (timeOutMilliseconds);
  13652. if (isThreadRunning())
  13653. {
  13654. // very bad karma if this point is reached, as there are bound to be
  13655. // locks and events left in silly states when a thread is killed by force..
  13656. jassertfalse;
  13657. Logger::writeToLog ("!! killing thread by force !!");
  13658. killThread();
  13659. RunningThreadsList::getInstance().remove (this);
  13660. threadHandle_ = 0;
  13661. threadId_ = 0;
  13662. }
  13663. }
  13664. }
  13665. bool Thread::setPriority (const int priority)
  13666. {
  13667. const ScopedLock sl (startStopLock);
  13668. if (setThreadPriority (threadHandle_, priority))
  13669. {
  13670. threadPriority_ = priority;
  13671. return true;
  13672. }
  13673. return false;
  13674. }
  13675. bool Thread::setCurrentThreadPriority (const int priority)
  13676. {
  13677. return setThreadPriority (0, priority);
  13678. }
  13679. void Thread::setAffinityMask (const uint32 affinityMask)
  13680. {
  13681. affinityMask_ = affinityMask;
  13682. }
  13683. bool Thread::wait (const int timeOutMilliseconds) const
  13684. {
  13685. return defaultEvent_.wait (timeOutMilliseconds);
  13686. }
  13687. void Thread::notify() const
  13688. {
  13689. defaultEvent_.signal();
  13690. }
  13691. int Thread::getNumRunningThreads()
  13692. {
  13693. return RunningThreadsList::getInstance().size();
  13694. }
  13695. Thread* Thread::getCurrentThread()
  13696. {
  13697. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13698. }
  13699. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13700. {
  13701. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13702. }
  13703. END_JUCE_NAMESPACE
  13704. /*** End of inlined file: juce_Thread.cpp ***/
  13705. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13706. BEGIN_JUCE_NAMESPACE
  13707. ThreadPoolJob::ThreadPoolJob (const String& name)
  13708. : jobName (name),
  13709. pool (0),
  13710. shouldStop (false),
  13711. isActive (false),
  13712. shouldBeDeleted (false)
  13713. {
  13714. }
  13715. ThreadPoolJob::~ThreadPoolJob()
  13716. {
  13717. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13718. // to remove it first!
  13719. jassert (pool == 0 || ! pool->contains (this));
  13720. }
  13721. const String ThreadPoolJob::getJobName() const
  13722. {
  13723. return jobName;
  13724. }
  13725. void ThreadPoolJob::setJobName (const String& newName)
  13726. {
  13727. jobName = newName;
  13728. }
  13729. void ThreadPoolJob::signalJobShouldExit()
  13730. {
  13731. shouldStop = true;
  13732. }
  13733. class ThreadPool::ThreadPoolThread : public Thread
  13734. {
  13735. public:
  13736. ThreadPoolThread (ThreadPool& pool_)
  13737. : Thread ("Pool"),
  13738. pool (pool_),
  13739. busy (false)
  13740. {
  13741. }
  13742. void run()
  13743. {
  13744. while (! threadShouldExit())
  13745. {
  13746. if (! pool.runNextJob())
  13747. wait (500);
  13748. }
  13749. }
  13750. private:
  13751. ThreadPool& pool;
  13752. bool volatile busy;
  13753. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13754. };
  13755. ThreadPool::ThreadPool (const int numThreads,
  13756. const bool startThreadsOnlyWhenNeeded,
  13757. const int stopThreadsWhenNotUsedTimeoutMs)
  13758. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13759. priority (5)
  13760. {
  13761. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13762. for (int i = jmax (1, numThreads); --i >= 0;)
  13763. threads.add (new ThreadPoolThread (*this));
  13764. if (! startThreadsOnlyWhenNeeded)
  13765. for (int i = threads.size(); --i >= 0;)
  13766. threads.getUnchecked(i)->startThread (priority);
  13767. }
  13768. ThreadPool::~ThreadPool()
  13769. {
  13770. removeAllJobs (true, 4000);
  13771. int i;
  13772. for (i = threads.size(); --i >= 0;)
  13773. threads.getUnchecked(i)->signalThreadShouldExit();
  13774. for (i = threads.size(); --i >= 0;)
  13775. threads.getUnchecked(i)->stopThread (500);
  13776. }
  13777. void ThreadPool::addJob (ThreadPoolJob* const job)
  13778. {
  13779. jassert (job != 0);
  13780. jassert (job->pool == 0);
  13781. if (job->pool == 0)
  13782. {
  13783. job->pool = this;
  13784. job->shouldStop = false;
  13785. job->isActive = false;
  13786. {
  13787. const ScopedLock sl (lock);
  13788. jobs.add (job);
  13789. int numRunning = 0;
  13790. for (int i = threads.size(); --i >= 0;)
  13791. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13792. ++numRunning;
  13793. if (numRunning < threads.size())
  13794. {
  13795. bool startedOne = false;
  13796. int n = 1000;
  13797. while (--n >= 0 && ! startedOne)
  13798. {
  13799. for (int i = threads.size(); --i >= 0;)
  13800. {
  13801. if (! threads.getUnchecked(i)->isThreadRunning())
  13802. {
  13803. threads.getUnchecked(i)->startThread (priority);
  13804. startedOne = true;
  13805. break;
  13806. }
  13807. }
  13808. if (! startedOne)
  13809. Thread::sleep (2);
  13810. }
  13811. }
  13812. }
  13813. for (int i = threads.size(); --i >= 0;)
  13814. threads.getUnchecked(i)->notify();
  13815. }
  13816. }
  13817. int ThreadPool::getNumJobs() const
  13818. {
  13819. return jobs.size();
  13820. }
  13821. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13822. {
  13823. const ScopedLock sl (lock);
  13824. return jobs [index];
  13825. }
  13826. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13827. {
  13828. const ScopedLock sl (lock);
  13829. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13830. }
  13831. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13832. {
  13833. const ScopedLock sl (lock);
  13834. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13835. }
  13836. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13837. const int timeOutMs) const
  13838. {
  13839. if (job != 0)
  13840. {
  13841. const uint32 start = Time::getMillisecondCounter();
  13842. while (contains (job))
  13843. {
  13844. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13845. return false;
  13846. jobFinishedSignal.wait (2);
  13847. }
  13848. }
  13849. return true;
  13850. }
  13851. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13852. const bool interruptIfRunning,
  13853. const int timeOutMs)
  13854. {
  13855. bool dontWait = true;
  13856. if (job != 0)
  13857. {
  13858. const ScopedLock sl (lock);
  13859. if (jobs.contains (job))
  13860. {
  13861. if (job->isActive)
  13862. {
  13863. if (interruptIfRunning)
  13864. job->signalJobShouldExit();
  13865. dontWait = false;
  13866. }
  13867. else
  13868. {
  13869. jobs.removeValue (job);
  13870. job->pool = 0;
  13871. }
  13872. }
  13873. }
  13874. return dontWait || waitForJobToFinish (job, timeOutMs);
  13875. }
  13876. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13877. const int timeOutMs,
  13878. const bool deleteInactiveJobs,
  13879. ThreadPool::JobSelector* selectedJobsToRemove)
  13880. {
  13881. Array <ThreadPoolJob*> jobsToWaitFor;
  13882. {
  13883. const ScopedLock sl (lock);
  13884. for (int i = jobs.size(); --i >= 0;)
  13885. {
  13886. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13887. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13888. {
  13889. if (job->isActive)
  13890. {
  13891. jobsToWaitFor.add (job);
  13892. if (interruptRunningJobs)
  13893. job->signalJobShouldExit();
  13894. }
  13895. else
  13896. {
  13897. jobs.remove (i);
  13898. if (deleteInactiveJobs)
  13899. delete job;
  13900. else
  13901. job->pool = 0;
  13902. }
  13903. }
  13904. }
  13905. }
  13906. const uint32 start = Time::getMillisecondCounter();
  13907. for (;;)
  13908. {
  13909. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13910. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13911. jobsToWaitFor.remove (i);
  13912. if (jobsToWaitFor.size() == 0)
  13913. break;
  13914. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13915. return false;
  13916. jobFinishedSignal.wait (20);
  13917. }
  13918. return true;
  13919. }
  13920. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13921. {
  13922. StringArray s;
  13923. const ScopedLock sl (lock);
  13924. for (int i = 0; i < jobs.size(); ++i)
  13925. {
  13926. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13927. if (job->isActive || ! onlyReturnActiveJobs)
  13928. s.add (job->getJobName());
  13929. }
  13930. return s;
  13931. }
  13932. bool ThreadPool::setThreadPriorities (const int newPriority)
  13933. {
  13934. bool ok = true;
  13935. if (priority != newPriority)
  13936. {
  13937. priority = newPriority;
  13938. for (int i = threads.size(); --i >= 0;)
  13939. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13940. ok = false;
  13941. }
  13942. return ok;
  13943. }
  13944. bool ThreadPool::runNextJob()
  13945. {
  13946. ThreadPoolJob* job = 0;
  13947. {
  13948. const ScopedLock sl (lock);
  13949. for (int i = 0; i < jobs.size(); ++i)
  13950. {
  13951. job = jobs[i];
  13952. if (job != 0 && ! (job->isActive || job->shouldStop))
  13953. break;
  13954. job = 0;
  13955. }
  13956. if (job != 0)
  13957. job->isActive = true;
  13958. }
  13959. if (job != 0)
  13960. {
  13961. JUCE_TRY
  13962. {
  13963. ThreadPoolJob::JobStatus result = job->runJob();
  13964. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13965. const ScopedLock sl (lock);
  13966. if (jobs.contains (job))
  13967. {
  13968. job->isActive = false;
  13969. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13970. {
  13971. job->pool = 0;
  13972. job->shouldStop = true;
  13973. jobs.removeValue (job);
  13974. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13975. delete job;
  13976. jobFinishedSignal.signal();
  13977. }
  13978. else
  13979. {
  13980. // move the job to the end of the queue if it wants another go
  13981. jobs.move (jobs.indexOf (job), -1);
  13982. }
  13983. }
  13984. }
  13985. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13986. catch (...)
  13987. {
  13988. const ScopedLock sl (lock);
  13989. jobs.removeValue (job);
  13990. }
  13991. #endif
  13992. }
  13993. else
  13994. {
  13995. if (threadStopTimeout > 0
  13996. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13997. {
  13998. const ScopedLock sl (lock);
  13999. if (jobs.size() == 0)
  14000. for (int i = threads.size(); --i >= 0;)
  14001. threads.getUnchecked(i)->signalThreadShouldExit();
  14002. }
  14003. else
  14004. {
  14005. return false;
  14006. }
  14007. }
  14008. return true;
  14009. }
  14010. END_JUCE_NAMESPACE
  14011. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14012. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14013. BEGIN_JUCE_NAMESPACE
  14014. TimeSliceThread::TimeSliceThread (const String& threadName)
  14015. : Thread (threadName),
  14016. index (0),
  14017. clientBeingCalled (0),
  14018. clientsChanged (false)
  14019. {
  14020. }
  14021. TimeSliceThread::~TimeSliceThread()
  14022. {
  14023. stopThread (2000);
  14024. }
  14025. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14026. {
  14027. const ScopedLock sl (listLock);
  14028. clients.addIfNotAlreadyThere (client);
  14029. clientsChanged = true;
  14030. notify();
  14031. }
  14032. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14033. {
  14034. const ScopedLock sl1 (listLock);
  14035. clientsChanged = true;
  14036. // if there's a chance we're in the middle of calling this client, we need to
  14037. // also lock the outer lock..
  14038. if (clientBeingCalled == client)
  14039. {
  14040. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14041. const ScopedLock sl2 (callbackLock);
  14042. const ScopedLock sl3 (listLock);
  14043. clients.removeValue (client);
  14044. }
  14045. else
  14046. {
  14047. clients.removeValue (client);
  14048. }
  14049. }
  14050. int TimeSliceThread::getNumClients() const
  14051. {
  14052. return clients.size();
  14053. }
  14054. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14055. {
  14056. const ScopedLock sl (listLock);
  14057. return clients [i];
  14058. }
  14059. void TimeSliceThread::run()
  14060. {
  14061. int numCallsSinceBusy = 0;
  14062. while (! threadShouldExit())
  14063. {
  14064. int timeToWait = 500;
  14065. {
  14066. const ScopedLock sl (callbackLock);
  14067. {
  14068. const ScopedLock sl2 (listLock);
  14069. if (clients.size() > 0)
  14070. {
  14071. index = (index + 1) % clients.size();
  14072. clientBeingCalled = clients [index];
  14073. }
  14074. else
  14075. {
  14076. index = 0;
  14077. clientBeingCalled = 0;
  14078. }
  14079. if (clientsChanged)
  14080. {
  14081. clientsChanged = false;
  14082. numCallsSinceBusy = 0;
  14083. }
  14084. }
  14085. if (clientBeingCalled != 0)
  14086. {
  14087. if (clientBeingCalled->useTimeSlice())
  14088. numCallsSinceBusy = 0;
  14089. else
  14090. ++numCallsSinceBusy;
  14091. if (numCallsSinceBusy >= clients.size())
  14092. timeToWait = 500;
  14093. else if (index == 0)
  14094. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14095. else
  14096. timeToWait = 0;
  14097. }
  14098. }
  14099. if (timeToWait > 0)
  14100. wait (timeToWait);
  14101. }
  14102. }
  14103. END_JUCE_NAMESPACE
  14104. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14105. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14106. BEGIN_JUCE_NAMESPACE
  14107. DeletedAtShutdown::DeletedAtShutdown()
  14108. {
  14109. const ScopedLock sl (getLock());
  14110. getObjects().add (this);
  14111. }
  14112. DeletedAtShutdown::~DeletedAtShutdown()
  14113. {
  14114. const ScopedLock sl (getLock());
  14115. getObjects().removeValue (this);
  14116. }
  14117. void DeletedAtShutdown::deleteAll()
  14118. {
  14119. // make a local copy of the array, so it can't get into a loop if something
  14120. // creates another DeletedAtShutdown object during its destructor.
  14121. Array <DeletedAtShutdown*> localCopy;
  14122. {
  14123. const ScopedLock sl (getLock());
  14124. localCopy = getObjects();
  14125. }
  14126. for (int i = localCopy.size(); --i >= 0;)
  14127. {
  14128. JUCE_TRY
  14129. {
  14130. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14131. // double-check that it's not already been deleted during another object's destructor.
  14132. {
  14133. const ScopedLock sl (getLock());
  14134. if (! getObjects().contains (deletee))
  14135. deletee = 0;
  14136. }
  14137. delete deletee;
  14138. }
  14139. JUCE_CATCH_EXCEPTION
  14140. }
  14141. // if no objects got re-created during shutdown, this should have been emptied by their
  14142. // destructors
  14143. jassert (getObjects().size() == 0);
  14144. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14145. }
  14146. CriticalSection& DeletedAtShutdown::getLock()
  14147. {
  14148. static CriticalSection lock;
  14149. return lock;
  14150. }
  14151. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14152. {
  14153. static Array <DeletedAtShutdown*> objects;
  14154. return objects;
  14155. }
  14156. END_JUCE_NAMESPACE
  14157. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14158. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14159. BEGIN_JUCE_NAMESPACE
  14160. UnitTest::UnitTest (const String& name_)
  14161. : name (name_), runner (0)
  14162. {
  14163. getAllTests().add (this);
  14164. }
  14165. UnitTest::~UnitTest()
  14166. {
  14167. getAllTests().removeValue (this);
  14168. }
  14169. Array<UnitTest*>& UnitTest::getAllTests()
  14170. {
  14171. static Array<UnitTest*> tests;
  14172. return tests;
  14173. }
  14174. void UnitTest::initialise() {}
  14175. void UnitTest::shutdown() {}
  14176. void UnitTest::performTest (UnitTestRunner* const runner_)
  14177. {
  14178. jassert (runner_ != 0);
  14179. runner = runner_;
  14180. initialise();
  14181. runTest();
  14182. shutdown();
  14183. }
  14184. void UnitTest::logMessage (const String& message)
  14185. {
  14186. runner->logMessage (message);
  14187. }
  14188. void UnitTest::beginTest (const String& testName)
  14189. {
  14190. runner->beginNewTest (this, testName);
  14191. }
  14192. void UnitTest::expect (const bool result, const String& failureMessage)
  14193. {
  14194. if (result)
  14195. runner->addPass();
  14196. else
  14197. runner->addFail (failureMessage);
  14198. }
  14199. UnitTestRunner::UnitTestRunner()
  14200. : currentTest (0), assertOnFailure (false)
  14201. {
  14202. }
  14203. UnitTestRunner::~UnitTestRunner()
  14204. {
  14205. }
  14206. int UnitTestRunner::getNumResults() const throw()
  14207. {
  14208. return results.size();
  14209. }
  14210. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14211. {
  14212. return results [index];
  14213. }
  14214. void UnitTestRunner::resultsUpdated()
  14215. {
  14216. }
  14217. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14218. {
  14219. results.clear();
  14220. assertOnFailure = assertOnFailure_;
  14221. resultsUpdated();
  14222. for (int i = 0; i < tests.size(); ++i)
  14223. {
  14224. try
  14225. {
  14226. tests.getUnchecked(i)->performTest (this);
  14227. }
  14228. catch (...)
  14229. {
  14230. addFail ("An unhandled exception was thrown!");
  14231. }
  14232. }
  14233. endTest();
  14234. }
  14235. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14236. {
  14237. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14238. }
  14239. void UnitTestRunner::logMessage (const String& message)
  14240. {
  14241. Logger::writeToLog (message);
  14242. }
  14243. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14244. {
  14245. endTest();
  14246. currentTest = test;
  14247. TestResult* const r = new TestResult();
  14248. r->unitTestName = test->getName();
  14249. r->subcategoryName = subCategory;
  14250. r->passes = 0;
  14251. r->failures = 0;
  14252. results.add (r);
  14253. logMessage ("-----------------------------------------------------------------");
  14254. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14255. resultsUpdated();
  14256. }
  14257. void UnitTestRunner::endTest()
  14258. {
  14259. if (results.size() > 0)
  14260. {
  14261. TestResult* const r = results.getLast();
  14262. if (r->failures > 0)
  14263. {
  14264. String m ("FAILED!!");
  14265. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14266. << " failed, out of a total of " << (r->passes + r->failures);
  14267. logMessage (String::empty);
  14268. logMessage (m);
  14269. logMessage (String::empty);
  14270. }
  14271. else
  14272. {
  14273. logMessage ("All tests completed successfully");
  14274. }
  14275. }
  14276. }
  14277. void UnitTestRunner::addPass()
  14278. {
  14279. {
  14280. const ScopedLock sl (results.getLock());
  14281. TestResult* const r = results.getLast();
  14282. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14283. r->passes++;
  14284. String message ("Test ");
  14285. message << (r->failures + r->passes) << " passed";
  14286. logMessage (message);
  14287. }
  14288. resultsUpdated();
  14289. }
  14290. void UnitTestRunner::addFail (const String& failureMessage)
  14291. {
  14292. {
  14293. const ScopedLock sl (results.getLock());
  14294. TestResult* const r = results.getLast();
  14295. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14296. r->failures++;
  14297. String message ("!!! Test ");
  14298. message << (r->failures + r->passes) << " failed";
  14299. if (failureMessage.isNotEmpty())
  14300. message << ": " << failureMessage;
  14301. r->messages.add (message);
  14302. logMessage (message);
  14303. }
  14304. resultsUpdated();
  14305. if (assertOnFailure) { jassertfalse }
  14306. }
  14307. END_JUCE_NAMESPACE
  14308. /*** End of inlined file: juce_UnitTest.cpp ***/
  14309. #endif
  14310. #if JUCE_BUILD_MISC
  14311. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14312. BEGIN_JUCE_NAMESPACE
  14313. class ValueTree::SetPropertyAction : public UndoableAction
  14314. {
  14315. public:
  14316. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14317. const var& newValue_, const var& oldValue_,
  14318. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14319. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14320. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14321. {
  14322. }
  14323. ~SetPropertyAction() {}
  14324. bool perform()
  14325. {
  14326. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14327. if (isDeletingProperty)
  14328. target->removeProperty (name, 0);
  14329. else
  14330. target->setProperty (name, newValue, 0);
  14331. return true;
  14332. }
  14333. bool undo()
  14334. {
  14335. if (isAddingNewProperty)
  14336. target->removeProperty (name, 0);
  14337. else
  14338. target->setProperty (name, oldValue, 0);
  14339. return true;
  14340. }
  14341. int getSizeInUnits()
  14342. {
  14343. return (int) sizeof (*this); //xxx should be more accurate
  14344. }
  14345. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14346. {
  14347. if (! (isAddingNewProperty || isDeletingProperty))
  14348. {
  14349. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14350. if (next != 0 && next->target == target && next->name == name
  14351. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14352. {
  14353. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14354. }
  14355. }
  14356. return 0;
  14357. }
  14358. private:
  14359. const SharedObjectPtr target;
  14360. const Identifier name;
  14361. const var newValue;
  14362. var oldValue;
  14363. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14364. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14365. };
  14366. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14367. {
  14368. public:
  14369. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14370. const SharedObjectPtr& newChild_)
  14371. : target (target_),
  14372. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14373. childIndex (childIndex_),
  14374. isDeleting (newChild_ == 0)
  14375. {
  14376. jassert (child != 0);
  14377. }
  14378. ~AddOrRemoveChildAction() {}
  14379. bool perform()
  14380. {
  14381. if (isDeleting)
  14382. target->removeChild (childIndex, 0);
  14383. else
  14384. target->addChild (child, childIndex, 0);
  14385. return true;
  14386. }
  14387. bool undo()
  14388. {
  14389. if (isDeleting)
  14390. {
  14391. target->addChild (child, childIndex, 0);
  14392. }
  14393. else
  14394. {
  14395. // If you hit this, it seems that your object's state is getting confused - probably
  14396. // because you've interleaved some undoable and non-undoable operations?
  14397. jassert (childIndex < target->children.size());
  14398. target->removeChild (childIndex, 0);
  14399. }
  14400. return true;
  14401. }
  14402. int getSizeInUnits()
  14403. {
  14404. return (int) sizeof (*this); //xxx should be more accurate
  14405. }
  14406. private:
  14407. const SharedObjectPtr target, child;
  14408. const int childIndex;
  14409. const bool isDeleting;
  14410. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14411. };
  14412. class ValueTree::MoveChildAction : public UndoableAction
  14413. {
  14414. public:
  14415. MoveChildAction (const SharedObjectPtr& parent_,
  14416. const int startIndex_, const int endIndex_)
  14417. : parent (parent_),
  14418. startIndex (startIndex_),
  14419. endIndex (endIndex_)
  14420. {
  14421. }
  14422. ~MoveChildAction() {}
  14423. bool perform()
  14424. {
  14425. parent->moveChild (startIndex, endIndex, 0);
  14426. return true;
  14427. }
  14428. bool undo()
  14429. {
  14430. parent->moveChild (endIndex, startIndex, 0);
  14431. return true;
  14432. }
  14433. int getSizeInUnits()
  14434. {
  14435. return (int) sizeof (*this); //xxx should be more accurate
  14436. }
  14437. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14438. {
  14439. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14440. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14441. return new MoveChildAction (parent, startIndex, next->endIndex);
  14442. return 0;
  14443. }
  14444. private:
  14445. const SharedObjectPtr parent;
  14446. const int startIndex, endIndex;
  14447. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14448. };
  14449. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14450. : type (type_), parent (0)
  14451. {
  14452. }
  14453. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14454. : type (other.type), properties (other.properties), parent (0)
  14455. {
  14456. for (int i = 0; i < other.children.size(); ++i)
  14457. {
  14458. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14459. child->parent = this;
  14460. children.add (child);
  14461. }
  14462. }
  14463. ValueTree::SharedObject::~SharedObject()
  14464. {
  14465. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14466. for (int i = children.size(); --i >= 0;)
  14467. {
  14468. const SharedObjectPtr c (children.getUnchecked(i));
  14469. c->parent = 0;
  14470. children.remove (i);
  14471. c->sendParentChangeMessage();
  14472. }
  14473. }
  14474. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14475. {
  14476. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14477. {
  14478. ValueTree* const v = valueTreesWithListeners[i];
  14479. if (v != 0)
  14480. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14481. }
  14482. }
  14483. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14484. {
  14485. ValueTree tree (this);
  14486. ValueTree::SharedObject* t = this;
  14487. while (t != 0)
  14488. {
  14489. t->sendPropertyChangeMessage (tree, property);
  14490. t = t->parent;
  14491. }
  14492. }
  14493. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14494. {
  14495. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14496. {
  14497. ValueTree* const v = valueTreesWithListeners[i];
  14498. if (v != 0)
  14499. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14500. }
  14501. }
  14502. void ValueTree::SharedObject::sendChildChangeMessage()
  14503. {
  14504. ValueTree tree (this);
  14505. ValueTree::SharedObject* t = this;
  14506. while (t != 0)
  14507. {
  14508. t->sendChildChangeMessage (tree);
  14509. t = t->parent;
  14510. }
  14511. }
  14512. void ValueTree::SharedObject::sendParentChangeMessage()
  14513. {
  14514. ValueTree tree (this);
  14515. int i;
  14516. for (i = children.size(); --i >= 0;)
  14517. {
  14518. SharedObject* const t = children[i];
  14519. if (t != 0)
  14520. t->sendParentChangeMessage();
  14521. }
  14522. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14523. {
  14524. ValueTree* const v = valueTreesWithListeners[i];
  14525. if (v != 0)
  14526. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14527. }
  14528. }
  14529. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14530. {
  14531. return properties [name];
  14532. }
  14533. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14534. {
  14535. return properties.getWithDefault (name, defaultReturnValue);
  14536. }
  14537. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14538. {
  14539. if (undoManager == 0)
  14540. {
  14541. if (properties.set (name, newValue))
  14542. sendPropertyChangeMessage (name);
  14543. }
  14544. else
  14545. {
  14546. var* const existingValue = properties.getVarPointer (name);
  14547. if (existingValue != 0)
  14548. {
  14549. if (*existingValue != newValue)
  14550. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14551. }
  14552. else
  14553. {
  14554. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14555. }
  14556. }
  14557. }
  14558. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14559. {
  14560. return properties.contains (name);
  14561. }
  14562. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14563. {
  14564. if (undoManager == 0)
  14565. {
  14566. if (properties.remove (name))
  14567. sendPropertyChangeMessage (name);
  14568. }
  14569. else
  14570. {
  14571. if (properties.contains (name))
  14572. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14573. }
  14574. }
  14575. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14576. {
  14577. if (undoManager == 0)
  14578. {
  14579. while (properties.size() > 0)
  14580. {
  14581. const Identifier name (properties.getName (properties.size() - 1));
  14582. properties.remove (name);
  14583. sendPropertyChangeMessage (name);
  14584. }
  14585. }
  14586. else
  14587. {
  14588. for (int i = properties.size(); --i >= 0;)
  14589. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14590. }
  14591. }
  14592. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14593. {
  14594. for (int i = 0; i < children.size(); ++i)
  14595. if (children.getUnchecked(i)->type == typeToMatch)
  14596. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14597. return ValueTree::invalid;
  14598. }
  14599. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14600. {
  14601. for (int i = 0; i < children.size(); ++i)
  14602. if (children.getUnchecked(i)->type == typeToMatch)
  14603. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14604. SharedObject* const newObject = new SharedObject (typeToMatch);
  14605. addChild (newObject, -1, undoManager);
  14606. return ValueTree (newObject);
  14607. }
  14608. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14609. {
  14610. for (int i = 0; i < children.size(); ++i)
  14611. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14612. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14613. return ValueTree::invalid;
  14614. }
  14615. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14616. {
  14617. const SharedObject* p = parent;
  14618. while (p != 0)
  14619. {
  14620. if (p == possibleParent)
  14621. return true;
  14622. p = p->parent;
  14623. }
  14624. return false;
  14625. }
  14626. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14627. {
  14628. return children.indexOf (child.object);
  14629. }
  14630. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14631. {
  14632. if (child != 0 && child->parent != this)
  14633. {
  14634. if (child != this && ! isAChildOf (child))
  14635. {
  14636. // You should always make sure that a child is removed from its previous parent before
  14637. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14638. // undomanager should be used when removing it from its current parent..
  14639. jassert (child->parent == 0);
  14640. if (child->parent != 0)
  14641. {
  14642. jassert (child->parent->children.indexOf (child) >= 0);
  14643. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14644. }
  14645. if (undoManager == 0)
  14646. {
  14647. children.insert (index, child);
  14648. child->parent = this;
  14649. sendChildChangeMessage();
  14650. child->sendParentChangeMessage();
  14651. }
  14652. else
  14653. {
  14654. if (index < 0)
  14655. index = children.size();
  14656. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14657. }
  14658. }
  14659. else
  14660. {
  14661. // You're attempting to create a recursive loop! A node
  14662. // can't be a child of one of its own children!
  14663. jassertfalse;
  14664. }
  14665. }
  14666. }
  14667. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14668. {
  14669. const SharedObjectPtr child (children [childIndex]);
  14670. if (child != 0)
  14671. {
  14672. if (undoManager == 0)
  14673. {
  14674. children.remove (childIndex);
  14675. child->parent = 0;
  14676. sendChildChangeMessage();
  14677. child->sendParentChangeMessage();
  14678. }
  14679. else
  14680. {
  14681. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14682. }
  14683. }
  14684. }
  14685. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14686. {
  14687. while (children.size() > 0)
  14688. removeChild (children.size() - 1, undoManager);
  14689. }
  14690. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14691. {
  14692. // The source index must be a valid index!
  14693. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14694. if (currentIndex != newIndex
  14695. && isPositiveAndBelow (currentIndex, children.size()))
  14696. {
  14697. if (undoManager == 0)
  14698. {
  14699. children.move (currentIndex, newIndex);
  14700. sendChildChangeMessage();
  14701. }
  14702. else
  14703. {
  14704. if (! isPositiveAndBelow (newIndex, children.size()))
  14705. newIndex = children.size() - 1;
  14706. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14707. }
  14708. }
  14709. }
  14710. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14711. {
  14712. jassert (newOrder.size() == children.size());
  14713. if (undoManager == 0)
  14714. {
  14715. children = newOrder;
  14716. sendChildChangeMessage();
  14717. }
  14718. else
  14719. {
  14720. for (int i = 0; i < children.size(); ++i)
  14721. {
  14722. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14723. {
  14724. jassert (children.contains (newOrder.getUnchecked(i)));
  14725. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14726. }
  14727. }
  14728. }
  14729. }
  14730. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14731. {
  14732. if (type != other.type
  14733. || properties.size() != other.properties.size()
  14734. || children.size() != other.children.size()
  14735. || properties != other.properties)
  14736. return false;
  14737. for (int i = 0; i < children.size(); ++i)
  14738. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14739. return false;
  14740. return true;
  14741. }
  14742. ValueTree::ValueTree() throw()
  14743. : object (0)
  14744. {
  14745. }
  14746. const ValueTree ValueTree::invalid;
  14747. ValueTree::ValueTree (const Identifier& type_)
  14748. : object (new ValueTree::SharedObject (type_))
  14749. {
  14750. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14751. }
  14752. ValueTree::ValueTree (SharedObject* const object_)
  14753. : object (object_)
  14754. {
  14755. }
  14756. ValueTree::ValueTree (const ValueTree& other)
  14757. : object (other.object)
  14758. {
  14759. }
  14760. ValueTree& ValueTree::operator= (const ValueTree& other)
  14761. {
  14762. if (listeners.size() > 0)
  14763. {
  14764. if (object != 0)
  14765. object->valueTreesWithListeners.removeValue (this);
  14766. if (other.object != 0)
  14767. other.object->valueTreesWithListeners.add (this);
  14768. }
  14769. object = other.object;
  14770. return *this;
  14771. }
  14772. ValueTree::~ValueTree()
  14773. {
  14774. if (listeners.size() > 0 && object != 0)
  14775. object->valueTreesWithListeners.removeValue (this);
  14776. }
  14777. bool ValueTree::operator== (const ValueTree& other) const throw()
  14778. {
  14779. return object == other.object;
  14780. }
  14781. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14782. {
  14783. return object != other.object;
  14784. }
  14785. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14786. {
  14787. return object == other.object
  14788. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14789. }
  14790. ValueTree ValueTree::createCopy() const
  14791. {
  14792. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14793. }
  14794. bool ValueTree::hasType (const Identifier& typeName) const
  14795. {
  14796. return object != 0 && object->type == typeName;
  14797. }
  14798. const Identifier ValueTree::getType() const
  14799. {
  14800. return object != 0 ? object->type : Identifier();
  14801. }
  14802. ValueTree ValueTree::getParent() const
  14803. {
  14804. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14805. }
  14806. ValueTree ValueTree::getSibling (const int delta) const
  14807. {
  14808. if (object == 0 || object->parent == 0)
  14809. return invalid;
  14810. const int index = object->parent->indexOf (*this) + delta;
  14811. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14812. }
  14813. const var& ValueTree::operator[] (const Identifier& name) const
  14814. {
  14815. return object == 0 ? var::null : object->getProperty (name);
  14816. }
  14817. const var& ValueTree::getProperty (const Identifier& name) const
  14818. {
  14819. return object == 0 ? var::null : object->getProperty (name);
  14820. }
  14821. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14822. {
  14823. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14824. }
  14825. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14826. {
  14827. jassert (name.toString().isNotEmpty());
  14828. if (object != 0 && name.toString().isNotEmpty())
  14829. object->setProperty (name, newValue, undoManager);
  14830. }
  14831. bool ValueTree::hasProperty (const Identifier& name) const
  14832. {
  14833. return object != 0 && object->hasProperty (name);
  14834. }
  14835. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14836. {
  14837. if (object != 0)
  14838. object->removeProperty (name, undoManager);
  14839. }
  14840. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14841. {
  14842. if (object != 0)
  14843. object->removeAllProperties (undoManager);
  14844. }
  14845. int ValueTree::getNumProperties() const
  14846. {
  14847. return object == 0 ? 0 : object->properties.size();
  14848. }
  14849. const Identifier ValueTree::getPropertyName (const int index) const
  14850. {
  14851. return object == 0 ? Identifier()
  14852. : object->properties.getName (index);
  14853. }
  14854. class ValueTreePropertyValueSource : public Value::ValueSource,
  14855. public ValueTree::Listener
  14856. {
  14857. public:
  14858. ValueTreePropertyValueSource (const ValueTree& tree_,
  14859. const Identifier& property_,
  14860. UndoManager* const undoManager_)
  14861. : tree (tree_),
  14862. property (property_),
  14863. undoManager (undoManager_)
  14864. {
  14865. tree.addListener (this);
  14866. }
  14867. ~ValueTreePropertyValueSource()
  14868. {
  14869. tree.removeListener (this);
  14870. }
  14871. const var getValue() const
  14872. {
  14873. return tree [property];
  14874. }
  14875. void setValue (const var& newValue)
  14876. {
  14877. tree.setProperty (property, newValue, undoManager);
  14878. }
  14879. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14880. {
  14881. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14882. sendChangeMessage (false);
  14883. }
  14884. void valueTreeChildrenChanged (ValueTree&) {}
  14885. void valueTreeParentChanged (ValueTree&) {}
  14886. private:
  14887. ValueTree tree;
  14888. const Identifier property;
  14889. UndoManager* const undoManager;
  14890. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14891. };
  14892. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14893. {
  14894. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14895. }
  14896. int ValueTree::getNumChildren() const
  14897. {
  14898. return object == 0 ? 0 : object->children.size();
  14899. }
  14900. ValueTree ValueTree::getChild (int index) const
  14901. {
  14902. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14903. }
  14904. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14905. {
  14906. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14907. }
  14908. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14909. {
  14910. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14911. }
  14912. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14913. {
  14914. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14915. }
  14916. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14917. {
  14918. return object != 0 && object->isAChildOf (possibleParent.object);
  14919. }
  14920. int ValueTree::indexOf (const ValueTree& child) const
  14921. {
  14922. return object != 0 ? object->indexOf (child) : -1;
  14923. }
  14924. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14925. {
  14926. if (object != 0)
  14927. object->addChild (child.object, index, undoManager);
  14928. }
  14929. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14930. {
  14931. if (object != 0)
  14932. object->removeChild (childIndex, undoManager);
  14933. }
  14934. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14935. {
  14936. if (object != 0)
  14937. object->removeChild (object->children.indexOf (child.object), undoManager);
  14938. }
  14939. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14940. {
  14941. if (object != 0)
  14942. object->removeAllChildren (undoManager);
  14943. }
  14944. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14945. {
  14946. if (object != 0)
  14947. object->moveChild (currentIndex, newIndex, undoManager);
  14948. }
  14949. void ValueTree::addListener (Listener* listener)
  14950. {
  14951. if (listener != 0)
  14952. {
  14953. if (listeners.size() == 0 && object != 0)
  14954. object->valueTreesWithListeners.add (this);
  14955. listeners.add (listener);
  14956. }
  14957. }
  14958. void ValueTree::removeListener (Listener* listener)
  14959. {
  14960. listeners.remove (listener);
  14961. if (listeners.size() == 0 && object != 0)
  14962. object->valueTreesWithListeners.removeValue (this);
  14963. }
  14964. XmlElement* ValueTree::SharedObject::createXml() const
  14965. {
  14966. XmlElement* xml = new XmlElement (type.toString());
  14967. int i;
  14968. for (i = 0; i < properties.size(); ++i)
  14969. {
  14970. Identifier name (properties.getName(i));
  14971. const var& v = properties [name];
  14972. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14973. xml->setAttribute (name.toString(), v.toString());
  14974. }
  14975. for (i = 0; i < children.size(); ++i)
  14976. xml->addChildElement (children.getUnchecked(i)->createXml());
  14977. return xml;
  14978. }
  14979. XmlElement* ValueTree::createXml() const
  14980. {
  14981. return object != 0 ? object->createXml() : 0;
  14982. }
  14983. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14984. {
  14985. ValueTree v (xml.getTagName());
  14986. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14987. for (int i = 0; i < numAtts; ++i)
  14988. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14989. forEachXmlChildElement (xml, e)
  14990. {
  14991. v.addChild (fromXml (*e), -1, 0);
  14992. }
  14993. return v;
  14994. }
  14995. void ValueTree::writeToStream (OutputStream& output)
  14996. {
  14997. output.writeString (getType().toString());
  14998. const int numProps = getNumProperties();
  14999. output.writeCompressedInt (numProps);
  15000. int i;
  15001. for (i = 0; i < numProps; ++i)
  15002. {
  15003. const Identifier name (getPropertyName(i));
  15004. output.writeString (name.toString());
  15005. getProperty(name).writeToStream (output);
  15006. }
  15007. const int numChildren = getNumChildren();
  15008. output.writeCompressedInt (numChildren);
  15009. for (i = 0; i < numChildren; ++i)
  15010. getChild (i).writeToStream (output);
  15011. }
  15012. ValueTree ValueTree::readFromStream (InputStream& input)
  15013. {
  15014. const String type (input.readString());
  15015. if (type.isEmpty())
  15016. return ValueTree::invalid;
  15017. ValueTree v (type);
  15018. const int numProps = input.readCompressedInt();
  15019. if (numProps < 0)
  15020. {
  15021. jassertfalse; // trying to read corrupted data!
  15022. return v;
  15023. }
  15024. int i;
  15025. for (i = 0; i < numProps; ++i)
  15026. {
  15027. const String name (input.readString());
  15028. jassert (name.isNotEmpty());
  15029. const var value (var::readFromStream (input));
  15030. v.setProperty (name, value, 0);
  15031. }
  15032. const int numChildren = input.readCompressedInt();
  15033. for (i = 0; i < numChildren; ++i)
  15034. v.addChild (readFromStream (input), -1, 0);
  15035. return v;
  15036. }
  15037. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15038. {
  15039. MemoryInputStream in (data, numBytes, false);
  15040. return readFromStream (in);
  15041. }
  15042. END_JUCE_NAMESPACE
  15043. /*** End of inlined file: juce_ValueTree.cpp ***/
  15044. /*** Start of inlined file: juce_Value.cpp ***/
  15045. BEGIN_JUCE_NAMESPACE
  15046. Value::ValueSource::ValueSource()
  15047. {
  15048. }
  15049. Value::ValueSource::~ValueSource()
  15050. {
  15051. }
  15052. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15053. {
  15054. if (synchronous)
  15055. {
  15056. for (int i = valuesWithListeners.size(); --i >= 0;)
  15057. {
  15058. Value* const v = valuesWithListeners[i];
  15059. if (v != 0)
  15060. v->callListeners();
  15061. }
  15062. }
  15063. else
  15064. {
  15065. triggerAsyncUpdate();
  15066. }
  15067. }
  15068. void Value::ValueSource::handleAsyncUpdate()
  15069. {
  15070. sendChangeMessage (true);
  15071. }
  15072. class SimpleValueSource : public Value::ValueSource
  15073. {
  15074. public:
  15075. SimpleValueSource()
  15076. {
  15077. }
  15078. SimpleValueSource (const var& initialValue)
  15079. : value (initialValue)
  15080. {
  15081. }
  15082. ~SimpleValueSource()
  15083. {
  15084. }
  15085. const var getValue() const
  15086. {
  15087. return value;
  15088. }
  15089. void setValue (const var& newValue)
  15090. {
  15091. if (newValue != value)
  15092. {
  15093. value = newValue;
  15094. sendChangeMessage (false);
  15095. }
  15096. }
  15097. private:
  15098. var value;
  15099. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  15100. };
  15101. Value::Value()
  15102. : value (new SimpleValueSource())
  15103. {
  15104. }
  15105. Value::Value (ValueSource* const value_)
  15106. : value (value_)
  15107. {
  15108. jassert (value_ != 0);
  15109. }
  15110. Value::Value (const var& initialValue)
  15111. : value (new SimpleValueSource (initialValue))
  15112. {
  15113. }
  15114. Value::Value (const Value& other)
  15115. : value (other.value)
  15116. {
  15117. }
  15118. Value& Value::operator= (const Value& other)
  15119. {
  15120. value = other.value;
  15121. return *this;
  15122. }
  15123. Value::~Value()
  15124. {
  15125. if (listeners.size() > 0)
  15126. value->valuesWithListeners.removeValue (this);
  15127. }
  15128. const var Value::getValue() const
  15129. {
  15130. return value->getValue();
  15131. }
  15132. Value::operator const var() const
  15133. {
  15134. return getValue();
  15135. }
  15136. void Value::setValue (const var& newValue)
  15137. {
  15138. value->setValue (newValue);
  15139. }
  15140. const String Value::toString() const
  15141. {
  15142. return value->getValue().toString();
  15143. }
  15144. Value& Value::operator= (const var& newValue)
  15145. {
  15146. value->setValue (newValue);
  15147. return *this;
  15148. }
  15149. void Value::referTo (const Value& valueToReferTo)
  15150. {
  15151. if (valueToReferTo.value != value)
  15152. {
  15153. if (listeners.size() > 0)
  15154. {
  15155. value->valuesWithListeners.removeValue (this);
  15156. valueToReferTo.value->valuesWithListeners.add (this);
  15157. }
  15158. value = valueToReferTo.value;
  15159. callListeners();
  15160. }
  15161. }
  15162. bool Value::refersToSameSourceAs (const Value& other) const
  15163. {
  15164. return value == other.value;
  15165. }
  15166. bool Value::operator== (const Value& other) const
  15167. {
  15168. return value == other.value || value->getValue() == other.getValue();
  15169. }
  15170. bool Value::operator!= (const Value& other) const
  15171. {
  15172. return value != other.value && value->getValue() != other.getValue();
  15173. }
  15174. void Value::addListener (ValueListener* const listener)
  15175. {
  15176. if (listener != 0)
  15177. {
  15178. if (listeners.size() == 0)
  15179. value->valuesWithListeners.add (this);
  15180. listeners.add (listener);
  15181. }
  15182. }
  15183. void Value::removeListener (ValueListener* const listener)
  15184. {
  15185. listeners.remove (listener);
  15186. if (listeners.size() == 0)
  15187. value->valuesWithListeners.removeValue (this);
  15188. }
  15189. void Value::callListeners()
  15190. {
  15191. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15192. listeners.call (&ValueListener::valueChanged, v);
  15193. }
  15194. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15195. {
  15196. return stream << value.toString();
  15197. }
  15198. END_JUCE_NAMESPACE
  15199. /*** End of inlined file: juce_Value.cpp ***/
  15200. /*** Start of inlined file: juce_Application.cpp ***/
  15201. BEGIN_JUCE_NAMESPACE
  15202. #if JUCE_MAC
  15203. extern void juce_initialiseMacMainMenu();
  15204. #endif
  15205. JUCEApplication::JUCEApplication()
  15206. : appReturnValue (0),
  15207. stillInitialising (true)
  15208. {
  15209. jassert (isStandaloneApp() && appInstance == 0);
  15210. appInstance = this;
  15211. }
  15212. JUCEApplication::~JUCEApplication()
  15213. {
  15214. if (appLock != 0)
  15215. {
  15216. appLock->exit();
  15217. appLock = 0;
  15218. }
  15219. jassert (appInstance == this);
  15220. appInstance = 0;
  15221. }
  15222. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15223. JUCEApplication* JUCEApplication::appInstance = 0;
  15224. bool JUCEApplication::moreThanOneInstanceAllowed()
  15225. {
  15226. return true;
  15227. }
  15228. void JUCEApplication::anotherInstanceStarted (const String&)
  15229. {
  15230. }
  15231. void JUCEApplication::systemRequestedQuit()
  15232. {
  15233. quit();
  15234. }
  15235. void JUCEApplication::quit()
  15236. {
  15237. MessageManager::getInstance()->stopDispatchLoop();
  15238. }
  15239. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15240. {
  15241. appReturnValue = newReturnValue;
  15242. }
  15243. void JUCEApplication::actionListenerCallback (const String& message)
  15244. {
  15245. if (message.startsWith (getApplicationName() + "/"))
  15246. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15247. }
  15248. void JUCEApplication::unhandledException (const std::exception*,
  15249. const String&,
  15250. const int)
  15251. {
  15252. jassertfalse;
  15253. }
  15254. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15255. const char* const sourceFile,
  15256. const int lineNumber)
  15257. {
  15258. if (appInstance != 0)
  15259. appInstance->unhandledException (e, sourceFile, lineNumber);
  15260. }
  15261. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15262. {
  15263. return 0;
  15264. }
  15265. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15266. {
  15267. commands.add (StandardApplicationCommandIDs::quit);
  15268. }
  15269. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15270. {
  15271. if (commandID == StandardApplicationCommandIDs::quit)
  15272. {
  15273. result.setInfo (TRANS("Quit"),
  15274. TRANS("Quits the application"),
  15275. "Application",
  15276. 0);
  15277. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15278. }
  15279. }
  15280. bool JUCEApplication::perform (const InvocationInfo& info)
  15281. {
  15282. if (info.commandID == StandardApplicationCommandIDs::quit)
  15283. {
  15284. systemRequestedQuit();
  15285. return true;
  15286. }
  15287. return false;
  15288. }
  15289. bool JUCEApplication::initialiseApp (const String& commandLine)
  15290. {
  15291. commandLineParameters = commandLine.trim();
  15292. #if ! JUCE_IOS
  15293. jassert (appLock == 0); // initialiseApp must only be called once!
  15294. if (! moreThanOneInstanceAllowed())
  15295. {
  15296. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15297. if (! appLock->enter(0))
  15298. {
  15299. appLock = 0;
  15300. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15301. DBG ("Another instance is running - quitting...");
  15302. return false;
  15303. }
  15304. }
  15305. #endif
  15306. // let the app do its setting-up..
  15307. initialise (commandLineParameters);
  15308. #if JUCE_MAC
  15309. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15310. #endif
  15311. // register for broadcast new app messages
  15312. MessageManager::getInstance()->registerBroadcastListener (this);
  15313. stillInitialising = false;
  15314. return true;
  15315. }
  15316. int JUCEApplication::shutdownApp()
  15317. {
  15318. jassert (appInstance == this);
  15319. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15320. JUCE_TRY
  15321. {
  15322. // give the app a chance to clean up..
  15323. shutdown();
  15324. }
  15325. JUCE_CATCH_EXCEPTION
  15326. return getApplicationReturnValue();
  15327. }
  15328. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15329. void JUCEApplication::appWillTerminateByForce()
  15330. {
  15331. {
  15332. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15333. if (app != 0)
  15334. app->shutdownApp();
  15335. }
  15336. shutdownJuce_GUI();
  15337. }
  15338. int JUCEApplication::main (const String& commandLine)
  15339. {
  15340. ScopedJuceInitialiser_GUI libraryInitialiser;
  15341. jassert (createInstance != 0);
  15342. int returnCode = 0;
  15343. {
  15344. const ScopedPointer<JUCEApplication> app (createInstance());
  15345. if (! app->initialiseApp (commandLine))
  15346. return 0;
  15347. JUCE_TRY
  15348. {
  15349. // loop until a quit message is received..
  15350. MessageManager::getInstance()->runDispatchLoop();
  15351. }
  15352. JUCE_CATCH_EXCEPTION
  15353. returnCode = app->shutdownApp();
  15354. }
  15355. return returnCode;
  15356. }
  15357. #if JUCE_IOS
  15358. extern int juce_iOSMain (int argc, const char* argv[]);
  15359. #endif
  15360. #if ! JUCE_WINDOWS
  15361. extern const char* juce_Argv0;
  15362. #endif
  15363. int JUCEApplication::main (int argc, const char* argv[])
  15364. {
  15365. JUCE_AUTORELEASEPOOL
  15366. #if ! JUCE_WINDOWS
  15367. jassert (createInstance != 0);
  15368. juce_Argv0 = argv[0];
  15369. #endif
  15370. #if JUCE_IOS
  15371. return juce_iOSMain (argc, argv);
  15372. #else
  15373. String cmd;
  15374. for (int i = 1; i < argc; ++i)
  15375. cmd << argv[i] << ' ';
  15376. return JUCEApplication::main (cmd);
  15377. #endif
  15378. }
  15379. END_JUCE_NAMESPACE
  15380. /*** End of inlined file: juce_Application.cpp ***/
  15381. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15382. BEGIN_JUCE_NAMESPACE
  15383. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15384. : commandID (commandID_),
  15385. flags (0)
  15386. {
  15387. }
  15388. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15389. const String& description_,
  15390. const String& categoryName_,
  15391. const int flags_) throw()
  15392. {
  15393. shortName = shortName_;
  15394. description = description_;
  15395. categoryName = categoryName_;
  15396. flags = flags_;
  15397. }
  15398. void ApplicationCommandInfo::setActive (const bool b) throw()
  15399. {
  15400. if (b)
  15401. flags &= ~isDisabled;
  15402. else
  15403. flags |= isDisabled;
  15404. }
  15405. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15406. {
  15407. if (b)
  15408. flags |= isTicked;
  15409. else
  15410. flags &= ~isTicked;
  15411. }
  15412. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15413. {
  15414. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15415. }
  15416. END_JUCE_NAMESPACE
  15417. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15418. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15419. BEGIN_JUCE_NAMESPACE
  15420. ApplicationCommandManager::ApplicationCommandManager()
  15421. : firstTarget (0)
  15422. {
  15423. keyMappings = new KeyPressMappingSet (this);
  15424. Desktop::getInstance().addFocusChangeListener (this);
  15425. }
  15426. ApplicationCommandManager::~ApplicationCommandManager()
  15427. {
  15428. Desktop::getInstance().removeFocusChangeListener (this);
  15429. keyMappings = 0;
  15430. }
  15431. void ApplicationCommandManager::clearCommands()
  15432. {
  15433. commands.clear();
  15434. keyMappings->clearAllKeyPresses();
  15435. triggerAsyncUpdate();
  15436. }
  15437. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15438. {
  15439. // zero isn't a valid command ID!
  15440. jassert (newCommand.commandID != 0);
  15441. // the name isn't optional!
  15442. jassert (newCommand.shortName.isNotEmpty());
  15443. if (getCommandForID (newCommand.commandID) == 0)
  15444. {
  15445. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15446. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15447. commands.add (newInfo);
  15448. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15449. triggerAsyncUpdate();
  15450. }
  15451. else
  15452. {
  15453. // trying to re-register the same command with different parameters?
  15454. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15455. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15456. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15457. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15458. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15459. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15460. }
  15461. }
  15462. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15463. {
  15464. if (target != 0)
  15465. {
  15466. Array <CommandID> commandIDs;
  15467. target->getAllCommands (commandIDs);
  15468. for (int i = 0; i < commandIDs.size(); ++i)
  15469. {
  15470. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15471. target->getCommandInfo (info.commandID, info);
  15472. registerCommand (info);
  15473. }
  15474. }
  15475. }
  15476. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15477. {
  15478. for (int i = commands.size(); --i >= 0;)
  15479. {
  15480. if (commands.getUnchecked (i)->commandID == commandID)
  15481. {
  15482. commands.remove (i);
  15483. triggerAsyncUpdate();
  15484. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15485. for (int j = keys.size(); --j >= 0;)
  15486. keyMappings->removeKeyPress (keys.getReference (j));
  15487. }
  15488. }
  15489. }
  15490. void ApplicationCommandManager::commandStatusChanged()
  15491. {
  15492. triggerAsyncUpdate();
  15493. }
  15494. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15495. {
  15496. for (int i = commands.size(); --i >= 0;)
  15497. if (commands.getUnchecked(i)->commandID == commandID)
  15498. return commands.getUnchecked(i);
  15499. return 0;
  15500. }
  15501. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15502. {
  15503. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15504. return (ci != 0) ? ci->shortName : String::empty;
  15505. }
  15506. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15507. {
  15508. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15509. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15510. : String::empty;
  15511. }
  15512. const StringArray ApplicationCommandManager::getCommandCategories() const
  15513. {
  15514. StringArray s;
  15515. for (int i = 0; i < commands.size(); ++i)
  15516. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15517. return s;
  15518. }
  15519. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15520. {
  15521. Array <CommandID> results;
  15522. for (int i = 0; i < commands.size(); ++i)
  15523. if (commands.getUnchecked(i)->categoryName == categoryName)
  15524. results.add (commands.getUnchecked(i)->commandID);
  15525. return results;
  15526. }
  15527. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15528. {
  15529. ApplicationCommandTarget::InvocationInfo info (commandID);
  15530. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15531. return invoke (info, asynchronously);
  15532. }
  15533. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15534. {
  15535. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15536. // manager first..
  15537. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15538. ApplicationCommandInfo commandInfo (0);
  15539. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15540. if (target == 0)
  15541. return false;
  15542. ApplicationCommandTarget::InvocationInfo info (info_);
  15543. info.commandFlags = commandInfo.flags;
  15544. sendListenerInvokeCallback (info);
  15545. const bool ok = target->invoke (info, asynchronously);
  15546. commandStatusChanged();
  15547. return ok;
  15548. }
  15549. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15550. {
  15551. return firstTarget != 0 ? firstTarget
  15552. : findDefaultComponentTarget();
  15553. }
  15554. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15555. {
  15556. firstTarget = newTarget;
  15557. }
  15558. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15559. ApplicationCommandInfo& upToDateInfo)
  15560. {
  15561. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15562. if (target == 0)
  15563. target = JUCEApplication::getInstance();
  15564. if (target != 0)
  15565. target = target->getTargetForCommand (commandID);
  15566. if (target != 0)
  15567. target->getCommandInfo (commandID, upToDateInfo);
  15568. return target;
  15569. }
  15570. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15571. {
  15572. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15573. if (target == 0 && c != 0)
  15574. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15575. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15576. return target;
  15577. }
  15578. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15579. {
  15580. Component* c = Component::getCurrentlyFocusedComponent();
  15581. if (c == 0)
  15582. {
  15583. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15584. if (activeWindow != 0)
  15585. {
  15586. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15587. if (c == 0)
  15588. c = activeWindow;
  15589. }
  15590. }
  15591. if (c == 0 && Process::isForegroundProcess())
  15592. {
  15593. // getting a bit desperate now - try all desktop comps..
  15594. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15595. {
  15596. ApplicationCommandTarget* const target
  15597. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15598. ->getPeer()->getLastFocusedSubcomponent());
  15599. if (target != 0)
  15600. return target;
  15601. }
  15602. }
  15603. if (c != 0)
  15604. {
  15605. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15606. // if we're focused on a ResizableWindow, chances are that it's the content
  15607. // component that really should get the event. And if not, the event will
  15608. // still be passed up to the top level window anyway, so let's send it to the
  15609. // content comp.
  15610. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15611. c = resizableWindow->getContentComponent();
  15612. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15613. if (target != 0)
  15614. return target;
  15615. }
  15616. return JUCEApplication::getInstance();
  15617. }
  15618. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15619. {
  15620. listeners.add (listener);
  15621. }
  15622. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15623. {
  15624. listeners.remove (listener);
  15625. }
  15626. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15627. {
  15628. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15629. }
  15630. void ApplicationCommandManager::handleAsyncUpdate()
  15631. {
  15632. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15633. }
  15634. void ApplicationCommandManager::globalFocusChanged (Component*)
  15635. {
  15636. commandStatusChanged();
  15637. }
  15638. END_JUCE_NAMESPACE
  15639. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15640. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15641. BEGIN_JUCE_NAMESPACE
  15642. ApplicationCommandTarget::ApplicationCommandTarget()
  15643. {
  15644. }
  15645. ApplicationCommandTarget::~ApplicationCommandTarget()
  15646. {
  15647. messageInvoker = 0;
  15648. }
  15649. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15650. {
  15651. if (isCommandActive (info.commandID))
  15652. {
  15653. if (async)
  15654. {
  15655. if (messageInvoker == 0)
  15656. messageInvoker = new CommandTargetMessageInvoker (this);
  15657. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15658. return true;
  15659. }
  15660. else
  15661. {
  15662. const bool success = perform (info);
  15663. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15664. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15665. // returns the command's info.
  15666. return success;
  15667. }
  15668. }
  15669. return false;
  15670. }
  15671. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15672. {
  15673. Component* c = dynamic_cast <Component*> (this);
  15674. if (c != 0)
  15675. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15676. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15677. return 0;
  15678. }
  15679. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15680. {
  15681. ApplicationCommandTarget* target = this;
  15682. int depth = 0;
  15683. while (target != 0)
  15684. {
  15685. Array <CommandID> commandIDs;
  15686. target->getAllCommands (commandIDs);
  15687. if (commandIDs.contains (commandID))
  15688. return target;
  15689. target = target->getNextCommandTarget();
  15690. ++depth;
  15691. jassert (depth < 100); // could be a recursive command chain??
  15692. jassert (target != this); // definitely a recursive command chain!
  15693. if (depth > 100 || target == this)
  15694. break;
  15695. }
  15696. if (target == 0)
  15697. {
  15698. target = JUCEApplication::getInstance();
  15699. if (target != 0)
  15700. {
  15701. Array <CommandID> commandIDs;
  15702. target->getAllCommands (commandIDs);
  15703. if (commandIDs.contains (commandID))
  15704. return target;
  15705. }
  15706. }
  15707. return 0;
  15708. }
  15709. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15710. {
  15711. ApplicationCommandInfo info (commandID);
  15712. info.flags = ApplicationCommandInfo::isDisabled;
  15713. getCommandInfo (commandID, info);
  15714. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15715. }
  15716. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15717. {
  15718. ApplicationCommandTarget* target = this;
  15719. int depth = 0;
  15720. while (target != 0)
  15721. {
  15722. if (target->tryToInvoke (info, async))
  15723. return true;
  15724. target = target->getNextCommandTarget();
  15725. ++depth;
  15726. jassert (depth < 100); // could be a recursive command chain??
  15727. jassert (target != this); // definitely a recursive command chain!
  15728. if (depth > 100 || target == this)
  15729. break;
  15730. }
  15731. if (target == 0)
  15732. {
  15733. target = JUCEApplication::getInstance();
  15734. if (target != 0)
  15735. return target->tryToInvoke (info, async);
  15736. }
  15737. return false;
  15738. }
  15739. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15740. {
  15741. ApplicationCommandTarget::InvocationInfo info (commandID);
  15742. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15743. return invoke (info, asynchronously);
  15744. }
  15745. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15746. : commandID (commandID_),
  15747. commandFlags (0),
  15748. invocationMethod (direct),
  15749. originatingComponent (0),
  15750. isKeyDown (false),
  15751. millisecsSinceKeyPressed (0)
  15752. {
  15753. }
  15754. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15755. : owner (owner_)
  15756. {
  15757. }
  15758. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15759. {
  15760. }
  15761. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15762. {
  15763. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15764. owner->tryToInvoke (*info, false);
  15765. }
  15766. END_JUCE_NAMESPACE
  15767. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15768. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15769. BEGIN_JUCE_NAMESPACE
  15770. juce_ImplementSingleton (ApplicationProperties)
  15771. ApplicationProperties::ApplicationProperties()
  15772. : msBeforeSaving (3000),
  15773. options (PropertiesFile::storeAsBinary),
  15774. commonSettingsAreReadOnly (0),
  15775. processLock (0)
  15776. {
  15777. }
  15778. ApplicationProperties::~ApplicationProperties()
  15779. {
  15780. closeFiles();
  15781. clearSingletonInstance();
  15782. }
  15783. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15784. const String& fileNameSuffix,
  15785. const String& folderName_,
  15786. const int millisecondsBeforeSaving,
  15787. const int propertiesFileOptions,
  15788. InterProcessLock* processLock_)
  15789. {
  15790. appName = applicationName;
  15791. fileSuffix = fileNameSuffix;
  15792. folderName = folderName_;
  15793. msBeforeSaving = millisecondsBeforeSaving;
  15794. options = propertiesFileOptions;
  15795. processLock = processLock_;
  15796. }
  15797. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15798. const bool testCommonSettings,
  15799. const bool showWarningDialogOnFailure)
  15800. {
  15801. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15802. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15803. if (! (userOk && commonOk))
  15804. {
  15805. if (showWarningDialogOnFailure)
  15806. {
  15807. String filenames;
  15808. if (userProps != 0 && ! userOk)
  15809. filenames << '\n' << userProps->getFile().getFullPathName();
  15810. if (commonProps != 0 && ! commonOk)
  15811. filenames << '\n' << commonProps->getFile().getFullPathName();
  15812. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15813. appName + TRANS(" - Unable to save settings"),
  15814. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15815. + appName + TRANS(" needs to be able to write to the following files:\n")
  15816. + filenames
  15817. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15818. }
  15819. return false;
  15820. }
  15821. return true;
  15822. }
  15823. void ApplicationProperties::openFiles()
  15824. {
  15825. // You need to call setStorageParameters() before trying to get hold of the
  15826. // properties!
  15827. jassert (appName.isNotEmpty());
  15828. if (appName.isNotEmpty())
  15829. {
  15830. if (userProps == 0)
  15831. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15832. false, msBeforeSaving, options, processLock);
  15833. if (commonProps == 0)
  15834. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15835. true, msBeforeSaving, options, processLock);
  15836. userProps->setFallbackPropertySet (commonProps);
  15837. }
  15838. }
  15839. PropertiesFile* ApplicationProperties::getUserSettings()
  15840. {
  15841. if (userProps == 0)
  15842. openFiles();
  15843. return userProps;
  15844. }
  15845. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15846. {
  15847. if (commonProps == 0)
  15848. openFiles();
  15849. if (returnUserPropsIfReadOnly)
  15850. {
  15851. if (commonSettingsAreReadOnly == 0)
  15852. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15853. if (commonSettingsAreReadOnly > 0)
  15854. return userProps;
  15855. }
  15856. return commonProps;
  15857. }
  15858. bool ApplicationProperties::saveIfNeeded()
  15859. {
  15860. return (userProps == 0 || userProps->saveIfNeeded())
  15861. && (commonProps == 0 || commonProps->saveIfNeeded());
  15862. }
  15863. void ApplicationProperties::closeFiles()
  15864. {
  15865. userProps = 0;
  15866. commonProps = 0;
  15867. }
  15868. END_JUCE_NAMESPACE
  15869. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15870. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15871. BEGIN_JUCE_NAMESPACE
  15872. namespace PropertyFileConstants
  15873. {
  15874. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15875. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15876. static const char* const fileTag = "PROPERTIES";
  15877. static const char* const valueTag = "VALUE";
  15878. static const char* const nameAttribute = "name";
  15879. static const char* const valueAttribute = "val";
  15880. }
  15881. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15882. const int options_, InterProcessLock* const processLock_)
  15883. : PropertySet (ignoreCaseOfKeyNames),
  15884. file (f),
  15885. timerInterval (millisecondsBeforeSaving),
  15886. options (options_),
  15887. loadedOk (false),
  15888. needsWriting (false),
  15889. processLock (processLock_)
  15890. {
  15891. // You need to correctly specify just one storage format for the file
  15892. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15893. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15894. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15895. ProcessScopedLock pl (createProcessLock());
  15896. if (pl != 0 && ! pl->isLocked())
  15897. return; // locking failure..
  15898. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15899. if (fileStream != 0)
  15900. {
  15901. int magicNumber = fileStream->readInt();
  15902. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15903. {
  15904. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15905. magicNumber = PropertyFileConstants::magicNumber;
  15906. }
  15907. if (magicNumber == PropertyFileConstants::magicNumber)
  15908. {
  15909. loadedOk = true;
  15910. BufferedInputStream in (fileStream.release(), 2048, true);
  15911. int numValues = in.readInt();
  15912. while (--numValues >= 0 && ! in.isExhausted())
  15913. {
  15914. const String key (in.readString());
  15915. const String value (in.readString());
  15916. jassert (key.isNotEmpty());
  15917. if (key.isNotEmpty())
  15918. getAllProperties().set (key, value);
  15919. }
  15920. }
  15921. else
  15922. {
  15923. // Not a binary props file - let's see if it's XML..
  15924. fileStream = 0;
  15925. XmlDocument parser (f);
  15926. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15927. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15928. {
  15929. doc = parser.getDocumentElement();
  15930. if (doc != 0)
  15931. {
  15932. loadedOk = true;
  15933. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15934. {
  15935. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15936. if (name.isNotEmpty())
  15937. {
  15938. getAllProperties().set (name,
  15939. e->getFirstChildElement() != 0
  15940. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15941. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15942. }
  15943. }
  15944. }
  15945. else
  15946. {
  15947. // must be a pretty broken XML file we're trying to parse here,
  15948. // or a sign that this object needs an InterProcessLock,
  15949. // or just a failure reading the file. This last reason is why
  15950. // we don't jassertfalse here.
  15951. }
  15952. }
  15953. }
  15954. }
  15955. else
  15956. {
  15957. loadedOk = ! f.exists();
  15958. }
  15959. }
  15960. PropertiesFile::~PropertiesFile()
  15961. {
  15962. if (! saveIfNeeded())
  15963. jassertfalse;
  15964. }
  15965. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15966. {
  15967. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15968. }
  15969. bool PropertiesFile::saveIfNeeded()
  15970. {
  15971. const ScopedLock sl (getLock());
  15972. return (! needsWriting) || save();
  15973. }
  15974. bool PropertiesFile::needsToBeSaved() const
  15975. {
  15976. const ScopedLock sl (getLock());
  15977. return needsWriting;
  15978. }
  15979. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15980. {
  15981. const ScopedLock sl (getLock());
  15982. needsWriting = needsToBeSaved_;
  15983. }
  15984. bool PropertiesFile::save()
  15985. {
  15986. const ScopedLock sl (getLock());
  15987. stopTimer();
  15988. if (file == File::nonexistent
  15989. || file.isDirectory()
  15990. || ! file.getParentDirectory().createDirectory())
  15991. return false;
  15992. if ((options & storeAsXML) != 0)
  15993. {
  15994. XmlElement doc (PropertyFileConstants::fileTag);
  15995. for (int i = 0; i < getAllProperties().size(); ++i)
  15996. {
  15997. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15998. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15999. // if the value seems to contain xml, store it as such..
  16000. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  16001. if (childElement != 0)
  16002. e->addChildElement (childElement);
  16003. else
  16004. e->setAttribute (PropertyFileConstants::valueAttribute,
  16005. getAllProperties().getAllValues() [i]);
  16006. }
  16007. ProcessScopedLock pl (createProcessLock());
  16008. if (pl != 0 && ! pl->isLocked())
  16009. return false; // locking failure..
  16010. if (doc.writeToFile (file, String::empty))
  16011. {
  16012. needsWriting = false;
  16013. return true;
  16014. }
  16015. }
  16016. else
  16017. {
  16018. ProcessScopedLock pl (createProcessLock());
  16019. if (pl != 0 && ! pl->isLocked())
  16020. return false; // locking failure..
  16021. TemporaryFile tempFile (file);
  16022. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16023. if (out != 0)
  16024. {
  16025. if ((options & storeAsCompressedBinary) != 0)
  16026. {
  16027. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16028. out->flush();
  16029. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16030. }
  16031. else
  16032. {
  16033. // have you set up the storage option flags correctly?
  16034. jassert ((options & storeAsBinary) != 0);
  16035. out->writeInt (PropertyFileConstants::magicNumber);
  16036. }
  16037. const int numProperties = getAllProperties().size();
  16038. out->writeInt (numProperties);
  16039. for (int i = 0; i < numProperties; ++i)
  16040. {
  16041. out->writeString (getAllProperties().getAllKeys() [i]);
  16042. out->writeString (getAllProperties().getAllValues() [i]);
  16043. }
  16044. out = 0;
  16045. if (tempFile.overwriteTargetFileWithTemporary())
  16046. {
  16047. needsWriting = false;
  16048. return true;
  16049. }
  16050. }
  16051. }
  16052. return false;
  16053. }
  16054. void PropertiesFile::timerCallback()
  16055. {
  16056. saveIfNeeded();
  16057. }
  16058. void PropertiesFile::propertyChanged()
  16059. {
  16060. sendChangeMessage();
  16061. needsWriting = true;
  16062. if (timerInterval > 0)
  16063. startTimer (timerInterval);
  16064. else if (timerInterval == 0)
  16065. saveIfNeeded();
  16066. }
  16067. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16068. const String& fileNameSuffix,
  16069. const String& folderName,
  16070. const bool commonToAllUsers)
  16071. {
  16072. // mustn't have illegal characters in this name..
  16073. jassert (applicationName == File::createLegalFileName (applicationName));
  16074. #if JUCE_MAC || JUCE_IOS
  16075. File dir (commonToAllUsers ? "/Library/Preferences"
  16076. : "~/Library/Preferences");
  16077. if (folderName.isNotEmpty())
  16078. dir = dir.getChildFile (folderName);
  16079. #endif
  16080. #ifdef JUCE_LINUX
  16081. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16082. + (folderName.isNotEmpty() ? folderName
  16083. : ("." + applicationName)));
  16084. #endif
  16085. #if JUCE_WINDOWS
  16086. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16087. : File::userApplicationDataDirectory));
  16088. if (dir == File::nonexistent)
  16089. return File::nonexistent;
  16090. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16091. : applicationName);
  16092. #endif
  16093. return dir.getChildFile (applicationName)
  16094. .withFileExtension (fileNameSuffix);
  16095. }
  16096. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16097. const String& fileNameSuffix,
  16098. const String& folderName,
  16099. const bool commonToAllUsers,
  16100. const int millisecondsBeforeSaving,
  16101. const int propertiesFileOptions,
  16102. InterProcessLock* processLock_)
  16103. {
  16104. const File file (getDefaultAppSettingsFile (applicationName,
  16105. fileNameSuffix,
  16106. folderName,
  16107. commonToAllUsers));
  16108. jassert (file != File::nonexistent);
  16109. if (file == File::nonexistent)
  16110. return 0;
  16111. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16112. }
  16113. END_JUCE_NAMESPACE
  16114. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16115. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16116. BEGIN_JUCE_NAMESPACE
  16117. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16118. const String& fileWildcard_,
  16119. const String& openFileDialogTitle_,
  16120. const String& saveFileDialogTitle_)
  16121. : changedSinceSave (false),
  16122. fileExtension (fileExtension_),
  16123. fileWildcard (fileWildcard_),
  16124. openFileDialogTitle (openFileDialogTitle_),
  16125. saveFileDialogTitle (saveFileDialogTitle_)
  16126. {
  16127. }
  16128. FileBasedDocument::~FileBasedDocument()
  16129. {
  16130. }
  16131. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16132. {
  16133. if (changedSinceSave != hasChanged)
  16134. {
  16135. changedSinceSave = hasChanged;
  16136. sendChangeMessage();
  16137. }
  16138. }
  16139. void FileBasedDocument::changed()
  16140. {
  16141. changedSinceSave = true;
  16142. sendChangeMessage();
  16143. }
  16144. void FileBasedDocument::setFile (const File& newFile)
  16145. {
  16146. if (documentFile != newFile)
  16147. {
  16148. documentFile = newFile;
  16149. changed();
  16150. }
  16151. }
  16152. bool FileBasedDocument::loadFrom (const File& newFile,
  16153. const bool showMessageOnFailure)
  16154. {
  16155. MouseCursor::showWaitCursor();
  16156. const File oldFile (documentFile);
  16157. documentFile = newFile;
  16158. String error;
  16159. if (newFile.existsAsFile())
  16160. {
  16161. error = loadDocument (newFile);
  16162. if (error.isEmpty())
  16163. {
  16164. setChangedFlag (false);
  16165. MouseCursor::hideWaitCursor();
  16166. setLastDocumentOpened (newFile);
  16167. return true;
  16168. }
  16169. }
  16170. else
  16171. {
  16172. error = "The file doesn't exist";
  16173. }
  16174. documentFile = oldFile;
  16175. MouseCursor::hideWaitCursor();
  16176. if (showMessageOnFailure)
  16177. {
  16178. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16179. TRANS("Failed to open file..."),
  16180. TRANS("There was an error while trying to load the file:\n\n")
  16181. + newFile.getFullPathName()
  16182. + "\n\n"
  16183. + error);
  16184. }
  16185. return false;
  16186. }
  16187. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16188. {
  16189. FileChooser fc (openFileDialogTitle,
  16190. getLastDocumentOpened(),
  16191. fileWildcard);
  16192. if (fc.browseForFileToOpen())
  16193. return loadFrom (fc.getResult(), showMessageOnFailure);
  16194. return false;
  16195. }
  16196. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16197. const bool showMessageOnFailure)
  16198. {
  16199. return saveAs (documentFile,
  16200. false,
  16201. askUserForFileIfNotSpecified,
  16202. showMessageOnFailure);
  16203. }
  16204. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16205. const bool warnAboutOverwritingExistingFiles,
  16206. const bool askUserForFileIfNotSpecified,
  16207. const bool showMessageOnFailure)
  16208. {
  16209. if (newFile == File::nonexistent)
  16210. {
  16211. if (askUserForFileIfNotSpecified)
  16212. {
  16213. return saveAsInteractive (true);
  16214. }
  16215. else
  16216. {
  16217. // can't save to an unspecified file
  16218. jassertfalse;
  16219. return failedToWriteToFile;
  16220. }
  16221. }
  16222. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16223. {
  16224. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16225. TRANS("File already exists"),
  16226. TRANS("There's already a file called:\n\n")
  16227. + newFile.getFullPathName()
  16228. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16229. TRANS("overwrite"),
  16230. TRANS("cancel")))
  16231. {
  16232. return userCancelledSave;
  16233. }
  16234. }
  16235. MouseCursor::showWaitCursor();
  16236. const File oldFile (documentFile);
  16237. documentFile = newFile;
  16238. String error (saveDocument (newFile));
  16239. if (error.isEmpty())
  16240. {
  16241. setChangedFlag (false);
  16242. MouseCursor::hideWaitCursor();
  16243. return savedOk;
  16244. }
  16245. documentFile = oldFile;
  16246. MouseCursor::hideWaitCursor();
  16247. if (showMessageOnFailure)
  16248. {
  16249. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16250. TRANS("Error writing to file..."),
  16251. TRANS("An error occurred while trying to save \"")
  16252. + getDocumentTitle()
  16253. + TRANS("\" to the file:\n\n")
  16254. + newFile.getFullPathName()
  16255. + "\n\n"
  16256. + error);
  16257. }
  16258. return failedToWriteToFile;
  16259. }
  16260. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16261. {
  16262. if (! hasChangedSinceSaved())
  16263. return savedOk;
  16264. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16265. TRANS("Closing document..."),
  16266. TRANS("Do you want to save the changes to \"")
  16267. + getDocumentTitle() + "\"?",
  16268. TRANS("save"),
  16269. TRANS("discard changes"),
  16270. TRANS("cancel"));
  16271. if (r == 1)
  16272. {
  16273. // save changes
  16274. return save (true, true);
  16275. }
  16276. else if (r == 2)
  16277. {
  16278. // discard changes
  16279. return savedOk;
  16280. }
  16281. return userCancelledSave;
  16282. }
  16283. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16284. {
  16285. File f;
  16286. if (documentFile.existsAsFile())
  16287. f = documentFile;
  16288. else
  16289. f = getLastDocumentOpened();
  16290. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16291. if (legalFilename.isEmpty())
  16292. legalFilename = "unnamed";
  16293. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16294. f = f.getSiblingFile (legalFilename);
  16295. else
  16296. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16297. f = f.withFileExtension (fileExtension)
  16298. .getNonexistentSibling (true);
  16299. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16300. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16301. {
  16302. File chosen (fc.getResult());
  16303. if (chosen.getFileExtension().isEmpty())
  16304. {
  16305. chosen = chosen.withFileExtension (fileExtension);
  16306. if (chosen.exists())
  16307. {
  16308. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16309. TRANS("File already exists"),
  16310. TRANS("There's already a file called:")
  16311. + "\n\n" + chosen.getFullPathName()
  16312. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16313. TRANS("overwrite"),
  16314. TRANS("cancel")))
  16315. {
  16316. return userCancelledSave;
  16317. }
  16318. }
  16319. }
  16320. setLastDocumentOpened (chosen);
  16321. return saveAs (chosen, false, false, true);
  16322. }
  16323. return userCancelledSave;
  16324. }
  16325. END_JUCE_NAMESPACE
  16326. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16327. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16328. BEGIN_JUCE_NAMESPACE
  16329. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16330. : maxNumberOfItems (10)
  16331. {
  16332. }
  16333. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16334. {
  16335. }
  16336. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16337. {
  16338. maxNumberOfItems = jmax (1, newMaxNumber);
  16339. while (getNumFiles() > maxNumberOfItems)
  16340. files.remove (getNumFiles() - 1);
  16341. }
  16342. int RecentlyOpenedFilesList::getNumFiles() const
  16343. {
  16344. return files.size();
  16345. }
  16346. const File RecentlyOpenedFilesList::getFile (const int index) const
  16347. {
  16348. return File (files [index]);
  16349. }
  16350. void RecentlyOpenedFilesList::clear()
  16351. {
  16352. files.clear();
  16353. }
  16354. void RecentlyOpenedFilesList::addFile (const File& file)
  16355. {
  16356. const String path (file.getFullPathName());
  16357. files.removeString (path, true);
  16358. files.insert (0, path);
  16359. setMaxNumberOfItems (maxNumberOfItems);
  16360. }
  16361. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16362. {
  16363. for (int i = getNumFiles(); --i >= 0;)
  16364. if (! getFile(i).exists())
  16365. files.remove (i);
  16366. }
  16367. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16368. const int baseItemId,
  16369. const bool showFullPaths,
  16370. const bool dontAddNonExistentFiles,
  16371. const File** filesToAvoid)
  16372. {
  16373. int num = 0;
  16374. for (int i = 0; i < getNumFiles(); ++i)
  16375. {
  16376. const File f (getFile(i));
  16377. if ((! dontAddNonExistentFiles) || f.exists())
  16378. {
  16379. bool needsAvoiding = false;
  16380. if (filesToAvoid != 0)
  16381. {
  16382. const File** avoid = filesToAvoid;
  16383. while (*avoid != 0)
  16384. {
  16385. if (f == **avoid)
  16386. {
  16387. needsAvoiding = true;
  16388. break;
  16389. }
  16390. ++avoid;
  16391. }
  16392. }
  16393. if (! needsAvoiding)
  16394. {
  16395. menuToAddTo.addItem (baseItemId + i,
  16396. showFullPaths ? f.getFullPathName()
  16397. : f.getFileName());
  16398. ++num;
  16399. }
  16400. }
  16401. }
  16402. return num;
  16403. }
  16404. const String RecentlyOpenedFilesList::toString() const
  16405. {
  16406. return files.joinIntoString ("\n");
  16407. }
  16408. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16409. {
  16410. clear();
  16411. files.addLines (stringifiedVersion);
  16412. setMaxNumberOfItems (maxNumberOfItems);
  16413. }
  16414. END_JUCE_NAMESPACE
  16415. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16416. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16417. BEGIN_JUCE_NAMESPACE
  16418. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16419. const int minimumTransactions)
  16420. : totalUnitsStored (0),
  16421. nextIndex (0),
  16422. newTransaction (true),
  16423. reentrancyCheck (false)
  16424. {
  16425. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16426. minimumTransactions);
  16427. }
  16428. UndoManager::~UndoManager()
  16429. {
  16430. clearUndoHistory();
  16431. }
  16432. void UndoManager::clearUndoHistory()
  16433. {
  16434. transactions.clear();
  16435. transactionNames.clear();
  16436. totalUnitsStored = 0;
  16437. nextIndex = 0;
  16438. sendChangeMessage();
  16439. }
  16440. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16441. {
  16442. return totalUnitsStored;
  16443. }
  16444. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16445. const int minimumTransactions)
  16446. {
  16447. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16448. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16449. }
  16450. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16451. {
  16452. if (command_ != 0)
  16453. {
  16454. ScopedPointer<UndoableAction> command (command_);
  16455. if (actionName.isNotEmpty())
  16456. currentTransactionName = actionName;
  16457. if (reentrancyCheck)
  16458. {
  16459. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16460. // undo() methods, or else these actions won't actually get done.
  16461. return false;
  16462. }
  16463. else if (command->perform())
  16464. {
  16465. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16466. if (commandSet != 0 && ! newTransaction)
  16467. {
  16468. UndoableAction* lastAction = commandSet->getLast();
  16469. if (lastAction != 0)
  16470. {
  16471. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16472. if (coalescedAction != 0)
  16473. {
  16474. command = coalescedAction;
  16475. totalUnitsStored -= lastAction->getSizeInUnits();
  16476. commandSet->removeLast();
  16477. }
  16478. }
  16479. }
  16480. else
  16481. {
  16482. commandSet = new OwnedArray<UndoableAction>();
  16483. transactions.insert (nextIndex, commandSet);
  16484. transactionNames.insert (nextIndex, currentTransactionName);
  16485. ++nextIndex;
  16486. }
  16487. totalUnitsStored += command->getSizeInUnits();
  16488. commandSet->add (command.release());
  16489. newTransaction = false;
  16490. while (nextIndex < transactions.size())
  16491. {
  16492. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16493. for (int i = lastSet->size(); --i >= 0;)
  16494. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16495. transactions.removeLast();
  16496. transactionNames.remove (transactionNames.size() - 1);
  16497. }
  16498. while (nextIndex > 0
  16499. && totalUnitsStored > maxNumUnitsToKeep
  16500. && transactions.size() > minimumTransactionsToKeep)
  16501. {
  16502. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16503. for (int i = firstSet->size(); --i >= 0;)
  16504. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16505. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16506. transactions.remove (0);
  16507. transactionNames.remove (0);
  16508. --nextIndex;
  16509. }
  16510. sendChangeMessage();
  16511. return true;
  16512. }
  16513. }
  16514. return false;
  16515. }
  16516. void UndoManager::beginNewTransaction (const String& actionName)
  16517. {
  16518. newTransaction = true;
  16519. currentTransactionName = actionName;
  16520. }
  16521. void UndoManager::setCurrentTransactionName (const String& newName)
  16522. {
  16523. currentTransactionName = newName;
  16524. }
  16525. bool UndoManager::canUndo() const
  16526. {
  16527. return nextIndex > 0;
  16528. }
  16529. bool UndoManager::canRedo() const
  16530. {
  16531. return nextIndex < transactions.size();
  16532. }
  16533. const String UndoManager::getUndoDescription() const
  16534. {
  16535. return transactionNames [nextIndex - 1];
  16536. }
  16537. const String UndoManager::getRedoDescription() const
  16538. {
  16539. return transactionNames [nextIndex];
  16540. }
  16541. bool UndoManager::undo()
  16542. {
  16543. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16544. if (commandSet == 0)
  16545. return false;
  16546. reentrancyCheck = true;
  16547. bool failed = false;
  16548. for (int i = commandSet->size(); --i >= 0;)
  16549. {
  16550. if (! commandSet->getUnchecked(i)->undo())
  16551. {
  16552. jassertfalse;
  16553. failed = true;
  16554. break;
  16555. }
  16556. }
  16557. reentrancyCheck = false;
  16558. if (failed)
  16559. clearUndoHistory();
  16560. else
  16561. --nextIndex;
  16562. beginNewTransaction();
  16563. sendChangeMessage();
  16564. return true;
  16565. }
  16566. bool UndoManager::redo()
  16567. {
  16568. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16569. if (commandSet == 0)
  16570. return false;
  16571. reentrancyCheck = true;
  16572. bool failed = false;
  16573. for (int i = 0; i < commandSet->size(); ++i)
  16574. {
  16575. if (! commandSet->getUnchecked(i)->perform())
  16576. {
  16577. jassertfalse;
  16578. failed = true;
  16579. break;
  16580. }
  16581. }
  16582. reentrancyCheck = false;
  16583. if (failed)
  16584. clearUndoHistory();
  16585. else
  16586. ++nextIndex;
  16587. beginNewTransaction();
  16588. sendChangeMessage();
  16589. return true;
  16590. }
  16591. bool UndoManager::undoCurrentTransactionOnly()
  16592. {
  16593. return newTransaction ? false : undo();
  16594. }
  16595. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16596. {
  16597. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16598. if (commandSet != 0 && ! newTransaction)
  16599. {
  16600. for (int i = 0; i < commandSet->size(); ++i)
  16601. actionsFound.add (commandSet->getUnchecked(i));
  16602. }
  16603. }
  16604. int UndoManager::getNumActionsInCurrentTransaction() const
  16605. {
  16606. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16607. if (commandSet != 0 && ! newTransaction)
  16608. return commandSet->size();
  16609. return 0;
  16610. }
  16611. END_JUCE_NAMESPACE
  16612. /*** End of inlined file: juce_UndoManager.cpp ***/
  16613. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16614. BEGIN_JUCE_NAMESPACE
  16615. static const char* const aiffFormatName = "AIFF file";
  16616. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16617. class AiffAudioFormatReader : public AudioFormatReader
  16618. {
  16619. public:
  16620. int bytesPerFrame;
  16621. int64 dataChunkStart;
  16622. bool littleEndian;
  16623. AiffAudioFormatReader (InputStream* in)
  16624. : AudioFormatReader (in, TRANS (aiffFormatName))
  16625. {
  16626. if (input->readInt() == chunkName ("FORM"))
  16627. {
  16628. const int len = input->readIntBigEndian();
  16629. const int64 end = input->getPosition() + len;
  16630. const int nextType = input->readInt();
  16631. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16632. {
  16633. bool hasGotVer = false;
  16634. bool hasGotData = false;
  16635. bool hasGotType = false;
  16636. while (input->getPosition() < end)
  16637. {
  16638. const int type = input->readInt();
  16639. const uint32 length = (uint32) input->readIntBigEndian();
  16640. const int64 chunkEnd = input->getPosition() + length;
  16641. if (type == chunkName ("FVER"))
  16642. {
  16643. hasGotVer = true;
  16644. const int ver = input->readIntBigEndian();
  16645. if (ver != 0 && ver != (int) 0xa2805140)
  16646. break;
  16647. }
  16648. else if (type == chunkName ("COMM"))
  16649. {
  16650. hasGotType = true;
  16651. numChannels = (unsigned int) input->readShortBigEndian();
  16652. lengthInSamples = input->readIntBigEndian();
  16653. bitsPerSample = input->readShortBigEndian();
  16654. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16655. unsigned char sampleRateBytes[10];
  16656. input->read (sampleRateBytes, 10);
  16657. const int byte0 = sampleRateBytes[0];
  16658. if ((byte0 & 0x80) != 0
  16659. || byte0 <= 0x3F || byte0 > 0x40
  16660. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16661. break;
  16662. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16663. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16664. sampleRate = (int) sampRate;
  16665. if (length <= 18)
  16666. {
  16667. // some types don't have a chunk large enough to include a compression
  16668. // type, so assume it's just big-endian pcm
  16669. littleEndian = false;
  16670. }
  16671. else
  16672. {
  16673. const int compType = input->readInt();
  16674. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16675. {
  16676. littleEndian = false;
  16677. }
  16678. else if (compType == chunkName ("sowt"))
  16679. {
  16680. littleEndian = true;
  16681. }
  16682. else
  16683. {
  16684. sampleRate = 0;
  16685. break;
  16686. }
  16687. }
  16688. }
  16689. else if (type == chunkName ("SSND"))
  16690. {
  16691. hasGotData = true;
  16692. const int offset = input->readIntBigEndian();
  16693. dataChunkStart = input->getPosition() + 4 + offset;
  16694. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16695. }
  16696. else if ((hasGotVer && hasGotData && hasGotType)
  16697. || chunkEnd < input->getPosition()
  16698. || input->isExhausted())
  16699. {
  16700. break;
  16701. }
  16702. input->setPosition (chunkEnd);
  16703. }
  16704. }
  16705. }
  16706. }
  16707. ~AiffAudioFormatReader()
  16708. {
  16709. }
  16710. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16711. int64 startSampleInFile, int numSamples)
  16712. {
  16713. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16714. if (samplesAvailable < numSamples)
  16715. {
  16716. for (int i = numDestChannels; --i >= 0;)
  16717. if (destSamples[i] != 0)
  16718. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16719. numSamples = (int) samplesAvailable;
  16720. }
  16721. if (numSamples <= 0)
  16722. return true;
  16723. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16724. while (numSamples > 0)
  16725. {
  16726. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16727. char tempBuffer [tempBufSize];
  16728. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16729. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16730. if (bytesRead < numThisTime * bytesPerFrame)
  16731. {
  16732. jassert (bytesRead >= 0);
  16733. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16734. }
  16735. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16736. if (littleEndian)
  16737. {
  16738. switch (bitsPerSample)
  16739. {
  16740. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16741. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16742. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16743. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16744. default: jassertfalse; break;
  16745. }
  16746. }
  16747. else
  16748. {
  16749. switch (bitsPerSample)
  16750. {
  16751. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16752. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16753. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16754. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16755. default: jassertfalse; break;
  16756. }
  16757. }
  16758. startOffsetInDestBuffer += numThisTime;
  16759. numSamples -= numThisTime;
  16760. }
  16761. return true;
  16762. }
  16763. private:
  16764. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16765. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16766. };
  16767. class AiffAudioFormatWriter : public AudioFormatWriter
  16768. {
  16769. public:
  16770. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16771. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16772. lengthInSamples (0),
  16773. bytesWritten (0),
  16774. writeFailed (false)
  16775. {
  16776. headerPosition = out->getPosition();
  16777. writeHeader();
  16778. }
  16779. ~AiffAudioFormatWriter()
  16780. {
  16781. if ((bytesWritten & 1) != 0)
  16782. output->writeByte (0);
  16783. writeHeader();
  16784. }
  16785. bool write (const int** data, int numSamples)
  16786. {
  16787. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16788. if (writeFailed)
  16789. return false;
  16790. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16791. tempBlock.ensureSize (bytes, false);
  16792. switch (bitsPerSample)
  16793. {
  16794. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16795. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16796. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16797. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16798. default: jassertfalse; break;
  16799. }
  16800. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16801. || ! output->write (tempBlock.getData(), bytes))
  16802. {
  16803. // failed to write to disk, so let's try writing the header.
  16804. // If it's just run out of disk space, then if it does manage
  16805. // to write the header, we'll still have a useable file..
  16806. writeHeader();
  16807. writeFailed = true;
  16808. return false;
  16809. }
  16810. else
  16811. {
  16812. bytesWritten += bytes;
  16813. lengthInSamples += numSamples;
  16814. return true;
  16815. }
  16816. }
  16817. private:
  16818. MemoryBlock tempBlock;
  16819. uint32 lengthInSamples, bytesWritten;
  16820. int64 headerPosition;
  16821. bool writeFailed;
  16822. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16823. void writeHeader()
  16824. {
  16825. const bool couldSeekOk = output->setPosition (headerPosition);
  16826. (void) couldSeekOk;
  16827. // if this fails, you've given it an output stream that can't seek! It needs
  16828. // to be able to seek back to write the header
  16829. jassert (couldSeekOk);
  16830. const int headerLen = 54;
  16831. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16832. audioBytes += (audioBytes & 1);
  16833. output->writeInt (chunkName ("FORM"));
  16834. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16835. output->writeInt (chunkName ("AIFF"));
  16836. output->writeInt (chunkName ("COMM"));
  16837. output->writeIntBigEndian (18);
  16838. output->writeShortBigEndian ((short) numChannels);
  16839. output->writeIntBigEndian (lengthInSamples);
  16840. output->writeShortBigEndian ((short) bitsPerSample);
  16841. uint8 sampleRateBytes[10];
  16842. zeromem (sampleRateBytes, 10);
  16843. if (sampleRate <= 1)
  16844. {
  16845. sampleRateBytes[0] = 0x3f;
  16846. sampleRateBytes[1] = 0xff;
  16847. sampleRateBytes[2] = 0x80;
  16848. }
  16849. else
  16850. {
  16851. int mask = 0x40000000;
  16852. sampleRateBytes[0] = 0x40;
  16853. if (sampleRate >= mask)
  16854. {
  16855. jassertfalse;
  16856. sampleRateBytes[1] = 0x1d;
  16857. }
  16858. else
  16859. {
  16860. int n = (int) sampleRate;
  16861. int i;
  16862. for (i = 0; i <= 32 ; ++i)
  16863. {
  16864. if ((n & mask) != 0)
  16865. break;
  16866. mask >>= 1;
  16867. }
  16868. n = n << (i + 1);
  16869. sampleRateBytes[1] = (uint8) (29 - i);
  16870. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16871. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16872. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16873. sampleRateBytes[5] = (uint8) (n & 0xff);
  16874. }
  16875. }
  16876. output->write (sampleRateBytes, 10);
  16877. output->writeInt (chunkName ("SSND"));
  16878. output->writeIntBigEndian (audioBytes + 8);
  16879. output->writeInt (0);
  16880. output->writeInt (0);
  16881. jassert (output->getPosition() == headerLen);
  16882. }
  16883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16884. };
  16885. AiffAudioFormat::AiffAudioFormat()
  16886. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16887. {
  16888. }
  16889. AiffAudioFormat::~AiffAudioFormat()
  16890. {
  16891. }
  16892. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16893. {
  16894. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16895. return Array <int> (rates);
  16896. }
  16897. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16898. {
  16899. const int depths[] = { 8, 16, 24, 0 };
  16900. return Array <int> (depths);
  16901. }
  16902. bool AiffAudioFormat::canDoStereo() { return true; }
  16903. bool AiffAudioFormat::canDoMono() { return true; }
  16904. #if JUCE_MAC
  16905. bool AiffAudioFormat::canHandleFile (const File& f)
  16906. {
  16907. if (AudioFormat::canHandleFile (f))
  16908. return true;
  16909. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16910. return type == 'AIFF' || type == 'AIFC'
  16911. || type == 'aiff' || type == 'aifc';
  16912. }
  16913. #endif
  16914. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16915. {
  16916. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16917. if (w->sampleRate != 0)
  16918. return w.release();
  16919. if (! deleteStreamIfOpeningFails)
  16920. w->input = 0;
  16921. return 0;
  16922. }
  16923. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16924. double sampleRate,
  16925. unsigned int numberOfChannels,
  16926. int bitsPerSample,
  16927. const StringPairArray& /*metadataValues*/,
  16928. int /*qualityOptionIndex*/)
  16929. {
  16930. if (getPossibleBitDepths().contains (bitsPerSample))
  16931. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16932. return 0;
  16933. }
  16934. END_JUCE_NAMESPACE
  16935. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16936. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16937. BEGIN_JUCE_NAMESPACE
  16938. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16939. : formatName (name),
  16940. fileExtensions (extensions)
  16941. {
  16942. }
  16943. AudioFormat::~AudioFormat()
  16944. {
  16945. }
  16946. bool AudioFormat::canHandleFile (const File& f)
  16947. {
  16948. for (int i = 0; i < fileExtensions.size(); ++i)
  16949. if (f.hasFileExtension (fileExtensions[i]))
  16950. return true;
  16951. return false;
  16952. }
  16953. const String& AudioFormat::getFormatName() const { return formatName; }
  16954. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16955. bool AudioFormat::isCompressed() { return false; }
  16956. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16957. END_JUCE_NAMESPACE
  16958. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16959. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16960. BEGIN_JUCE_NAMESPACE
  16961. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16962. const String& formatName_)
  16963. : sampleRate (0),
  16964. bitsPerSample (0),
  16965. lengthInSamples (0),
  16966. numChannels (0),
  16967. usesFloatingPointData (false),
  16968. input (in),
  16969. formatName (formatName_)
  16970. {
  16971. }
  16972. AudioFormatReader::~AudioFormatReader()
  16973. {
  16974. delete input;
  16975. }
  16976. bool AudioFormatReader::read (int* const* destSamples,
  16977. int numDestChannels,
  16978. int64 startSampleInSource,
  16979. int numSamplesToRead,
  16980. const bool fillLeftoverChannelsWithCopies)
  16981. {
  16982. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16983. int startOffsetInDestBuffer = 0;
  16984. if (startSampleInSource < 0)
  16985. {
  16986. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16987. for (int i = numDestChannels; --i >= 0;)
  16988. if (destSamples[i] != 0)
  16989. zeromem (destSamples[i], sizeof (int) * silence);
  16990. startOffsetInDestBuffer += silence;
  16991. numSamplesToRead -= silence;
  16992. startSampleInSource = 0;
  16993. }
  16994. if (numSamplesToRead <= 0)
  16995. return true;
  16996. if (! readSamples (const_cast<int**> (destSamples),
  16997. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16998. startSampleInSource, numSamplesToRead))
  16999. return false;
  17000. if (numDestChannels > (int) numChannels)
  17001. {
  17002. if (fillLeftoverChannelsWithCopies)
  17003. {
  17004. int* lastFullChannel = destSamples[0];
  17005. for (int i = (int) numChannels; --i > 0;)
  17006. {
  17007. if (destSamples[i] != 0)
  17008. {
  17009. lastFullChannel = destSamples[i];
  17010. break;
  17011. }
  17012. }
  17013. if (lastFullChannel != 0)
  17014. for (int i = numChannels; i < numDestChannels; ++i)
  17015. if (destSamples[i] != 0)
  17016. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17017. }
  17018. else
  17019. {
  17020. for (int i = numChannels; i < numDestChannels; ++i)
  17021. if (destSamples[i] != 0)
  17022. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17023. }
  17024. }
  17025. return true;
  17026. }
  17027. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17028. int64 numSamples,
  17029. float& lowestLeft, float& highestLeft,
  17030. float& lowestRight, float& highestRight)
  17031. {
  17032. if (numSamples <= 0)
  17033. {
  17034. lowestLeft = 0;
  17035. lowestRight = 0;
  17036. highestLeft = 0;
  17037. highestRight = 0;
  17038. return;
  17039. }
  17040. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17041. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17042. int* tempBuffer[3];
  17043. tempBuffer[0] = tempSpace.getData();
  17044. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17045. tempBuffer[2] = 0;
  17046. if (usesFloatingPointData)
  17047. {
  17048. float lmin = 1.0e6f;
  17049. float lmax = -lmin;
  17050. float rmin = lmin;
  17051. float rmax = lmax;
  17052. while (numSamples > 0)
  17053. {
  17054. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17055. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17056. numSamples -= numToDo;
  17057. startSampleInFile += numToDo;
  17058. float bufMin, bufMax;
  17059. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  17060. lmin = jmin (lmin, bufMin);
  17061. lmax = jmax (lmax, bufMax);
  17062. if (numChannels > 1)
  17063. {
  17064. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  17065. rmin = jmin (rmin, bufMin);
  17066. rmax = jmax (rmax, bufMax);
  17067. }
  17068. }
  17069. if (numChannels <= 1)
  17070. {
  17071. rmax = lmax;
  17072. rmin = lmin;
  17073. }
  17074. lowestLeft = lmin;
  17075. highestLeft = lmax;
  17076. lowestRight = rmin;
  17077. highestRight = rmax;
  17078. }
  17079. else
  17080. {
  17081. int lmax = std::numeric_limits<int>::min();
  17082. int lmin = std::numeric_limits<int>::max();
  17083. int rmax = std::numeric_limits<int>::min();
  17084. int rmin = std::numeric_limits<int>::max();
  17085. while (numSamples > 0)
  17086. {
  17087. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17088. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  17089. break;
  17090. numSamples -= numToDo;
  17091. startSampleInFile += numToDo;
  17092. for (int j = numChannels; --j >= 0;)
  17093. {
  17094. int bufMin, bufMax;
  17095. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  17096. if (j == 0)
  17097. {
  17098. lmax = jmax (lmax, bufMax);
  17099. lmin = jmin (lmin, bufMin);
  17100. }
  17101. else
  17102. {
  17103. rmax = jmax (rmax, bufMax);
  17104. rmin = jmin (rmin, bufMin);
  17105. }
  17106. }
  17107. }
  17108. if (numChannels <= 1)
  17109. {
  17110. rmax = lmax;
  17111. rmin = lmin;
  17112. }
  17113. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17114. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17115. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17116. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17117. }
  17118. }
  17119. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17120. int64 numSamplesToSearch,
  17121. const double magnitudeRangeMinimum,
  17122. const double magnitudeRangeMaximum,
  17123. const int minimumConsecutiveSamples)
  17124. {
  17125. if (numSamplesToSearch == 0)
  17126. return -1;
  17127. const int bufferSize = 4096;
  17128. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17129. int* tempBuffer[3];
  17130. tempBuffer[0] = tempSpace.getData();
  17131. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17132. tempBuffer[2] = 0;
  17133. int consecutive = 0;
  17134. int64 firstMatchPos = -1;
  17135. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17136. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17137. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17138. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17139. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17140. while (numSamplesToSearch != 0)
  17141. {
  17142. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17143. int64 bufferStart = startSample;
  17144. if (numSamplesToSearch < 0)
  17145. bufferStart -= numThisTime;
  17146. if (bufferStart >= (int) lengthInSamples)
  17147. break;
  17148. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17149. int num = numThisTime;
  17150. while (--num >= 0)
  17151. {
  17152. if (numSamplesToSearch < 0)
  17153. --startSample;
  17154. bool matches = false;
  17155. const int index = (int) (startSample - bufferStart);
  17156. if (usesFloatingPointData)
  17157. {
  17158. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17159. if (sample1 >= magnitudeRangeMinimum
  17160. && sample1 <= magnitudeRangeMaximum)
  17161. {
  17162. matches = true;
  17163. }
  17164. else if (numChannels > 1)
  17165. {
  17166. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17167. matches = (sample2 >= magnitudeRangeMinimum
  17168. && sample2 <= magnitudeRangeMaximum);
  17169. }
  17170. }
  17171. else
  17172. {
  17173. const int sample1 = abs (tempBuffer[0] [index]);
  17174. if (sample1 >= intMagnitudeRangeMinimum
  17175. && sample1 <= intMagnitudeRangeMaximum)
  17176. {
  17177. matches = true;
  17178. }
  17179. else if (numChannels > 1)
  17180. {
  17181. const int sample2 = abs (tempBuffer[1][index]);
  17182. matches = (sample2 >= intMagnitudeRangeMinimum
  17183. && sample2 <= intMagnitudeRangeMaximum);
  17184. }
  17185. }
  17186. if (matches)
  17187. {
  17188. if (firstMatchPos < 0)
  17189. firstMatchPos = startSample;
  17190. if (++consecutive >= minimumConsecutiveSamples)
  17191. {
  17192. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17193. return -1;
  17194. return firstMatchPos;
  17195. }
  17196. }
  17197. else
  17198. {
  17199. consecutive = 0;
  17200. firstMatchPos = -1;
  17201. }
  17202. if (numSamplesToSearch > 0)
  17203. ++startSample;
  17204. }
  17205. if (numSamplesToSearch > 0)
  17206. numSamplesToSearch -= numThisTime;
  17207. else
  17208. numSamplesToSearch += numThisTime;
  17209. }
  17210. return -1;
  17211. }
  17212. END_JUCE_NAMESPACE
  17213. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17214. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17215. BEGIN_JUCE_NAMESPACE
  17216. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17217. const String& formatName_,
  17218. const double rate,
  17219. const unsigned int numChannels_,
  17220. const unsigned int bitsPerSample_)
  17221. : sampleRate (rate),
  17222. numChannels (numChannels_),
  17223. bitsPerSample (bitsPerSample_),
  17224. usesFloatingPointData (false),
  17225. output (out),
  17226. formatName (formatName_)
  17227. {
  17228. }
  17229. AudioFormatWriter::~AudioFormatWriter()
  17230. {
  17231. delete output;
  17232. }
  17233. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17234. int64 startSample,
  17235. int64 numSamplesToRead)
  17236. {
  17237. const int bufferSize = 16384;
  17238. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17239. int* buffers [128];
  17240. zerostruct (buffers);
  17241. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17242. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17243. if (numSamplesToRead < 0)
  17244. numSamplesToRead = reader.lengthInSamples;
  17245. while (numSamplesToRead > 0)
  17246. {
  17247. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17248. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17249. return false;
  17250. if (reader.usesFloatingPointData != isFloatingPoint())
  17251. {
  17252. int** bufferChan = buffers;
  17253. while (*bufferChan != 0)
  17254. {
  17255. int* b = *bufferChan++;
  17256. if (isFloatingPoint())
  17257. {
  17258. // int -> float
  17259. const double factor = 1.0 / std::numeric_limits<int>::max();
  17260. for (int i = 0; i < numToDo; ++i)
  17261. ((float*) b)[i] = (float) (factor * b[i]);
  17262. }
  17263. else
  17264. {
  17265. // float -> int
  17266. for (int i = 0; i < numToDo; ++i)
  17267. {
  17268. const double samp = *(const float*) b;
  17269. if (samp <= -1.0)
  17270. *b++ = std::numeric_limits<int>::min();
  17271. else if (samp >= 1.0)
  17272. *b++ = std::numeric_limits<int>::max();
  17273. else
  17274. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17275. }
  17276. }
  17277. }
  17278. }
  17279. if (! write (const_cast<const int**> (buffers), numToDo))
  17280. return false;
  17281. numSamplesToRead -= numToDo;
  17282. startSample += numToDo;
  17283. }
  17284. return true;
  17285. }
  17286. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17287. {
  17288. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17289. while (numSamplesToRead > 0)
  17290. {
  17291. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17292. AudioSourceChannelInfo info;
  17293. info.buffer = &tempBuffer;
  17294. info.startSample = 0;
  17295. info.numSamples = numToDo;
  17296. info.clearActiveBufferRegion();
  17297. source.getNextAudioBlock (info);
  17298. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17299. return false;
  17300. numSamplesToRead -= numToDo;
  17301. }
  17302. return true;
  17303. }
  17304. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17305. {
  17306. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17307. if (numSamples <= 0)
  17308. return true;
  17309. HeapBlock<int> tempBuffer;
  17310. HeapBlock<int*> chans (numChannels + 1);
  17311. chans [numChannels] = 0;
  17312. if (isFloatingPoint())
  17313. {
  17314. for (int i = numChannels; --i >= 0;)
  17315. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17316. }
  17317. else
  17318. {
  17319. tempBuffer.malloc (numSamples * numChannels);
  17320. for (unsigned int i = 0; i < numChannels; ++i)
  17321. {
  17322. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17323. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17324. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17325. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17326. destData.convertSamples (sourceData, numSamples);
  17327. }
  17328. }
  17329. return write ((const int**) chans.getData(), numSamples);
  17330. }
  17331. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17332. public AbstractFifo
  17333. {
  17334. public:
  17335. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17336. : AbstractFifo (bufferSize),
  17337. buffer (numChannels, bufferSize),
  17338. timeSliceThread (timeSliceThread_),
  17339. writer (writer_),
  17340. thumbnailToUpdate (0),
  17341. samplesWritten (0),
  17342. isRunning (true)
  17343. {
  17344. timeSliceThread.addTimeSliceClient (this);
  17345. }
  17346. ~Buffer()
  17347. {
  17348. isRunning = false;
  17349. timeSliceThread.removeTimeSliceClient (this);
  17350. while (useTimeSlice())
  17351. {}
  17352. }
  17353. bool write (const float** data, int numSamples)
  17354. {
  17355. if (numSamples <= 0 || ! isRunning)
  17356. return true;
  17357. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17358. int start1, size1, start2, size2;
  17359. prepareToWrite (numSamples, start1, size1, start2, size2);
  17360. if (size1 + size2 < numSamples)
  17361. return false;
  17362. for (int i = buffer.getNumChannels(); --i >= 0;)
  17363. {
  17364. buffer.copyFrom (i, start1, data[i], size1);
  17365. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17366. }
  17367. finishedWrite (size1 + size2);
  17368. timeSliceThread.notify();
  17369. return true;
  17370. }
  17371. bool useTimeSlice()
  17372. {
  17373. const int numToDo = getTotalSize() / 4;
  17374. int start1, size1, start2, size2;
  17375. prepareToRead (numToDo, start1, size1, start2, size2);
  17376. if (size1 <= 0)
  17377. return false;
  17378. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17379. const ScopedLock sl (thumbnailLock);
  17380. if (thumbnailToUpdate != 0)
  17381. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17382. samplesWritten += size1;
  17383. if (size2 > 0)
  17384. {
  17385. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17386. if (thumbnailToUpdate != 0)
  17387. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17388. samplesWritten += size2;
  17389. }
  17390. finishedRead (size1 + size2);
  17391. return true;
  17392. }
  17393. void setThumbnail (AudioThumbnail* thumb)
  17394. {
  17395. if (thumb != 0)
  17396. thumb->reset (buffer.getNumChannels(), writer->getSampleRate());
  17397. const ScopedLock sl (thumbnailLock);
  17398. thumbnailToUpdate = thumb;
  17399. samplesWritten = 0;
  17400. }
  17401. private:
  17402. AudioSampleBuffer buffer;
  17403. TimeSliceThread& timeSliceThread;
  17404. ScopedPointer<AudioFormatWriter> writer;
  17405. CriticalSection thumbnailLock;
  17406. AudioThumbnail* thumbnailToUpdate;
  17407. int64 samplesWritten;
  17408. volatile bool isRunning;
  17409. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17410. };
  17411. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17412. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17413. {
  17414. }
  17415. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17416. {
  17417. }
  17418. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17419. {
  17420. return buffer->write (data, numSamples);
  17421. }
  17422. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17423. {
  17424. buffer->setThumbnail (thumb);
  17425. }
  17426. END_JUCE_NAMESPACE
  17427. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17428. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17429. BEGIN_JUCE_NAMESPACE
  17430. AudioFormatManager::AudioFormatManager()
  17431. : defaultFormatIndex (0)
  17432. {
  17433. }
  17434. AudioFormatManager::~AudioFormatManager()
  17435. {
  17436. }
  17437. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17438. {
  17439. jassert (newFormat != 0);
  17440. if (newFormat != 0)
  17441. {
  17442. #if JUCE_DEBUG
  17443. for (int i = getNumKnownFormats(); --i >= 0;)
  17444. {
  17445. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17446. {
  17447. jassertfalse; // trying to add the same format twice!
  17448. }
  17449. }
  17450. #endif
  17451. if (makeThisTheDefaultFormat)
  17452. defaultFormatIndex = getNumKnownFormats();
  17453. knownFormats.add (newFormat);
  17454. }
  17455. }
  17456. void AudioFormatManager::registerBasicFormats()
  17457. {
  17458. #if JUCE_MAC
  17459. registerFormat (new AiffAudioFormat(), true);
  17460. registerFormat (new WavAudioFormat(), false);
  17461. #else
  17462. registerFormat (new WavAudioFormat(), true);
  17463. registerFormat (new AiffAudioFormat(), false);
  17464. #endif
  17465. #if JUCE_USE_FLAC
  17466. registerFormat (new FlacAudioFormat(), false);
  17467. #endif
  17468. #if JUCE_USE_OGGVORBIS
  17469. registerFormat (new OggVorbisAudioFormat(), false);
  17470. #endif
  17471. }
  17472. void AudioFormatManager::clearFormats()
  17473. {
  17474. knownFormats.clear();
  17475. defaultFormatIndex = 0;
  17476. }
  17477. int AudioFormatManager::getNumKnownFormats() const
  17478. {
  17479. return knownFormats.size();
  17480. }
  17481. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17482. {
  17483. return knownFormats [index];
  17484. }
  17485. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17486. {
  17487. return getKnownFormat (defaultFormatIndex);
  17488. }
  17489. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17490. {
  17491. String e (fileExtension);
  17492. if (! e.startsWithChar ('.'))
  17493. e = "." + e;
  17494. for (int i = 0; i < getNumKnownFormats(); ++i)
  17495. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17496. return getKnownFormat(i);
  17497. return 0;
  17498. }
  17499. const String AudioFormatManager::getWildcardForAllFormats() const
  17500. {
  17501. StringArray allExtensions;
  17502. int i;
  17503. for (i = 0; i < getNumKnownFormats(); ++i)
  17504. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17505. allExtensions.trim();
  17506. allExtensions.removeEmptyStrings();
  17507. String s;
  17508. for (i = 0; i < allExtensions.size(); ++i)
  17509. {
  17510. s << '*';
  17511. if (! allExtensions[i].startsWithChar ('.'))
  17512. s << '.';
  17513. s << allExtensions[i];
  17514. if (i < allExtensions.size() - 1)
  17515. s << ';';
  17516. }
  17517. return s;
  17518. }
  17519. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17520. {
  17521. // you need to actually register some formats before the manager can
  17522. // use them to open a file!
  17523. jassert (getNumKnownFormats() > 0);
  17524. for (int i = 0; i < getNumKnownFormats(); ++i)
  17525. {
  17526. AudioFormat* const af = getKnownFormat(i);
  17527. if (af->canHandleFile (file))
  17528. {
  17529. InputStream* const in = file.createInputStream();
  17530. if (in != 0)
  17531. {
  17532. AudioFormatReader* const r = af->createReaderFor (in, true);
  17533. if (r != 0)
  17534. return r;
  17535. }
  17536. }
  17537. }
  17538. return 0;
  17539. }
  17540. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17541. {
  17542. // you need to actually register some formats before the manager can
  17543. // use them to open a file!
  17544. jassert (getNumKnownFormats() > 0);
  17545. ScopedPointer <InputStream> in (audioFileStream);
  17546. if (in != 0)
  17547. {
  17548. const int64 originalStreamPos = in->getPosition();
  17549. for (int i = 0; i < getNumKnownFormats(); ++i)
  17550. {
  17551. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17552. if (r != 0)
  17553. {
  17554. in.release();
  17555. return r;
  17556. }
  17557. in->setPosition (originalStreamPos);
  17558. // the stream that is passed-in must be capable of being repositioned so
  17559. // that all the formats can have a go at opening it.
  17560. jassert (in->getPosition() == originalStreamPos);
  17561. }
  17562. }
  17563. return 0;
  17564. }
  17565. END_JUCE_NAMESPACE
  17566. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17567. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17568. BEGIN_JUCE_NAMESPACE
  17569. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17570. const int64 startSample_,
  17571. const int64 length_,
  17572. const bool deleteSourceWhenDeleted_)
  17573. : AudioFormatReader (0, source_->getFormatName()),
  17574. source (source_),
  17575. startSample (startSample_),
  17576. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17577. {
  17578. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17579. sampleRate = source->sampleRate;
  17580. bitsPerSample = source->bitsPerSample;
  17581. lengthInSamples = length;
  17582. numChannels = source->numChannels;
  17583. usesFloatingPointData = source->usesFloatingPointData;
  17584. }
  17585. AudioSubsectionReader::~AudioSubsectionReader()
  17586. {
  17587. if (deleteSourceWhenDeleted)
  17588. delete source;
  17589. }
  17590. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17591. int64 startSampleInFile, int numSamples)
  17592. {
  17593. if (startSampleInFile + numSamples > length)
  17594. {
  17595. for (int i = numDestChannels; --i >= 0;)
  17596. if (destSamples[i] != 0)
  17597. zeromem (destSamples[i], sizeof (int) * numSamples);
  17598. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17599. if (numSamples <= 0)
  17600. return true;
  17601. }
  17602. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17603. startSampleInFile + startSample, numSamples);
  17604. }
  17605. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17606. int64 numSamples,
  17607. float& lowestLeft,
  17608. float& highestLeft,
  17609. float& lowestRight,
  17610. float& highestRight)
  17611. {
  17612. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17613. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17614. source->readMaxLevels (startSampleInFile + startSample,
  17615. numSamples,
  17616. lowestLeft,
  17617. highestLeft,
  17618. lowestRight,
  17619. highestRight);
  17620. }
  17621. END_JUCE_NAMESPACE
  17622. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17623. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17624. BEGIN_JUCE_NAMESPACE
  17625. struct AudioThumbnail::MinMaxValue
  17626. {
  17627. char minValue;
  17628. char maxValue;
  17629. MinMaxValue() : minValue (0), maxValue (0)
  17630. {
  17631. }
  17632. inline void set (const char newMin, const char newMax) throw()
  17633. {
  17634. minValue = newMin;
  17635. maxValue = newMax;
  17636. }
  17637. inline void setFloat (const float newMin, const float newMax) throw()
  17638. {
  17639. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17640. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17641. if (maxValue == minValue)
  17642. maxValue = (char) jmin (127, maxValue + 1);
  17643. }
  17644. inline bool isNonZero() const throw()
  17645. {
  17646. return maxValue > minValue;
  17647. }
  17648. inline int getPeak() const throw()
  17649. {
  17650. return jmax (std::abs ((int) minValue),
  17651. std::abs ((int) maxValue));
  17652. }
  17653. inline void read (InputStream& input)
  17654. {
  17655. minValue = input.readByte();
  17656. maxValue = input.readByte();
  17657. }
  17658. inline void write (OutputStream& output)
  17659. {
  17660. output.writeByte (minValue);
  17661. output.writeByte (maxValue);
  17662. }
  17663. };
  17664. class AudioThumbnail::LevelDataSource : public TimeSliceClient,
  17665. public Timer
  17666. {
  17667. public:
  17668. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17669. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17670. hashCode (hash), owner (owner_), reader (newReader)
  17671. {
  17672. }
  17673. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17674. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17675. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17676. {
  17677. }
  17678. ~LevelDataSource()
  17679. {
  17680. owner.cache.removeTimeSliceClient (this);
  17681. }
  17682. enum { timeBeforeDeletingReader = 2000 };
  17683. void initialise (int64 numSamplesFinished_)
  17684. {
  17685. const ScopedLock sl (readerLock);
  17686. numSamplesFinished = numSamplesFinished_;
  17687. createReader();
  17688. if (reader != 0)
  17689. {
  17690. lengthInSamples = reader->lengthInSamples;
  17691. numChannels = reader->numChannels;
  17692. sampleRate = reader->sampleRate;
  17693. if (lengthInSamples <= 0)
  17694. reader = 0;
  17695. else if (! isFullyLoaded())
  17696. owner.cache.addTimeSliceClient (this);
  17697. }
  17698. }
  17699. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17700. {
  17701. const ScopedLock sl (readerLock);
  17702. createReader();
  17703. if (reader != 0)
  17704. {
  17705. float l[4] = { 0 };
  17706. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17707. levels.clearQuick();
  17708. levels.addArray ((const float*) l, 4);
  17709. }
  17710. }
  17711. void releaseResources()
  17712. {
  17713. const ScopedLock sl (readerLock);
  17714. reader = 0;
  17715. }
  17716. bool useTimeSlice()
  17717. {
  17718. if (isFullyLoaded())
  17719. {
  17720. if (reader != 0 && source != 0)
  17721. startTimer (timeBeforeDeletingReader);
  17722. owner.cache.removeTimeSliceClient (this);
  17723. return false;
  17724. }
  17725. stopTimer();
  17726. bool justFinished = false;
  17727. {
  17728. const ScopedLock sl (readerLock);
  17729. createReader();
  17730. if (reader != 0)
  17731. {
  17732. if (! readNextBlock())
  17733. return true;
  17734. justFinished = true;
  17735. }
  17736. }
  17737. if (justFinished)
  17738. owner.cache.storeThumb (owner, hashCode);
  17739. return false;
  17740. }
  17741. void timerCallback()
  17742. {
  17743. stopTimer();
  17744. releaseResources();
  17745. }
  17746. bool isFullyLoaded() const throw()
  17747. {
  17748. return numSamplesFinished >= lengthInSamples;
  17749. }
  17750. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17751. {
  17752. return (int) (originalSample / owner.samplesPerThumbSample);
  17753. }
  17754. int64 lengthInSamples, numSamplesFinished;
  17755. double sampleRate;
  17756. int numChannels;
  17757. int64 hashCode;
  17758. private:
  17759. AudioThumbnail& owner;
  17760. ScopedPointer <InputSource> source;
  17761. ScopedPointer <AudioFormatReader> reader;
  17762. CriticalSection readerLock;
  17763. void createReader()
  17764. {
  17765. if (reader == 0 && source != 0)
  17766. {
  17767. InputStream* audioFileStream = source->createInputStream();
  17768. if (audioFileStream != 0)
  17769. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17770. }
  17771. }
  17772. bool readNextBlock()
  17773. {
  17774. jassert (reader != 0);
  17775. if (! isFullyLoaded())
  17776. {
  17777. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17778. if (numToDo > 0)
  17779. {
  17780. int64 startSample = numSamplesFinished;
  17781. const int firstThumbIndex = sampleToThumbSample (startSample);
  17782. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17783. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17784. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17785. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17786. for (int i = 0; i < numThumbSamps; ++i)
  17787. {
  17788. float lowestLeft, highestLeft, lowestRight, highestRight;
  17789. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17790. lowestLeft, highestLeft, lowestRight, highestRight);
  17791. levels[0][i].setFloat (lowestLeft, highestLeft);
  17792. levels[1][i].setFloat (lowestRight, highestRight);
  17793. }
  17794. {
  17795. const ScopedUnlock su (readerLock);
  17796. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17797. }
  17798. numSamplesFinished += numToDo;
  17799. }
  17800. }
  17801. return isFullyLoaded();
  17802. }
  17803. };
  17804. class AudioThumbnail::ThumbData
  17805. {
  17806. public:
  17807. ThumbData (const int numThumbSamples)
  17808. : peakLevel (-1)
  17809. {
  17810. ensureSize (numThumbSamples);
  17811. }
  17812. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17813. {
  17814. jassert (thumbSampleIndex < data.size());
  17815. return data.getRawDataPointer() + thumbSampleIndex;
  17816. }
  17817. int getSize() const throw()
  17818. {
  17819. return data.size();
  17820. }
  17821. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17822. {
  17823. if (startSample >= 0)
  17824. {
  17825. endSample = jmin (endSample, data.size() - 1);
  17826. char mx = -128;
  17827. char mn = 127;
  17828. while (startSample <= endSample)
  17829. {
  17830. const MinMaxValue& v = data.getReference (startSample);
  17831. if (v.minValue < mn) mn = v.minValue;
  17832. if (v.maxValue > mx) mx = v.maxValue;
  17833. ++startSample;
  17834. }
  17835. if (mn <= mx)
  17836. {
  17837. result.set (mn, mx);
  17838. return;
  17839. }
  17840. }
  17841. result.set (1, 0);
  17842. }
  17843. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17844. {
  17845. resetPeak();
  17846. if (startIndex + numValues > data.size())
  17847. ensureSize (startIndex + numValues);
  17848. MinMaxValue* const dest = getData (startIndex);
  17849. for (int i = 0; i < numValues; ++i)
  17850. dest[i] = source[i];
  17851. }
  17852. void resetPeak()
  17853. {
  17854. peakLevel = -1;
  17855. }
  17856. int getPeak()
  17857. {
  17858. if (peakLevel < 0)
  17859. {
  17860. for (int i = 0; i < data.size(); ++i)
  17861. {
  17862. const int peak = data[i].getPeak();
  17863. if (peak > peakLevel)
  17864. peakLevel = peak;
  17865. }
  17866. }
  17867. return peakLevel;
  17868. }
  17869. private:
  17870. Array <MinMaxValue> data;
  17871. int peakLevel;
  17872. void ensureSize (const int thumbSamples)
  17873. {
  17874. const int extraNeeded = thumbSamples - data.size();
  17875. if (extraNeeded > 0)
  17876. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17877. }
  17878. };
  17879. class AudioThumbnail::CachedWindow
  17880. {
  17881. public:
  17882. CachedWindow()
  17883. : cachedStart (0), cachedTimePerPixel (0),
  17884. numChannelsCached (0), numSamplesCached (0),
  17885. cacheNeedsRefilling (true)
  17886. {
  17887. }
  17888. void invalidate()
  17889. {
  17890. cacheNeedsRefilling = true;
  17891. }
  17892. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17893. const double startTime, const double endTime,
  17894. const int channelNum, const float verticalZoomFactor,
  17895. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17896. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17897. {
  17898. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17899. numChannels, samplesPerThumbSample, levelData, channels);
  17900. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17901. {
  17902. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17903. if (! clip.isEmpty())
  17904. {
  17905. const float topY = (float) area.getY();
  17906. const float bottomY = (float) area.getBottom();
  17907. const float midY = (topY + bottomY) * 0.5f;
  17908. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17909. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17910. int x = clip.getX();
  17911. for (int w = clip.getWidth(); --w >= 0;)
  17912. {
  17913. if (cacheData->isNonZero())
  17914. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17915. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17916. ++x;
  17917. ++cacheData;
  17918. }
  17919. }
  17920. }
  17921. }
  17922. private:
  17923. Array <MinMaxValue> data;
  17924. double cachedStart, cachedTimePerPixel;
  17925. int numChannelsCached, numSamplesCached;
  17926. bool cacheNeedsRefilling;
  17927. void refillCache (const int numSamples, double startTime, const double endTime,
  17928. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17929. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17930. {
  17931. const double timePerPixel = (endTime - startTime) / numSamples;
  17932. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17933. {
  17934. invalidate();
  17935. return;
  17936. }
  17937. if (numSamples == numSamplesCached
  17938. && numChannelsCached == numChannels
  17939. && startTime == cachedStart
  17940. && timePerPixel == cachedTimePerPixel
  17941. && ! cacheNeedsRefilling)
  17942. {
  17943. return;
  17944. }
  17945. numSamplesCached = numSamples;
  17946. numChannelsCached = numChannels;
  17947. cachedStart = startTime;
  17948. cachedTimePerPixel = timePerPixel;
  17949. cacheNeedsRefilling = false;
  17950. ensureSize (numSamples);
  17951. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17952. {
  17953. int sample = roundToInt (startTime * sampleRate);
  17954. Array<float> levels;
  17955. int i;
  17956. for (i = 0; i < numSamples; ++i)
  17957. {
  17958. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17959. if (sample >= 0)
  17960. {
  17961. if (sample >= levelData->lengthInSamples)
  17962. break;
  17963. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17964. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17965. for (int chan = 0; chan < numChans; ++chan)
  17966. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17967. levels.getUnchecked (chan * 2 + 1));
  17968. }
  17969. startTime += timePerPixel;
  17970. sample = nextSample;
  17971. }
  17972. numSamplesCached = i;
  17973. }
  17974. else
  17975. {
  17976. jassert (channels.size() == numChannelsCached);
  17977. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17978. {
  17979. ThumbData* channelData = channels.getUnchecked (channelNum);
  17980. MinMaxValue* cacheData = getData (channelNum, 0);
  17981. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17982. startTime = cachedStart;
  17983. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17984. for (int i = numSamples; --i >= 0;)
  17985. {
  17986. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17987. channelData->getMinMax (sample, nextSample, *cacheData);
  17988. ++cacheData;
  17989. startTime += timePerPixel;
  17990. sample = nextSample;
  17991. }
  17992. }
  17993. }
  17994. }
  17995. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17996. {
  17997. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17998. return data.getRawDataPointer() + channelNum * numSamplesCached
  17999. + cacheIndex;
  18000. }
  18001. void ensureSize (const int numSamples)
  18002. {
  18003. const int itemsRequired = numSamples * numChannelsCached;
  18004. if (data.size() < itemsRequired)
  18005. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  18006. }
  18007. };
  18008. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  18009. AudioFormatManager& formatManagerToUse_,
  18010. AudioThumbnailCache& cacheToUse)
  18011. : formatManagerToUse (formatManagerToUse_),
  18012. cache (cacheToUse),
  18013. window (new CachedWindow()),
  18014. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  18015. totalSamples (0),
  18016. numChannels (0),
  18017. sampleRate (0)
  18018. {
  18019. }
  18020. AudioThumbnail::~AudioThumbnail()
  18021. {
  18022. clear();
  18023. }
  18024. void AudioThumbnail::clear()
  18025. {
  18026. source = 0;
  18027. const ScopedLock sl (lock);
  18028. window->invalidate();
  18029. channels.clear();
  18030. totalSamples = numSamplesFinished = 0;
  18031. numChannels = 0;
  18032. sampleRate = 0;
  18033. sendChangeMessage();
  18034. }
  18035. void AudioThumbnail::reset (int newNumChannels, double newSampleRate)
  18036. {
  18037. clear();
  18038. numChannels = newNumChannels;
  18039. sampleRate = newSampleRate;
  18040. createChannels (0);
  18041. }
  18042. void AudioThumbnail::createChannels (const int length)
  18043. {
  18044. while (channels.size() < numChannels)
  18045. channels.add (new ThumbData (length));
  18046. }
  18047. void AudioThumbnail::loadFrom (InputStream& input)
  18048. {
  18049. clear();
  18050. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  18051. return;
  18052. samplesPerThumbSample = input.readInt();
  18053. totalSamples = input.readInt64(); // Total number of source samples.
  18054. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  18055. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  18056. numChannels = input.readInt(); // Number of audio channels.
  18057. sampleRate = input.readInt(); // Source sample rate.
  18058. input.skipNextBytes (16); // reserved area
  18059. createChannels (numThumbnailSamples);
  18060. for (int i = 0; i < numThumbnailSamples; ++i)
  18061. for (int chan = 0; chan < numChannels; ++chan)
  18062. channels.getUnchecked(chan)->getData(i)->read (input);
  18063. }
  18064. void AudioThumbnail::saveTo (OutputStream& output) const
  18065. {
  18066. const ScopedLock sl (lock);
  18067. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  18068. output.write ("jatm", 4);
  18069. output.writeInt (samplesPerThumbSample);
  18070. output.writeInt64 (totalSamples);
  18071. output.writeInt64 (numSamplesFinished);
  18072. output.writeInt (numThumbnailSamples);
  18073. output.writeInt (numChannels);
  18074. output.writeInt ((int) sampleRate);
  18075. output.writeInt64 (0);
  18076. output.writeInt64 (0);
  18077. for (int i = 0; i < numThumbnailSamples; ++i)
  18078. for (int chan = 0; chan < numChannels; ++chan)
  18079. channels.getUnchecked(chan)->getData(i)->write (output);
  18080. }
  18081. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  18082. {
  18083. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  18084. numSamplesFinished = 0;
  18085. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  18086. {
  18087. source = newSource; // (make sure this isn't done before loadThumb is called)
  18088. source->lengthInSamples = totalSamples;
  18089. source->sampleRate = sampleRate;
  18090. source->numChannels = numChannels;
  18091. source->numSamplesFinished = numSamplesFinished;
  18092. }
  18093. else
  18094. {
  18095. source = newSource; // (make sure this isn't done before loadThumb is called)
  18096. const ScopedLock sl (lock);
  18097. source->initialise (numSamplesFinished);
  18098. totalSamples = source->lengthInSamples;
  18099. sampleRate = source->sampleRate;
  18100. numChannels = source->numChannels;
  18101. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  18102. }
  18103. return sampleRate > 0 && totalSamples > 0;
  18104. }
  18105. bool AudioThumbnail::setSource (InputSource* const newSource)
  18106. {
  18107. clear();
  18108. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  18109. }
  18110. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  18111. {
  18112. clear();
  18113. if (newReader != 0)
  18114. setDataSource (new LevelDataSource (*this, newReader, hash));
  18115. }
  18116. int64 AudioThumbnail::getHashCode() const
  18117. {
  18118. return source == 0 ? 0 : source->hashCode;
  18119. }
  18120. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  18121. int startOffsetInBuffer, int numSamples)
  18122. {
  18123. jassert (startSample >= 0);
  18124. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  18125. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  18126. const int numToDo = lastThumbIndex - firstThumbIndex;
  18127. if (numToDo > 0)
  18128. {
  18129. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  18130. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  18131. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  18132. for (int chan = 0; chan < numChans; ++chan)
  18133. {
  18134. const float* const source = incoming.getSampleData (chan, startOffsetInBuffer);
  18135. MinMaxValue* const dest = thumbData + numToDo * chan;
  18136. thumbChannels [chan] = dest;
  18137. for (int i = 0; i < numToDo; ++i)
  18138. {
  18139. float low, high;
  18140. const int start = i * samplesPerThumbSample;
  18141. findMinAndMax (source + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  18142. dest[i].setFloat (low, high);
  18143. }
  18144. }
  18145. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  18146. }
  18147. }
  18148. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  18149. {
  18150. const ScopedLock sl (lock);
  18151. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  18152. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  18153. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  18154. totalSamples = jmax (numSamplesFinished, totalSamples);
  18155. window->invalidate();
  18156. sendChangeMessage();
  18157. }
  18158. int AudioThumbnail::getNumChannels() const throw()
  18159. {
  18160. return numChannels;
  18161. }
  18162. double AudioThumbnail::getTotalLength() const throw()
  18163. {
  18164. return totalSamples / sampleRate;
  18165. }
  18166. bool AudioThumbnail::isFullyLoaded() const throw()
  18167. {
  18168. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  18169. }
  18170. float AudioThumbnail::getApproximatePeak() const
  18171. {
  18172. int peak = 0;
  18173. for (int i = channels.size(); --i >= 0;)
  18174. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  18175. return jlimit (0, 127, peak) / 127.0f;
  18176. }
  18177. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  18178. double endTime, int channelNum, float verticalZoomFactor)
  18179. {
  18180. const ScopedLock sl (lock);
  18181. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  18182. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  18183. }
  18184. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  18185. double endTimeSeconds, float verticalZoomFactor)
  18186. {
  18187. for (int i = 0; i < numChannels; ++i)
  18188. {
  18189. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  18190. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  18191. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  18192. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  18193. }
  18194. }
  18195. END_JUCE_NAMESPACE
  18196. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18197. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18198. BEGIN_JUCE_NAMESPACE
  18199. struct ThumbnailCacheEntry
  18200. {
  18201. int64 hash;
  18202. uint32 lastUsed;
  18203. MemoryBlock data;
  18204. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18205. };
  18206. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18207. : TimeSliceThread ("thumb cache"),
  18208. maxNumThumbsToStore (maxNumThumbsToStore_)
  18209. {
  18210. startThread (2);
  18211. }
  18212. AudioThumbnailCache::~AudioThumbnailCache()
  18213. {
  18214. }
  18215. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  18216. {
  18217. for (int i = thumbs.size(); --i >= 0;)
  18218. if (thumbs.getUnchecked(i)->hash == hash)
  18219. return thumbs.getUnchecked(i);
  18220. return 0;
  18221. }
  18222. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18223. {
  18224. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18225. if (te != 0)
  18226. {
  18227. te->lastUsed = Time::getMillisecondCounter();
  18228. MemoryInputStream in (te->data, false);
  18229. thumb.loadFrom (in);
  18230. return true;
  18231. }
  18232. return false;
  18233. }
  18234. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18235. const int64 hashCode)
  18236. {
  18237. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18238. if (te == 0)
  18239. {
  18240. te = new ThumbnailCacheEntry();
  18241. te->hash = hashCode;
  18242. if (thumbs.size() < maxNumThumbsToStore)
  18243. {
  18244. thumbs.add (te);
  18245. }
  18246. else
  18247. {
  18248. int oldest = 0;
  18249. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  18250. for (int i = thumbs.size(); --i >= 0;)
  18251. {
  18252. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  18253. {
  18254. oldest = i;
  18255. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  18256. }
  18257. }
  18258. thumbs.set (oldest, te);
  18259. }
  18260. }
  18261. te->lastUsed = Time::getMillisecondCounter();
  18262. MemoryOutputStream out (te->data, false);
  18263. thumb.saveTo (out);
  18264. }
  18265. void AudioThumbnailCache::clear()
  18266. {
  18267. thumbs.clear();
  18268. }
  18269. END_JUCE_NAMESPACE
  18270. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18271. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18272. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18273. #if ! JUCE_WINDOWS
  18274. #include <QuickTime/Movies.h>
  18275. #include <QuickTime/QTML.h>
  18276. #include <QuickTime/QuickTimeComponents.h>
  18277. #include <QuickTime/MediaHandlers.h>
  18278. #include <QuickTime/ImageCodec.h>
  18279. #else
  18280. #if JUCE_MSVC
  18281. #pragma warning (push)
  18282. #pragma warning (disable : 4100)
  18283. #endif
  18284. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18285. add its header directory to your include path.
  18286. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18287. flag in juce_Config.h
  18288. */
  18289. #include <Movies.h>
  18290. #include <QTML.h>
  18291. #include <QuickTimeComponents.h>
  18292. #include <MediaHandlers.h>
  18293. #include <ImageCodec.h>
  18294. #if JUCE_MSVC
  18295. #pragma warning (pop)
  18296. #endif
  18297. #endif
  18298. BEGIN_JUCE_NAMESPACE
  18299. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18300. static const char* const quickTimeFormatName = "QuickTime file";
  18301. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18302. class QTAudioReader : public AudioFormatReader
  18303. {
  18304. public:
  18305. QTAudioReader (InputStream* const input_, const int trackNum_)
  18306. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18307. ok (false),
  18308. movie (0),
  18309. trackNum (trackNum_),
  18310. lastSampleRead (0),
  18311. lastThreadId (0),
  18312. extractor (0),
  18313. dataHandle (0)
  18314. {
  18315. JUCE_AUTORELEASEPOOL
  18316. bufferList.calloc (256, 1);
  18317. #if JUCE_WINDOWS
  18318. if (InitializeQTML (0) != noErr)
  18319. return;
  18320. #endif
  18321. if (EnterMovies() != noErr)
  18322. return;
  18323. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18324. if (! opened)
  18325. return;
  18326. {
  18327. const int numTracks = GetMovieTrackCount (movie);
  18328. int trackCount = 0;
  18329. for (int i = 1; i <= numTracks; ++i)
  18330. {
  18331. track = GetMovieIndTrack (movie, i);
  18332. media = GetTrackMedia (track);
  18333. OSType mediaType;
  18334. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18335. if (mediaType == SoundMediaType
  18336. && trackCount++ == trackNum_)
  18337. {
  18338. ok = true;
  18339. break;
  18340. }
  18341. }
  18342. }
  18343. if (! ok)
  18344. return;
  18345. ok = false;
  18346. lengthInSamples = GetMediaDecodeDuration (media);
  18347. usesFloatingPointData = false;
  18348. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18349. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18350. / GetMediaTimeScale (media);
  18351. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18352. unsigned long output_layout_size;
  18353. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18354. kQTPropertyClass_MovieAudioExtraction_Audio,
  18355. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18356. 0, &output_layout_size, 0);
  18357. if (err != noErr)
  18358. return;
  18359. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18360. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18361. err = MovieAudioExtractionGetProperty (extractor,
  18362. kQTPropertyClass_MovieAudioExtraction_Audio,
  18363. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18364. output_layout_size, qt_audio_channel_layout, 0);
  18365. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18366. err = MovieAudioExtractionSetProperty (extractor,
  18367. kQTPropertyClass_MovieAudioExtraction_Audio,
  18368. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18369. output_layout_size,
  18370. qt_audio_channel_layout);
  18371. err = MovieAudioExtractionGetProperty (extractor,
  18372. kQTPropertyClass_MovieAudioExtraction_Audio,
  18373. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18374. sizeof (inputStreamDesc),
  18375. &inputStreamDesc, 0);
  18376. if (err != noErr)
  18377. return;
  18378. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18379. | kAudioFormatFlagIsPacked
  18380. | kAudioFormatFlagsNativeEndian;
  18381. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18382. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18383. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18384. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18385. err = MovieAudioExtractionSetProperty (extractor,
  18386. kQTPropertyClass_MovieAudioExtraction_Audio,
  18387. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18388. sizeof (inputStreamDesc),
  18389. &inputStreamDesc);
  18390. if (err != noErr)
  18391. return;
  18392. Boolean allChannelsDiscrete = false;
  18393. err = MovieAudioExtractionSetProperty (extractor,
  18394. kQTPropertyClass_MovieAudioExtraction_Movie,
  18395. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18396. sizeof (allChannelsDiscrete),
  18397. &allChannelsDiscrete);
  18398. if (err != noErr)
  18399. return;
  18400. bufferList->mNumberBuffers = 1;
  18401. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18402. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18403. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18404. bufferList->mBuffers[0].mData = dataBuffer;
  18405. sampleRate = inputStreamDesc.mSampleRate;
  18406. bitsPerSample = 16;
  18407. numChannels = inputStreamDesc.mChannelsPerFrame;
  18408. detachThread();
  18409. ok = true;
  18410. }
  18411. ~QTAudioReader()
  18412. {
  18413. JUCE_AUTORELEASEPOOL
  18414. checkThreadIsAttached();
  18415. if (dataHandle != 0)
  18416. DisposeHandle (dataHandle);
  18417. if (extractor != 0)
  18418. {
  18419. MovieAudioExtractionEnd (extractor);
  18420. extractor = 0;
  18421. }
  18422. DisposeMovie (movie);
  18423. #if JUCE_MAC
  18424. ExitMoviesOnThread ();
  18425. #endif
  18426. }
  18427. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18428. int64 startSampleInFile, int numSamples)
  18429. {
  18430. JUCE_AUTORELEASEPOOL
  18431. checkThreadIsAttached();
  18432. bool ok = true;
  18433. while (numSamples > 0)
  18434. {
  18435. if (lastSampleRead != startSampleInFile)
  18436. {
  18437. TimeRecord time;
  18438. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18439. time.base = 0;
  18440. time.value.hi = 0;
  18441. time.value.lo = (UInt32) startSampleInFile;
  18442. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18443. kQTPropertyClass_MovieAudioExtraction_Movie,
  18444. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18445. sizeof (time), &time);
  18446. if (err != noErr)
  18447. {
  18448. ok = false;
  18449. break;
  18450. }
  18451. }
  18452. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18453. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18454. UInt32 outFlags = 0;
  18455. UInt32 actualNumFrames = framesToDo;
  18456. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18457. if (err != noErr)
  18458. {
  18459. ok = false;
  18460. break;
  18461. }
  18462. lastSampleRead = startSampleInFile + actualNumFrames;
  18463. const int samplesReceived = actualNumFrames;
  18464. for (int j = numDestChannels; --j >= 0;)
  18465. {
  18466. if (destSamples[j] != 0)
  18467. {
  18468. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18469. for (int i = 0; i < samplesReceived; ++i)
  18470. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18471. }
  18472. }
  18473. startOffsetInDestBuffer += samplesReceived;
  18474. startSampleInFile += samplesReceived;
  18475. numSamples -= samplesReceived;
  18476. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18477. {
  18478. for (int j = numDestChannels; --j >= 0;)
  18479. if (destSamples[j] != 0)
  18480. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18481. break;
  18482. }
  18483. }
  18484. detachThread();
  18485. return ok;
  18486. }
  18487. bool ok;
  18488. private:
  18489. Movie movie;
  18490. Media media;
  18491. Track track;
  18492. const int trackNum;
  18493. double trackUnitsPerFrame;
  18494. int samplesPerFrame;
  18495. int64 lastSampleRead;
  18496. Thread::ThreadID lastThreadId;
  18497. MovieAudioExtractionRef extractor;
  18498. AudioStreamBasicDescription inputStreamDesc;
  18499. HeapBlock <AudioBufferList> bufferList;
  18500. HeapBlock <char> dataBuffer;
  18501. Handle dataHandle;
  18502. void checkThreadIsAttached()
  18503. {
  18504. #if JUCE_MAC
  18505. if (Thread::getCurrentThreadId() != lastThreadId)
  18506. EnterMoviesOnThread (0);
  18507. AttachMovieToCurrentThread (movie);
  18508. #endif
  18509. }
  18510. void detachThread()
  18511. {
  18512. #if JUCE_MAC
  18513. DetachMovieFromCurrentThread (movie);
  18514. #endif
  18515. }
  18516. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18517. };
  18518. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18519. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18520. {
  18521. }
  18522. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18523. {
  18524. }
  18525. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18526. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18527. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18528. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18529. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18530. const bool deleteStreamIfOpeningFails)
  18531. {
  18532. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18533. if (r->ok)
  18534. return r.release();
  18535. if (! deleteStreamIfOpeningFails)
  18536. r->input = 0;
  18537. return 0;
  18538. }
  18539. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18540. double /*sampleRateToUse*/,
  18541. unsigned int /*numberOfChannels*/,
  18542. int /*bitsPerSample*/,
  18543. const StringPairArray& /*metadataValues*/,
  18544. int /*qualityOptionIndex*/)
  18545. {
  18546. jassertfalse; // not yet implemented!
  18547. return 0;
  18548. }
  18549. END_JUCE_NAMESPACE
  18550. #endif
  18551. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18552. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18553. BEGIN_JUCE_NAMESPACE
  18554. static const char* const wavFormatName = "WAV file";
  18555. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18556. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18557. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18558. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18559. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18560. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18561. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18562. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18563. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18564. const String& originator,
  18565. const String& originatorRef,
  18566. const Time& date,
  18567. const int64 timeReferenceSamples,
  18568. const String& codingHistory)
  18569. {
  18570. StringPairArray m;
  18571. m.set (bwavDescription, description);
  18572. m.set (bwavOriginator, originator);
  18573. m.set (bwavOriginatorRef, originatorRef);
  18574. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18575. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18576. m.set (bwavTimeReference, String (timeReferenceSamples));
  18577. m.set (bwavCodingHistory, codingHistory);
  18578. return m;
  18579. }
  18580. #if JUCE_MSVC
  18581. #pragma pack (push, 1)
  18582. #define PACKED
  18583. #elif JUCE_GCC
  18584. #define PACKED __attribute__((packed))
  18585. #else
  18586. #define PACKED
  18587. #endif
  18588. struct BWAVChunk
  18589. {
  18590. char description [256];
  18591. char originator [32];
  18592. char originatorRef [32];
  18593. char originationDate [10];
  18594. char originationTime [8];
  18595. uint32 timeRefLow;
  18596. uint32 timeRefHigh;
  18597. uint16 version;
  18598. uint8 umid[64];
  18599. uint8 reserved[190];
  18600. char codingHistory[1];
  18601. void copyTo (StringPairArray& values) const
  18602. {
  18603. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18604. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18605. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18606. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18607. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18608. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18609. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18610. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18611. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18612. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18613. }
  18614. static MemoryBlock createFrom (const StringPairArray& values)
  18615. {
  18616. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18617. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18618. data.fillWith (0);
  18619. BWAVChunk* b = (BWAVChunk*) data.getData();
  18620. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18621. // as they get called in the right order..
  18622. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18623. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18624. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18625. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18626. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18627. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18628. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18629. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18630. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18631. if (b->description[0] != 0
  18632. || b->originator[0] != 0
  18633. || b->originationDate[0] != 0
  18634. || b->originationTime[0] != 0
  18635. || b->codingHistory[0] != 0
  18636. || time != 0)
  18637. {
  18638. return data;
  18639. }
  18640. return MemoryBlock();
  18641. }
  18642. } PACKED;
  18643. struct SMPLChunk
  18644. {
  18645. struct SampleLoop
  18646. {
  18647. uint32 identifier;
  18648. uint32 type;
  18649. uint32 start;
  18650. uint32 end;
  18651. uint32 fraction;
  18652. uint32 playCount;
  18653. } PACKED;
  18654. uint32 manufacturer;
  18655. uint32 product;
  18656. uint32 samplePeriod;
  18657. uint32 midiUnityNote;
  18658. uint32 midiPitchFraction;
  18659. uint32 smpteFormat;
  18660. uint32 smpteOffset;
  18661. uint32 numSampleLoops;
  18662. uint32 samplerData;
  18663. SampleLoop loops[1];
  18664. void copyTo (StringPairArray& values, const int totalSize) const
  18665. {
  18666. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18667. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18668. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18669. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18670. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18671. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18672. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18673. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18674. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18675. for (uint32 i = 0; i < numSampleLoops; ++i)
  18676. {
  18677. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18678. break;
  18679. const String prefix ("Loop" + String(i));
  18680. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18681. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18682. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18683. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18684. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18685. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18686. }
  18687. }
  18688. static MemoryBlock createFrom (const StringPairArray& values)
  18689. {
  18690. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18691. if (numLoops <= 0)
  18692. return MemoryBlock();
  18693. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18694. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18695. data.fillWith (0);
  18696. SMPLChunk* s = (SMPLChunk*) data.getData();
  18697. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18698. // as they get called in the right order..
  18699. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18700. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18701. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18702. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18703. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18704. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18705. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18706. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18707. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18708. for (int i = 0; i < numLoops; ++i)
  18709. {
  18710. const String prefix ("Loop" + String(i));
  18711. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18712. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18713. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18714. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18715. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18716. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18717. }
  18718. return data;
  18719. }
  18720. } PACKED;
  18721. struct ExtensibleWavSubFormat
  18722. {
  18723. uint32 data1;
  18724. uint16 data2;
  18725. uint16 data3;
  18726. uint8 data4[8];
  18727. } PACKED;
  18728. #if JUCE_MSVC
  18729. #pragma pack (pop)
  18730. #endif
  18731. #undef PACKED
  18732. class WavAudioFormatReader : public AudioFormatReader
  18733. {
  18734. public:
  18735. WavAudioFormatReader (InputStream* const in)
  18736. : AudioFormatReader (in, TRANS (wavFormatName)),
  18737. bwavChunkStart (0),
  18738. bwavSize (0),
  18739. dataLength (0)
  18740. {
  18741. if (input->readInt() == chunkName ("RIFF"))
  18742. {
  18743. const uint32 len = (uint32) input->readInt();
  18744. const int64 end = input->getPosition() + len;
  18745. bool hasGotType = false;
  18746. bool hasGotData = false;
  18747. if (input->readInt() == chunkName ("WAVE"))
  18748. {
  18749. while (input->getPosition() < end
  18750. && ! input->isExhausted())
  18751. {
  18752. const int chunkType = input->readInt();
  18753. uint32 length = (uint32) input->readInt();
  18754. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18755. if (chunkType == chunkName ("fmt "))
  18756. {
  18757. // read the format chunk
  18758. const unsigned short format = input->readShort();
  18759. const short numChans = input->readShort();
  18760. sampleRate = input->readInt();
  18761. const int bytesPerSec = input->readInt();
  18762. numChannels = numChans;
  18763. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18764. bitsPerSample = 8 * bytesPerFrame / numChans;
  18765. if (format == 3)
  18766. {
  18767. usesFloatingPointData = true;
  18768. }
  18769. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18770. {
  18771. if (length < 40) // too short
  18772. {
  18773. bytesPerFrame = 0;
  18774. }
  18775. else
  18776. {
  18777. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18778. ExtensibleWavSubFormat subFormat;
  18779. subFormat.data1 = input->readInt();
  18780. subFormat.data2 = input->readShort();
  18781. subFormat.data3 = input->readShort();
  18782. input->read (subFormat.data4, sizeof (subFormat.data4));
  18783. const ExtensibleWavSubFormat pcmFormat
  18784. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18785. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18786. {
  18787. const ExtensibleWavSubFormat ambisonicFormat
  18788. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18789. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18790. bytesPerFrame = 0;
  18791. }
  18792. }
  18793. }
  18794. else if (format != 1)
  18795. {
  18796. bytesPerFrame = 0;
  18797. }
  18798. hasGotType = true;
  18799. }
  18800. else if (chunkType == chunkName ("data"))
  18801. {
  18802. // get the data chunk's position
  18803. dataLength = length;
  18804. dataChunkStart = input->getPosition();
  18805. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18806. hasGotData = true;
  18807. }
  18808. else if (chunkType == chunkName ("bext"))
  18809. {
  18810. bwavChunkStart = input->getPosition();
  18811. bwavSize = length;
  18812. // Broadcast-wav extension chunk..
  18813. HeapBlock <BWAVChunk> bwav;
  18814. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18815. input->read (bwav, length);
  18816. bwav->copyTo (metadataValues);
  18817. }
  18818. else if (chunkType == chunkName ("smpl"))
  18819. {
  18820. HeapBlock <SMPLChunk> smpl;
  18821. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18822. input->read (smpl, length);
  18823. smpl->copyTo (metadataValues, length);
  18824. }
  18825. else if (chunkEnd <= input->getPosition())
  18826. {
  18827. break;
  18828. }
  18829. input->setPosition (chunkEnd);
  18830. }
  18831. }
  18832. }
  18833. }
  18834. ~WavAudioFormatReader()
  18835. {
  18836. }
  18837. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18838. int64 startSampleInFile, int numSamples)
  18839. {
  18840. jassert (destSamples != 0);
  18841. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18842. if (samplesAvailable < numSamples)
  18843. {
  18844. for (int i = numDestChannels; --i >= 0;)
  18845. if (destSamples[i] != 0)
  18846. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18847. numSamples = (int) samplesAvailable;
  18848. }
  18849. if (numSamples <= 0)
  18850. return true;
  18851. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18852. while (numSamples > 0)
  18853. {
  18854. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18855. char tempBuffer [tempBufSize];
  18856. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18857. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18858. if (bytesRead < numThisTime * bytesPerFrame)
  18859. {
  18860. jassert (bytesRead >= 0);
  18861. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18862. }
  18863. switch (bitsPerSample)
  18864. {
  18865. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18866. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18867. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18868. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18869. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18870. default: jassertfalse; break;
  18871. }
  18872. startOffsetInDestBuffer += numThisTime;
  18873. numSamples -= numThisTime;
  18874. }
  18875. return true;
  18876. }
  18877. int64 bwavChunkStart, bwavSize;
  18878. private:
  18879. ScopedPointer<AudioData::Converter> converter;
  18880. int bytesPerFrame;
  18881. int64 dataChunkStart, dataLength;
  18882. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18884. };
  18885. class WavAudioFormatWriter : public AudioFormatWriter
  18886. {
  18887. public:
  18888. WavAudioFormatWriter (OutputStream* const out,
  18889. const double sampleRate_,
  18890. const unsigned int numChannels_,
  18891. const int bits,
  18892. const StringPairArray& metadataValues)
  18893. : AudioFormatWriter (out,
  18894. TRANS (wavFormatName),
  18895. sampleRate_,
  18896. numChannels_,
  18897. bits),
  18898. lengthInSamples (0),
  18899. bytesWritten (0),
  18900. writeFailed (false)
  18901. {
  18902. if (metadataValues.size() > 0)
  18903. {
  18904. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18905. smplChunk = SMPLChunk::createFrom (metadataValues);
  18906. }
  18907. headerPosition = out->getPosition();
  18908. writeHeader();
  18909. }
  18910. ~WavAudioFormatWriter()
  18911. {
  18912. writeHeader();
  18913. }
  18914. bool write (const int** data, int numSamples)
  18915. {
  18916. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18917. if (writeFailed)
  18918. return false;
  18919. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18920. tempBlock.ensureSize (bytes, false);
  18921. switch (bitsPerSample)
  18922. {
  18923. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18924. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18925. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18926. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18927. default: jassertfalse; break;
  18928. }
  18929. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18930. || ! output->write (tempBlock.getData(), bytes))
  18931. {
  18932. // failed to write to disk, so let's try writing the header.
  18933. // If it's just run out of disk space, then if it does manage
  18934. // to write the header, we'll still have a useable file..
  18935. writeHeader();
  18936. writeFailed = true;
  18937. return false;
  18938. }
  18939. else
  18940. {
  18941. bytesWritten += bytes;
  18942. lengthInSamples += numSamples;
  18943. return true;
  18944. }
  18945. }
  18946. private:
  18947. ScopedPointer<AudioData::Converter> converter;
  18948. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18949. uint32 lengthInSamples, bytesWritten;
  18950. int64 headerPosition;
  18951. bool writeFailed;
  18952. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18953. void writeHeader()
  18954. {
  18955. const bool seekedOk = output->setPosition (headerPosition);
  18956. (void) seekedOk;
  18957. // if this fails, you've given it an output stream that can't seek! It needs
  18958. // to be able to seek back to write the header
  18959. jassert (seekedOk);
  18960. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18961. output->writeInt (chunkName ("RIFF"));
  18962. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18963. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18964. output->writeInt (chunkName ("WAVE"));
  18965. output->writeInt (chunkName ("fmt "));
  18966. output->writeInt (16);
  18967. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18968. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18969. output->writeShort ((short) numChannels);
  18970. output->writeInt ((int) sampleRate);
  18971. output->writeInt (bytesPerFrame * (int) sampleRate);
  18972. output->writeShort ((short) bytesPerFrame);
  18973. output->writeShort ((short) bitsPerSample);
  18974. if (bwavChunk.getSize() > 0)
  18975. {
  18976. output->writeInt (chunkName ("bext"));
  18977. output->writeInt ((int) bwavChunk.getSize());
  18978. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18979. }
  18980. if (smplChunk.getSize() > 0)
  18981. {
  18982. output->writeInt (chunkName ("smpl"));
  18983. output->writeInt ((int) smplChunk.getSize());
  18984. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18985. }
  18986. output->writeInt (chunkName ("data"));
  18987. output->writeInt (lengthInSamples * bytesPerFrame);
  18988. usesFloatingPointData = (bitsPerSample == 32);
  18989. }
  18990. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18991. };
  18992. WavAudioFormat::WavAudioFormat()
  18993. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18994. {
  18995. }
  18996. WavAudioFormat::~WavAudioFormat()
  18997. {
  18998. }
  18999. const Array <int> WavAudioFormat::getPossibleSampleRates()
  19000. {
  19001. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  19002. return Array <int> (rates);
  19003. }
  19004. const Array <int> WavAudioFormat::getPossibleBitDepths()
  19005. {
  19006. const int depths[] = { 8, 16, 24, 32, 0 };
  19007. return Array <int> (depths);
  19008. }
  19009. bool WavAudioFormat::canDoStereo() { return true; }
  19010. bool WavAudioFormat::canDoMono() { return true; }
  19011. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  19012. const bool deleteStreamIfOpeningFails)
  19013. {
  19014. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  19015. if (r->sampleRate != 0)
  19016. return r.release();
  19017. if (! deleteStreamIfOpeningFails)
  19018. r->input = 0;
  19019. return 0;
  19020. }
  19021. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  19022. double sampleRate,
  19023. unsigned int numChannels,
  19024. int bitsPerSample,
  19025. const StringPairArray& metadataValues,
  19026. int /*qualityOptionIndex*/)
  19027. {
  19028. if (getPossibleBitDepths().contains (bitsPerSample))
  19029. {
  19030. return new WavAudioFormatWriter (out,
  19031. sampleRate,
  19032. numChannels,
  19033. bitsPerSample,
  19034. metadataValues);
  19035. }
  19036. return 0;
  19037. }
  19038. namespace
  19039. {
  19040. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  19041. {
  19042. TemporaryFile tempFile (file);
  19043. WavAudioFormat wav;
  19044. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  19045. if (reader != 0)
  19046. {
  19047. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  19048. if (outStream != 0)
  19049. {
  19050. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  19051. reader->numChannels, reader->bitsPerSample,
  19052. metadata, 0));
  19053. if (writer != 0)
  19054. {
  19055. outStream.release();
  19056. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  19057. writer = 0;
  19058. reader = 0;
  19059. return ok && tempFile.overwriteTargetFileWithTemporary();
  19060. }
  19061. }
  19062. }
  19063. return false;
  19064. }
  19065. }
  19066. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  19067. {
  19068. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  19069. if (reader != 0)
  19070. {
  19071. const int64 bwavPos = reader->bwavChunkStart;
  19072. const int64 bwavSize = reader->bwavSize;
  19073. reader = 0;
  19074. if (bwavSize > 0)
  19075. {
  19076. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19077. if (chunk.getSize() <= (size_t) bwavSize)
  19078. {
  19079. // the new one will fit in the space available, so write it directly..
  19080. const int64 oldSize = wavFile.getSize();
  19081. {
  19082. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19083. out->setPosition (bwavPos);
  19084. out->write (chunk.getData(), (int) chunk.getSize());
  19085. out->setPosition (oldSize);
  19086. }
  19087. jassert (wavFile.getSize() == oldSize);
  19088. return true;
  19089. }
  19090. }
  19091. }
  19092. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19093. }
  19094. END_JUCE_NAMESPACE
  19095. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19096. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19097. #if JUCE_USE_CDREADER
  19098. BEGIN_JUCE_NAMESPACE
  19099. int AudioCDReader::getNumTracks() const
  19100. {
  19101. return trackStartSamples.size() - 1;
  19102. }
  19103. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19104. {
  19105. return trackStartSamples [trackNum];
  19106. }
  19107. const Array<int>& AudioCDReader::getTrackOffsets() const
  19108. {
  19109. return trackStartSamples;
  19110. }
  19111. int AudioCDReader::getCDDBId()
  19112. {
  19113. int checksum = 0;
  19114. const int numTracks = getNumTracks();
  19115. for (int i = 0; i < numTracks; ++i)
  19116. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19117. checksum += offset % 10;
  19118. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19119. // CCLLLLTT: checksum, length, tracks
  19120. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19121. }
  19122. END_JUCE_NAMESPACE
  19123. #endif
  19124. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19125. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19126. BEGIN_JUCE_NAMESPACE
  19127. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19128. const bool deleteReaderWhenThisIsDeleted)
  19129. : reader (reader_),
  19130. deleteReader (deleteReaderWhenThisIsDeleted),
  19131. nextPlayPos (0),
  19132. looping (false)
  19133. {
  19134. jassert (reader != 0);
  19135. }
  19136. AudioFormatReaderSource::~AudioFormatReaderSource()
  19137. {
  19138. releaseResources();
  19139. if (deleteReader)
  19140. delete reader;
  19141. }
  19142. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19143. {
  19144. nextPlayPos = newPosition;
  19145. }
  19146. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19147. {
  19148. looping = shouldLoop;
  19149. }
  19150. int AudioFormatReaderSource::getNextReadPosition() const
  19151. {
  19152. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19153. : nextPlayPos;
  19154. }
  19155. int AudioFormatReaderSource::getTotalLength() const
  19156. {
  19157. return (int) reader->lengthInSamples;
  19158. }
  19159. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19160. double /*sampleRate*/)
  19161. {
  19162. }
  19163. void AudioFormatReaderSource::releaseResources()
  19164. {
  19165. }
  19166. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19167. {
  19168. if (info.numSamples > 0)
  19169. {
  19170. const int start = nextPlayPos;
  19171. if (looping)
  19172. {
  19173. const int newStart = start % (int) reader->lengthInSamples;
  19174. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19175. if (newEnd > newStart)
  19176. {
  19177. info.buffer->readFromAudioReader (reader,
  19178. info.startSample,
  19179. newEnd - newStart,
  19180. newStart,
  19181. true, true);
  19182. }
  19183. else
  19184. {
  19185. const int endSamps = (int) reader->lengthInSamples - newStart;
  19186. info.buffer->readFromAudioReader (reader,
  19187. info.startSample,
  19188. endSamps,
  19189. newStart,
  19190. true, true);
  19191. info.buffer->readFromAudioReader (reader,
  19192. info.startSample + endSamps,
  19193. newEnd,
  19194. 0,
  19195. true, true);
  19196. }
  19197. nextPlayPos = newEnd;
  19198. }
  19199. else
  19200. {
  19201. info.buffer->readFromAudioReader (reader,
  19202. info.startSample,
  19203. info.numSamples,
  19204. start,
  19205. true, true);
  19206. nextPlayPos += info.numSamples;
  19207. }
  19208. }
  19209. }
  19210. END_JUCE_NAMESPACE
  19211. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19212. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19213. BEGIN_JUCE_NAMESPACE
  19214. AudioSourcePlayer::AudioSourcePlayer()
  19215. : source (0),
  19216. sampleRate (0),
  19217. bufferSize (0),
  19218. tempBuffer (2, 8),
  19219. lastGain (1.0f),
  19220. gain (1.0f)
  19221. {
  19222. }
  19223. AudioSourcePlayer::~AudioSourcePlayer()
  19224. {
  19225. setSource (0);
  19226. }
  19227. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19228. {
  19229. if (source != newSource)
  19230. {
  19231. AudioSource* const oldSource = source;
  19232. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19233. newSource->prepareToPlay (bufferSize, sampleRate);
  19234. {
  19235. const ScopedLock sl (readLock);
  19236. source = newSource;
  19237. }
  19238. if (oldSource != 0)
  19239. oldSource->releaseResources();
  19240. }
  19241. }
  19242. void AudioSourcePlayer::setGain (const float newGain) throw()
  19243. {
  19244. gain = newGain;
  19245. }
  19246. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19247. int totalNumInputChannels,
  19248. float** outputChannelData,
  19249. int totalNumOutputChannels,
  19250. int numSamples)
  19251. {
  19252. // these should have been prepared by audioDeviceAboutToStart()...
  19253. jassert (sampleRate > 0 && bufferSize > 0);
  19254. const ScopedLock sl (readLock);
  19255. if (source != 0)
  19256. {
  19257. AudioSourceChannelInfo info;
  19258. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19259. // messy stuff needed to compact the channels down into an array
  19260. // of non-zero pointers..
  19261. for (i = 0; i < totalNumInputChannels; ++i)
  19262. {
  19263. if (inputChannelData[i] != 0)
  19264. {
  19265. inputChans [numInputs++] = inputChannelData[i];
  19266. if (numInputs >= numElementsInArray (inputChans))
  19267. break;
  19268. }
  19269. }
  19270. for (i = 0; i < totalNumOutputChannels; ++i)
  19271. {
  19272. if (outputChannelData[i] != 0)
  19273. {
  19274. outputChans [numOutputs++] = outputChannelData[i];
  19275. if (numOutputs >= numElementsInArray (outputChans))
  19276. break;
  19277. }
  19278. }
  19279. if (numInputs > numOutputs)
  19280. {
  19281. // if there aren't enough output channels for the number of
  19282. // inputs, we need to create some temporary extra ones (can't
  19283. // use the input data in case it gets written to)
  19284. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19285. false, false, true);
  19286. for (i = 0; i < numOutputs; ++i)
  19287. {
  19288. channels[numActiveChans] = outputChans[i];
  19289. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19290. ++numActiveChans;
  19291. }
  19292. for (i = numOutputs; i < numInputs; ++i)
  19293. {
  19294. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19295. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19296. ++numActiveChans;
  19297. }
  19298. }
  19299. else
  19300. {
  19301. for (i = 0; i < numInputs; ++i)
  19302. {
  19303. channels[numActiveChans] = outputChans[i];
  19304. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19305. ++numActiveChans;
  19306. }
  19307. for (i = numInputs; i < numOutputs; ++i)
  19308. {
  19309. channels[numActiveChans] = outputChans[i];
  19310. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19311. ++numActiveChans;
  19312. }
  19313. }
  19314. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19315. info.buffer = &buffer;
  19316. info.startSample = 0;
  19317. info.numSamples = numSamples;
  19318. source->getNextAudioBlock (info);
  19319. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19320. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19321. lastGain = gain;
  19322. }
  19323. else
  19324. {
  19325. for (int i = 0; i < totalNumOutputChannels; ++i)
  19326. if (outputChannelData[i] != 0)
  19327. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19328. }
  19329. }
  19330. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19331. {
  19332. sampleRate = device->getCurrentSampleRate();
  19333. bufferSize = device->getCurrentBufferSizeSamples();
  19334. zeromem (channels, sizeof (channels));
  19335. if (source != 0)
  19336. source->prepareToPlay (bufferSize, sampleRate);
  19337. }
  19338. void AudioSourcePlayer::audioDeviceStopped()
  19339. {
  19340. if (source != 0)
  19341. source->releaseResources();
  19342. sampleRate = 0.0;
  19343. bufferSize = 0;
  19344. tempBuffer.setSize (2, 8);
  19345. }
  19346. END_JUCE_NAMESPACE
  19347. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19348. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19349. BEGIN_JUCE_NAMESPACE
  19350. AudioTransportSource::AudioTransportSource()
  19351. : source (0),
  19352. resamplerSource (0),
  19353. bufferingSource (0),
  19354. positionableSource (0),
  19355. masterSource (0),
  19356. gain (1.0f),
  19357. lastGain (1.0f),
  19358. playing (false),
  19359. stopped (true),
  19360. sampleRate (44100.0),
  19361. sourceSampleRate (0.0),
  19362. blockSize (128),
  19363. readAheadBufferSize (0),
  19364. isPrepared (false),
  19365. inputStreamEOF (false)
  19366. {
  19367. }
  19368. AudioTransportSource::~AudioTransportSource()
  19369. {
  19370. setSource (0);
  19371. releaseResources();
  19372. }
  19373. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19374. int readAheadBufferSize_,
  19375. double sourceSampleRateToCorrectFor)
  19376. {
  19377. if (source == newSource)
  19378. {
  19379. if (source == 0)
  19380. return;
  19381. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19382. }
  19383. readAheadBufferSize = readAheadBufferSize_;
  19384. sourceSampleRate = sourceSampleRateToCorrectFor;
  19385. ResamplingAudioSource* newResamplerSource = 0;
  19386. BufferingAudioSource* newBufferingSource = 0;
  19387. PositionableAudioSource* newPositionableSource = 0;
  19388. AudioSource* newMasterSource = 0;
  19389. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19390. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19391. AudioSource* oldMasterSource = masterSource;
  19392. if (newSource != 0)
  19393. {
  19394. newPositionableSource = newSource;
  19395. if (readAheadBufferSize_ > 0)
  19396. newPositionableSource = newBufferingSource
  19397. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19398. newPositionableSource->setNextReadPosition (0);
  19399. if (sourceSampleRateToCorrectFor != 0)
  19400. newMasterSource = newResamplerSource
  19401. = new ResamplingAudioSource (newPositionableSource, false);
  19402. else
  19403. newMasterSource = newPositionableSource;
  19404. if (isPrepared)
  19405. {
  19406. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19407. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19408. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19409. }
  19410. }
  19411. {
  19412. const ScopedLock sl (callbackLock);
  19413. source = newSource;
  19414. resamplerSource = newResamplerSource;
  19415. bufferingSource = newBufferingSource;
  19416. masterSource = newMasterSource;
  19417. positionableSource = newPositionableSource;
  19418. playing = false;
  19419. }
  19420. if (oldMasterSource != 0)
  19421. oldMasterSource->releaseResources();
  19422. }
  19423. void AudioTransportSource::start()
  19424. {
  19425. if ((! playing) && masterSource != 0)
  19426. {
  19427. {
  19428. const ScopedLock sl (callbackLock);
  19429. playing = true;
  19430. stopped = false;
  19431. inputStreamEOF = false;
  19432. }
  19433. sendChangeMessage();
  19434. }
  19435. }
  19436. void AudioTransportSource::stop()
  19437. {
  19438. if (playing)
  19439. {
  19440. {
  19441. const ScopedLock sl (callbackLock);
  19442. playing = false;
  19443. }
  19444. int n = 500;
  19445. while (--n >= 0 && ! stopped)
  19446. Thread::sleep (2);
  19447. sendChangeMessage();
  19448. }
  19449. }
  19450. void AudioTransportSource::setPosition (double newPosition)
  19451. {
  19452. if (sampleRate > 0.0)
  19453. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19454. }
  19455. double AudioTransportSource::getCurrentPosition() const
  19456. {
  19457. if (sampleRate > 0.0)
  19458. return getNextReadPosition() / sampleRate;
  19459. else
  19460. return 0.0;
  19461. }
  19462. double AudioTransportSource::getLengthInSeconds() const
  19463. {
  19464. return getTotalLength() / sampleRate;
  19465. }
  19466. void AudioTransportSource::setNextReadPosition (int newPosition)
  19467. {
  19468. if (positionableSource != 0)
  19469. {
  19470. if (sampleRate > 0 && sourceSampleRate > 0)
  19471. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19472. positionableSource->setNextReadPosition (newPosition);
  19473. }
  19474. }
  19475. int AudioTransportSource::getNextReadPosition() const
  19476. {
  19477. if (positionableSource != 0)
  19478. {
  19479. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19480. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19481. }
  19482. return 0;
  19483. }
  19484. int AudioTransportSource::getTotalLength() const
  19485. {
  19486. const ScopedLock sl (callbackLock);
  19487. if (positionableSource != 0)
  19488. {
  19489. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19490. return roundToInt (positionableSource->getTotalLength() * ratio);
  19491. }
  19492. return 0;
  19493. }
  19494. bool AudioTransportSource::isLooping() const
  19495. {
  19496. const ScopedLock sl (callbackLock);
  19497. return positionableSource != 0
  19498. && positionableSource->isLooping();
  19499. }
  19500. void AudioTransportSource::setGain (const float newGain) throw()
  19501. {
  19502. gain = newGain;
  19503. }
  19504. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19505. double sampleRate_)
  19506. {
  19507. const ScopedLock sl (callbackLock);
  19508. sampleRate = sampleRate_;
  19509. blockSize = samplesPerBlockExpected;
  19510. if (masterSource != 0)
  19511. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19512. if (resamplerSource != 0 && sourceSampleRate != 0)
  19513. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19514. isPrepared = true;
  19515. }
  19516. void AudioTransportSource::releaseResources()
  19517. {
  19518. const ScopedLock sl (callbackLock);
  19519. if (masterSource != 0)
  19520. masterSource->releaseResources();
  19521. isPrepared = false;
  19522. }
  19523. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19524. {
  19525. const ScopedLock sl (callbackLock);
  19526. inputStreamEOF = false;
  19527. if (masterSource != 0 && ! stopped)
  19528. {
  19529. masterSource->getNextAudioBlock (info);
  19530. if (! playing)
  19531. {
  19532. // just stopped playing, so fade out the last block..
  19533. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19534. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19535. if (info.numSamples > 256)
  19536. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19537. }
  19538. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19539. && ! positionableSource->isLooping())
  19540. {
  19541. playing = false;
  19542. inputStreamEOF = true;
  19543. sendChangeMessage();
  19544. }
  19545. stopped = ! playing;
  19546. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19547. {
  19548. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19549. lastGain, gain);
  19550. }
  19551. }
  19552. else
  19553. {
  19554. info.clearActiveBufferRegion();
  19555. stopped = true;
  19556. }
  19557. lastGain = gain;
  19558. }
  19559. END_JUCE_NAMESPACE
  19560. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19561. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19562. BEGIN_JUCE_NAMESPACE
  19563. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19564. public Thread,
  19565. private Timer
  19566. {
  19567. public:
  19568. SharedBufferingAudioSourceThread()
  19569. : Thread ("Audio Buffer")
  19570. {
  19571. }
  19572. ~SharedBufferingAudioSourceThread()
  19573. {
  19574. stopThread (10000);
  19575. clearSingletonInstance();
  19576. }
  19577. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19578. void addSource (BufferingAudioSource* source)
  19579. {
  19580. const ScopedLock sl (lock);
  19581. if (! sources.contains (source))
  19582. {
  19583. sources.add (source);
  19584. startThread();
  19585. stopTimer();
  19586. }
  19587. notify();
  19588. }
  19589. void removeSource (BufferingAudioSource* source)
  19590. {
  19591. const ScopedLock sl (lock);
  19592. sources.removeValue (source);
  19593. if (sources.size() == 0)
  19594. startTimer (5000);
  19595. }
  19596. private:
  19597. Array <BufferingAudioSource*> sources;
  19598. CriticalSection lock;
  19599. void run()
  19600. {
  19601. while (! threadShouldExit())
  19602. {
  19603. bool busy = false;
  19604. for (int i = sources.size(); --i >= 0;)
  19605. {
  19606. if (threadShouldExit())
  19607. return;
  19608. const ScopedLock sl (lock);
  19609. BufferingAudioSource* const b = sources[i];
  19610. if (b != 0 && b->readNextBufferChunk())
  19611. busy = true;
  19612. }
  19613. if (! busy)
  19614. wait (500);
  19615. }
  19616. }
  19617. void timerCallback()
  19618. {
  19619. stopTimer();
  19620. if (sources.size() == 0)
  19621. deleteInstance();
  19622. }
  19623. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19624. };
  19625. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19626. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19627. const bool deleteSourceWhenDeleted_,
  19628. int numberOfSamplesToBuffer_)
  19629. : source (source_),
  19630. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19631. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19632. buffer (2, 0),
  19633. bufferValidStart (0),
  19634. bufferValidEnd (0),
  19635. nextPlayPos (0),
  19636. wasSourceLooping (false)
  19637. {
  19638. jassert (source_ != 0);
  19639. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19640. // not using a larger buffer..
  19641. }
  19642. BufferingAudioSource::~BufferingAudioSource()
  19643. {
  19644. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19645. if (thread != 0)
  19646. thread->removeSource (this);
  19647. if (deleteSourceWhenDeleted)
  19648. delete source;
  19649. }
  19650. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19651. {
  19652. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19653. sampleRate = sampleRate_;
  19654. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19655. buffer.clear();
  19656. bufferValidStart = 0;
  19657. bufferValidEnd = 0;
  19658. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19659. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19660. buffer.getNumSamples() / 2))
  19661. {
  19662. SharedBufferingAudioSourceThread::getInstance()->notify();
  19663. Thread::sleep (5);
  19664. }
  19665. }
  19666. void BufferingAudioSource::releaseResources()
  19667. {
  19668. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19669. if (thread != 0)
  19670. thread->removeSource (this);
  19671. buffer.setSize (2, 0);
  19672. source->releaseResources();
  19673. }
  19674. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19675. {
  19676. const ScopedLock sl (bufferStartPosLock);
  19677. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19678. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19679. if (validStart == validEnd)
  19680. {
  19681. // total cache miss
  19682. info.clearActiveBufferRegion();
  19683. }
  19684. else
  19685. {
  19686. if (validStart > 0)
  19687. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19688. if (validEnd < info.numSamples)
  19689. info.buffer->clear (info.startSample + validEnd,
  19690. info.numSamples - validEnd); // partial cache miss at end
  19691. if (validStart < validEnd)
  19692. {
  19693. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19694. {
  19695. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19696. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19697. if (startBufferIndex < endBufferIndex)
  19698. {
  19699. info.buffer->copyFrom (chan, info.startSample + validStart,
  19700. buffer,
  19701. chan, startBufferIndex,
  19702. validEnd - validStart);
  19703. }
  19704. else
  19705. {
  19706. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19707. info.buffer->copyFrom (chan, info.startSample + validStart,
  19708. buffer,
  19709. chan, startBufferIndex,
  19710. initialSize);
  19711. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19712. buffer,
  19713. chan, 0,
  19714. (validEnd - validStart) - initialSize);
  19715. }
  19716. }
  19717. }
  19718. nextPlayPos += info.numSamples;
  19719. if (source->isLooping() && nextPlayPos > 0)
  19720. nextPlayPos %= source->getTotalLength();
  19721. }
  19722. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19723. if (thread != 0)
  19724. thread->notify();
  19725. }
  19726. int BufferingAudioSource::getNextReadPosition() const
  19727. {
  19728. return (source->isLooping() && nextPlayPos > 0)
  19729. ? nextPlayPos % source->getTotalLength()
  19730. : nextPlayPos;
  19731. }
  19732. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19733. {
  19734. const ScopedLock sl (bufferStartPosLock);
  19735. nextPlayPos = newPosition;
  19736. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19737. if (thread != 0)
  19738. thread->notify();
  19739. }
  19740. bool BufferingAudioSource::readNextBufferChunk()
  19741. {
  19742. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19743. {
  19744. const ScopedLock sl (bufferStartPosLock);
  19745. if (wasSourceLooping != isLooping())
  19746. {
  19747. wasSourceLooping = isLooping();
  19748. bufferValidStart = 0;
  19749. bufferValidEnd = 0;
  19750. }
  19751. newBVS = jmax (0, nextPlayPos);
  19752. newBVE = newBVS + buffer.getNumSamples() - 4;
  19753. sectionToReadStart = 0;
  19754. sectionToReadEnd = 0;
  19755. const int maxChunkSize = 2048;
  19756. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19757. {
  19758. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19759. sectionToReadStart = newBVS;
  19760. sectionToReadEnd = newBVE;
  19761. bufferValidStart = 0;
  19762. bufferValidEnd = 0;
  19763. }
  19764. else if (abs (newBVS - bufferValidStart) > 512
  19765. || abs (newBVE - bufferValidEnd) > 512)
  19766. {
  19767. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19768. sectionToReadStart = bufferValidEnd;
  19769. sectionToReadEnd = newBVE;
  19770. bufferValidStart = newBVS;
  19771. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19772. }
  19773. }
  19774. if (sectionToReadStart != sectionToReadEnd)
  19775. {
  19776. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19777. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19778. if (bufferIndexStart < bufferIndexEnd)
  19779. {
  19780. readBufferSection (sectionToReadStart,
  19781. sectionToReadEnd - sectionToReadStart,
  19782. bufferIndexStart);
  19783. }
  19784. else
  19785. {
  19786. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19787. readBufferSection (sectionToReadStart,
  19788. initialSize,
  19789. bufferIndexStart);
  19790. readBufferSection (sectionToReadStart + initialSize,
  19791. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19792. 0);
  19793. }
  19794. const ScopedLock sl2 (bufferStartPosLock);
  19795. bufferValidStart = newBVS;
  19796. bufferValidEnd = newBVE;
  19797. return true;
  19798. }
  19799. else
  19800. {
  19801. return false;
  19802. }
  19803. }
  19804. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19805. {
  19806. if (source->getNextReadPosition() != start)
  19807. source->setNextReadPosition (start);
  19808. AudioSourceChannelInfo info;
  19809. info.buffer = &buffer;
  19810. info.startSample = bufferOffset;
  19811. info.numSamples = length;
  19812. source->getNextAudioBlock (info);
  19813. }
  19814. END_JUCE_NAMESPACE
  19815. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19816. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19817. BEGIN_JUCE_NAMESPACE
  19818. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19819. const bool deleteSourceWhenDeleted_)
  19820. : requiredNumberOfChannels (2),
  19821. source (source_),
  19822. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19823. buffer (2, 16)
  19824. {
  19825. remappedInfo.buffer = &buffer;
  19826. remappedInfo.startSample = 0;
  19827. }
  19828. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19829. {
  19830. if (deleteSourceWhenDeleted)
  19831. delete source;
  19832. }
  19833. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19834. {
  19835. const ScopedLock sl (lock);
  19836. requiredNumberOfChannels = requiredNumberOfChannels_;
  19837. }
  19838. void ChannelRemappingAudioSource::clearAllMappings()
  19839. {
  19840. const ScopedLock sl (lock);
  19841. remappedInputs.clear();
  19842. remappedOutputs.clear();
  19843. }
  19844. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19845. {
  19846. const ScopedLock sl (lock);
  19847. while (remappedInputs.size() < destIndex)
  19848. remappedInputs.add (-1);
  19849. remappedInputs.set (destIndex, sourceIndex);
  19850. }
  19851. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19852. {
  19853. const ScopedLock sl (lock);
  19854. while (remappedOutputs.size() < sourceIndex)
  19855. remappedOutputs.add (-1);
  19856. remappedOutputs.set (sourceIndex, destIndex);
  19857. }
  19858. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19859. {
  19860. const ScopedLock sl (lock);
  19861. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19862. return remappedInputs.getUnchecked (inputChannelIndex);
  19863. return -1;
  19864. }
  19865. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19866. {
  19867. const ScopedLock sl (lock);
  19868. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19869. return remappedOutputs .getUnchecked (outputChannelIndex);
  19870. return -1;
  19871. }
  19872. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19873. {
  19874. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19875. }
  19876. void ChannelRemappingAudioSource::releaseResources()
  19877. {
  19878. source->releaseResources();
  19879. }
  19880. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19881. {
  19882. const ScopedLock sl (lock);
  19883. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19884. const int numChans = bufferToFill.buffer->getNumChannels();
  19885. int i;
  19886. for (i = 0; i < buffer.getNumChannels(); ++i)
  19887. {
  19888. const int remappedChan = getRemappedInputChannel (i);
  19889. if (remappedChan >= 0 && remappedChan < numChans)
  19890. {
  19891. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19892. remappedChan,
  19893. bufferToFill.startSample,
  19894. bufferToFill.numSamples);
  19895. }
  19896. else
  19897. {
  19898. buffer.clear (i, 0, bufferToFill.numSamples);
  19899. }
  19900. }
  19901. remappedInfo.numSamples = bufferToFill.numSamples;
  19902. source->getNextAudioBlock (remappedInfo);
  19903. bufferToFill.clearActiveBufferRegion();
  19904. for (i = 0; i < requiredNumberOfChannels; ++i)
  19905. {
  19906. const int remappedChan = getRemappedOutputChannel (i);
  19907. if (remappedChan >= 0 && remappedChan < numChans)
  19908. {
  19909. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19910. buffer, i, 0, bufferToFill.numSamples);
  19911. }
  19912. }
  19913. }
  19914. XmlElement* ChannelRemappingAudioSource::createXml() const
  19915. {
  19916. XmlElement* e = new XmlElement ("MAPPINGS");
  19917. String ins, outs;
  19918. int i;
  19919. const ScopedLock sl (lock);
  19920. for (i = 0; i < remappedInputs.size(); ++i)
  19921. ins << remappedInputs.getUnchecked(i) << ' ';
  19922. for (i = 0; i < remappedOutputs.size(); ++i)
  19923. outs << remappedOutputs.getUnchecked(i) << ' ';
  19924. e->setAttribute ("inputs", ins.trimEnd());
  19925. e->setAttribute ("outputs", outs.trimEnd());
  19926. return e;
  19927. }
  19928. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19929. {
  19930. if (e.hasTagName ("MAPPINGS"))
  19931. {
  19932. const ScopedLock sl (lock);
  19933. clearAllMappings();
  19934. StringArray ins, outs;
  19935. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19936. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19937. int i;
  19938. for (i = 0; i < ins.size(); ++i)
  19939. remappedInputs.add (ins[i].getIntValue());
  19940. for (i = 0; i < outs.size(); ++i)
  19941. remappedOutputs.add (outs[i].getIntValue());
  19942. }
  19943. }
  19944. END_JUCE_NAMESPACE
  19945. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19946. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19947. BEGIN_JUCE_NAMESPACE
  19948. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19949. const bool deleteInputWhenDeleted_)
  19950. : input (inputSource),
  19951. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19952. {
  19953. jassert (inputSource != 0);
  19954. for (int i = 2; --i >= 0;)
  19955. iirFilters.add (new IIRFilter());
  19956. }
  19957. IIRFilterAudioSource::~IIRFilterAudioSource()
  19958. {
  19959. if (deleteInputWhenDeleted)
  19960. delete input;
  19961. }
  19962. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19963. {
  19964. for (int i = iirFilters.size(); --i >= 0;)
  19965. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19966. }
  19967. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19968. {
  19969. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19970. for (int i = iirFilters.size(); --i >= 0;)
  19971. iirFilters.getUnchecked(i)->reset();
  19972. }
  19973. void IIRFilterAudioSource::releaseResources()
  19974. {
  19975. input->releaseResources();
  19976. }
  19977. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19978. {
  19979. input->getNextAudioBlock (bufferToFill);
  19980. const int numChannels = bufferToFill.buffer->getNumChannels();
  19981. while (numChannels > iirFilters.size())
  19982. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19983. for (int i = 0; i < numChannels; ++i)
  19984. iirFilters.getUnchecked(i)
  19985. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19986. bufferToFill.numSamples);
  19987. }
  19988. END_JUCE_NAMESPACE
  19989. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19990. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19991. BEGIN_JUCE_NAMESPACE
  19992. MixerAudioSource::MixerAudioSource()
  19993. : tempBuffer (2, 0),
  19994. currentSampleRate (0.0),
  19995. bufferSizeExpected (0)
  19996. {
  19997. }
  19998. MixerAudioSource::~MixerAudioSource()
  19999. {
  20000. removeAllInputs();
  20001. }
  20002. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  20003. {
  20004. if (input != 0 && ! inputs.contains (input))
  20005. {
  20006. double localRate;
  20007. int localBufferSize;
  20008. {
  20009. const ScopedLock sl (lock);
  20010. localRate = currentSampleRate;
  20011. localBufferSize = bufferSizeExpected;
  20012. }
  20013. if (localRate != 0.0)
  20014. input->prepareToPlay (localBufferSize, localRate);
  20015. const ScopedLock sl (lock);
  20016. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  20017. inputs.add (input);
  20018. }
  20019. }
  20020. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  20021. {
  20022. if (input != 0)
  20023. {
  20024. int index;
  20025. {
  20026. const ScopedLock sl (lock);
  20027. index = inputs.indexOf (input);
  20028. if (index >= 0)
  20029. {
  20030. inputsToDelete.shiftBits (index, 1);
  20031. inputs.remove (index);
  20032. }
  20033. }
  20034. if (index >= 0)
  20035. {
  20036. input->releaseResources();
  20037. if (deleteInput)
  20038. delete input;
  20039. }
  20040. }
  20041. }
  20042. void MixerAudioSource::removeAllInputs()
  20043. {
  20044. OwnedArray<AudioSource> toDelete;
  20045. {
  20046. const ScopedLock sl (lock);
  20047. for (int i = inputs.size(); --i >= 0;)
  20048. if (inputsToDelete[i])
  20049. toDelete.add (inputs.getUnchecked(i));
  20050. }
  20051. }
  20052. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20053. {
  20054. tempBuffer.setSize (2, samplesPerBlockExpected);
  20055. const ScopedLock sl (lock);
  20056. currentSampleRate = sampleRate;
  20057. bufferSizeExpected = samplesPerBlockExpected;
  20058. for (int i = inputs.size(); --i >= 0;)
  20059. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20060. }
  20061. void MixerAudioSource::releaseResources()
  20062. {
  20063. const ScopedLock sl (lock);
  20064. for (int i = inputs.size(); --i >= 0;)
  20065. inputs.getUnchecked(i)->releaseResources();
  20066. tempBuffer.setSize (2, 0);
  20067. currentSampleRate = 0;
  20068. bufferSizeExpected = 0;
  20069. }
  20070. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20071. {
  20072. const ScopedLock sl (lock);
  20073. if (inputs.size() > 0)
  20074. {
  20075. inputs.getUnchecked(0)->getNextAudioBlock (info);
  20076. if (inputs.size() > 1)
  20077. {
  20078. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20079. info.buffer->getNumSamples());
  20080. AudioSourceChannelInfo info2;
  20081. info2.buffer = &tempBuffer;
  20082. info2.numSamples = info.numSamples;
  20083. info2.startSample = 0;
  20084. for (int i = 1; i < inputs.size(); ++i)
  20085. {
  20086. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20087. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20088. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20089. }
  20090. }
  20091. }
  20092. else
  20093. {
  20094. info.clearActiveBufferRegion();
  20095. }
  20096. }
  20097. END_JUCE_NAMESPACE
  20098. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20099. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20100. BEGIN_JUCE_NAMESPACE
  20101. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20102. const bool deleteInputWhenDeleted_,
  20103. const int numChannels_)
  20104. : input (inputSource),
  20105. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20106. ratio (1.0),
  20107. lastRatio (1.0),
  20108. buffer (numChannels_, 0),
  20109. sampsInBuffer (0),
  20110. numChannels (numChannels_)
  20111. {
  20112. jassert (input != 0);
  20113. }
  20114. ResamplingAudioSource::~ResamplingAudioSource()
  20115. {
  20116. if (deleteInputWhenDeleted)
  20117. delete input;
  20118. }
  20119. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20120. {
  20121. jassert (samplesInPerOutputSample > 0);
  20122. const ScopedLock sl (ratioLock);
  20123. ratio = jmax (0.0, samplesInPerOutputSample);
  20124. }
  20125. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20126. double sampleRate)
  20127. {
  20128. const ScopedLock sl (ratioLock);
  20129. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20130. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20131. buffer.clear();
  20132. sampsInBuffer = 0;
  20133. bufferPos = 0;
  20134. subSampleOffset = 0.0;
  20135. filterStates.calloc (numChannels);
  20136. srcBuffers.calloc (numChannels);
  20137. destBuffers.calloc (numChannels);
  20138. createLowPass (ratio);
  20139. resetFilters();
  20140. }
  20141. void ResamplingAudioSource::releaseResources()
  20142. {
  20143. input->releaseResources();
  20144. buffer.setSize (numChannels, 0);
  20145. }
  20146. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20147. {
  20148. const ScopedLock sl (ratioLock);
  20149. if (lastRatio != ratio)
  20150. {
  20151. createLowPass (ratio);
  20152. lastRatio = ratio;
  20153. }
  20154. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20155. int bufferSize = buffer.getNumSamples();
  20156. if (bufferSize < sampsNeeded + 8)
  20157. {
  20158. bufferPos %= bufferSize;
  20159. bufferSize = sampsNeeded + 32;
  20160. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20161. }
  20162. bufferPos %= bufferSize;
  20163. int endOfBufferPos = bufferPos + sampsInBuffer;
  20164. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20165. while (sampsNeeded > sampsInBuffer)
  20166. {
  20167. endOfBufferPos %= bufferSize;
  20168. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20169. bufferSize - endOfBufferPos);
  20170. AudioSourceChannelInfo readInfo;
  20171. readInfo.buffer = &buffer;
  20172. readInfo.numSamples = numToDo;
  20173. readInfo.startSample = endOfBufferPos;
  20174. input->getNextAudioBlock (readInfo);
  20175. if (ratio > 1.0001)
  20176. {
  20177. // for down-sampling, pre-apply the filter..
  20178. for (int i = channelsToProcess; --i >= 0;)
  20179. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20180. }
  20181. sampsInBuffer += numToDo;
  20182. endOfBufferPos += numToDo;
  20183. }
  20184. for (int channel = 0; channel < channelsToProcess; ++channel)
  20185. {
  20186. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20187. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20188. }
  20189. int nextPos = (bufferPos + 1) % bufferSize;
  20190. for (int m = info.numSamples; --m >= 0;)
  20191. {
  20192. const float alpha = (float) subSampleOffset;
  20193. const float invAlpha = 1.0f - alpha;
  20194. for (int channel = 0; channel < channelsToProcess; ++channel)
  20195. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20196. subSampleOffset += ratio;
  20197. jassert (sampsInBuffer > 0);
  20198. while (subSampleOffset >= 1.0)
  20199. {
  20200. if (++bufferPos >= bufferSize)
  20201. bufferPos = 0;
  20202. --sampsInBuffer;
  20203. nextPos = (bufferPos + 1) % bufferSize;
  20204. subSampleOffset -= 1.0;
  20205. }
  20206. }
  20207. if (ratio < 0.9999)
  20208. {
  20209. // for up-sampling, apply the filter after transposing..
  20210. for (int i = channelsToProcess; --i >= 0;)
  20211. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20212. }
  20213. else if (ratio <= 1.0001)
  20214. {
  20215. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20216. for (int i = channelsToProcess; --i >= 0;)
  20217. {
  20218. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20219. FilterState& fs = filterStates[i];
  20220. if (info.numSamples > 1)
  20221. {
  20222. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20223. }
  20224. else
  20225. {
  20226. fs.y2 = fs.y1;
  20227. fs.x2 = fs.x1;
  20228. }
  20229. fs.y1 = fs.x1 = *endOfBuffer;
  20230. }
  20231. }
  20232. jassert (sampsInBuffer >= 0);
  20233. }
  20234. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20235. {
  20236. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20237. : 0.5 * frequencyRatio;
  20238. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20239. const double nSquared = n * n;
  20240. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20241. setFilterCoefficients (c1,
  20242. c1 * 2.0f,
  20243. c1,
  20244. 1.0,
  20245. c1 * 2.0 * (1.0 - nSquared),
  20246. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20247. }
  20248. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20249. {
  20250. const double a = 1.0 / c4;
  20251. c1 *= a;
  20252. c2 *= a;
  20253. c3 *= a;
  20254. c5 *= a;
  20255. c6 *= a;
  20256. coefficients[0] = c1;
  20257. coefficients[1] = c2;
  20258. coefficients[2] = c3;
  20259. coefficients[3] = c4;
  20260. coefficients[4] = c5;
  20261. coefficients[5] = c6;
  20262. }
  20263. void ResamplingAudioSource::resetFilters()
  20264. {
  20265. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20266. }
  20267. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20268. {
  20269. while (--num >= 0)
  20270. {
  20271. const double in = *samples;
  20272. double out = coefficients[0] * in
  20273. + coefficients[1] * fs.x1
  20274. + coefficients[2] * fs.x2
  20275. - coefficients[4] * fs.y1
  20276. - coefficients[5] * fs.y2;
  20277. #if JUCE_INTEL
  20278. if (! (out < -1.0e-8 || out > 1.0e-8))
  20279. out = 0;
  20280. #endif
  20281. fs.x2 = fs.x1;
  20282. fs.x1 = in;
  20283. fs.y2 = fs.y1;
  20284. fs.y1 = out;
  20285. *samples++ = (float) out;
  20286. }
  20287. }
  20288. END_JUCE_NAMESPACE
  20289. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20290. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20291. BEGIN_JUCE_NAMESPACE
  20292. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20293. : frequency (1000.0),
  20294. sampleRate (44100.0),
  20295. currentPhase (0.0),
  20296. phasePerSample (0.0),
  20297. amplitude (0.5f)
  20298. {
  20299. }
  20300. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20301. {
  20302. }
  20303. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20304. {
  20305. amplitude = newAmplitude;
  20306. }
  20307. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20308. {
  20309. frequency = newFrequencyHz;
  20310. phasePerSample = 0.0;
  20311. }
  20312. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20313. double sampleRate_)
  20314. {
  20315. currentPhase = 0.0;
  20316. phasePerSample = 0.0;
  20317. sampleRate = sampleRate_;
  20318. }
  20319. void ToneGeneratorAudioSource::releaseResources()
  20320. {
  20321. }
  20322. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20323. {
  20324. if (phasePerSample == 0.0)
  20325. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20326. for (int i = 0; i < info.numSamples; ++i)
  20327. {
  20328. const float sample = amplitude * (float) std::sin (currentPhase);
  20329. currentPhase += phasePerSample;
  20330. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20331. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20332. }
  20333. }
  20334. END_JUCE_NAMESPACE
  20335. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20336. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20337. BEGIN_JUCE_NAMESPACE
  20338. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20339. : sampleRate (0),
  20340. bufferSize (0),
  20341. useDefaultInputChannels (true),
  20342. useDefaultOutputChannels (true)
  20343. {
  20344. }
  20345. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20346. {
  20347. return outputDeviceName == other.outputDeviceName
  20348. && inputDeviceName == other.inputDeviceName
  20349. && sampleRate == other.sampleRate
  20350. && bufferSize == other.bufferSize
  20351. && inputChannels == other.inputChannels
  20352. && useDefaultInputChannels == other.useDefaultInputChannels
  20353. && outputChannels == other.outputChannels
  20354. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20355. }
  20356. AudioDeviceManager::AudioDeviceManager()
  20357. : currentAudioDevice (0),
  20358. numInputChansNeeded (0),
  20359. numOutputChansNeeded (2),
  20360. listNeedsScanning (true),
  20361. useInputNames (false),
  20362. inputLevelMeasurementEnabledCount (0),
  20363. inputLevel (0),
  20364. tempBuffer (2, 2),
  20365. defaultMidiOutput (0),
  20366. cpuUsageMs (0),
  20367. timeToCpuScale (0)
  20368. {
  20369. callbackHandler.owner = this;
  20370. }
  20371. AudioDeviceManager::~AudioDeviceManager()
  20372. {
  20373. currentAudioDevice = 0;
  20374. defaultMidiOutput = 0;
  20375. }
  20376. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20377. {
  20378. if (availableDeviceTypes.size() == 0)
  20379. {
  20380. createAudioDeviceTypes (availableDeviceTypes);
  20381. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20382. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20383. if (availableDeviceTypes.size() > 0)
  20384. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20385. }
  20386. }
  20387. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20388. {
  20389. scanDevicesIfNeeded();
  20390. return availableDeviceTypes;
  20391. }
  20392. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20393. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20394. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20395. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20396. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20397. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20398. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20399. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20400. {
  20401. (void) list; // (to avoid 'unused param' warnings)
  20402. #if JUCE_WINDOWS
  20403. #if JUCE_WASAPI
  20404. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20405. list.add (juce_createAudioIODeviceType_WASAPI());
  20406. #endif
  20407. #if JUCE_DIRECTSOUND
  20408. list.add (juce_createAudioIODeviceType_DirectSound());
  20409. #endif
  20410. #if JUCE_ASIO
  20411. list.add (juce_createAudioIODeviceType_ASIO());
  20412. #endif
  20413. #endif
  20414. #if JUCE_MAC
  20415. list.add (juce_createAudioIODeviceType_CoreAudio());
  20416. #endif
  20417. #if JUCE_IOS
  20418. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20419. #endif
  20420. #if JUCE_LINUX && JUCE_ALSA
  20421. list.add (juce_createAudioIODeviceType_ALSA());
  20422. #endif
  20423. #if JUCE_LINUX && JUCE_JACK
  20424. list.add (juce_createAudioIODeviceType_JACK());
  20425. #endif
  20426. }
  20427. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20428. const int numOutputChannelsNeeded,
  20429. const XmlElement* const e,
  20430. const bool selectDefaultDeviceOnFailure,
  20431. const String& preferredDefaultDeviceName,
  20432. const AudioDeviceSetup* preferredSetupOptions)
  20433. {
  20434. scanDevicesIfNeeded();
  20435. numInputChansNeeded = numInputChannelsNeeded;
  20436. numOutputChansNeeded = numOutputChannelsNeeded;
  20437. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20438. {
  20439. lastExplicitSettings = new XmlElement (*e);
  20440. String error;
  20441. AudioDeviceSetup setup;
  20442. if (preferredSetupOptions != 0)
  20443. setup = *preferredSetupOptions;
  20444. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20445. {
  20446. setup.inputDeviceName = setup.outputDeviceName
  20447. = e->getStringAttribute ("audioDeviceName");
  20448. }
  20449. else
  20450. {
  20451. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20452. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20453. }
  20454. currentDeviceType = e->getStringAttribute ("deviceType");
  20455. if (currentDeviceType.isEmpty())
  20456. {
  20457. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20458. if (type != 0)
  20459. currentDeviceType = type->getTypeName();
  20460. else if (availableDeviceTypes.size() > 0)
  20461. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20462. }
  20463. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20464. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20465. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20466. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20467. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20468. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20469. error = setAudioDeviceSetup (setup, true);
  20470. midiInsFromXml.clear();
  20471. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20472. midiInsFromXml.add (c->getStringAttribute ("name"));
  20473. const StringArray allMidiIns (MidiInput::getDevices());
  20474. for (int i = allMidiIns.size(); --i >= 0;)
  20475. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20476. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20477. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20478. false, preferredDefaultDeviceName);
  20479. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20480. return error;
  20481. }
  20482. else
  20483. {
  20484. AudioDeviceSetup setup;
  20485. if (preferredSetupOptions != 0)
  20486. {
  20487. setup = *preferredSetupOptions;
  20488. }
  20489. else if (preferredDefaultDeviceName.isNotEmpty())
  20490. {
  20491. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20492. {
  20493. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20494. StringArray outs (type->getDeviceNames (false));
  20495. int i;
  20496. for (i = 0; i < outs.size(); ++i)
  20497. {
  20498. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20499. {
  20500. setup.outputDeviceName = outs[i];
  20501. break;
  20502. }
  20503. }
  20504. StringArray ins (type->getDeviceNames (true));
  20505. for (i = 0; i < ins.size(); ++i)
  20506. {
  20507. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20508. {
  20509. setup.inputDeviceName = ins[i];
  20510. break;
  20511. }
  20512. }
  20513. }
  20514. }
  20515. insertDefaultDeviceNames (setup);
  20516. return setAudioDeviceSetup (setup, false);
  20517. }
  20518. }
  20519. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20520. {
  20521. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20522. if (type != 0)
  20523. {
  20524. if (setup.outputDeviceName.isEmpty())
  20525. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20526. if (setup.inputDeviceName.isEmpty())
  20527. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20528. }
  20529. }
  20530. XmlElement* AudioDeviceManager::createStateXml() const
  20531. {
  20532. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20533. }
  20534. void AudioDeviceManager::scanDevicesIfNeeded()
  20535. {
  20536. if (listNeedsScanning)
  20537. {
  20538. listNeedsScanning = false;
  20539. createDeviceTypesIfNeeded();
  20540. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20541. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20542. }
  20543. }
  20544. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20545. {
  20546. scanDevicesIfNeeded();
  20547. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20548. {
  20549. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20550. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20551. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20552. {
  20553. return type;
  20554. }
  20555. }
  20556. return 0;
  20557. }
  20558. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20559. {
  20560. setup = currentSetup;
  20561. }
  20562. void AudioDeviceManager::deleteCurrentDevice()
  20563. {
  20564. currentAudioDevice = 0;
  20565. currentSetup.inputDeviceName = String::empty;
  20566. currentSetup.outputDeviceName = String::empty;
  20567. }
  20568. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20569. const bool treatAsChosenDevice)
  20570. {
  20571. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20572. {
  20573. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20574. && currentDeviceType != type)
  20575. {
  20576. currentDeviceType = type;
  20577. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20578. insertDefaultDeviceNames (s);
  20579. setAudioDeviceSetup (s, treatAsChosenDevice);
  20580. sendChangeMessage();
  20581. break;
  20582. }
  20583. }
  20584. }
  20585. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20586. {
  20587. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20588. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20589. return availableDeviceTypes[i];
  20590. return availableDeviceTypes[0];
  20591. }
  20592. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20593. const bool treatAsChosenDevice)
  20594. {
  20595. jassert (&newSetup != &currentSetup); // this will have no effect
  20596. if (newSetup == currentSetup && currentAudioDevice != 0)
  20597. return String::empty;
  20598. if (! (newSetup == currentSetup))
  20599. sendChangeMessage();
  20600. stopDevice();
  20601. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20602. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20603. String error;
  20604. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20605. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20606. {
  20607. deleteCurrentDevice();
  20608. if (treatAsChosenDevice)
  20609. updateXml();
  20610. return String::empty;
  20611. }
  20612. if (currentSetup.inputDeviceName != newInputDeviceName
  20613. || currentSetup.outputDeviceName != newOutputDeviceName
  20614. || currentAudioDevice == 0)
  20615. {
  20616. deleteCurrentDevice();
  20617. scanDevicesIfNeeded();
  20618. if (newOutputDeviceName.isNotEmpty()
  20619. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20620. {
  20621. return "No such device: " + newOutputDeviceName;
  20622. }
  20623. if (newInputDeviceName.isNotEmpty()
  20624. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20625. {
  20626. return "No such device: " + newInputDeviceName;
  20627. }
  20628. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20629. if (currentAudioDevice == 0)
  20630. 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!";
  20631. else
  20632. error = currentAudioDevice->getLastError();
  20633. if (error.isNotEmpty())
  20634. {
  20635. deleteCurrentDevice();
  20636. return error;
  20637. }
  20638. if (newSetup.useDefaultInputChannels)
  20639. {
  20640. inputChannels.clear();
  20641. inputChannels.setRange (0, numInputChansNeeded, true);
  20642. }
  20643. if (newSetup.useDefaultOutputChannels)
  20644. {
  20645. outputChannels.clear();
  20646. outputChannels.setRange (0, numOutputChansNeeded, true);
  20647. }
  20648. if (newInputDeviceName.isEmpty())
  20649. inputChannels.clear();
  20650. if (newOutputDeviceName.isEmpty())
  20651. outputChannels.clear();
  20652. }
  20653. if (! newSetup.useDefaultInputChannels)
  20654. inputChannels = newSetup.inputChannels;
  20655. if (! newSetup.useDefaultOutputChannels)
  20656. outputChannels = newSetup.outputChannels;
  20657. currentSetup = newSetup;
  20658. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20659. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20660. error = currentAudioDevice->open (inputChannels,
  20661. outputChannels,
  20662. currentSetup.sampleRate,
  20663. currentSetup.bufferSize);
  20664. if (error.isEmpty())
  20665. {
  20666. currentDeviceType = currentAudioDevice->getTypeName();
  20667. currentAudioDevice->start (&callbackHandler);
  20668. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20669. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20670. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20671. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20672. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20673. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20674. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20675. if (treatAsChosenDevice)
  20676. updateXml();
  20677. }
  20678. else
  20679. {
  20680. deleteCurrentDevice();
  20681. }
  20682. return error;
  20683. }
  20684. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20685. {
  20686. jassert (currentAudioDevice != 0);
  20687. if (rate > 0)
  20688. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20689. if (currentAudioDevice->getSampleRate (i) == rate)
  20690. return rate;
  20691. double lowestAbove44 = 0.0;
  20692. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20693. {
  20694. const double sr = currentAudioDevice->getSampleRate (i);
  20695. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20696. lowestAbove44 = sr;
  20697. }
  20698. if (lowestAbove44 > 0.0)
  20699. return lowestAbove44;
  20700. return currentAudioDevice->getSampleRate (0);
  20701. }
  20702. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20703. {
  20704. jassert (currentAudioDevice != 0);
  20705. if (bufferSize > 0)
  20706. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20707. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20708. return bufferSize;
  20709. return currentAudioDevice->getDefaultBufferSize();
  20710. }
  20711. void AudioDeviceManager::stopDevice()
  20712. {
  20713. if (currentAudioDevice != 0)
  20714. currentAudioDevice->stop();
  20715. testSound = 0;
  20716. }
  20717. void AudioDeviceManager::closeAudioDevice()
  20718. {
  20719. stopDevice();
  20720. currentAudioDevice = 0;
  20721. }
  20722. void AudioDeviceManager::restartLastAudioDevice()
  20723. {
  20724. if (currentAudioDevice == 0)
  20725. {
  20726. if (currentSetup.inputDeviceName.isEmpty()
  20727. && currentSetup.outputDeviceName.isEmpty())
  20728. {
  20729. // This method will only reload the last device that was running
  20730. // before closeAudioDevice() was called - you need to actually open
  20731. // one first, with setAudioDevice().
  20732. jassertfalse;
  20733. return;
  20734. }
  20735. AudioDeviceSetup s (currentSetup);
  20736. setAudioDeviceSetup (s, false);
  20737. }
  20738. }
  20739. void AudioDeviceManager::updateXml()
  20740. {
  20741. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20742. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20743. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20744. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20745. if (currentAudioDevice != 0)
  20746. {
  20747. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20748. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20749. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20750. if (! currentSetup.useDefaultInputChannels)
  20751. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20752. if (! currentSetup.useDefaultOutputChannels)
  20753. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20754. }
  20755. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20756. {
  20757. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20758. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20759. }
  20760. if (midiInsFromXml.size() > 0)
  20761. {
  20762. // Add any midi devices that have been enabled before, but which aren't currently
  20763. // open because the device has been disconnected.
  20764. const StringArray availableMidiDevices (MidiInput::getDevices());
  20765. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20766. {
  20767. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20768. {
  20769. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20770. m->setAttribute ("name", midiInsFromXml[i]);
  20771. }
  20772. }
  20773. }
  20774. if (defaultMidiOutputName.isNotEmpty())
  20775. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20776. }
  20777. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20778. {
  20779. {
  20780. const ScopedLock sl (audioCallbackLock);
  20781. if (callbacks.contains (newCallback))
  20782. return;
  20783. }
  20784. if (currentAudioDevice != 0 && newCallback != 0)
  20785. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20786. const ScopedLock sl (audioCallbackLock);
  20787. callbacks.add (newCallback);
  20788. }
  20789. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20790. {
  20791. if (callback != 0)
  20792. {
  20793. bool needsDeinitialising = currentAudioDevice != 0;
  20794. {
  20795. const ScopedLock sl (audioCallbackLock);
  20796. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20797. callbacks.removeValue (callback);
  20798. }
  20799. if (needsDeinitialising)
  20800. callback->audioDeviceStopped();
  20801. }
  20802. }
  20803. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20804. int numInputChannels,
  20805. float** outputChannelData,
  20806. int numOutputChannels,
  20807. int numSamples)
  20808. {
  20809. const ScopedLock sl (audioCallbackLock);
  20810. if (inputLevelMeasurementEnabledCount > 0)
  20811. {
  20812. for (int j = 0; j < numSamples; ++j)
  20813. {
  20814. float s = 0;
  20815. for (int i = 0; i < numInputChannels; ++i)
  20816. s += std::abs (inputChannelData[i][j]);
  20817. s /= numInputChannels;
  20818. const double decayFactor = 0.99992;
  20819. if (s > inputLevel)
  20820. inputLevel = s;
  20821. else if (inputLevel > 0.001f)
  20822. inputLevel *= decayFactor;
  20823. else
  20824. inputLevel = 0;
  20825. }
  20826. }
  20827. if (callbacks.size() > 0)
  20828. {
  20829. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20830. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20831. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20832. outputChannelData, numOutputChannels, numSamples);
  20833. float** const tempChans = tempBuffer.getArrayOfChannels();
  20834. for (int i = callbacks.size(); --i > 0;)
  20835. {
  20836. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20837. tempChans, numOutputChannels, numSamples);
  20838. for (int chan = 0; chan < numOutputChannels; ++chan)
  20839. {
  20840. const float* const src = tempChans [chan];
  20841. float* const dst = outputChannelData [chan];
  20842. if (src != 0 && dst != 0)
  20843. for (int j = 0; j < numSamples; ++j)
  20844. dst[j] += src[j];
  20845. }
  20846. }
  20847. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20848. const double filterAmount = 0.2;
  20849. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20850. }
  20851. else
  20852. {
  20853. for (int i = 0; i < numOutputChannels; ++i)
  20854. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20855. }
  20856. if (testSound != 0)
  20857. {
  20858. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20859. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20860. for (int i = 0; i < numOutputChannels; ++i)
  20861. for (int j = 0; j < numSamps; ++j)
  20862. outputChannelData [i][j] += src[j];
  20863. testSoundPosition += numSamps;
  20864. if (testSoundPosition >= testSound->getNumSamples())
  20865. testSound = 0;
  20866. }
  20867. }
  20868. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20869. {
  20870. cpuUsageMs = 0;
  20871. const double sampleRate = device->getCurrentSampleRate();
  20872. const int blockSize = device->getCurrentBufferSizeSamples();
  20873. if (sampleRate > 0.0 && blockSize > 0)
  20874. {
  20875. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20876. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20877. }
  20878. {
  20879. const ScopedLock sl (audioCallbackLock);
  20880. for (int i = callbacks.size(); --i >= 0;)
  20881. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20882. }
  20883. sendChangeMessage();
  20884. }
  20885. void AudioDeviceManager::audioDeviceStoppedInt()
  20886. {
  20887. cpuUsageMs = 0;
  20888. timeToCpuScale = 0;
  20889. sendChangeMessage();
  20890. const ScopedLock sl (audioCallbackLock);
  20891. for (int i = callbacks.size(); --i >= 0;)
  20892. callbacks.getUnchecked(i)->audioDeviceStopped();
  20893. }
  20894. double AudioDeviceManager::getCpuUsage() const
  20895. {
  20896. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20897. }
  20898. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20899. const bool enabled)
  20900. {
  20901. if (enabled != isMidiInputEnabled (name))
  20902. {
  20903. if (enabled)
  20904. {
  20905. const int index = MidiInput::getDevices().indexOf (name);
  20906. if (index >= 0)
  20907. {
  20908. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20909. if (min != 0)
  20910. {
  20911. enabledMidiInputs.add (min);
  20912. min->start();
  20913. }
  20914. }
  20915. }
  20916. else
  20917. {
  20918. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20919. if (enabledMidiInputs[i]->getName() == name)
  20920. enabledMidiInputs.remove (i);
  20921. }
  20922. updateXml();
  20923. sendChangeMessage();
  20924. }
  20925. }
  20926. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20927. {
  20928. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20929. if (enabledMidiInputs[i]->getName() == name)
  20930. return true;
  20931. return false;
  20932. }
  20933. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20934. MidiInputCallback* callback)
  20935. {
  20936. removeMidiInputCallback (name, callback);
  20937. if (name.isEmpty())
  20938. {
  20939. midiCallbacks.add (callback);
  20940. midiCallbackDevices.add (0);
  20941. }
  20942. else
  20943. {
  20944. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20945. {
  20946. if (enabledMidiInputs[i]->getName() == name)
  20947. {
  20948. const ScopedLock sl (midiCallbackLock);
  20949. midiCallbacks.add (callback);
  20950. midiCallbackDevices.add (enabledMidiInputs[i]);
  20951. break;
  20952. }
  20953. }
  20954. }
  20955. }
  20956. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20957. MidiInputCallback* /*callback*/)
  20958. {
  20959. const ScopedLock sl (midiCallbackLock);
  20960. for (int i = midiCallbacks.size(); --i >= 0;)
  20961. {
  20962. String devName;
  20963. if (midiCallbackDevices.getUnchecked(i) != 0)
  20964. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20965. if (devName == name)
  20966. {
  20967. midiCallbacks.remove (i);
  20968. midiCallbackDevices.remove (i);
  20969. }
  20970. }
  20971. }
  20972. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20973. const MidiMessage& message)
  20974. {
  20975. if (! message.isActiveSense())
  20976. {
  20977. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20978. const ScopedLock sl (midiCallbackLock);
  20979. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20980. {
  20981. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20982. if (md == source || (md == 0 && isDefaultSource))
  20983. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20984. }
  20985. }
  20986. }
  20987. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20988. {
  20989. if (defaultMidiOutputName != deviceName)
  20990. {
  20991. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20992. {
  20993. const ScopedLock sl (audioCallbackLock);
  20994. oldCallbacks = callbacks;
  20995. callbacks.clear();
  20996. }
  20997. if (currentAudioDevice != 0)
  20998. for (int i = oldCallbacks.size(); --i >= 0;)
  20999. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  21000. defaultMidiOutput = 0;
  21001. defaultMidiOutputName = deviceName;
  21002. if (deviceName.isNotEmpty())
  21003. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  21004. if (currentAudioDevice != 0)
  21005. for (int i = oldCallbacks.size(); --i >= 0;)
  21006. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  21007. {
  21008. const ScopedLock sl (audioCallbackLock);
  21009. callbacks = oldCallbacks;
  21010. }
  21011. updateXml();
  21012. sendChangeMessage();
  21013. }
  21014. }
  21015. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  21016. int numInputChannels,
  21017. float** outputChannelData,
  21018. int numOutputChannels,
  21019. int numSamples)
  21020. {
  21021. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  21022. }
  21023. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  21024. {
  21025. owner->audioDeviceAboutToStartInt (device);
  21026. }
  21027. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  21028. {
  21029. owner->audioDeviceStoppedInt();
  21030. }
  21031. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  21032. {
  21033. owner->handleIncomingMidiMessageInt (source, message);
  21034. }
  21035. void AudioDeviceManager::playTestSound()
  21036. {
  21037. { // cunningly nested to swap, unlock and delete in that order.
  21038. ScopedPointer <AudioSampleBuffer> oldSound;
  21039. {
  21040. const ScopedLock sl (audioCallbackLock);
  21041. oldSound = testSound;
  21042. }
  21043. }
  21044. testSoundPosition = 0;
  21045. if (currentAudioDevice != 0)
  21046. {
  21047. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  21048. const int soundLength = (int) sampleRate;
  21049. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  21050. float* samples = newSound->getSampleData (0);
  21051. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  21052. const float amplitude = 0.5f;
  21053. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  21054. for (int i = 0; i < soundLength; ++i)
  21055. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  21056. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  21057. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  21058. const ScopedLock sl (audioCallbackLock);
  21059. testSound = newSound;
  21060. }
  21061. }
  21062. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  21063. {
  21064. const ScopedLock sl (audioCallbackLock);
  21065. if (enableMeasurement)
  21066. ++inputLevelMeasurementEnabledCount;
  21067. else
  21068. --inputLevelMeasurementEnabledCount;
  21069. inputLevel = 0;
  21070. }
  21071. double AudioDeviceManager::getCurrentInputLevel() const
  21072. {
  21073. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21074. return inputLevel;
  21075. }
  21076. END_JUCE_NAMESPACE
  21077. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21078. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21079. BEGIN_JUCE_NAMESPACE
  21080. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21081. : name (deviceName),
  21082. typeName (typeName_)
  21083. {
  21084. }
  21085. AudioIODevice::~AudioIODevice()
  21086. {
  21087. }
  21088. bool AudioIODevice::hasControlPanel() const
  21089. {
  21090. return false;
  21091. }
  21092. bool AudioIODevice::showControlPanel()
  21093. {
  21094. jassertfalse; // this should only be called for devices which return true from
  21095. // their hasControlPanel() method.
  21096. return false;
  21097. }
  21098. END_JUCE_NAMESPACE
  21099. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21100. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21101. BEGIN_JUCE_NAMESPACE
  21102. AudioIODeviceType::AudioIODeviceType (const String& name)
  21103. : typeName (name)
  21104. {
  21105. }
  21106. AudioIODeviceType::~AudioIODeviceType()
  21107. {
  21108. }
  21109. END_JUCE_NAMESPACE
  21110. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21111. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21112. BEGIN_JUCE_NAMESPACE
  21113. MidiOutput::MidiOutput()
  21114. : Thread ("midi out"),
  21115. internal (0),
  21116. firstMessage (0)
  21117. {
  21118. }
  21119. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21120. const double sampleNumber)
  21121. : message (data, len, sampleNumber)
  21122. {
  21123. }
  21124. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21125. const double millisecondCounterToStartAt,
  21126. double samplesPerSecondForBuffer)
  21127. {
  21128. // You've got to call startBackgroundThread() for this to actually work..
  21129. jassert (isThreadRunning());
  21130. // this needs to be a value in the future - RTFM for this method!
  21131. jassert (millisecondCounterToStartAt > 0);
  21132. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21133. MidiBuffer::Iterator i (buffer);
  21134. const uint8* data;
  21135. int len, time;
  21136. while (i.getNextEvent (data, len, time))
  21137. {
  21138. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21139. PendingMessage* const m
  21140. = new PendingMessage (data, len, eventTime);
  21141. const ScopedLock sl (lock);
  21142. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21143. {
  21144. m->next = firstMessage;
  21145. firstMessage = m;
  21146. }
  21147. else
  21148. {
  21149. PendingMessage* mm = firstMessage;
  21150. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21151. mm = mm->next;
  21152. m->next = mm->next;
  21153. mm->next = m;
  21154. }
  21155. }
  21156. notify();
  21157. }
  21158. void MidiOutput::clearAllPendingMessages()
  21159. {
  21160. const ScopedLock sl (lock);
  21161. while (firstMessage != 0)
  21162. {
  21163. PendingMessage* const m = firstMessage;
  21164. firstMessage = firstMessage->next;
  21165. delete m;
  21166. }
  21167. }
  21168. void MidiOutput::startBackgroundThread()
  21169. {
  21170. startThread (9);
  21171. }
  21172. void MidiOutput::stopBackgroundThread()
  21173. {
  21174. stopThread (5000);
  21175. }
  21176. void MidiOutput::run()
  21177. {
  21178. while (! threadShouldExit())
  21179. {
  21180. uint32 now = Time::getMillisecondCounter();
  21181. uint32 eventTime = 0;
  21182. uint32 timeToWait = 500;
  21183. PendingMessage* message;
  21184. {
  21185. const ScopedLock sl (lock);
  21186. message = firstMessage;
  21187. if (message != 0)
  21188. {
  21189. eventTime = roundToInt (message->message.getTimeStamp());
  21190. if (eventTime > now + 20)
  21191. {
  21192. timeToWait = eventTime - (now + 20);
  21193. message = 0;
  21194. }
  21195. else
  21196. {
  21197. firstMessage = message->next;
  21198. }
  21199. }
  21200. }
  21201. if (message != 0)
  21202. {
  21203. if (eventTime > now)
  21204. {
  21205. Time::waitForMillisecondCounter (eventTime);
  21206. if (threadShouldExit())
  21207. break;
  21208. }
  21209. if (eventTime > now - 200)
  21210. sendMessageNow (message->message);
  21211. delete message;
  21212. }
  21213. else
  21214. {
  21215. jassert (timeToWait < 1000 * 30);
  21216. wait (timeToWait);
  21217. }
  21218. }
  21219. clearAllPendingMessages();
  21220. }
  21221. END_JUCE_NAMESPACE
  21222. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21223. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21224. BEGIN_JUCE_NAMESPACE
  21225. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21226. {
  21227. const double maxVal = (double) 0x7fff;
  21228. char* intData = static_cast <char*> (dest);
  21229. if (dest != (void*) source || destBytesPerSample <= 4)
  21230. {
  21231. for (int i = 0; i < numSamples; ++i)
  21232. {
  21233. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21234. intData += destBytesPerSample;
  21235. }
  21236. }
  21237. else
  21238. {
  21239. intData += destBytesPerSample * numSamples;
  21240. for (int i = numSamples; --i >= 0;)
  21241. {
  21242. intData -= destBytesPerSample;
  21243. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21244. }
  21245. }
  21246. }
  21247. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21248. {
  21249. const double maxVal = (double) 0x7fff;
  21250. char* intData = static_cast <char*> (dest);
  21251. if (dest != (void*) source || destBytesPerSample <= 4)
  21252. {
  21253. for (int i = 0; i < numSamples; ++i)
  21254. {
  21255. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21256. intData += destBytesPerSample;
  21257. }
  21258. }
  21259. else
  21260. {
  21261. intData += destBytesPerSample * numSamples;
  21262. for (int i = numSamples; --i >= 0;)
  21263. {
  21264. intData -= destBytesPerSample;
  21265. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21266. }
  21267. }
  21268. }
  21269. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21270. {
  21271. const double maxVal = (double) 0x7fffff;
  21272. char* intData = static_cast <char*> (dest);
  21273. if (dest != (void*) source || destBytesPerSample <= 4)
  21274. {
  21275. for (int i = 0; i < numSamples; ++i)
  21276. {
  21277. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21278. intData += destBytesPerSample;
  21279. }
  21280. }
  21281. else
  21282. {
  21283. intData += destBytesPerSample * numSamples;
  21284. for (int i = numSamples; --i >= 0;)
  21285. {
  21286. intData -= destBytesPerSample;
  21287. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21288. }
  21289. }
  21290. }
  21291. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21292. {
  21293. const double maxVal = (double) 0x7fffff;
  21294. char* intData = static_cast <char*> (dest);
  21295. if (dest != (void*) source || destBytesPerSample <= 4)
  21296. {
  21297. for (int i = 0; i < numSamples; ++i)
  21298. {
  21299. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21300. intData += destBytesPerSample;
  21301. }
  21302. }
  21303. else
  21304. {
  21305. intData += destBytesPerSample * numSamples;
  21306. for (int i = numSamples; --i >= 0;)
  21307. {
  21308. intData -= destBytesPerSample;
  21309. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21310. }
  21311. }
  21312. }
  21313. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21314. {
  21315. const double maxVal = (double) 0x7fffffff;
  21316. char* intData = static_cast <char*> (dest);
  21317. if (dest != (void*) source || destBytesPerSample <= 4)
  21318. {
  21319. for (int i = 0; i < numSamples; ++i)
  21320. {
  21321. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21322. intData += destBytesPerSample;
  21323. }
  21324. }
  21325. else
  21326. {
  21327. intData += destBytesPerSample * numSamples;
  21328. for (int i = numSamples; --i >= 0;)
  21329. {
  21330. intData -= destBytesPerSample;
  21331. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21332. }
  21333. }
  21334. }
  21335. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21336. {
  21337. const double maxVal = (double) 0x7fffffff;
  21338. char* intData = static_cast <char*> (dest);
  21339. if (dest != (void*) source || destBytesPerSample <= 4)
  21340. {
  21341. for (int i = 0; i < numSamples; ++i)
  21342. {
  21343. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21344. intData += destBytesPerSample;
  21345. }
  21346. }
  21347. else
  21348. {
  21349. intData += destBytesPerSample * numSamples;
  21350. for (int i = numSamples; --i >= 0;)
  21351. {
  21352. intData -= destBytesPerSample;
  21353. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21354. }
  21355. }
  21356. }
  21357. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21358. {
  21359. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21360. char* d = static_cast <char*> (dest);
  21361. for (int i = 0; i < numSamples; ++i)
  21362. {
  21363. *(float*) d = source[i];
  21364. #if JUCE_BIG_ENDIAN
  21365. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21366. #endif
  21367. d += destBytesPerSample;
  21368. }
  21369. }
  21370. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21371. {
  21372. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21373. char* d = static_cast <char*> (dest);
  21374. for (int i = 0; i < numSamples; ++i)
  21375. {
  21376. *(float*) d = source[i];
  21377. #if JUCE_LITTLE_ENDIAN
  21378. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21379. #endif
  21380. d += destBytesPerSample;
  21381. }
  21382. }
  21383. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21384. {
  21385. const float scale = 1.0f / 0x7fff;
  21386. const char* intData = static_cast <const char*> (source);
  21387. if (source != (void*) dest || srcBytesPerSample >= 4)
  21388. {
  21389. for (int i = 0; i < numSamples; ++i)
  21390. {
  21391. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21392. intData += srcBytesPerSample;
  21393. }
  21394. }
  21395. else
  21396. {
  21397. intData += srcBytesPerSample * numSamples;
  21398. for (int i = numSamples; --i >= 0;)
  21399. {
  21400. intData -= srcBytesPerSample;
  21401. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21402. }
  21403. }
  21404. }
  21405. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21406. {
  21407. const float scale = 1.0f / 0x7fff;
  21408. const char* intData = static_cast <const char*> (source);
  21409. if (source != (void*) dest || srcBytesPerSample >= 4)
  21410. {
  21411. for (int i = 0; i < numSamples; ++i)
  21412. {
  21413. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21414. intData += srcBytesPerSample;
  21415. }
  21416. }
  21417. else
  21418. {
  21419. intData += srcBytesPerSample * numSamples;
  21420. for (int i = numSamples; --i >= 0;)
  21421. {
  21422. intData -= srcBytesPerSample;
  21423. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21424. }
  21425. }
  21426. }
  21427. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21428. {
  21429. const float scale = 1.0f / 0x7fffff;
  21430. const char* intData = static_cast <const char*> (source);
  21431. if (source != (void*) dest || srcBytesPerSample >= 4)
  21432. {
  21433. for (int i = 0; i < numSamples; ++i)
  21434. {
  21435. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21436. intData += srcBytesPerSample;
  21437. }
  21438. }
  21439. else
  21440. {
  21441. intData += srcBytesPerSample * numSamples;
  21442. for (int i = numSamples; --i >= 0;)
  21443. {
  21444. intData -= srcBytesPerSample;
  21445. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21446. }
  21447. }
  21448. }
  21449. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21450. {
  21451. const float scale = 1.0f / 0x7fffff;
  21452. const char* intData = static_cast <const char*> (source);
  21453. if (source != (void*) dest || srcBytesPerSample >= 4)
  21454. {
  21455. for (int i = 0; i < numSamples; ++i)
  21456. {
  21457. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21458. intData += srcBytesPerSample;
  21459. }
  21460. }
  21461. else
  21462. {
  21463. intData += srcBytesPerSample * numSamples;
  21464. for (int i = numSamples; --i >= 0;)
  21465. {
  21466. intData -= srcBytesPerSample;
  21467. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21468. }
  21469. }
  21470. }
  21471. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21472. {
  21473. const float scale = 1.0f / 0x7fffffff;
  21474. const char* intData = static_cast <const char*> (source);
  21475. if (source != (void*) dest || srcBytesPerSample >= 4)
  21476. {
  21477. for (int i = 0; i < numSamples; ++i)
  21478. {
  21479. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21480. intData += srcBytesPerSample;
  21481. }
  21482. }
  21483. else
  21484. {
  21485. intData += srcBytesPerSample * numSamples;
  21486. for (int i = numSamples; --i >= 0;)
  21487. {
  21488. intData -= srcBytesPerSample;
  21489. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21490. }
  21491. }
  21492. }
  21493. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21494. {
  21495. const float scale = 1.0f / 0x7fffffff;
  21496. const char* intData = static_cast <const char*> (source);
  21497. if (source != (void*) dest || srcBytesPerSample >= 4)
  21498. {
  21499. for (int i = 0; i < numSamples; ++i)
  21500. {
  21501. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21502. intData += srcBytesPerSample;
  21503. }
  21504. }
  21505. else
  21506. {
  21507. intData += srcBytesPerSample * numSamples;
  21508. for (int i = numSamples; --i >= 0;)
  21509. {
  21510. intData -= srcBytesPerSample;
  21511. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21512. }
  21513. }
  21514. }
  21515. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21516. {
  21517. const char* s = static_cast <const char*> (source);
  21518. for (int i = 0; i < numSamples; ++i)
  21519. {
  21520. dest[i] = *(float*)s;
  21521. #if JUCE_BIG_ENDIAN
  21522. uint32* const d = (uint32*) (dest + i);
  21523. *d = ByteOrder::swap (*d);
  21524. #endif
  21525. s += srcBytesPerSample;
  21526. }
  21527. }
  21528. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21529. {
  21530. const char* s = static_cast <const char*> (source);
  21531. for (int i = 0; i < numSamples; ++i)
  21532. {
  21533. dest[i] = *(float*)s;
  21534. #if JUCE_LITTLE_ENDIAN
  21535. uint32* const d = (uint32*) (dest + i);
  21536. *d = ByteOrder::swap (*d);
  21537. #endif
  21538. s += srcBytesPerSample;
  21539. }
  21540. }
  21541. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21542. const float* const source,
  21543. void* const dest,
  21544. const int numSamples)
  21545. {
  21546. switch (destFormat)
  21547. {
  21548. case int16LE:
  21549. convertFloatToInt16LE (source, dest, numSamples);
  21550. break;
  21551. case int16BE:
  21552. convertFloatToInt16BE (source, dest, numSamples);
  21553. break;
  21554. case int24LE:
  21555. convertFloatToInt24LE (source, dest, numSamples);
  21556. break;
  21557. case int24BE:
  21558. convertFloatToInt24BE (source, dest, numSamples);
  21559. break;
  21560. case int32LE:
  21561. convertFloatToInt32LE (source, dest, numSamples);
  21562. break;
  21563. case int32BE:
  21564. convertFloatToInt32BE (source, dest, numSamples);
  21565. break;
  21566. case float32LE:
  21567. convertFloatToFloat32LE (source, dest, numSamples);
  21568. break;
  21569. case float32BE:
  21570. convertFloatToFloat32BE (source, dest, numSamples);
  21571. break;
  21572. default:
  21573. jassertfalse;
  21574. break;
  21575. }
  21576. }
  21577. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21578. const void* const source,
  21579. float* const dest,
  21580. const int numSamples)
  21581. {
  21582. switch (sourceFormat)
  21583. {
  21584. case int16LE:
  21585. convertInt16LEToFloat (source, dest, numSamples);
  21586. break;
  21587. case int16BE:
  21588. convertInt16BEToFloat (source, dest, numSamples);
  21589. break;
  21590. case int24LE:
  21591. convertInt24LEToFloat (source, dest, numSamples);
  21592. break;
  21593. case int24BE:
  21594. convertInt24BEToFloat (source, dest, numSamples);
  21595. break;
  21596. case int32LE:
  21597. convertInt32LEToFloat (source, dest, numSamples);
  21598. break;
  21599. case int32BE:
  21600. convertInt32BEToFloat (source, dest, numSamples);
  21601. break;
  21602. case float32LE:
  21603. convertFloat32LEToFloat (source, dest, numSamples);
  21604. break;
  21605. case float32BE:
  21606. convertFloat32BEToFloat (source, dest, numSamples);
  21607. break;
  21608. default:
  21609. jassertfalse;
  21610. break;
  21611. }
  21612. }
  21613. void AudioDataConverters::interleaveSamples (const float** const source,
  21614. float* const dest,
  21615. const int numSamples,
  21616. const int numChannels)
  21617. {
  21618. for (int chan = 0; chan < numChannels; ++chan)
  21619. {
  21620. int i = chan;
  21621. const float* src = source [chan];
  21622. for (int j = 0; j < numSamples; ++j)
  21623. {
  21624. dest [i] = src [j];
  21625. i += numChannels;
  21626. }
  21627. }
  21628. }
  21629. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21630. float** const dest,
  21631. const int numSamples,
  21632. const int numChannels)
  21633. {
  21634. for (int chan = 0; chan < numChannels; ++chan)
  21635. {
  21636. int i = chan;
  21637. float* dst = dest [chan];
  21638. for (int j = 0; j < numSamples; ++j)
  21639. {
  21640. dst [j] = source [i];
  21641. i += numChannels;
  21642. }
  21643. }
  21644. }
  21645. #if JUCE_UNIT_TESTS
  21646. class AudioConversionTests : public UnitTest
  21647. {
  21648. public:
  21649. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21650. template <class F1, class E1, class F2, class E2>
  21651. struct Test5
  21652. {
  21653. static void test (UnitTest& unitTest)
  21654. {
  21655. test (unitTest, false);
  21656. test (unitTest, true);
  21657. }
  21658. static void test (UnitTest& unitTest, bool inPlace)
  21659. {
  21660. const int numSamples = 2048;
  21661. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21662. {
  21663. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21664. bool clippingFailed = false;
  21665. for (int i = 0; i < numSamples / 2; ++i)
  21666. {
  21667. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21668. if (! d.isFloatingPoint())
  21669. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21670. ++d;
  21671. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21672. ++d;
  21673. }
  21674. unitTest.expect (! clippingFailed);
  21675. }
  21676. // convert data from the source to dest format..
  21677. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21678. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21679. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21680. // ..and back again..
  21681. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21682. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21683. if (! inPlace)
  21684. zerostruct (reversed);
  21685. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21686. {
  21687. int biggestDiff = 0;
  21688. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21689. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21690. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21691. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21692. for (int i = 0; i < numSamples; ++i)
  21693. {
  21694. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21695. ++d1;
  21696. ++d2;
  21697. }
  21698. unitTest.expect (biggestDiff <= errorMargin);
  21699. }
  21700. }
  21701. };
  21702. template <class F1, class E1, class FormatType>
  21703. struct Test3
  21704. {
  21705. static void test (UnitTest& unitTest)
  21706. {
  21707. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21708. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21709. }
  21710. };
  21711. template <class FormatType, class Endianness>
  21712. struct Test2
  21713. {
  21714. static void test (UnitTest& unitTest)
  21715. {
  21716. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21717. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21718. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21719. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21720. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21721. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21722. }
  21723. };
  21724. template <class FormatType>
  21725. struct Test1
  21726. {
  21727. static void test (UnitTest& unitTest)
  21728. {
  21729. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21730. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21731. }
  21732. };
  21733. void runTest()
  21734. {
  21735. beginTest ("Round-trip conversion");
  21736. Test1 <AudioData::Int8>::test (*this);
  21737. Test1 <AudioData::Int16>::test (*this);
  21738. Test1 <AudioData::Int24>::test (*this);
  21739. Test1 <AudioData::Int32>::test (*this);
  21740. Test1 <AudioData::Float32>::test (*this);
  21741. }
  21742. };
  21743. static AudioConversionTests audioConversionUnitTests;
  21744. #endif
  21745. END_JUCE_NAMESPACE
  21746. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21747. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21748. BEGIN_JUCE_NAMESPACE
  21749. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21750. const int numSamples) throw()
  21751. : numChannels (numChannels_),
  21752. size (numSamples)
  21753. {
  21754. jassert (numSamples >= 0);
  21755. jassert (numChannels_ > 0);
  21756. allocateData();
  21757. }
  21758. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21759. : numChannels (other.numChannels),
  21760. size (other.size)
  21761. {
  21762. allocateData();
  21763. const size_t numBytes = size * sizeof (float);
  21764. for (int i = 0; i < numChannels; ++i)
  21765. memcpy (channels[i], other.channels[i], numBytes);
  21766. }
  21767. void AudioSampleBuffer::allocateData()
  21768. {
  21769. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21770. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21771. allocatedData.malloc (allocatedBytes);
  21772. channels = reinterpret_cast <float**> (allocatedData.getData());
  21773. float* chan = (float*) (allocatedData + channelListSize);
  21774. for (int i = 0; i < numChannels; ++i)
  21775. {
  21776. channels[i] = chan;
  21777. chan += size;
  21778. }
  21779. channels [numChannels] = 0;
  21780. }
  21781. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21782. const int numChannels_,
  21783. const int numSamples) throw()
  21784. : numChannels (numChannels_),
  21785. size (numSamples),
  21786. allocatedBytes (0)
  21787. {
  21788. jassert (numChannels_ > 0);
  21789. allocateChannels (dataToReferTo);
  21790. }
  21791. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21792. const int newNumChannels,
  21793. const int newNumSamples) throw()
  21794. {
  21795. jassert (newNumChannels > 0);
  21796. allocatedBytes = 0;
  21797. allocatedData.free();
  21798. numChannels = newNumChannels;
  21799. size = newNumSamples;
  21800. allocateChannels (dataToReferTo);
  21801. }
  21802. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21803. {
  21804. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21805. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21806. {
  21807. channels = static_cast <float**> (preallocatedChannelSpace);
  21808. }
  21809. else
  21810. {
  21811. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21812. channels = reinterpret_cast <float**> (allocatedData.getData());
  21813. }
  21814. for (int i = 0; i < numChannels; ++i)
  21815. {
  21816. // you have to pass in the same number of valid pointers as numChannels
  21817. jassert (dataToReferTo[i] != 0);
  21818. channels[i] = dataToReferTo[i];
  21819. }
  21820. channels [numChannels] = 0;
  21821. }
  21822. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21823. {
  21824. if (this != &other)
  21825. {
  21826. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21827. const size_t numBytes = size * sizeof (float);
  21828. for (int i = 0; i < numChannels; ++i)
  21829. memcpy (channels[i], other.channels[i], numBytes);
  21830. }
  21831. return *this;
  21832. }
  21833. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21834. {
  21835. }
  21836. void AudioSampleBuffer::setSize (const int newNumChannels,
  21837. const int newNumSamples,
  21838. const bool keepExistingContent,
  21839. const bool clearExtraSpace,
  21840. const bool avoidReallocating) throw()
  21841. {
  21842. jassert (newNumChannels > 0);
  21843. if (newNumSamples != size || newNumChannels != numChannels)
  21844. {
  21845. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21846. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21847. if (keepExistingContent)
  21848. {
  21849. HeapBlock <char> newData;
  21850. newData.allocate (newTotalBytes, clearExtraSpace);
  21851. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21852. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21853. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21854. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21855. for (int i = 0; i < numChansToCopy; ++i)
  21856. {
  21857. memcpy (newChan, channels[i], numBytesToCopy);
  21858. newChannels[i] = newChan;
  21859. newChan += newNumSamples;
  21860. }
  21861. allocatedData.swapWith (newData);
  21862. allocatedBytes = (int) newTotalBytes;
  21863. channels = newChannels;
  21864. }
  21865. else
  21866. {
  21867. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21868. {
  21869. if (clearExtraSpace)
  21870. zeromem (allocatedData, newTotalBytes);
  21871. }
  21872. else
  21873. {
  21874. allocatedBytes = newTotalBytes;
  21875. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21876. channels = reinterpret_cast <float**> (allocatedData.getData());
  21877. }
  21878. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21879. for (int i = 0; i < newNumChannels; ++i)
  21880. {
  21881. channels[i] = chan;
  21882. chan += newNumSamples;
  21883. }
  21884. }
  21885. channels [newNumChannels] = 0;
  21886. size = newNumSamples;
  21887. numChannels = newNumChannels;
  21888. }
  21889. }
  21890. void AudioSampleBuffer::clear() throw()
  21891. {
  21892. for (int i = 0; i < numChannels; ++i)
  21893. zeromem (channels[i], size * sizeof (float));
  21894. }
  21895. void AudioSampleBuffer::clear (const int startSample,
  21896. const int numSamples) throw()
  21897. {
  21898. jassert (startSample >= 0 && startSample + numSamples <= size);
  21899. for (int i = 0; i < numChannels; ++i)
  21900. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21901. }
  21902. void AudioSampleBuffer::clear (const int channel,
  21903. const int startSample,
  21904. const int numSamples) throw()
  21905. {
  21906. jassert (isPositiveAndBelow (channel, numChannels));
  21907. jassert (startSample >= 0 && startSample + numSamples <= size);
  21908. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21909. }
  21910. void AudioSampleBuffer::applyGain (const int channel,
  21911. const int startSample,
  21912. int numSamples,
  21913. const float gain) throw()
  21914. {
  21915. jassert (isPositiveAndBelow (channel, numChannels));
  21916. jassert (startSample >= 0 && startSample + numSamples <= size);
  21917. if (gain != 1.0f)
  21918. {
  21919. float* d = channels [channel] + startSample;
  21920. if (gain == 0.0f)
  21921. {
  21922. zeromem (d, sizeof (float) * numSamples);
  21923. }
  21924. else
  21925. {
  21926. while (--numSamples >= 0)
  21927. *d++ *= gain;
  21928. }
  21929. }
  21930. }
  21931. void AudioSampleBuffer::applyGainRamp (const int channel,
  21932. const int startSample,
  21933. int numSamples,
  21934. float startGain,
  21935. float endGain) throw()
  21936. {
  21937. if (startGain == endGain)
  21938. {
  21939. applyGain (channel, startSample, numSamples, startGain);
  21940. }
  21941. else
  21942. {
  21943. jassert (isPositiveAndBelow (channel, numChannels));
  21944. jassert (startSample >= 0 && startSample + numSamples <= size);
  21945. const float increment = (endGain - startGain) / numSamples;
  21946. float* d = channels [channel] + startSample;
  21947. while (--numSamples >= 0)
  21948. {
  21949. *d++ *= startGain;
  21950. startGain += increment;
  21951. }
  21952. }
  21953. }
  21954. void AudioSampleBuffer::applyGain (const int startSample,
  21955. const int numSamples,
  21956. const float gain) throw()
  21957. {
  21958. for (int i = 0; i < numChannels; ++i)
  21959. applyGain (i, startSample, numSamples, gain);
  21960. }
  21961. void AudioSampleBuffer::addFrom (const int destChannel,
  21962. const int destStartSample,
  21963. const AudioSampleBuffer& source,
  21964. const int sourceChannel,
  21965. const int sourceStartSample,
  21966. int numSamples,
  21967. const float gain) throw()
  21968. {
  21969. jassert (&source != this || sourceChannel != destChannel);
  21970. jassert (isPositiveAndBelow (destChannel, numChannels));
  21971. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21972. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21973. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21974. if (gain != 0.0f && numSamples > 0)
  21975. {
  21976. float* d = channels [destChannel] + destStartSample;
  21977. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21978. if (gain != 1.0f)
  21979. {
  21980. while (--numSamples >= 0)
  21981. *d++ += gain * *s++;
  21982. }
  21983. else
  21984. {
  21985. while (--numSamples >= 0)
  21986. *d++ += *s++;
  21987. }
  21988. }
  21989. }
  21990. void AudioSampleBuffer::addFrom (const int destChannel,
  21991. const int destStartSample,
  21992. const float* source,
  21993. int numSamples,
  21994. const float gain) throw()
  21995. {
  21996. jassert (isPositiveAndBelow (destChannel, numChannels));
  21997. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21998. jassert (source != 0);
  21999. if (gain != 0.0f && numSamples > 0)
  22000. {
  22001. float* d = channels [destChannel] + destStartSample;
  22002. if (gain != 1.0f)
  22003. {
  22004. while (--numSamples >= 0)
  22005. *d++ += gain * *source++;
  22006. }
  22007. else
  22008. {
  22009. while (--numSamples >= 0)
  22010. *d++ += *source++;
  22011. }
  22012. }
  22013. }
  22014. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  22015. const int destStartSample,
  22016. const float* source,
  22017. int numSamples,
  22018. float startGain,
  22019. const float endGain) throw()
  22020. {
  22021. jassert (isPositiveAndBelow (destChannel, numChannels));
  22022. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22023. jassert (source != 0);
  22024. if (startGain == endGain)
  22025. {
  22026. addFrom (destChannel,
  22027. destStartSample,
  22028. source,
  22029. numSamples,
  22030. startGain);
  22031. }
  22032. else
  22033. {
  22034. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22035. {
  22036. const float increment = (endGain - startGain) / numSamples;
  22037. float* d = channels [destChannel] + destStartSample;
  22038. while (--numSamples >= 0)
  22039. {
  22040. *d++ += startGain * *source++;
  22041. startGain += increment;
  22042. }
  22043. }
  22044. }
  22045. }
  22046. void AudioSampleBuffer::copyFrom (const int destChannel,
  22047. const int destStartSample,
  22048. const AudioSampleBuffer& source,
  22049. const int sourceChannel,
  22050. const int sourceStartSample,
  22051. int numSamples) throw()
  22052. {
  22053. jassert (&source != this || sourceChannel != destChannel);
  22054. jassert (isPositiveAndBelow (destChannel, numChannels));
  22055. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22056. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  22057. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  22058. if (numSamples > 0)
  22059. {
  22060. memcpy (channels [destChannel] + destStartSample,
  22061. source.channels [sourceChannel] + sourceStartSample,
  22062. sizeof (float) * numSamples);
  22063. }
  22064. }
  22065. void AudioSampleBuffer::copyFrom (const int destChannel,
  22066. const int destStartSample,
  22067. const float* source,
  22068. int numSamples) throw()
  22069. {
  22070. jassert (isPositiveAndBelow (destChannel, numChannels));
  22071. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22072. jassert (source != 0);
  22073. if (numSamples > 0)
  22074. {
  22075. memcpy (channels [destChannel] + destStartSample,
  22076. source,
  22077. sizeof (float) * numSamples);
  22078. }
  22079. }
  22080. void AudioSampleBuffer::copyFrom (const int destChannel,
  22081. const int destStartSample,
  22082. const float* source,
  22083. int numSamples,
  22084. const float gain) throw()
  22085. {
  22086. jassert (isPositiveAndBelow (destChannel, numChannels));
  22087. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22088. jassert (source != 0);
  22089. if (numSamples > 0)
  22090. {
  22091. float* d = channels [destChannel] + destStartSample;
  22092. if (gain != 1.0f)
  22093. {
  22094. if (gain == 0)
  22095. {
  22096. zeromem (d, sizeof (float) * numSamples);
  22097. }
  22098. else
  22099. {
  22100. while (--numSamples >= 0)
  22101. *d++ = gain * *source++;
  22102. }
  22103. }
  22104. else
  22105. {
  22106. memcpy (d, source, sizeof (float) * numSamples);
  22107. }
  22108. }
  22109. }
  22110. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22111. const int destStartSample,
  22112. const float* source,
  22113. int numSamples,
  22114. float startGain,
  22115. float endGain) throw()
  22116. {
  22117. jassert (isPositiveAndBelow (destChannel, numChannels));
  22118. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22119. jassert (source != 0);
  22120. if (startGain == endGain)
  22121. {
  22122. copyFrom (destChannel,
  22123. destStartSample,
  22124. source,
  22125. numSamples,
  22126. startGain);
  22127. }
  22128. else
  22129. {
  22130. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22131. {
  22132. const float increment = (endGain - startGain) / numSamples;
  22133. float* d = channels [destChannel] + destStartSample;
  22134. while (--numSamples >= 0)
  22135. {
  22136. *d++ = startGain * *source++;
  22137. startGain += increment;
  22138. }
  22139. }
  22140. }
  22141. }
  22142. void AudioSampleBuffer::findMinMax (const int channel,
  22143. const int startSample,
  22144. int numSamples,
  22145. float& minVal,
  22146. float& maxVal) const throw()
  22147. {
  22148. jassert (isPositiveAndBelow (channel, numChannels));
  22149. jassert (startSample >= 0 && startSample + numSamples <= size);
  22150. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  22151. }
  22152. float AudioSampleBuffer::getMagnitude (const int channel,
  22153. const int startSample,
  22154. const int numSamples) const throw()
  22155. {
  22156. jassert (isPositiveAndBelow (channel, numChannels));
  22157. jassert (startSample >= 0 && startSample + numSamples <= size);
  22158. float mn, mx;
  22159. findMinMax (channel, startSample, numSamples, mn, mx);
  22160. return jmax (mn, -mn, mx, -mx);
  22161. }
  22162. float AudioSampleBuffer::getMagnitude (const int startSample,
  22163. const int numSamples) const throw()
  22164. {
  22165. float mag = 0.0f;
  22166. for (int i = 0; i < numChannels; ++i)
  22167. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22168. return mag;
  22169. }
  22170. float AudioSampleBuffer::getRMSLevel (const int channel,
  22171. const int startSample,
  22172. const int numSamples) const throw()
  22173. {
  22174. jassert (isPositiveAndBelow (channel, numChannels));
  22175. jassert (startSample >= 0 && startSample + numSamples <= size);
  22176. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22177. return 0.0f;
  22178. const float* const data = channels [channel] + startSample;
  22179. double sum = 0.0;
  22180. for (int i = 0; i < numSamples; ++i)
  22181. {
  22182. const float sample = data [i];
  22183. sum += sample * sample;
  22184. }
  22185. return (float) std::sqrt (sum / numSamples);
  22186. }
  22187. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22188. const int startSample,
  22189. const int numSamples,
  22190. const int readerStartSample,
  22191. const bool useLeftChan,
  22192. const bool useRightChan)
  22193. {
  22194. jassert (reader != 0);
  22195. jassert (startSample >= 0 && startSample + numSamples <= size);
  22196. if (numSamples > 0)
  22197. {
  22198. int* chans[3];
  22199. if (useLeftChan == useRightChan)
  22200. {
  22201. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22202. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22203. }
  22204. else if (useLeftChan || (reader->numChannels == 1))
  22205. {
  22206. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22207. chans[1] = 0;
  22208. }
  22209. else if (useRightChan)
  22210. {
  22211. chans[0] = 0;
  22212. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22213. }
  22214. chans[2] = 0;
  22215. reader->read (chans, 2, readerStartSample, numSamples, true);
  22216. if (! reader->usesFloatingPointData)
  22217. {
  22218. for (int j = 0; j < 2; ++j)
  22219. {
  22220. float* const d = reinterpret_cast <float*> (chans[j]);
  22221. if (d != 0)
  22222. {
  22223. const float multiplier = 1.0f / 0x7fffffff;
  22224. for (int i = 0; i < numSamples; ++i)
  22225. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22226. }
  22227. }
  22228. }
  22229. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22230. {
  22231. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22232. memcpy (getSampleData (1, startSample),
  22233. getSampleData (0, startSample),
  22234. sizeof (float) * numSamples);
  22235. }
  22236. }
  22237. }
  22238. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22239. const int startSample,
  22240. const int numSamples) const
  22241. {
  22242. jassert (writer != 0);
  22243. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22244. }
  22245. END_JUCE_NAMESPACE
  22246. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22247. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22248. BEGIN_JUCE_NAMESPACE
  22249. IIRFilter::IIRFilter()
  22250. : active (false)
  22251. {
  22252. reset();
  22253. }
  22254. IIRFilter::IIRFilter (const IIRFilter& other)
  22255. : active (other.active)
  22256. {
  22257. const ScopedLock sl (other.processLock);
  22258. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22259. reset();
  22260. }
  22261. IIRFilter::~IIRFilter()
  22262. {
  22263. }
  22264. void IIRFilter::reset() throw()
  22265. {
  22266. const ScopedLock sl (processLock);
  22267. x1 = 0;
  22268. x2 = 0;
  22269. y1 = 0;
  22270. y2 = 0;
  22271. }
  22272. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22273. {
  22274. float out = coefficients[0] * in
  22275. + coefficients[1] * x1
  22276. + coefficients[2] * x2
  22277. - coefficients[4] * y1
  22278. - coefficients[5] * y2;
  22279. #if JUCE_INTEL
  22280. if (! (out < -1.0e-8 || out > 1.0e-8))
  22281. out = 0;
  22282. #endif
  22283. x2 = x1;
  22284. x1 = in;
  22285. y2 = y1;
  22286. y1 = out;
  22287. return out;
  22288. }
  22289. void IIRFilter::processSamples (float* const samples,
  22290. const int numSamples) throw()
  22291. {
  22292. const ScopedLock sl (processLock);
  22293. if (active)
  22294. {
  22295. for (int i = 0; i < numSamples; ++i)
  22296. {
  22297. const float in = samples[i];
  22298. float out = coefficients[0] * in
  22299. + coefficients[1] * x1
  22300. + coefficients[2] * x2
  22301. - coefficients[4] * y1
  22302. - coefficients[5] * y2;
  22303. #if JUCE_INTEL
  22304. if (! (out < -1.0e-8 || out > 1.0e-8))
  22305. out = 0;
  22306. #endif
  22307. x2 = x1;
  22308. x1 = in;
  22309. y2 = y1;
  22310. y1 = out;
  22311. samples[i] = out;
  22312. }
  22313. }
  22314. }
  22315. void IIRFilter::makeLowPass (const double sampleRate,
  22316. const double frequency) throw()
  22317. {
  22318. jassert (sampleRate > 0);
  22319. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22320. const double nSquared = n * n;
  22321. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22322. setCoefficients (c1,
  22323. c1 * 2.0f,
  22324. c1,
  22325. 1.0,
  22326. c1 * 2.0 * (1.0 - nSquared),
  22327. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22328. }
  22329. void IIRFilter::makeHighPass (const double sampleRate,
  22330. const double frequency) throw()
  22331. {
  22332. const double n = tan (double_Pi * frequency / sampleRate);
  22333. const double nSquared = n * n;
  22334. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22335. setCoefficients (c1,
  22336. c1 * -2.0f,
  22337. c1,
  22338. 1.0,
  22339. c1 * 2.0 * (nSquared - 1.0),
  22340. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22341. }
  22342. void IIRFilter::makeLowShelf (const double sampleRate,
  22343. const double cutOffFrequency,
  22344. const double Q,
  22345. const float gainFactor) throw()
  22346. {
  22347. jassert (sampleRate > 0);
  22348. jassert (Q > 0);
  22349. const double A = jmax (0.0f, gainFactor);
  22350. const double aminus1 = A - 1.0;
  22351. const double aplus1 = A + 1.0;
  22352. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22353. const double coso = std::cos (omega);
  22354. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22355. const double aminus1TimesCoso = aminus1 * coso;
  22356. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22357. A * 2.0 * (aminus1 - aplus1 * coso),
  22358. A * (aplus1 - aminus1TimesCoso - beta),
  22359. aplus1 + aminus1TimesCoso + beta,
  22360. -2.0 * (aminus1 + aplus1 * coso),
  22361. aplus1 + aminus1TimesCoso - beta);
  22362. }
  22363. void IIRFilter::makeHighShelf (const double sampleRate,
  22364. const double cutOffFrequency,
  22365. const double Q,
  22366. const float gainFactor) throw()
  22367. {
  22368. jassert (sampleRate > 0);
  22369. jassert (Q > 0);
  22370. const double A = jmax (0.0f, gainFactor);
  22371. const double aminus1 = A - 1.0;
  22372. const double aplus1 = A + 1.0;
  22373. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22374. const double coso = std::cos (omega);
  22375. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22376. const double aminus1TimesCoso = aminus1 * coso;
  22377. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22378. A * -2.0 * (aminus1 + aplus1 * coso),
  22379. A * (aplus1 + aminus1TimesCoso - beta),
  22380. aplus1 - aminus1TimesCoso + beta,
  22381. 2.0 * (aminus1 - aplus1 * coso),
  22382. aplus1 - aminus1TimesCoso - beta);
  22383. }
  22384. void IIRFilter::makeBandPass (const double sampleRate,
  22385. const double centreFrequency,
  22386. const double Q,
  22387. const float gainFactor) throw()
  22388. {
  22389. jassert (sampleRate > 0);
  22390. jassert (Q > 0);
  22391. const double A = jmax (0.0f, gainFactor);
  22392. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22393. const double alpha = 0.5 * std::sin (omega) / Q;
  22394. const double c2 = -2.0 * std::cos (omega);
  22395. const double alphaTimesA = alpha * A;
  22396. const double alphaOverA = alpha / A;
  22397. setCoefficients (1.0 + alphaTimesA,
  22398. c2,
  22399. 1.0 - alphaTimesA,
  22400. 1.0 + alphaOverA,
  22401. c2,
  22402. 1.0 - alphaOverA);
  22403. }
  22404. void IIRFilter::makeInactive() throw()
  22405. {
  22406. const ScopedLock sl (processLock);
  22407. active = false;
  22408. }
  22409. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22410. {
  22411. const ScopedLock sl (processLock);
  22412. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22413. active = other.active;
  22414. }
  22415. void IIRFilter::setCoefficients (double c1,
  22416. double c2,
  22417. double c3,
  22418. double c4,
  22419. double c5,
  22420. double c6) throw()
  22421. {
  22422. const double a = 1.0 / c4;
  22423. c1 *= a;
  22424. c2 *= a;
  22425. c3 *= a;
  22426. c5 *= a;
  22427. c6 *= a;
  22428. const ScopedLock sl (processLock);
  22429. coefficients[0] = (float) c1;
  22430. coefficients[1] = (float) c2;
  22431. coefficients[2] = (float) c3;
  22432. coefficients[3] = (float) c4;
  22433. coefficients[4] = (float) c5;
  22434. coefficients[5] = (float) c6;
  22435. active = true;
  22436. }
  22437. END_JUCE_NAMESPACE
  22438. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22439. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22440. BEGIN_JUCE_NAMESPACE
  22441. MidiBuffer::MidiBuffer() throw()
  22442. : bytesUsed (0)
  22443. {
  22444. }
  22445. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22446. : bytesUsed (0)
  22447. {
  22448. addEvent (message, 0);
  22449. }
  22450. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22451. : data (other.data),
  22452. bytesUsed (other.bytesUsed)
  22453. {
  22454. }
  22455. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22456. {
  22457. bytesUsed = other.bytesUsed;
  22458. data = other.data;
  22459. return *this;
  22460. }
  22461. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22462. {
  22463. data.swapWith (other.data);
  22464. swapVariables <int> (bytesUsed, other.bytesUsed);
  22465. }
  22466. MidiBuffer::~MidiBuffer()
  22467. {
  22468. }
  22469. inline uint8* MidiBuffer::getData() const throw()
  22470. {
  22471. return static_cast <uint8*> (data.getData());
  22472. }
  22473. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22474. {
  22475. return *static_cast <const int*> (d);
  22476. }
  22477. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22478. {
  22479. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22480. }
  22481. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22482. {
  22483. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22484. }
  22485. void MidiBuffer::clear() throw()
  22486. {
  22487. bytesUsed = 0;
  22488. }
  22489. void MidiBuffer::clear (const int startSample, const int numSamples)
  22490. {
  22491. uint8* const start = findEventAfter (getData(), startSample - 1);
  22492. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22493. if (end > start)
  22494. {
  22495. const int bytesToMove = bytesUsed - (int) (end - getData());
  22496. if (bytesToMove > 0)
  22497. memmove (start, end, bytesToMove);
  22498. bytesUsed -= (int) (end - start);
  22499. }
  22500. }
  22501. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22502. {
  22503. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22504. }
  22505. namespace MidiBufferHelpers
  22506. {
  22507. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22508. {
  22509. unsigned int byte = (unsigned int) *data;
  22510. int size = 0;
  22511. if (byte == 0xf0 || byte == 0xf7)
  22512. {
  22513. const uint8* d = data + 1;
  22514. while (d < data + maxBytes)
  22515. if (*d++ == 0xf7)
  22516. break;
  22517. size = (int) (d - data);
  22518. }
  22519. else if (byte == 0xff)
  22520. {
  22521. int n;
  22522. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22523. size = jmin (maxBytes, n + 2 + bytesLeft);
  22524. }
  22525. else if (byte >= 0x80)
  22526. {
  22527. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22528. }
  22529. return size;
  22530. }
  22531. }
  22532. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22533. {
  22534. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22535. if (numBytes > 0)
  22536. {
  22537. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22538. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22539. uint8* d = findEventAfter (getData(), sampleNumber);
  22540. const int bytesToMove = bytesUsed - (int) (d - getData());
  22541. if (bytesToMove > 0)
  22542. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22543. *reinterpret_cast <int*> (d) = sampleNumber;
  22544. d += sizeof (int);
  22545. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22546. d += sizeof (uint16);
  22547. memcpy (d, newData, numBytes);
  22548. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22549. }
  22550. }
  22551. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22552. const int startSample,
  22553. const int numSamples,
  22554. const int sampleDeltaToAdd)
  22555. {
  22556. Iterator i (otherBuffer);
  22557. i.setNextSamplePosition (startSample);
  22558. const uint8* eventData;
  22559. int eventSize, position;
  22560. while (i.getNextEvent (eventData, eventSize, position)
  22561. && (position < startSample + numSamples || numSamples < 0))
  22562. {
  22563. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22564. }
  22565. }
  22566. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22567. {
  22568. data.ensureSize (minimumNumBytes);
  22569. }
  22570. bool MidiBuffer::isEmpty() const throw()
  22571. {
  22572. return bytesUsed == 0;
  22573. }
  22574. int MidiBuffer::getNumEvents() const throw()
  22575. {
  22576. int n = 0;
  22577. const uint8* d = getData();
  22578. const uint8* const end = d + bytesUsed;
  22579. while (d < end)
  22580. {
  22581. d += getEventTotalSize (d);
  22582. ++n;
  22583. }
  22584. return n;
  22585. }
  22586. int MidiBuffer::getFirstEventTime() const throw()
  22587. {
  22588. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22589. }
  22590. int MidiBuffer::getLastEventTime() const throw()
  22591. {
  22592. if (bytesUsed == 0)
  22593. return 0;
  22594. const uint8* d = getData();
  22595. const uint8* const endData = d + bytesUsed;
  22596. for (;;)
  22597. {
  22598. const uint8* const nextOne = d + getEventTotalSize (d);
  22599. if (nextOne >= endData)
  22600. return getEventTime (d);
  22601. d = nextOne;
  22602. }
  22603. }
  22604. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22605. {
  22606. const uint8* const endData = getData() + bytesUsed;
  22607. while (d < endData && getEventTime (d) <= samplePosition)
  22608. d += getEventTotalSize (d);
  22609. return d;
  22610. }
  22611. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22612. : buffer (buffer_),
  22613. data (buffer_.getData())
  22614. {
  22615. }
  22616. MidiBuffer::Iterator::~Iterator() throw()
  22617. {
  22618. }
  22619. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22620. {
  22621. data = buffer.getData();
  22622. const uint8* dataEnd = data + buffer.bytesUsed;
  22623. while (data < dataEnd && getEventTime (data) < samplePosition)
  22624. data += getEventTotalSize (data);
  22625. }
  22626. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22627. {
  22628. if (data >= buffer.getData() + buffer.bytesUsed)
  22629. return false;
  22630. samplePosition = getEventTime (data);
  22631. numBytes = getEventDataSize (data);
  22632. data += sizeof (int) + sizeof (uint16);
  22633. midiData = data;
  22634. data += numBytes;
  22635. return true;
  22636. }
  22637. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22638. {
  22639. if (data >= buffer.getData() + buffer.bytesUsed)
  22640. return false;
  22641. samplePosition = getEventTime (data);
  22642. const int numBytes = getEventDataSize (data);
  22643. data += sizeof (int) + sizeof (uint16);
  22644. result = MidiMessage (data, numBytes, samplePosition);
  22645. data += numBytes;
  22646. return true;
  22647. }
  22648. END_JUCE_NAMESPACE
  22649. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22650. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22651. BEGIN_JUCE_NAMESPACE
  22652. namespace MidiFileHelpers
  22653. {
  22654. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22655. {
  22656. unsigned int buffer = v & 0x7F;
  22657. while ((v >>= 7) != 0)
  22658. {
  22659. buffer <<= 8;
  22660. buffer |= ((v & 0x7F) | 0x80);
  22661. }
  22662. for (;;)
  22663. {
  22664. out.writeByte ((char) buffer);
  22665. if (buffer & 0x80)
  22666. buffer >>= 8;
  22667. else
  22668. break;
  22669. }
  22670. }
  22671. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22672. {
  22673. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22674. data += 4;
  22675. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22676. {
  22677. bool ok = false;
  22678. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22679. {
  22680. for (int i = 0; i < 8; ++i)
  22681. {
  22682. ch = ByteOrder::bigEndianInt (data);
  22683. data += 4;
  22684. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22685. {
  22686. ok = true;
  22687. break;
  22688. }
  22689. }
  22690. }
  22691. if (! ok)
  22692. return false;
  22693. }
  22694. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22695. data += 4;
  22696. fileType = (short) ByteOrder::bigEndianShort (data);
  22697. data += 2;
  22698. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22699. data += 2;
  22700. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22701. data += 2;
  22702. bytesRemaining -= 6;
  22703. data += bytesRemaining;
  22704. return true;
  22705. }
  22706. double convertTicksToSeconds (const double time,
  22707. const MidiMessageSequence& tempoEvents,
  22708. const int timeFormat)
  22709. {
  22710. if (timeFormat > 0)
  22711. {
  22712. int numer = 4, denom = 4;
  22713. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22714. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22715. double secsPerTick = 0.5 * tickLen;
  22716. const int numEvents = tempoEvents.getNumEvents();
  22717. for (int i = 0; i < numEvents; ++i)
  22718. {
  22719. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22720. if (time <= m.getTimeStamp())
  22721. break;
  22722. if (timeFormat > 0)
  22723. {
  22724. correctedTempoTime = correctedTempoTime
  22725. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22726. }
  22727. else
  22728. {
  22729. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22730. }
  22731. tempoTime = m.getTimeStamp();
  22732. if (m.isTempoMetaEvent())
  22733. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22734. else if (m.isTimeSignatureMetaEvent())
  22735. m.getTimeSignatureInfo (numer, denom);
  22736. while (i + 1 < numEvents)
  22737. {
  22738. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22739. if (m2.getTimeStamp() == tempoTime)
  22740. {
  22741. ++i;
  22742. if (m2.isTempoMetaEvent())
  22743. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22744. else if (m2.isTimeSignatureMetaEvent())
  22745. m2.getTimeSignatureInfo (numer, denom);
  22746. }
  22747. else
  22748. {
  22749. break;
  22750. }
  22751. }
  22752. }
  22753. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22754. }
  22755. else
  22756. {
  22757. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22758. }
  22759. }
  22760. // a comparator that puts all the note-offs before note-ons that have the same time
  22761. struct Sorter
  22762. {
  22763. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22764. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22765. {
  22766. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22767. if (diff == 0)
  22768. {
  22769. if (first->message.isNoteOff() && second->message.isNoteOn())
  22770. return -1;
  22771. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22772. return 1;
  22773. else
  22774. return 0;
  22775. }
  22776. else
  22777. {
  22778. return (diff > 0) ? 1 : -1;
  22779. }
  22780. }
  22781. };
  22782. }
  22783. MidiFile::MidiFile()
  22784. : timeFormat ((short) (unsigned short) 0xe728)
  22785. {
  22786. }
  22787. MidiFile::~MidiFile()
  22788. {
  22789. clear();
  22790. }
  22791. void MidiFile::clear()
  22792. {
  22793. tracks.clear();
  22794. }
  22795. int MidiFile::getNumTracks() const throw()
  22796. {
  22797. return tracks.size();
  22798. }
  22799. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22800. {
  22801. return tracks [index];
  22802. }
  22803. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22804. {
  22805. tracks.add (new MidiMessageSequence (trackSequence));
  22806. }
  22807. short MidiFile::getTimeFormat() const throw()
  22808. {
  22809. return timeFormat;
  22810. }
  22811. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22812. {
  22813. timeFormat = (short) ticks;
  22814. }
  22815. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22816. const int subframeResolution) throw()
  22817. {
  22818. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22819. }
  22820. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22821. {
  22822. for (int i = tracks.size(); --i >= 0;)
  22823. {
  22824. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22825. for (int j = 0; j < numEvents; ++j)
  22826. {
  22827. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22828. if (m.isTempoMetaEvent())
  22829. tempoChangeEvents.addEvent (m);
  22830. }
  22831. }
  22832. }
  22833. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22834. {
  22835. for (int i = tracks.size(); --i >= 0;)
  22836. {
  22837. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22838. for (int j = 0; j < numEvents; ++j)
  22839. {
  22840. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22841. if (m.isTimeSignatureMetaEvent())
  22842. timeSigEvents.addEvent (m);
  22843. }
  22844. }
  22845. }
  22846. double MidiFile::getLastTimestamp() const
  22847. {
  22848. double t = 0.0;
  22849. for (int i = tracks.size(); --i >= 0;)
  22850. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22851. return t;
  22852. }
  22853. bool MidiFile::readFrom (InputStream& sourceStream)
  22854. {
  22855. clear();
  22856. MemoryBlock data;
  22857. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22858. // (put a sanity-check on the file size, as midi files are generally small)
  22859. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22860. {
  22861. size_t size = data.getSize();
  22862. const uint8* d = static_cast <const uint8*> (data.getData());
  22863. short fileType, expectedTracks;
  22864. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22865. {
  22866. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22867. int track = 0;
  22868. while (size > 0 && track < expectedTracks)
  22869. {
  22870. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22871. d += 4;
  22872. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22873. d += 4;
  22874. if (chunkSize <= 0)
  22875. break;
  22876. if (size < 0)
  22877. return false;
  22878. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22879. {
  22880. readNextTrack (d, chunkSize);
  22881. }
  22882. size -= chunkSize + 8;
  22883. d += chunkSize;
  22884. ++track;
  22885. }
  22886. return true;
  22887. }
  22888. }
  22889. return false;
  22890. }
  22891. void MidiFile::readNextTrack (const uint8* data, int size)
  22892. {
  22893. double time = 0;
  22894. char lastStatusByte = 0;
  22895. MidiMessageSequence result;
  22896. while (size > 0)
  22897. {
  22898. int bytesUsed;
  22899. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22900. data += bytesUsed;
  22901. size -= bytesUsed;
  22902. time += delay;
  22903. int messSize = 0;
  22904. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22905. if (messSize <= 0)
  22906. break;
  22907. size -= messSize;
  22908. data += messSize;
  22909. result.addEvent (mm);
  22910. const char firstByte = *(mm.getRawData());
  22911. if ((firstByte & 0xf0) != 0xf0)
  22912. lastStatusByte = firstByte;
  22913. }
  22914. // use a sort that puts all the note-offs before note-ons that have the same time
  22915. MidiFileHelpers::Sorter sorter;
  22916. result.list.sort (sorter, true);
  22917. result.updateMatchedPairs();
  22918. addTrack (result);
  22919. }
  22920. void MidiFile::convertTimestampTicksToSeconds()
  22921. {
  22922. MidiMessageSequence tempoEvents;
  22923. findAllTempoEvents (tempoEvents);
  22924. findAllTimeSigEvents (tempoEvents);
  22925. for (int i = 0; i < tracks.size(); ++i)
  22926. {
  22927. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22928. for (int j = ms.getNumEvents(); --j >= 0;)
  22929. {
  22930. MidiMessage& m = ms.getEventPointer(j)->message;
  22931. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22932. tempoEvents,
  22933. timeFormat));
  22934. }
  22935. }
  22936. }
  22937. bool MidiFile::writeTo (OutputStream& out)
  22938. {
  22939. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22940. out.writeIntBigEndian (6);
  22941. out.writeShortBigEndian (1); // type
  22942. out.writeShortBigEndian ((short) tracks.size());
  22943. out.writeShortBigEndian (timeFormat);
  22944. for (int i = 0; i < tracks.size(); ++i)
  22945. writeTrack (out, i);
  22946. out.flush();
  22947. return true;
  22948. }
  22949. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22950. {
  22951. MemoryOutputStream out;
  22952. const MidiMessageSequence& ms = *tracks[trackNum];
  22953. int lastTick = 0;
  22954. char lastStatusByte = 0;
  22955. for (int i = 0; i < ms.getNumEvents(); ++i)
  22956. {
  22957. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22958. const int tick = roundToInt (mm.getTimeStamp());
  22959. const int delta = jmax (0, tick - lastTick);
  22960. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22961. lastTick = tick;
  22962. const char statusByte = *(mm.getRawData());
  22963. if ((statusByte == lastStatusByte)
  22964. && ((statusByte & 0xf0) != 0xf0)
  22965. && i > 0
  22966. && mm.getRawDataSize() > 1)
  22967. {
  22968. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22969. }
  22970. else
  22971. {
  22972. out.write (mm.getRawData(), mm.getRawDataSize());
  22973. }
  22974. lastStatusByte = statusByte;
  22975. }
  22976. out.writeByte (0);
  22977. const MidiMessage m (MidiMessage::endOfTrack());
  22978. out.write (m.getRawData(),
  22979. m.getRawDataSize());
  22980. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22981. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22982. mainOut.write (out.getData(), (int) out.getDataSize());
  22983. }
  22984. END_JUCE_NAMESPACE
  22985. /*** End of inlined file: juce_MidiFile.cpp ***/
  22986. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22987. BEGIN_JUCE_NAMESPACE
  22988. MidiKeyboardState::MidiKeyboardState()
  22989. {
  22990. zerostruct (noteStates);
  22991. }
  22992. MidiKeyboardState::~MidiKeyboardState()
  22993. {
  22994. }
  22995. void MidiKeyboardState::reset()
  22996. {
  22997. const ScopedLock sl (lock);
  22998. zerostruct (noteStates);
  22999. eventsToAdd.clear();
  23000. }
  23001. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  23002. {
  23003. jassert (midiChannel >= 0 && midiChannel <= 16);
  23004. return isPositiveAndBelow (n, (int) 128)
  23005. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  23006. }
  23007. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  23008. {
  23009. return isPositiveAndBelow (n, (int) 128)
  23010. && (noteStates[n] & midiChannelMask) != 0;
  23011. }
  23012. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  23013. {
  23014. jassert (midiChannel >= 0 && midiChannel <= 16);
  23015. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  23016. const ScopedLock sl (lock);
  23017. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  23018. {
  23019. const int timeNow = (int) Time::getMillisecondCounter();
  23020. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  23021. eventsToAdd.clear (0, timeNow - 500);
  23022. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  23023. }
  23024. }
  23025. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  23026. {
  23027. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  23028. {
  23029. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  23030. for (int i = listeners.size(); --i >= 0;)
  23031. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  23032. }
  23033. }
  23034. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  23035. {
  23036. const ScopedLock sl (lock);
  23037. if (isNoteOn (midiChannel, midiNoteNumber))
  23038. {
  23039. const int timeNow = (int) Time::getMillisecondCounter();
  23040. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  23041. eventsToAdd.clear (0, timeNow - 500);
  23042. noteOffInternal (midiChannel, midiNoteNumber);
  23043. }
  23044. }
  23045. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  23046. {
  23047. if (isNoteOn (midiChannel, midiNoteNumber))
  23048. {
  23049. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  23050. for (int i = listeners.size(); --i >= 0;)
  23051. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  23052. }
  23053. }
  23054. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23055. {
  23056. const ScopedLock sl (lock);
  23057. if (midiChannel <= 0)
  23058. {
  23059. for (int i = 1; i <= 16; ++i)
  23060. allNotesOff (i);
  23061. }
  23062. else
  23063. {
  23064. for (int i = 0; i < 128; ++i)
  23065. noteOff (midiChannel, i);
  23066. }
  23067. }
  23068. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23069. {
  23070. if (message.isNoteOn())
  23071. {
  23072. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23073. }
  23074. else if (message.isNoteOff())
  23075. {
  23076. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23077. }
  23078. else if (message.isAllNotesOff())
  23079. {
  23080. for (int i = 0; i < 128; ++i)
  23081. noteOffInternal (message.getChannel(), i);
  23082. }
  23083. }
  23084. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23085. const int startSample,
  23086. const int numSamples,
  23087. const bool injectIndirectEvents)
  23088. {
  23089. MidiBuffer::Iterator i (buffer);
  23090. MidiMessage message (0xf4, 0.0);
  23091. int time;
  23092. const ScopedLock sl (lock);
  23093. while (i.getNextEvent (message, time))
  23094. processNextMidiEvent (message);
  23095. if (injectIndirectEvents)
  23096. {
  23097. MidiBuffer::Iterator i2 (eventsToAdd);
  23098. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23099. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23100. while (i2.getNextEvent (message, time))
  23101. {
  23102. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23103. buffer.addEvent (message, startSample + pos);
  23104. }
  23105. }
  23106. eventsToAdd.clear();
  23107. }
  23108. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23109. {
  23110. const ScopedLock sl (lock);
  23111. listeners.addIfNotAlreadyThere (listener);
  23112. }
  23113. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23114. {
  23115. const ScopedLock sl (lock);
  23116. listeners.removeValue (listener);
  23117. }
  23118. END_JUCE_NAMESPACE
  23119. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23120. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23121. BEGIN_JUCE_NAMESPACE
  23122. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23123. {
  23124. numBytesUsed = 0;
  23125. int v = 0;
  23126. int i;
  23127. do
  23128. {
  23129. i = (int) *data++;
  23130. if (++numBytesUsed > 6)
  23131. break;
  23132. v = (v << 7) + (i & 0x7f);
  23133. } while (i & 0x80);
  23134. return v;
  23135. }
  23136. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23137. {
  23138. // this method only works for valid starting bytes of a short midi message
  23139. jassert (firstByte >= 0x80
  23140. && firstByte != 0xf0
  23141. && firstByte != 0xf7);
  23142. static const char messageLengths[] =
  23143. {
  23144. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23145. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23146. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23147. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23148. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23149. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23150. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23151. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23152. };
  23153. return messageLengths [firstByte & 0x7f];
  23154. }
  23155. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23156. : timeStamp (t),
  23157. size (dataSize)
  23158. {
  23159. jassert (dataSize > 0);
  23160. if (dataSize <= 4)
  23161. data = static_cast<uint8*> (preallocatedData.asBytes);
  23162. else
  23163. data = new uint8 [dataSize];
  23164. memcpy (data, d, dataSize);
  23165. // check that the length matches the data..
  23166. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23167. }
  23168. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23169. : timeStamp (t),
  23170. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23171. size (1)
  23172. {
  23173. data[0] = (uint8) byte1;
  23174. // check that the length matches the data..
  23175. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23176. }
  23177. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23178. : timeStamp (t),
  23179. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23180. size (2)
  23181. {
  23182. data[0] = (uint8) byte1;
  23183. data[1] = (uint8) byte2;
  23184. // check that the length matches the data..
  23185. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23186. }
  23187. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23188. : timeStamp (t),
  23189. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23190. size (3)
  23191. {
  23192. data[0] = (uint8) byte1;
  23193. data[1] = (uint8) byte2;
  23194. data[2] = (uint8) byte3;
  23195. // check that the length matches the data..
  23196. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23197. }
  23198. MidiMessage::MidiMessage (const MidiMessage& other)
  23199. : timeStamp (other.timeStamp),
  23200. size (other.size)
  23201. {
  23202. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23203. {
  23204. data = new uint8 [size];
  23205. memcpy (data, other.data, size);
  23206. }
  23207. else
  23208. {
  23209. data = static_cast<uint8*> (preallocatedData.asBytes);
  23210. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23211. }
  23212. }
  23213. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23214. : timeStamp (newTimeStamp),
  23215. size (other.size)
  23216. {
  23217. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23218. {
  23219. data = new uint8 [size];
  23220. memcpy (data, other.data, size);
  23221. }
  23222. else
  23223. {
  23224. data = static_cast<uint8*> (preallocatedData.asBytes);
  23225. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23226. }
  23227. }
  23228. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23229. : timeStamp (t),
  23230. data (static_cast<uint8*> (preallocatedData.asBytes))
  23231. {
  23232. const uint8* src = static_cast <const uint8*> (src_);
  23233. unsigned int byte = (unsigned int) *src;
  23234. if (byte < 0x80)
  23235. {
  23236. byte = (unsigned int) (uint8) lastStatusByte;
  23237. numBytesUsed = -1;
  23238. }
  23239. else
  23240. {
  23241. numBytesUsed = 0;
  23242. --sz;
  23243. ++src;
  23244. }
  23245. if (byte >= 0x80)
  23246. {
  23247. if (byte == 0xf0)
  23248. {
  23249. const uint8* d = src;
  23250. bool haveReadAllLengthBytes = false;
  23251. while (d < src + sz)
  23252. {
  23253. if (*d >= 0x80)
  23254. {
  23255. if (*d == 0xf7)
  23256. {
  23257. ++d; // include the trailing 0xf7 when we hit it
  23258. break;
  23259. }
  23260. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23261. break; // bytes, assume it's the end of the sysex
  23262. ++d;
  23263. continue;
  23264. }
  23265. haveReadAllLengthBytes = true;
  23266. ++d;
  23267. }
  23268. size = 1 + (int) (d - src);
  23269. data = new uint8 [size];
  23270. *data = (uint8) byte;
  23271. memcpy (data + 1, src, size - 1);
  23272. }
  23273. else if (byte == 0xff)
  23274. {
  23275. int n;
  23276. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23277. size = jmin (sz + 1, n + 2 + bytesLeft);
  23278. data = new uint8 [size];
  23279. *data = (uint8) byte;
  23280. memcpy (data + 1, src, size - 1);
  23281. }
  23282. else
  23283. {
  23284. preallocatedData.asInt32 = 0;
  23285. size = getMessageLengthFromFirstByte ((uint8) byte);
  23286. data[0] = (uint8) byte;
  23287. if (size > 1)
  23288. {
  23289. data[1] = src[0];
  23290. if (size > 2)
  23291. data[2] = src[1];
  23292. }
  23293. }
  23294. numBytesUsed += size;
  23295. }
  23296. else
  23297. {
  23298. preallocatedData.asInt32 = 0;
  23299. size = 0;
  23300. }
  23301. }
  23302. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23303. {
  23304. if (this != &other)
  23305. {
  23306. timeStamp = other.timeStamp;
  23307. size = other.size;
  23308. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23309. delete[] data;
  23310. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23311. {
  23312. data = new uint8 [size];
  23313. memcpy (data, other.data, size);
  23314. }
  23315. else
  23316. {
  23317. data = static_cast<uint8*> (preallocatedData.asBytes);
  23318. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23319. }
  23320. }
  23321. return *this;
  23322. }
  23323. MidiMessage::~MidiMessage()
  23324. {
  23325. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23326. delete[] data;
  23327. }
  23328. int MidiMessage::getChannel() const throw()
  23329. {
  23330. if ((data[0] & 0xf0) != 0xf0)
  23331. return (data[0] & 0xf) + 1;
  23332. else
  23333. return 0;
  23334. }
  23335. bool MidiMessage::isForChannel (const int channel) const throw()
  23336. {
  23337. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23338. return ((data[0] & 0xf) == channel - 1)
  23339. && ((data[0] & 0xf0) != 0xf0);
  23340. }
  23341. void MidiMessage::setChannel (const int channel) throw()
  23342. {
  23343. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23344. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23345. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23346. | (uint8)(channel - 1));
  23347. }
  23348. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23349. {
  23350. return ((data[0] & 0xf0) == 0x90)
  23351. && (returnTrueForVelocity0 || data[2] != 0);
  23352. }
  23353. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23354. {
  23355. return ((data[0] & 0xf0) == 0x80)
  23356. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23357. }
  23358. bool MidiMessage::isNoteOnOrOff() const throw()
  23359. {
  23360. const int d = data[0] & 0xf0;
  23361. return (d == 0x90) || (d == 0x80);
  23362. }
  23363. int MidiMessage::getNoteNumber() const throw()
  23364. {
  23365. return data[1];
  23366. }
  23367. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23368. {
  23369. if (isNoteOnOrOff())
  23370. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23371. }
  23372. uint8 MidiMessage::getVelocity() const throw()
  23373. {
  23374. if (isNoteOnOrOff())
  23375. return data[2];
  23376. else
  23377. return 0;
  23378. }
  23379. float MidiMessage::getFloatVelocity() const throw()
  23380. {
  23381. return getVelocity() * (1.0f / 127.0f);
  23382. }
  23383. void MidiMessage::setVelocity (const float newVelocity) throw()
  23384. {
  23385. if (isNoteOnOrOff())
  23386. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23387. }
  23388. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23389. {
  23390. if (isNoteOnOrOff())
  23391. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23392. }
  23393. bool MidiMessage::isAftertouch() const throw()
  23394. {
  23395. return (data[0] & 0xf0) == 0xa0;
  23396. }
  23397. int MidiMessage::getAfterTouchValue() const throw()
  23398. {
  23399. return data[2];
  23400. }
  23401. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23402. const int noteNum,
  23403. const int aftertouchValue) throw()
  23404. {
  23405. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23406. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23407. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23408. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23409. noteNum & 0x7f,
  23410. aftertouchValue & 0x7f);
  23411. }
  23412. bool MidiMessage::isChannelPressure() const throw()
  23413. {
  23414. return (data[0] & 0xf0) == 0xd0;
  23415. }
  23416. int MidiMessage::getChannelPressureValue() const throw()
  23417. {
  23418. jassert (isChannelPressure());
  23419. return data[1];
  23420. }
  23421. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23422. const int pressure) throw()
  23423. {
  23424. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23425. jassert (isPositiveAndBelow (pressure, (int) 128));
  23426. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23427. pressure & 0x7f);
  23428. }
  23429. bool MidiMessage::isProgramChange() const throw()
  23430. {
  23431. return (data[0] & 0xf0) == 0xc0;
  23432. }
  23433. int MidiMessage::getProgramChangeNumber() const throw()
  23434. {
  23435. return data[1];
  23436. }
  23437. const MidiMessage MidiMessage::programChange (const int channel,
  23438. const int programNumber) throw()
  23439. {
  23440. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23441. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23442. programNumber & 0x7f);
  23443. }
  23444. bool MidiMessage::isPitchWheel() const throw()
  23445. {
  23446. return (data[0] & 0xf0) == 0xe0;
  23447. }
  23448. int MidiMessage::getPitchWheelValue() const throw()
  23449. {
  23450. return data[1] | (data[2] << 7);
  23451. }
  23452. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23453. const int position) throw()
  23454. {
  23455. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23456. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23457. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23458. position & 127,
  23459. (position >> 7) & 127);
  23460. }
  23461. bool MidiMessage::isController() const throw()
  23462. {
  23463. return (data[0] & 0xf0) == 0xb0;
  23464. }
  23465. int MidiMessage::getControllerNumber() const throw()
  23466. {
  23467. jassert (isController());
  23468. return data[1];
  23469. }
  23470. int MidiMessage::getControllerValue() const throw()
  23471. {
  23472. jassert (isController());
  23473. return data[2];
  23474. }
  23475. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23476. const int controllerType,
  23477. const int value) throw()
  23478. {
  23479. // the channel must be between 1 and 16 inclusive
  23480. jassert (channel > 0 && channel <= 16);
  23481. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23482. controllerType & 127,
  23483. value & 127);
  23484. }
  23485. const MidiMessage MidiMessage::noteOn (const int channel,
  23486. const int noteNumber,
  23487. const float velocity) throw()
  23488. {
  23489. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23490. }
  23491. const MidiMessage MidiMessage::noteOn (const int channel,
  23492. const int noteNumber,
  23493. const uint8 velocity) throw()
  23494. {
  23495. jassert (channel > 0 && channel <= 16);
  23496. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23497. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23498. noteNumber & 127,
  23499. jlimit (0, 127, roundToInt (velocity)));
  23500. }
  23501. const MidiMessage MidiMessage::noteOff (const int channel,
  23502. const int noteNumber) throw()
  23503. {
  23504. jassert (channel > 0 && channel <= 16);
  23505. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23506. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23507. }
  23508. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23509. {
  23510. return controllerEvent (channel, 123, 0);
  23511. }
  23512. bool MidiMessage::isAllNotesOff() const throw()
  23513. {
  23514. return (data[0] & 0xf0) == 0xb0
  23515. && data[1] == 123;
  23516. }
  23517. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23518. {
  23519. return controllerEvent (channel, 120, 0);
  23520. }
  23521. bool MidiMessage::isAllSoundOff() const throw()
  23522. {
  23523. return (data[0] & 0xf0) == 0xb0
  23524. && data[1] == 120;
  23525. }
  23526. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23527. {
  23528. return controllerEvent (channel, 121, 0);
  23529. }
  23530. const MidiMessage MidiMessage::masterVolume (const float volume)
  23531. {
  23532. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23533. uint8 buf[8];
  23534. buf[0] = 0xf0;
  23535. buf[1] = 0x7f;
  23536. buf[2] = 0x7f;
  23537. buf[3] = 0x04;
  23538. buf[4] = 0x01;
  23539. buf[5] = (uint8) (vol & 0x7f);
  23540. buf[6] = (uint8) (vol >> 7);
  23541. buf[7] = 0xf7;
  23542. return MidiMessage (buf, 8);
  23543. }
  23544. bool MidiMessage::isSysEx() const throw()
  23545. {
  23546. return *data == 0xf0;
  23547. }
  23548. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23549. {
  23550. MemoryBlock mm (dataSize + 2);
  23551. uint8* const m = static_cast <uint8*> (mm.getData());
  23552. m[0] = 0xf0;
  23553. memcpy (m + 1, sysexData, dataSize);
  23554. m[dataSize + 1] = 0xf7;
  23555. return MidiMessage (m, dataSize + 2);
  23556. }
  23557. const uint8* MidiMessage::getSysExData() const throw()
  23558. {
  23559. return (isSysEx()) ? getRawData() + 1 : 0;
  23560. }
  23561. int MidiMessage::getSysExDataSize() const throw()
  23562. {
  23563. return (isSysEx()) ? size - 2 : 0;
  23564. }
  23565. bool MidiMessage::isMetaEvent() const throw()
  23566. {
  23567. return *data == 0xff;
  23568. }
  23569. bool MidiMessage::isActiveSense() const throw()
  23570. {
  23571. return *data == 0xfe;
  23572. }
  23573. int MidiMessage::getMetaEventType() const throw()
  23574. {
  23575. if (*data != 0xff)
  23576. return -1;
  23577. else
  23578. return data[1];
  23579. }
  23580. int MidiMessage::getMetaEventLength() const throw()
  23581. {
  23582. if (*data == 0xff)
  23583. {
  23584. int n;
  23585. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23586. }
  23587. return 0;
  23588. }
  23589. const uint8* MidiMessage::getMetaEventData() const throw()
  23590. {
  23591. int n;
  23592. const uint8* d = data + 2;
  23593. readVariableLengthVal (d, n);
  23594. return d + n;
  23595. }
  23596. bool MidiMessage::isTrackMetaEvent() const throw()
  23597. {
  23598. return getMetaEventType() == 0;
  23599. }
  23600. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23601. {
  23602. return getMetaEventType() == 47;
  23603. }
  23604. bool MidiMessage::isTextMetaEvent() const throw()
  23605. {
  23606. const int t = getMetaEventType();
  23607. return t > 0 && t < 16;
  23608. }
  23609. const String MidiMessage::getTextFromTextMetaEvent() const
  23610. {
  23611. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23612. }
  23613. bool MidiMessage::isTrackNameEvent() const throw()
  23614. {
  23615. return (data[1] == 3)
  23616. && (*data == 0xff);
  23617. }
  23618. bool MidiMessage::isTempoMetaEvent() const throw()
  23619. {
  23620. return (data[1] == 81)
  23621. && (*data == 0xff);
  23622. }
  23623. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23624. {
  23625. return (data[1] == 0x20)
  23626. && (*data == 0xff)
  23627. && (data[2] == 1);
  23628. }
  23629. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23630. {
  23631. return data[3] + 1;
  23632. }
  23633. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23634. {
  23635. if (! isTempoMetaEvent())
  23636. return 0.0;
  23637. const uint8* const d = getMetaEventData();
  23638. return (((unsigned int) d[0] << 16)
  23639. | ((unsigned int) d[1] << 8)
  23640. | d[2])
  23641. / 1000000.0;
  23642. }
  23643. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23644. {
  23645. if (timeFormat > 0)
  23646. {
  23647. if (! isTempoMetaEvent())
  23648. return 0.5 / timeFormat;
  23649. return getTempoSecondsPerQuarterNote() / timeFormat;
  23650. }
  23651. else
  23652. {
  23653. const int frameCode = (-timeFormat) >> 8;
  23654. double framesPerSecond;
  23655. switch (frameCode)
  23656. {
  23657. case 24: framesPerSecond = 24.0; break;
  23658. case 25: framesPerSecond = 25.0; break;
  23659. case 29: framesPerSecond = 29.97; break;
  23660. case 30: framesPerSecond = 30.0; break;
  23661. default: framesPerSecond = 30.0; break;
  23662. }
  23663. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23664. }
  23665. }
  23666. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23667. {
  23668. uint8 d[8];
  23669. d[0] = 0xff;
  23670. d[1] = 81;
  23671. d[2] = 3;
  23672. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23673. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23674. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23675. return MidiMessage (d, 6, 0.0);
  23676. }
  23677. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23678. {
  23679. return (data[1] == 0x58)
  23680. && (*data == (uint8) 0xff);
  23681. }
  23682. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23683. {
  23684. if (isTimeSignatureMetaEvent())
  23685. {
  23686. const uint8* const d = getMetaEventData();
  23687. numerator = d[0];
  23688. denominator = 1 << d[1];
  23689. }
  23690. else
  23691. {
  23692. numerator = 4;
  23693. denominator = 4;
  23694. }
  23695. }
  23696. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23697. {
  23698. uint8 d[8];
  23699. d[0] = 0xff;
  23700. d[1] = 0x58;
  23701. d[2] = 0x04;
  23702. d[3] = (uint8) numerator;
  23703. int n = 1;
  23704. int powerOfTwo = 0;
  23705. while (n < denominator)
  23706. {
  23707. n <<= 1;
  23708. ++powerOfTwo;
  23709. }
  23710. d[4] = (uint8) powerOfTwo;
  23711. d[5] = 0x01;
  23712. d[6] = 96;
  23713. return MidiMessage (d, 7, 0.0);
  23714. }
  23715. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23716. {
  23717. uint8 d[8];
  23718. d[0] = 0xff;
  23719. d[1] = 0x20;
  23720. d[2] = 0x01;
  23721. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23722. return MidiMessage (d, 4, 0.0);
  23723. }
  23724. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23725. {
  23726. return getMetaEventType() == 89;
  23727. }
  23728. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23729. {
  23730. return (int) *getMetaEventData();
  23731. }
  23732. const MidiMessage MidiMessage::endOfTrack() throw()
  23733. {
  23734. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23735. }
  23736. bool MidiMessage::isSongPositionPointer() const throw()
  23737. {
  23738. return *data == 0xf2;
  23739. }
  23740. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23741. {
  23742. return data[1] | (data[2] << 7);
  23743. }
  23744. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23745. {
  23746. return MidiMessage (0xf2,
  23747. positionInMidiBeats & 127,
  23748. (positionInMidiBeats >> 7) & 127);
  23749. }
  23750. bool MidiMessage::isMidiStart() const throw()
  23751. {
  23752. return *data == 0xfa;
  23753. }
  23754. const MidiMessage MidiMessage::midiStart() throw()
  23755. {
  23756. return MidiMessage (0xfa);
  23757. }
  23758. bool MidiMessage::isMidiContinue() const throw()
  23759. {
  23760. return *data == 0xfb;
  23761. }
  23762. const MidiMessage MidiMessage::midiContinue() throw()
  23763. {
  23764. return MidiMessage (0xfb);
  23765. }
  23766. bool MidiMessage::isMidiStop() const throw()
  23767. {
  23768. return *data == 0xfc;
  23769. }
  23770. const MidiMessage MidiMessage::midiStop() throw()
  23771. {
  23772. return MidiMessage (0xfc);
  23773. }
  23774. bool MidiMessage::isMidiClock() const throw()
  23775. {
  23776. return *data == 0xf8;
  23777. }
  23778. const MidiMessage MidiMessage::midiClock() throw()
  23779. {
  23780. return MidiMessage (0xf8);
  23781. }
  23782. bool MidiMessage::isQuarterFrame() const throw()
  23783. {
  23784. return *data == 0xf1;
  23785. }
  23786. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23787. {
  23788. return ((int) data[1]) >> 4;
  23789. }
  23790. int MidiMessage::getQuarterFrameValue() const throw()
  23791. {
  23792. return ((int) data[1]) & 0x0f;
  23793. }
  23794. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23795. const int value) throw()
  23796. {
  23797. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23798. }
  23799. bool MidiMessage::isFullFrame() const throw()
  23800. {
  23801. return data[0] == 0xf0
  23802. && data[1] == 0x7f
  23803. && size >= 10
  23804. && data[3] == 0x01
  23805. && data[4] == 0x01;
  23806. }
  23807. void MidiMessage::getFullFrameParameters (int& hours,
  23808. int& minutes,
  23809. int& seconds,
  23810. int& frames,
  23811. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23812. {
  23813. jassert (isFullFrame());
  23814. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23815. hours = data[5] & 0x1f;
  23816. minutes = data[6];
  23817. seconds = data[7];
  23818. frames = data[8];
  23819. }
  23820. const MidiMessage MidiMessage::fullFrame (const int hours,
  23821. const int minutes,
  23822. const int seconds,
  23823. const int frames,
  23824. MidiMessage::SmpteTimecodeType timecodeType)
  23825. {
  23826. uint8 d[10];
  23827. d[0] = 0xf0;
  23828. d[1] = 0x7f;
  23829. d[2] = 0x7f;
  23830. d[3] = 0x01;
  23831. d[4] = 0x01;
  23832. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23833. d[6] = (uint8) minutes;
  23834. d[7] = (uint8) seconds;
  23835. d[8] = (uint8) frames;
  23836. d[9] = 0xf7;
  23837. return MidiMessage (d, 10, 0.0);
  23838. }
  23839. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23840. {
  23841. return data[0] == 0xf0
  23842. && data[1] == 0x7f
  23843. && data[3] == 0x06
  23844. && size > 5;
  23845. }
  23846. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23847. {
  23848. jassert (isMidiMachineControlMessage());
  23849. return (MidiMachineControlCommand) data[4];
  23850. }
  23851. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23852. {
  23853. uint8 d[6];
  23854. d[0] = 0xf0;
  23855. d[1] = 0x7f;
  23856. d[2] = 0x00;
  23857. d[3] = 0x06;
  23858. d[4] = (uint8) command;
  23859. d[5] = 0xf7;
  23860. return MidiMessage (d, 6, 0.0);
  23861. }
  23862. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23863. int& minutes,
  23864. int& seconds,
  23865. int& frames) const throw()
  23866. {
  23867. if (size >= 12
  23868. && data[0] == 0xf0
  23869. && data[1] == 0x7f
  23870. && data[3] == 0x06
  23871. && data[4] == 0x44
  23872. && data[5] == 0x06
  23873. && data[6] == 0x01)
  23874. {
  23875. hours = data[7] % 24; // (that some machines send out hours > 24)
  23876. minutes = data[8];
  23877. seconds = data[9];
  23878. frames = data[10];
  23879. return true;
  23880. }
  23881. return false;
  23882. }
  23883. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23884. int minutes,
  23885. int seconds,
  23886. int frames)
  23887. {
  23888. uint8 d[12];
  23889. d[0] = 0xf0;
  23890. d[1] = 0x7f;
  23891. d[2] = 0x00;
  23892. d[3] = 0x06;
  23893. d[4] = 0x44;
  23894. d[5] = 0x06;
  23895. d[6] = 0x01;
  23896. d[7] = (uint8) hours;
  23897. d[8] = (uint8) minutes;
  23898. d[9] = (uint8) seconds;
  23899. d[10] = (uint8) frames;
  23900. d[11] = 0xf7;
  23901. return MidiMessage (d, 12, 0.0);
  23902. }
  23903. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23904. {
  23905. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23906. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23907. if (isPositiveAndBelow (note, (int) 128))
  23908. {
  23909. String s (useSharps ? sharpNoteNames [note % 12]
  23910. : flatNoteNames [note % 12]);
  23911. if (includeOctaveNumber)
  23912. s << (note / 12 + (octaveNumForMiddleC - 5));
  23913. return s;
  23914. }
  23915. return String::empty;
  23916. }
  23917. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23918. {
  23919. noteNumber -= 12 * 6 + 9; // now 0 = A
  23920. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23921. }
  23922. const String MidiMessage::getGMInstrumentName (const int n)
  23923. {
  23924. const char* names[] =
  23925. {
  23926. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23927. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23928. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23929. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23930. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23931. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23932. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23933. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23934. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23935. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23936. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23937. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23938. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23939. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23940. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23941. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23942. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23943. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23944. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23945. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23946. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23947. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23948. "Applause", "Gunshot"
  23949. };
  23950. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23951. }
  23952. const String MidiMessage::getGMInstrumentBankName (const int n)
  23953. {
  23954. const char* names[] =
  23955. {
  23956. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23957. "Bass", "Strings", "Ensemble", "Brass",
  23958. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23959. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23960. };
  23961. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23962. }
  23963. const String MidiMessage::getRhythmInstrumentName (const int n)
  23964. {
  23965. const char* names[] =
  23966. {
  23967. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23968. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23969. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23970. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23971. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23972. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23973. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23974. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23975. "Mute Triangle", "Open Triangle"
  23976. };
  23977. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23978. }
  23979. const String MidiMessage::getControllerName (const int n)
  23980. {
  23981. const char* names[] =
  23982. {
  23983. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23984. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23985. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23986. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23987. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23988. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23989. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23990. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23991. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23992. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23993. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23994. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23995. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23996. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23997. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23998. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23999. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  24000. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  24001. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  24002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  24003. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  24004. "Poly Operation"
  24005. };
  24006. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  24007. }
  24008. END_JUCE_NAMESPACE
  24009. /*** End of inlined file: juce_MidiMessage.cpp ***/
  24010. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  24011. BEGIN_JUCE_NAMESPACE
  24012. MidiMessageCollector::MidiMessageCollector()
  24013. : lastCallbackTime (0),
  24014. sampleRate (44100.0001)
  24015. {
  24016. }
  24017. MidiMessageCollector::~MidiMessageCollector()
  24018. {
  24019. }
  24020. void MidiMessageCollector::reset (const double sampleRate_)
  24021. {
  24022. jassert (sampleRate_ > 0);
  24023. const ScopedLock sl (midiCallbackLock);
  24024. sampleRate = sampleRate_;
  24025. incomingMessages.clear();
  24026. lastCallbackTime = Time::getMillisecondCounterHiRes();
  24027. }
  24028. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  24029. {
  24030. // you need to call reset() to set the correct sample rate before using this object
  24031. jassert (sampleRate != 44100.0001);
  24032. // the messages that come in here need to be time-stamped correctly - see MidiInput
  24033. // for details of what the number should be.
  24034. jassert (message.getTimeStamp() != 0);
  24035. const ScopedLock sl (midiCallbackLock);
  24036. const int sampleNumber
  24037. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  24038. incomingMessages.addEvent (message, sampleNumber);
  24039. // if the messages don't get used for over a second, we'd better
  24040. // get rid of any old ones to avoid the queue getting too big
  24041. if (sampleNumber > sampleRate)
  24042. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  24043. }
  24044. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  24045. const int numSamples)
  24046. {
  24047. // you need to call reset() to set the correct sample rate before using this object
  24048. jassert (sampleRate != 44100.0001);
  24049. const double timeNow = Time::getMillisecondCounterHiRes();
  24050. const double msElapsed = timeNow - lastCallbackTime;
  24051. const ScopedLock sl (midiCallbackLock);
  24052. lastCallbackTime = timeNow;
  24053. if (! incomingMessages.isEmpty())
  24054. {
  24055. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  24056. int startSample = 0;
  24057. int scale = 1 << 16;
  24058. const uint8* midiData;
  24059. int numBytes, samplePosition;
  24060. MidiBuffer::Iterator iter (incomingMessages);
  24061. if (numSourceSamples > numSamples)
  24062. {
  24063. // if our list of events is longer than the buffer we're being
  24064. // asked for, scale them down to squeeze them all in..
  24065. const int maxBlockLengthToUse = numSamples << 5;
  24066. if (numSourceSamples > maxBlockLengthToUse)
  24067. {
  24068. startSample = numSourceSamples - maxBlockLengthToUse;
  24069. numSourceSamples = maxBlockLengthToUse;
  24070. iter.setNextSamplePosition (startSample);
  24071. }
  24072. scale = (numSamples << 10) / numSourceSamples;
  24073. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24074. {
  24075. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24076. destBuffer.addEvent (midiData, numBytes,
  24077. jlimit (0, numSamples - 1, samplePosition));
  24078. }
  24079. }
  24080. else
  24081. {
  24082. // if our event list is shorter than the number we need, put them
  24083. // towards the end of the buffer
  24084. startSample = numSamples - numSourceSamples;
  24085. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24086. {
  24087. destBuffer.addEvent (midiData, numBytes,
  24088. jlimit (0, numSamples - 1, samplePosition + startSample));
  24089. }
  24090. }
  24091. incomingMessages.clear();
  24092. }
  24093. }
  24094. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24095. {
  24096. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24097. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24098. addMessageToQueue (m);
  24099. }
  24100. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24101. {
  24102. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24103. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24104. addMessageToQueue (m);
  24105. }
  24106. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24107. {
  24108. addMessageToQueue (message);
  24109. }
  24110. END_JUCE_NAMESPACE
  24111. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24112. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24113. BEGIN_JUCE_NAMESPACE
  24114. MidiMessageSequence::MidiMessageSequence()
  24115. {
  24116. }
  24117. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24118. {
  24119. list.ensureStorageAllocated (other.list.size());
  24120. for (int i = 0; i < other.list.size(); ++i)
  24121. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24122. }
  24123. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24124. {
  24125. MidiMessageSequence otherCopy (other);
  24126. swapWith (otherCopy);
  24127. return *this;
  24128. }
  24129. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24130. {
  24131. list.swapWithArray (other.list);
  24132. }
  24133. MidiMessageSequence::~MidiMessageSequence()
  24134. {
  24135. }
  24136. void MidiMessageSequence::clear()
  24137. {
  24138. list.clear();
  24139. }
  24140. int MidiMessageSequence::getNumEvents() const
  24141. {
  24142. return list.size();
  24143. }
  24144. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24145. {
  24146. return list [index];
  24147. }
  24148. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24149. {
  24150. const MidiEventHolder* const meh = list [index];
  24151. if (meh != 0 && meh->noteOffObject != 0)
  24152. return meh->noteOffObject->message.getTimeStamp();
  24153. else
  24154. return 0.0;
  24155. }
  24156. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24157. {
  24158. const MidiEventHolder* const meh = list [index];
  24159. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24160. }
  24161. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24162. {
  24163. return list.indexOf (event);
  24164. }
  24165. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24166. {
  24167. const int numEvents = list.size();
  24168. int i;
  24169. for (i = 0; i < numEvents; ++i)
  24170. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24171. break;
  24172. return i;
  24173. }
  24174. double MidiMessageSequence::getStartTime() const
  24175. {
  24176. if (list.size() > 0)
  24177. return list.getUnchecked(0)->message.getTimeStamp();
  24178. else
  24179. return 0;
  24180. }
  24181. double MidiMessageSequence::getEndTime() const
  24182. {
  24183. if (list.size() > 0)
  24184. return list.getLast()->message.getTimeStamp();
  24185. else
  24186. return 0;
  24187. }
  24188. double MidiMessageSequence::getEventTime (const int index) const
  24189. {
  24190. if (isPositiveAndBelow (index, list.size()))
  24191. return list.getUnchecked (index)->message.getTimeStamp();
  24192. return 0.0;
  24193. }
  24194. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24195. double timeAdjustment)
  24196. {
  24197. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24198. timeAdjustment += newMessage.getTimeStamp();
  24199. newOne->message.setTimeStamp (timeAdjustment);
  24200. int i;
  24201. for (i = list.size(); --i >= 0;)
  24202. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24203. break;
  24204. list.insert (i + 1, newOne);
  24205. }
  24206. void MidiMessageSequence::deleteEvent (const int index,
  24207. const bool deleteMatchingNoteUp)
  24208. {
  24209. if (isPositiveAndBelow (index, list.size()))
  24210. {
  24211. if (deleteMatchingNoteUp)
  24212. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24213. list.remove (index);
  24214. }
  24215. }
  24216. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24217. double timeAdjustment,
  24218. double firstAllowableTime,
  24219. double endOfAllowableDestTimes)
  24220. {
  24221. firstAllowableTime -= timeAdjustment;
  24222. endOfAllowableDestTimes -= timeAdjustment;
  24223. for (int i = 0; i < other.list.size(); ++i)
  24224. {
  24225. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24226. const double t = m.getTimeStamp();
  24227. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24228. {
  24229. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24230. newOne->message.setTimeStamp (timeAdjustment + t);
  24231. list.add (newOne);
  24232. }
  24233. }
  24234. sort();
  24235. }
  24236. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24237. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24238. {
  24239. const double diff = first->message.getTimeStamp()
  24240. - second->message.getTimeStamp();
  24241. return (diff > 0) - (diff < 0);
  24242. }
  24243. void MidiMessageSequence::sort()
  24244. {
  24245. list.sort (*this, true);
  24246. }
  24247. void MidiMessageSequence::updateMatchedPairs()
  24248. {
  24249. for (int i = 0; i < list.size(); ++i)
  24250. {
  24251. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24252. if (m1.isNoteOn())
  24253. {
  24254. list.getUnchecked(i)->noteOffObject = 0;
  24255. const int note = m1.getNoteNumber();
  24256. const int chan = m1.getChannel();
  24257. const int len = list.size();
  24258. for (int j = i + 1; j < len; ++j)
  24259. {
  24260. const MidiMessage& m = list.getUnchecked(j)->message;
  24261. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24262. {
  24263. if (m.isNoteOff())
  24264. {
  24265. list.getUnchecked(i)->noteOffObject = list[j];
  24266. break;
  24267. }
  24268. else if (m.isNoteOn())
  24269. {
  24270. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24271. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24272. list.getUnchecked(i)->noteOffObject = list[j];
  24273. break;
  24274. }
  24275. }
  24276. }
  24277. }
  24278. }
  24279. }
  24280. void MidiMessageSequence::addTimeToMessages (const double delta)
  24281. {
  24282. for (int i = list.size(); --i >= 0;)
  24283. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24284. + delta);
  24285. }
  24286. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24287. MidiMessageSequence& destSequence,
  24288. const bool alsoIncludeMetaEvents) const
  24289. {
  24290. for (int i = 0; i < list.size(); ++i)
  24291. {
  24292. const MidiMessage& mm = list.getUnchecked(i)->message;
  24293. if (mm.isForChannel (channelNumberToExtract)
  24294. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24295. {
  24296. destSequence.addEvent (mm);
  24297. }
  24298. }
  24299. }
  24300. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24301. {
  24302. for (int i = 0; i < list.size(); ++i)
  24303. {
  24304. const MidiMessage& mm = list.getUnchecked(i)->message;
  24305. if (mm.isSysEx())
  24306. destSequence.addEvent (mm);
  24307. }
  24308. }
  24309. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24310. {
  24311. for (int i = list.size(); --i >= 0;)
  24312. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24313. list.remove(i);
  24314. }
  24315. void MidiMessageSequence::deleteSysExMessages()
  24316. {
  24317. for (int i = list.size(); --i >= 0;)
  24318. if (list.getUnchecked(i)->message.isSysEx())
  24319. list.remove(i);
  24320. }
  24321. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24322. const double time,
  24323. OwnedArray<MidiMessage>& dest)
  24324. {
  24325. bool doneProg = false;
  24326. bool donePitchWheel = false;
  24327. Array <int> doneControllers;
  24328. doneControllers.ensureStorageAllocated (32);
  24329. for (int i = list.size(); --i >= 0;)
  24330. {
  24331. const MidiMessage& mm = list.getUnchecked(i)->message;
  24332. if (mm.isForChannel (channelNumber)
  24333. && mm.getTimeStamp() <= time)
  24334. {
  24335. if (mm.isProgramChange())
  24336. {
  24337. if (! doneProg)
  24338. {
  24339. dest.add (new MidiMessage (mm, 0.0));
  24340. doneProg = true;
  24341. }
  24342. }
  24343. else if (mm.isController())
  24344. {
  24345. if (! doneControllers.contains (mm.getControllerNumber()))
  24346. {
  24347. dest.add (new MidiMessage (mm, 0.0));
  24348. doneControllers.add (mm.getControllerNumber());
  24349. }
  24350. }
  24351. else if (mm.isPitchWheel())
  24352. {
  24353. if (! donePitchWheel)
  24354. {
  24355. dest.add (new MidiMessage (mm, 0.0));
  24356. donePitchWheel = true;
  24357. }
  24358. }
  24359. }
  24360. }
  24361. }
  24362. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24363. : message (message_),
  24364. noteOffObject (0)
  24365. {
  24366. }
  24367. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24368. {
  24369. }
  24370. END_JUCE_NAMESPACE
  24371. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24372. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24373. BEGIN_JUCE_NAMESPACE
  24374. AudioPluginFormat::AudioPluginFormat() throw()
  24375. {
  24376. }
  24377. AudioPluginFormat::~AudioPluginFormat()
  24378. {
  24379. }
  24380. END_JUCE_NAMESPACE
  24381. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24382. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24383. BEGIN_JUCE_NAMESPACE
  24384. AudioPluginFormatManager::AudioPluginFormatManager()
  24385. {
  24386. }
  24387. AudioPluginFormatManager::~AudioPluginFormatManager()
  24388. {
  24389. clearSingletonInstance();
  24390. }
  24391. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24392. void AudioPluginFormatManager::addDefaultFormats()
  24393. {
  24394. #if JUCE_DEBUG
  24395. // you should only call this method once!
  24396. for (int i = formats.size(); --i >= 0;)
  24397. {
  24398. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24399. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24400. #endif
  24401. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24402. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24403. #endif
  24404. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24405. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24406. #endif
  24407. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24408. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24409. #endif
  24410. }
  24411. #endif
  24412. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24413. formats.add (new AudioUnitPluginFormat());
  24414. #endif
  24415. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24416. formats.add (new VSTPluginFormat());
  24417. #endif
  24418. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24419. formats.add (new DirectXPluginFormat());
  24420. #endif
  24421. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24422. formats.add (new LADSPAPluginFormat());
  24423. #endif
  24424. }
  24425. int AudioPluginFormatManager::getNumFormats()
  24426. {
  24427. return formats.size();
  24428. }
  24429. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24430. {
  24431. return formats [index];
  24432. }
  24433. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24434. {
  24435. formats.add (format);
  24436. }
  24437. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24438. String& errorMessage) const
  24439. {
  24440. AudioPluginInstance* result = 0;
  24441. for (int i = 0; i < formats.size(); ++i)
  24442. {
  24443. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24444. if (result != 0)
  24445. break;
  24446. }
  24447. if (result == 0)
  24448. {
  24449. if (! doesPluginStillExist (description))
  24450. errorMessage = TRANS ("This plug-in file no longer exists");
  24451. else
  24452. errorMessage = TRANS ("This plug-in failed to load correctly");
  24453. }
  24454. return result;
  24455. }
  24456. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24457. {
  24458. for (int i = 0; i < formats.size(); ++i)
  24459. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24460. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24461. return false;
  24462. }
  24463. END_JUCE_NAMESPACE
  24464. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24465. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24466. #define JUCE_PLUGIN_HOST 1
  24467. BEGIN_JUCE_NAMESPACE
  24468. AudioPluginInstance::AudioPluginInstance()
  24469. {
  24470. }
  24471. AudioPluginInstance::~AudioPluginInstance()
  24472. {
  24473. }
  24474. void* AudioPluginInstance::getPlatformSpecificData()
  24475. {
  24476. return 0;
  24477. }
  24478. END_JUCE_NAMESPACE
  24479. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24480. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24481. BEGIN_JUCE_NAMESPACE
  24482. KnownPluginList::KnownPluginList()
  24483. {
  24484. }
  24485. KnownPluginList::~KnownPluginList()
  24486. {
  24487. }
  24488. void KnownPluginList::clear()
  24489. {
  24490. if (types.size() > 0)
  24491. {
  24492. types.clear();
  24493. sendChangeMessage();
  24494. }
  24495. }
  24496. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24497. {
  24498. for (int i = 0; i < types.size(); ++i)
  24499. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24500. return types.getUnchecked(i);
  24501. return 0;
  24502. }
  24503. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24504. {
  24505. for (int i = 0; i < types.size(); ++i)
  24506. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24507. return types.getUnchecked(i);
  24508. return 0;
  24509. }
  24510. bool KnownPluginList::addType (const PluginDescription& type)
  24511. {
  24512. for (int i = types.size(); --i >= 0;)
  24513. {
  24514. if (types.getUnchecked(i)->isDuplicateOf (type))
  24515. {
  24516. // strange - found a duplicate plugin with different info..
  24517. jassert (types.getUnchecked(i)->name == type.name);
  24518. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24519. *types.getUnchecked(i) = type;
  24520. return false;
  24521. }
  24522. }
  24523. types.add (new PluginDescription (type));
  24524. sendChangeMessage();
  24525. return true;
  24526. }
  24527. void KnownPluginList::removeType (const int index)
  24528. {
  24529. types.remove (index);
  24530. sendChangeMessage();
  24531. }
  24532. namespace
  24533. {
  24534. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24535. {
  24536. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24537. return File (fileOrIdentifier).getLastModificationTime();
  24538. return Time (0);
  24539. }
  24540. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24541. {
  24542. return t1 != t2 || t1 == Time (0);
  24543. }
  24544. }
  24545. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24546. {
  24547. if (getTypeForFile (fileOrIdentifier) == 0)
  24548. return false;
  24549. for (int i = types.size(); --i >= 0;)
  24550. {
  24551. const PluginDescription* const d = types.getUnchecked(i);
  24552. if (d->fileOrIdentifier == fileOrIdentifier
  24553. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24554. {
  24555. return false;
  24556. }
  24557. }
  24558. return true;
  24559. }
  24560. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24561. const bool dontRescanIfAlreadyInList,
  24562. OwnedArray <PluginDescription>& typesFound,
  24563. AudioPluginFormat& format)
  24564. {
  24565. bool addedOne = false;
  24566. if (dontRescanIfAlreadyInList
  24567. && getTypeForFile (fileOrIdentifier) != 0)
  24568. {
  24569. bool needsRescanning = false;
  24570. for (int i = types.size(); --i >= 0;)
  24571. {
  24572. const PluginDescription* const d = types.getUnchecked(i);
  24573. if (d->fileOrIdentifier == fileOrIdentifier)
  24574. {
  24575. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24576. needsRescanning = true;
  24577. else
  24578. typesFound.add (new PluginDescription (*d));
  24579. }
  24580. }
  24581. if (! needsRescanning)
  24582. return false;
  24583. }
  24584. OwnedArray <PluginDescription> found;
  24585. format.findAllTypesForFile (found, fileOrIdentifier);
  24586. for (int i = 0; i < found.size(); ++i)
  24587. {
  24588. PluginDescription* const desc = found.getUnchecked(i);
  24589. jassert (desc != 0);
  24590. if (addType (*desc))
  24591. addedOne = true;
  24592. typesFound.add (new PluginDescription (*desc));
  24593. }
  24594. return addedOne;
  24595. }
  24596. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24597. OwnedArray <PluginDescription>& typesFound)
  24598. {
  24599. for (int i = 0; i < files.size(); ++i)
  24600. {
  24601. bool loaded = false;
  24602. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24603. {
  24604. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24605. if (scanAndAddFile (files[i], true, typesFound, *format))
  24606. loaded = true;
  24607. }
  24608. if (! loaded)
  24609. {
  24610. const File f (files[i]);
  24611. if (f.isDirectory())
  24612. {
  24613. StringArray s;
  24614. {
  24615. Array<File> subFiles;
  24616. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24617. for (int j = 0; j < subFiles.size(); ++j)
  24618. s.add (subFiles.getReference(j).getFullPathName());
  24619. }
  24620. scanAndAddDragAndDroppedFiles (s, typesFound);
  24621. }
  24622. }
  24623. }
  24624. }
  24625. class PluginSorter
  24626. {
  24627. public:
  24628. KnownPluginList::SortMethod method;
  24629. PluginSorter() throw() {}
  24630. int compareElements (const PluginDescription* const first,
  24631. const PluginDescription* const second) const
  24632. {
  24633. int diff = 0;
  24634. if (method == KnownPluginList::sortByCategory)
  24635. diff = first->category.compareLexicographically (second->category);
  24636. else if (method == KnownPluginList::sortByManufacturer)
  24637. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24638. else if (method == KnownPluginList::sortByFileSystemLocation)
  24639. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24640. .upToLastOccurrenceOf ("/", false, false)
  24641. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24642. .upToLastOccurrenceOf ("/", false, false));
  24643. if (diff == 0)
  24644. diff = first->name.compareLexicographically (second->name);
  24645. return diff;
  24646. }
  24647. };
  24648. void KnownPluginList::sort (const SortMethod method)
  24649. {
  24650. if (method != defaultOrder)
  24651. {
  24652. PluginSorter sorter;
  24653. sorter.method = method;
  24654. types.sort (sorter, true);
  24655. sendChangeMessage();
  24656. }
  24657. }
  24658. XmlElement* KnownPluginList::createXml() const
  24659. {
  24660. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24661. for (int i = 0; i < types.size(); ++i)
  24662. e->addChildElement (types.getUnchecked(i)->createXml());
  24663. return e;
  24664. }
  24665. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24666. {
  24667. clear();
  24668. if (xml.hasTagName ("KNOWNPLUGINS"))
  24669. {
  24670. forEachXmlChildElement (xml, e)
  24671. {
  24672. PluginDescription info;
  24673. if (info.loadFromXml (*e))
  24674. addType (info);
  24675. }
  24676. }
  24677. }
  24678. const int menuIdBase = 0x324503f4;
  24679. // This is used to turn a bunch of paths into a nested menu structure.
  24680. struct PluginFilesystemTree
  24681. {
  24682. private:
  24683. String folder;
  24684. OwnedArray <PluginFilesystemTree> subFolders;
  24685. Array <PluginDescription*> plugins;
  24686. void addPlugin (PluginDescription* const pd, const String& path)
  24687. {
  24688. if (path.isEmpty())
  24689. {
  24690. plugins.add (pd);
  24691. }
  24692. else
  24693. {
  24694. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24695. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24696. for (int i = subFolders.size(); --i >= 0;)
  24697. {
  24698. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24699. {
  24700. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24701. return;
  24702. }
  24703. }
  24704. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24705. newFolder->folder = firstSubFolder;
  24706. subFolders.add (newFolder);
  24707. newFolder->addPlugin (pd, remainingPath);
  24708. }
  24709. }
  24710. // removes any deeply nested folders that don't contain any actual plugins
  24711. void optimise()
  24712. {
  24713. for (int i = subFolders.size(); --i >= 0;)
  24714. {
  24715. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24716. sub->optimise();
  24717. if (sub->plugins.size() == 0)
  24718. {
  24719. for (int j = 0; j < sub->subFolders.size(); ++j)
  24720. subFolders.add (sub->subFolders.getUnchecked(j));
  24721. sub->subFolders.clear (false);
  24722. subFolders.remove (i);
  24723. }
  24724. }
  24725. }
  24726. public:
  24727. void buildTree (const Array <PluginDescription*>& allPlugins)
  24728. {
  24729. for (int i = 0; i < allPlugins.size(); ++i)
  24730. {
  24731. String path (allPlugins.getUnchecked(i)
  24732. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24733. .upToLastOccurrenceOf ("/", false, false));
  24734. if (path.substring (1, 2) == ":")
  24735. path = path.substring (2);
  24736. addPlugin (allPlugins.getUnchecked(i), path);
  24737. }
  24738. optimise();
  24739. }
  24740. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24741. {
  24742. int i;
  24743. for (i = 0; i < subFolders.size(); ++i)
  24744. {
  24745. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24746. PopupMenu subMenu;
  24747. sub->addToMenu (subMenu, allPlugins);
  24748. #if JUCE_MAC
  24749. // avoid the special AU formatting nonsense on Mac..
  24750. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24751. #else
  24752. m.addSubMenu (sub->folder, subMenu);
  24753. #endif
  24754. }
  24755. for (i = 0; i < plugins.size(); ++i)
  24756. {
  24757. PluginDescription* const plugin = plugins.getUnchecked(i);
  24758. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24759. plugin->name, true, false);
  24760. }
  24761. }
  24762. };
  24763. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24764. {
  24765. Array <PluginDescription*> sorted;
  24766. {
  24767. PluginSorter sorter;
  24768. sorter.method = sortMethod;
  24769. for (int i = 0; i < types.size(); ++i)
  24770. sorted.addSorted (sorter, types.getUnchecked(i));
  24771. }
  24772. if (sortMethod == sortByCategory
  24773. || sortMethod == sortByManufacturer)
  24774. {
  24775. String lastSubMenuName;
  24776. PopupMenu sub;
  24777. for (int i = 0; i < sorted.size(); ++i)
  24778. {
  24779. const PluginDescription* const pd = sorted.getUnchecked(i);
  24780. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24781. : pd->manufacturerName);
  24782. if (! thisSubMenuName.containsNonWhitespaceChars())
  24783. thisSubMenuName = "Other";
  24784. if (thisSubMenuName != lastSubMenuName)
  24785. {
  24786. if (sub.getNumItems() > 0)
  24787. {
  24788. menu.addSubMenu (lastSubMenuName, sub);
  24789. sub.clear();
  24790. }
  24791. lastSubMenuName = thisSubMenuName;
  24792. }
  24793. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24794. }
  24795. if (sub.getNumItems() > 0)
  24796. menu.addSubMenu (lastSubMenuName, sub);
  24797. }
  24798. else if (sortMethod == sortByFileSystemLocation)
  24799. {
  24800. PluginFilesystemTree root;
  24801. root.buildTree (sorted);
  24802. root.addToMenu (menu, types);
  24803. }
  24804. else
  24805. {
  24806. for (int i = 0; i < sorted.size(); ++i)
  24807. {
  24808. const PluginDescription* const pd = sorted.getUnchecked(i);
  24809. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24810. }
  24811. }
  24812. }
  24813. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24814. {
  24815. const int i = menuResultCode - menuIdBase;
  24816. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24817. }
  24818. END_JUCE_NAMESPACE
  24819. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24820. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24821. BEGIN_JUCE_NAMESPACE
  24822. PluginDescription::PluginDescription()
  24823. : uid (0),
  24824. isInstrument (false),
  24825. numInputChannels (0),
  24826. numOutputChannels (0)
  24827. {
  24828. }
  24829. PluginDescription::~PluginDescription()
  24830. {
  24831. }
  24832. PluginDescription::PluginDescription (const PluginDescription& other)
  24833. : name (other.name),
  24834. descriptiveName (other.descriptiveName),
  24835. pluginFormatName (other.pluginFormatName),
  24836. category (other.category),
  24837. manufacturerName (other.manufacturerName),
  24838. version (other.version),
  24839. fileOrIdentifier (other.fileOrIdentifier),
  24840. lastFileModTime (other.lastFileModTime),
  24841. uid (other.uid),
  24842. isInstrument (other.isInstrument),
  24843. numInputChannels (other.numInputChannels),
  24844. numOutputChannels (other.numOutputChannels)
  24845. {
  24846. }
  24847. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24848. {
  24849. name = other.name;
  24850. descriptiveName = other.descriptiveName;
  24851. pluginFormatName = other.pluginFormatName;
  24852. category = other.category;
  24853. manufacturerName = other.manufacturerName;
  24854. version = other.version;
  24855. fileOrIdentifier = other.fileOrIdentifier;
  24856. uid = other.uid;
  24857. isInstrument = other.isInstrument;
  24858. lastFileModTime = other.lastFileModTime;
  24859. numInputChannels = other.numInputChannels;
  24860. numOutputChannels = other.numOutputChannels;
  24861. return *this;
  24862. }
  24863. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24864. {
  24865. return fileOrIdentifier == other.fileOrIdentifier
  24866. && uid == other.uid;
  24867. }
  24868. const String PluginDescription::createIdentifierString() const
  24869. {
  24870. return pluginFormatName
  24871. + "-" + name
  24872. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24873. + "-" + String::toHexString (uid);
  24874. }
  24875. XmlElement* PluginDescription::createXml() const
  24876. {
  24877. XmlElement* const e = new XmlElement ("PLUGIN");
  24878. e->setAttribute ("name", name);
  24879. if (descriptiveName != name)
  24880. e->setAttribute ("descriptiveName", descriptiveName);
  24881. e->setAttribute ("format", pluginFormatName);
  24882. e->setAttribute ("category", category);
  24883. e->setAttribute ("manufacturer", manufacturerName);
  24884. e->setAttribute ("version", version);
  24885. e->setAttribute ("file", fileOrIdentifier);
  24886. e->setAttribute ("uid", String::toHexString (uid));
  24887. e->setAttribute ("isInstrument", isInstrument);
  24888. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24889. e->setAttribute ("numInputs", numInputChannels);
  24890. e->setAttribute ("numOutputs", numOutputChannels);
  24891. return e;
  24892. }
  24893. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24894. {
  24895. if (xml.hasTagName ("PLUGIN"))
  24896. {
  24897. name = xml.getStringAttribute ("name");
  24898. descriptiveName = xml.getStringAttribute ("name", name);
  24899. pluginFormatName = xml.getStringAttribute ("format");
  24900. category = xml.getStringAttribute ("category");
  24901. manufacturerName = xml.getStringAttribute ("manufacturer");
  24902. version = xml.getStringAttribute ("version");
  24903. fileOrIdentifier = xml.getStringAttribute ("file");
  24904. uid = xml.getStringAttribute ("uid").getHexValue32();
  24905. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24906. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24907. numInputChannels = xml.getIntAttribute ("numInputs");
  24908. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24909. return true;
  24910. }
  24911. return false;
  24912. }
  24913. END_JUCE_NAMESPACE
  24914. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24915. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24916. BEGIN_JUCE_NAMESPACE
  24917. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24918. AudioPluginFormat& formatToLookFor,
  24919. FileSearchPath directoriesToSearch,
  24920. const bool recursive,
  24921. const File& deadMansPedalFile_)
  24922. : list (listToAddTo),
  24923. format (formatToLookFor),
  24924. deadMansPedalFile (deadMansPedalFile_),
  24925. nextIndex (0),
  24926. progress (0)
  24927. {
  24928. directoriesToSearch.removeRedundantPaths();
  24929. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24930. // If any plugins have crashed recently when being loaded, move them to the
  24931. // end of the list to give the others a chance to load correctly..
  24932. const StringArray crashedPlugins (getDeadMansPedalFile());
  24933. for (int i = 0; i < crashedPlugins.size(); ++i)
  24934. {
  24935. const String f = crashedPlugins[i];
  24936. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24937. if (f == filesOrIdentifiersToScan[j])
  24938. filesOrIdentifiersToScan.move (j, -1);
  24939. }
  24940. }
  24941. PluginDirectoryScanner::~PluginDirectoryScanner()
  24942. {
  24943. }
  24944. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24945. {
  24946. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24947. }
  24948. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24949. {
  24950. String file (filesOrIdentifiersToScan [nextIndex]);
  24951. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24952. {
  24953. OwnedArray <PluginDescription> typesFound;
  24954. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24955. StringArray crashedPlugins (getDeadMansPedalFile());
  24956. crashedPlugins.removeString (file);
  24957. crashedPlugins.add (file);
  24958. setDeadMansPedalFile (crashedPlugins);
  24959. list.scanAndAddFile (file,
  24960. dontRescanIfAlreadyInList,
  24961. typesFound,
  24962. format);
  24963. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24964. crashedPlugins.removeString (file);
  24965. setDeadMansPedalFile (crashedPlugins);
  24966. if (typesFound.size() == 0)
  24967. failedFiles.add (file);
  24968. }
  24969. return skipNextFile();
  24970. }
  24971. bool PluginDirectoryScanner::skipNextFile()
  24972. {
  24973. if (nextIndex >= filesOrIdentifiersToScan.size())
  24974. return false;
  24975. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24976. return nextIndex < filesOrIdentifiersToScan.size();
  24977. }
  24978. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24979. {
  24980. StringArray lines;
  24981. if (deadMansPedalFile != File::nonexistent)
  24982. {
  24983. lines.addLines (deadMansPedalFile.loadFileAsString());
  24984. lines.removeEmptyStrings();
  24985. }
  24986. return lines;
  24987. }
  24988. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24989. {
  24990. if (deadMansPedalFile != File::nonexistent)
  24991. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24992. }
  24993. END_JUCE_NAMESPACE
  24994. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24995. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24996. BEGIN_JUCE_NAMESPACE
  24997. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24998. const File& deadMansPedalFile_,
  24999. PropertiesFile* const propertiesToUse_)
  25000. : list (listToEdit),
  25001. deadMansPedalFile (deadMansPedalFile_),
  25002. optionsButton ("Options..."),
  25003. propertiesToUse (propertiesToUse_)
  25004. {
  25005. listBox.setModel (this);
  25006. addAndMakeVisible (&listBox);
  25007. addAndMakeVisible (&optionsButton);
  25008. optionsButton.addButtonListener (this);
  25009. optionsButton.setTriggeredOnMouseDown (true);
  25010. setSize (400, 600);
  25011. list.addChangeListener (this);
  25012. changeListenerCallback (0);
  25013. }
  25014. PluginListComponent::~PluginListComponent()
  25015. {
  25016. list.removeChangeListener (this);
  25017. }
  25018. void PluginListComponent::resized()
  25019. {
  25020. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  25021. optionsButton.changeWidthToFitText (24);
  25022. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  25023. }
  25024. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  25025. {
  25026. listBox.updateContent();
  25027. listBox.repaint();
  25028. }
  25029. int PluginListComponent::getNumRows()
  25030. {
  25031. return list.getNumTypes();
  25032. }
  25033. void PluginListComponent::paintListBoxItem (int row,
  25034. Graphics& g,
  25035. int width, int height,
  25036. bool rowIsSelected)
  25037. {
  25038. if (rowIsSelected)
  25039. g.fillAll (findColour (TextEditor::highlightColourId));
  25040. const PluginDescription* const pd = list.getType (row);
  25041. if (pd != 0)
  25042. {
  25043. GlyphArrangement ga;
  25044. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  25045. g.setColour (Colours::black);
  25046. ga.draw (g);
  25047. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  25048. String desc;
  25049. desc << pd->pluginFormatName
  25050. << (pd->isInstrument ? " instrument" : " effect")
  25051. << " - "
  25052. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  25053. << " / "
  25054. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  25055. if (pd->manufacturerName.isNotEmpty())
  25056. desc << " - " << pd->manufacturerName;
  25057. if (pd->version.isNotEmpty())
  25058. desc << " - " << pd->version;
  25059. if (pd->category.isNotEmpty())
  25060. desc << " - category: '" << pd->category << '\'';
  25061. g.setColour (Colours::grey);
  25062. ga.clear();
  25063. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  25064. ga.draw (g);
  25065. }
  25066. }
  25067. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  25068. {
  25069. list.removeType (lastRowSelected);
  25070. }
  25071. void PluginListComponent::buttonClicked (Button* button)
  25072. {
  25073. if (button == &optionsButton)
  25074. {
  25075. PopupMenu menu;
  25076. menu.addItem (1, TRANS("Clear list"));
  25077. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  25078. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  25079. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25080. menu.addSeparator();
  25081. menu.addItem (2, TRANS("Sort alphabetically"));
  25082. menu.addItem (3, TRANS("Sort by category"));
  25083. menu.addItem (4, TRANS("Sort by manufacturer"));
  25084. menu.addSeparator();
  25085. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25086. {
  25087. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25088. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25089. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25090. }
  25091. const int r = menu.showAt (&optionsButton);
  25092. if (r == 1)
  25093. {
  25094. list.clear();
  25095. }
  25096. else if (r == 2)
  25097. {
  25098. list.sort (KnownPluginList::sortAlphabetically);
  25099. }
  25100. else if (r == 3)
  25101. {
  25102. list.sort (KnownPluginList::sortByCategory);
  25103. }
  25104. else if (r == 4)
  25105. {
  25106. list.sort (KnownPluginList::sortByManufacturer);
  25107. }
  25108. else if (r == 5)
  25109. {
  25110. const SparseSet <int> selected (listBox.getSelectedRows());
  25111. for (int i = list.getNumTypes(); --i >= 0;)
  25112. if (selected.contains (i))
  25113. list.removeType (i);
  25114. }
  25115. else if (r == 6)
  25116. {
  25117. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25118. if (desc != 0)
  25119. {
  25120. if (File (desc->fileOrIdentifier).existsAsFile())
  25121. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25122. }
  25123. }
  25124. else if (r == 7)
  25125. {
  25126. for (int i = list.getNumTypes(); --i >= 0;)
  25127. {
  25128. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25129. {
  25130. list.removeType (i);
  25131. }
  25132. }
  25133. }
  25134. else if (r != 0)
  25135. {
  25136. typeToScan = r - 10;
  25137. startTimer (1);
  25138. }
  25139. }
  25140. }
  25141. void PluginListComponent::timerCallback()
  25142. {
  25143. stopTimer();
  25144. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25145. }
  25146. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25147. {
  25148. return true;
  25149. }
  25150. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25151. {
  25152. OwnedArray <PluginDescription> typesFound;
  25153. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25154. }
  25155. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25156. {
  25157. if (format == 0)
  25158. return;
  25159. FileSearchPath path (format->getDefaultLocationsToSearch());
  25160. if (propertiesToUse != 0)
  25161. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25162. {
  25163. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25164. FileSearchPathListComponent pathList;
  25165. pathList.setSize (500, 300);
  25166. pathList.setPath (path);
  25167. aw.addCustomComponent (&pathList);
  25168. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25169. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  25170. if (aw.runModalLoop() == 0)
  25171. return;
  25172. path = pathList.getPath();
  25173. }
  25174. if (propertiesToUse != 0)
  25175. {
  25176. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25177. propertiesToUse->saveIfNeeded();
  25178. }
  25179. double progress = 0.0;
  25180. AlertWindow aw (TRANS("Scanning for plugins..."),
  25181. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25182. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  25183. aw.addProgressBarComponent (progress);
  25184. aw.enterModalState();
  25185. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25186. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25187. for (;;)
  25188. {
  25189. aw.setMessage (TRANS("Testing:\n\n")
  25190. + scanner.getNextPluginFileThatWillBeScanned());
  25191. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25192. if (! scanner.scanNextFile (true))
  25193. break;
  25194. if (! aw.isCurrentlyModal())
  25195. break;
  25196. progress = scanner.getProgress();
  25197. }
  25198. if (scanner.getFailedFiles().size() > 0)
  25199. {
  25200. StringArray shortNames;
  25201. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25202. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25203. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25204. TRANS("Scan complete"),
  25205. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25206. + shortNames.joinIntoString (", "));
  25207. }
  25208. }
  25209. END_JUCE_NAMESPACE
  25210. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25211. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25212. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25213. #include <AudioUnit/AudioUnit.h>
  25214. #include <AudioUnit/AUCocoaUIView.h>
  25215. #include <CoreAudioKit/AUGenericView.h>
  25216. #if JUCE_SUPPORT_CARBON
  25217. #include <AudioToolbox/AudioUnitUtilities.h>
  25218. #include <AudioUnit/AudioUnitCarbonView.h>
  25219. #endif
  25220. BEGIN_JUCE_NAMESPACE
  25221. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25222. #endif
  25223. #if JUCE_MAC
  25224. // Change this to disable logging of various activities
  25225. #ifndef AU_LOGGING
  25226. #define AU_LOGGING 1
  25227. #endif
  25228. #if AU_LOGGING
  25229. #define log(a) Logger::writeToLog(a);
  25230. #else
  25231. #define log(a)
  25232. #endif
  25233. namespace AudioUnitFormatHelpers
  25234. {
  25235. static int insideCallback = 0;
  25236. const String osTypeToString (OSType type)
  25237. {
  25238. char s[4];
  25239. s[0] = (char) (((uint32) type) >> 24);
  25240. s[1] = (char) (((uint32) type) >> 16);
  25241. s[2] = (char) (((uint32) type) >> 8);
  25242. s[3] = (char) ((uint32) type);
  25243. return String (s, 4);
  25244. }
  25245. OSType stringToOSType (const String& s1)
  25246. {
  25247. const String s (s1 + " ");
  25248. return (((OSType) (unsigned char) s[0]) << 24)
  25249. | (((OSType) (unsigned char) s[1]) << 16)
  25250. | (((OSType) (unsigned char) s[2]) << 8)
  25251. | ((OSType) (unsigned char) s[3]);
  25252. }
  25253. static const char* auIdentifierPrefix = "AudioUnit:";
  25254. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25255. {
  25256. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25257. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25258. String s (auIdentifierPrefix);
  25259. if (desc.componentType == kAudioUnitType_MusicDevice)
  25260. s << "Synths/";
  25261. else if (desc.componentType == kAudioUnitType_MusicEffect
  25262. || desc.componentType == kAudioUnitType_Effect)
  25263. s << "Effects/";
  25264. else if (desc.componentType == kAudioUnitType_Generator)
  25265. s << "Generators/";
  25266. else if (desc.componentType == kAudioUnitType_Panner)
  25267. s << "Panners/";
  25268. s << osTypeToString (desc.componentType) << ","
  25269. << osTypeToString (desc.componentSubType) << ","
  25270. << osTypeToString (desc.componentManufacturer);
  25271. return s;
  25272. }
  25273. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25274. {
  25275. Handle componentNameHandle = NewHandle (sizeof (void*));
  25276. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25277. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25278. {
  25279. ComponentDescription desc;
  25280. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25281. {
  25282. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25283. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25284. if (nameString != 0 && nameString[0] != 0)
  25285. {
  25286. const String all ((const char*) nameString + 1, nameString[0]);
  25287. DBG ("name: "+ all);
  25288. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25289. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25290. }
  25291. if (infoString != 0 && infoString[0] != 0)
  25292. {
  25293. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25294. }
  25295. if (name.isEmpty())
  25296. name = "<Unknown>";
  25297. }
  25298. DisposeHandle (componentNameHandle);
  25299. DisposeHandle (componentInfoHandle);
  25300. }
  25301. }
  25302. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25303. String& name, String& version, String& manufacturer)
  25304. {
  25305. zerostruct (desc);
  25306. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25307. {
  25308. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25309. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25310. StringArray tokens;
  25311. tokens.addTokens (s, ",", String::empty);
  25312. tokens.trim();
  25313. tokens.removeEmptyStrings();
  25314. if (tokens.size() == 3)
  25315. {
  25316. desc.componentType = stringToOSType (tokens[0]);
  25317. desc.componentSubType = stringToOSType (tokens[1]);
  25318. desc.componentManufacturer = stringToOSType (tokens[2]);
  25319. ComponentRecord* comp = FindNextComponent (0, &desc);
  25320. if (comp != 0)
  25321. {
  25322. getAUDetails (comp, name, manufacturer);
  25323. return true;
  25324. }
  25325. }
  25326. }
  25327. return false;
  25328. }
  25329. }
  25330. class AudioUnitPluginWindowCarbon;
  25331. class AudioUnitPluginWindowCocoa;
  25332. class AudioUnitPluginInstance : public AudioPluginInstance
  25333. {
  25334. public:
  25335. ~AudioUnitPluginInstance();
  25336. void initialise();
  25337. // AudioPluginInstance methods:
  25338. void fillInPluginDescription (PluginDescription& desc) const
  25339. {
  25340. desc.name = pluginName;
  25341. desc.descriptiveName = pluginName;
  25342. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25343. desc.uid = ((int) componentDesc.componentType)
  25344. ^ ((int) componentDesc.componentSubType)
  25345. ^ ((int) componentDesc.componentManufacturer);
  25346. desc.lastFileModTime = 0;
  25347. desc.pluginFormatName = "AudioUnit";
  25348. desc.category = getCategory();
  25349. desc.manufacturerName = manufacturer;
  25350. desc.version = version;
  25351. desc.numInputChannels = getNumInputChannels();
  25352. desc.numOutputChannels = getNumOutputChannels();
  25353. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25354. }
  25355. void* getPlatformSpecificData() { return audioUnit; }
  25356. const String getName() const { return pluginName; }
  25357. bool acceptsMidi() const { return wantsMidiMessages; }
  25358. bool producesMidi() const { return false; }
  25359. // AudioProcessor methods:
  25360. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25361. void releaseResources();
  25362. void processBlock (AudioSampleBuffer& buffer,
  25363. MidiBuffer& midiMessages);
  25364. bool hasEditor() const;
  25365. AudioProcessorEditor* createEditor();
  25366. const String getInputChannelName (int index) const;
  25367. bool isInputChannelStereoPair (int index) const;
  25368. const String getOutputChannelName (int index) const;
  25369. bool isOutputChannelStereoPair (int index) const;
  25370. int getNumParameters();
  25371. float getParameter (int index);
  25372. void setParameter (int index, float newValue);
  25373. const String getParameterName (int index);
  25374. const String getParameterText (int index);
  25375. bool isParameterAutomatable (int index) const;
  25376. int getNumPrograms();
  25377. int getCurrentProgram();
  25378. void setCurrentProgram (int index);
  25379. const String getProgramName (int index);
  25380. void changeProgramName (int index, const String& newName);
  25381. void getStateInformation (MemoryBlock& destData);
  25382. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25383. void setStateInformation (const void* data, int sizeInBytes);
  25384. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25385. private:
  25386. friend class AudioUnitPluginWindowCarbon;
  25387. friend class AudioUnitPluginWindowCocoa;
  25388. friend class AudioUnitPluginFormat;
  25389. ComponentDescription componentDesc;
  25390. String pluginName, manufacturer, version;
  25391. String fileOrIdentifier;
  25392. CriticalSection lock;
  25393. bool wantsMidiMessages, wasPlaying, prepared;
  25394. HeapBlock <AudioBufferList> outputBufferList;
  25395. AudioTimeStamp timeStamp;
  25396. AudioSampleBuffer* currentBuffer;
  25397. AudioUnit audioUnit;
  25398. Array <int> parameterIds;
  25399. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25400. void setPluginCallbacks();
  25401. void getParameterListFromPlugin();
  25402. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25403. const AudioTimeStamp* inTimeStamp,
  25404. UInt32 inBusNumber,
  25405. UInt32 inNumberFrames,
  25406. AudioBufferList* ioData) const;
  25407. static OSStatus renderGetInputCallback (void* inRefCon,
  25408. AudioUnitRenderActionFlags* ioActionFlags,
  25409. const AudioTimeStamp* inTimeStamp,
  25410. UInt32 inBusNumber,
  25411. UInt32 inNumberFrames,
  25412. AudioBufferList* ioData)
  25413. {
  25414. return ((AudioUnitPluginInstance*) inRefCon)
  25415. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25416. }
  25417. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25418. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25419. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25420. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25421. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25422. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25423. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25424. {
  25425. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25426. }
  25427. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25428. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25429. Float64* outCurrentMeasureDownBeat)
  25430. {
  25431. return ((AudioUnitPluginInstance*) inHostUserData)
  25432. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25433. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25434. }
  25435. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25436. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25437. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25438. {
  25439. return ((AudioUnitPluginInstance*) inHostUserData)
  25440. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25441. outCurrentSampleInTimeLine, outIsCycling,
  25442. outCycleStartBeat, outCycleEndBeat);
  25443. }
  25444. void getNumChannels (int& numIns, int& numOuts)
  25445. {
  25446. numIns = 0;
  25447. numOuts = 0;
  25448. AUChannelInfo supportedChannels [128];
  25449. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25450. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25451. 0, supportedChannels, &supportedChannelsSize) == noErr
  25452. && supportedChannelsSize > 0)
  25453. {
  25454. int explicitNumIns = 0;
  25455. int explicitNumOuts = 0;
  25456. int maximumNumIns = 0;
  25457. int maximumNumOuts = 0;
  25458. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25459. {
  25460. const int inChannels = (int) supportedChannels[i].inChannels;
  25461. const int outChannels = (int) supportedChannels[i].outChannels;
  25462. if (inChannels < 0)
  25463. maximumNumIns = jmin (maximumNumIns, inChannels);
  25464. else
  25465. explicitNumIns = jmax (explicitNumIns, inChannels);
  25466. if (outChannels < 0)
  25467. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25468. else
  25469. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25470. }
  25471. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25472. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25473. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25474. {
  25475. numIns = numOuts = 2;
  25476. }
  25477. else
  25478. {
  25479. numIns = explicitNumIns;
  25480. numOuts = explicitNumOuts;
  25481. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25482. numIns = 2;
  25483. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25484. numOuts = 2;
  25485. }
  25486. }
  25487. else
  25488. {
  25489. // (this really means the plugin will take any number of ins/outs as long
  25490. // as they are the same)
  25491. numIns = numOuts = 2;
  25492. }
  25493. }
  25494. const String getCategory() const;
  25495. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25497. };
  25498. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25499. : fileOrIdentifier (fileOrIdentifier),
  25500. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25501. audioUnit (0),
  25502. currentBuffer (0)
  25503. {
  25504. using namespace AudioUnitFormatHelpers;
  25505. try
  25506. {
  25507. ++insideCallback;
  25508. log ("Opening AU: " + fileOrIdentifier);
  25509. if (getComponentDescFromFile (fileOrIdentifier))
  25510. {
  25511. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25512. if (comp != 0)
  25513. {
  25514. audioUnit = (AudioUnit) OpenComponent (comp);
  25515. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25516. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25517. }
  25518. }
  25519. --insideCallback;
  25520. }
  25521. catch (...)
  25522. {
  25523. --insideCallback;
  25524. }
  25525. }
  25526. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25527. {
  25528. const ScopedLock sl (lock);
  25529. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25530. if (audioUnit != 0)
  25531. {
  25532. AudioUnitUninitialize (audioUnit);
  25533. CloseComponent (audioUnit);
  25534. audioUnit = 0;
  25535. }
  25536. }
  25537. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25538. {
  25539. zerostruct (componentDesc);
  25540. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25541. return true;
  25542. const File file (fileOrIdentifier);
  25543. if (! file.hasFileExtension (".component"))
  25544. return false;
  25545. const char* const utf8 = fileOrIdentifier.toUTF8();
  25546. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25547. strlen (utf8), file.isDirectory());
  25548. if (url != 0)
  25549. {
  25550. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25551. CFRelease (url);
  25552. if (bundleRef != 0)
  25553. {
  25554. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25555. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25556. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25557. if (pluginName.isEmpty())
  25558. pluginName = file.getFileNameWithoutExtension();
  25559. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25560. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25561. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25562. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25563. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25564. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25565. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25566. UseResFile (resFileId);
  25567. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25568. {
  25569. Handle h = Get1IndResource ('thng', i);
  25570. if (h != 0)
  25571. {
  25572. HLock (h);
  25573. const uint32* const types = (const uint32*) *h;
  25574. if (types[0] == kAudioUnitType_MusicDevice
  25575. || types[0] == kAudioUnitType_MusicEffect
  25576. || types[0] == kAudioUnitType_Effect
  25577. || types[0] == kAudioUnitType_Generator
  25578. || types[0] == kAudioUnitType_Panner)
  25579. {
  25580. componentDesc.componentType = types[0];
  25581. componentDesc.componentSubType = types[1];
  25582. componentDesc.componentManufacturer = types[2];
  25583. break;
  25584. }
  25585. HUnlock (h);
  25586. ReleaseResource (h);
  25587. }
  25588. }
  25589. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25590. CFRelease (bundleRef);
  25591. }
  25592. }
  25593. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25594. }
  25595. void AudioUnitPluginInstance::initialise()
  25596. {
  25597. getParameterListFromPlugin();
  25598. setPluginCallbacks();
  25599. int numIns, numOuts;
  25600. getNumChannels (numIns, numOuts);
  25601. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25602. setLatencySamples (0);
  25603. }
  25604. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25605. {
  25606. parameterIds.clear();
  25607. if (audioUnit != 0)
  25608. {
  25609. UInt32 paramListSize = 0;
  25610. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25611. 0, 0, &paramListSize);
  25612. if (paramListSize > 0)
  25613. {
  25614. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25615. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25616. 0, &parameterIds.getReference(0), &paramListSize);
  25617. }
  25618. }
  25619. }
  25620. void AudioUnitPluginInstance::setPluginCallbacks()
  25621. {
  25622. if (audioUnit != 0)
  25623. {
  25624. {
  25625. AURenderCallbackStruct info;
  25626. zerostruct (info);
  25627. info.inputProcRefCon = this;
  25628. info.inputProc = renderGetInputCallback;
  25629. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25630. 0, &info, sizeof (info));
  25631. }
  25632. {
  25633. HostCallbackInfo info;
  25634. zerostruct (info);
  25635. info.hostUserData = this;
  25636. info.beatAndTempoProc = getBeatAndTempoCallback;
  25637. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25638. info.transportStateProc = getTransportStateCallback;
  25639. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25640. 0, &info, sizeof (info));
  25641. }
  25642. }
  25643. }
  25644. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25645. int samplesPerBlockExpected)
  25646. {
  25647. if (audioUnit != 0)
  25648. {
  25649. releaseResources();
  25650. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25651. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25652. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25653. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25654. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25655. {
  25656. Float64 sr = sampleRate_;
  25657. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25658. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25659. }
  25660. int numIns, numOuts;
  25661. getNumChannels (numIns, numOuts);
  25662. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25663. Float64 latencySecs = 0.0;
  25664. UInt32 latencySize = sizeof (latencySecs);
  25665. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25666. 0, &latencySecs, &latencySize);
  25667. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25668. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25669. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25670. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25671. {
  25672. AudioStreamBasicDescription stream;
  25673. zerostruct (stream);
  25674. stream.mSampleRate = sampleRate_;
  25675. stream.mFormatID = kAudioFormatLinearPCM;
  25676. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25677. stream.mFramesPerPacket = 1;
  25678. stream.mBytesPerPacket = 4;
  25679. stream.mBytesPerFrame = 4;
  25680. stream.mBitsPerChannel = 32;
  25681. stream.mChannelsPerFrame = numIns;
  25682. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25683. 0, &stream, sizeof (stream));
  25684. stream.mChannelsPerFrame = numOuts;
  25685. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25686. 0, &stream, sizeof (stream));
  25687. }
  25688. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25689. outputBufferList->mNumberBuffers = numOuts;
  25690. for (int i = numOuts; --i >= 0;)
  25691. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25692. zerostruct (timeStamp);
  25693. timeStamp.mSampleTime = 0;
  25694. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25695. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25696. currentBuffer = 0;
  25697. wasPlaying = false;
  25698. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25699. }
  25700. }
  25701. void AudioUnitPluginInstance::releaseResources()
  25702. {
  25703. if (prepared)
  25704. {
  25705. AudioUnitUninitialize (audioUnit);
  25706. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25707. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25708. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25709. outputBufferList.free();
  25710. currentBuffer = 0;
  25711. prepared = false;
  25712. }
  25713. }
  25714. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25715. const AudioTimeStamp* inTimeStamp,
  25716. UInt32 inBusNumber,
  25717. UInt32 inNumberFrames,
  25718. AudioBufferList* ioData) const
  25719. {
  25720. if (inBusNumber == 0
  25721. && currentBuffer != 0)
  25722. {
  25723. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25724. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25725. {
  25726. if (i < currentBuffer->getNumChannels())
  25727. {
  25728. memcpy (ioData->mBuffers[i].mData,
  25729. currentBuffer->getSampleData (i, 0),
  25730. sizeof (float) * inNumberFrames);
  25731. }
  25732. else
  25733. {
  25734. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25735. }
  25736. }
  25737. }
  25738. return noErr;
  25739. }
  25740. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25741. MidiBuffer& midiMessages)
  25742. {
  25743. const int numSamples = buffer.getNumSamples();
  25744. if (prepared)
  25745. {
  25746. AudioUnitRenderActionFlags flags = 0;
  25747. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25748. for (int i = getNumOutputChannels(); --i >= 0;)
  25749. {
  25750. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25751. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25752. }
  25753. currentBuffer = &buffer;
  25754. if (wantsMidiMessages)
  25755. {
  25756. const uint8* midiEventData;
  25757. int midiEventSize, midiEventPosition;
  25758. MidiBuffer::Iterator i (midiMessages);
  25759. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25760. {
  25761. if (midiEventSize <= 3)
  25762. MusicDeviceMIDIEvent (audioUnit,
  25763. midiEventData[0], midiEventData[1], midiEventData[2],
  25764. midiEventPosition);
  25765. else
  25766. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25767. }
  25768. midiMessages.clear();
  25769. }
  25770. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25771. 0, numSamples, outputBufferList);
  25772. timeStamp.mSampleTime += numSamples;
  25773. }
  25774. else
  25775. {
  25776. // Plugin not working correctly, so just bypass..
  25777. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25778. buffer.clear (i, 0, buffer.getNumSamples());
  25779. }
  25780. }
  25781. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25782. {
  25783. AudioPlayHead* const ph = getPlayHead();
  25784. AudioPlayHead::CurrentPositionInfo result;
  25785. if (ph != 0 && ph->getCurrentPosition (result))
  25786. {
  25787. if (outCurrentBeat != 0)
  25788. *outCurrentBeat = result.ppqPosition;
  25789. if (outCurrentTempo != 0)
  25790. *outCurrentTempo = result.bpm;
  25791. }
  25792. else
  25793. {
  25794. if (outCurrentBeat != 0)
  25795. *outCurrentBeat = 0;
  25796. if (outCurrentTempo != 0)
  25797. *outCurrentTempo = 120.0;
  25798. }
  25799. return noErr;
  25800. }
  25801. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25802. Float32* outTimeSig_Numerator,
  25803. UInt32* outTimeSig_Denominator,
  25804. Float64* outCurrentMeasureDownBeat) const
  25805. {
  25806. AudioPlayHead* const ph = getPlayHead();
  25807. AudioPlayHead::CurrentPositionInfo result;
  25808. if (ph != 0 && ph->getCurrentPosition (result))
  25809. {
  25810. if (outTimeSig_Numerator != 0)
  25811. *outTimeSig_Numerator = result.timeSigNumerator;
  25812. if (outTimeSig_Denominator != 0)
  25813. *outTimeSig_Denominator = result.timeSigDenominator;
  25814. if (outDeltaSampleOffsetToNextBeat != 0)
  25815. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25816. if (outCurrentMeasureDownBeat != 0)
  25817. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25818. }
  25819. else
  25820. {
  25821. if (outDeltaSampleOffsetToNextBeat != 0)
  25822. *outDeltaSampleOffsetToNextBeat = 0;
  25823. if (outTimeSig_Numerator != 0)
  25824. *outTimeSig_Numerator = 4;
  25825. if (outTimeSig_Denominator != 0)
  25826. *outTimeSig_Denominator = 4;
  25827. if (outCurrentMeasureDownBeat != 0)
  25828. *outCurrentMeasureDownBeat = 0;
  25829. }
  25830. return noErr;
  25831. }
  25832. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25833. Boolean* outTransportStateChanged,
  25834. Float64* outCurrentSampleInTimeLine,
  25835. Boolean* outIsCycling,
  25836. Float64* outCycleStartBeat,
  25837. Float64* outCycleEndBeat)
  25838. {
  25839. AudioPlayHead* const ph = getPlayHead();
  25840. AudioPlayHead::CurrentPositionInfo result;
  25841. if (ph != 0 && ph->getCurrentPosition (result))
  25842. {
  25843. if (outIsPlaying != 0)
  25844. *outIsPlaying = result.isPlaying;
  25845. if (outTransportStateChanged != 0)
  25846. {
  25847. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25848. wasPlaying = result.isPlaying;
  25849. }
  25850. if (outCurrentSampleInTimeLine != 0)
  25851. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25852. if (outIsCycling != 0)
  25853. *outIsCycling = false;
  25854. if (outCycleStartBeat != 0)
  25855. *outCycleStartBeat = 0;
  25856. if (outCycleEndBeat != 0)
  25857. *outCycleEndBeat = 0;
  25858. }
  25859. else
  25860. {
  25861. if (outIsPlaying != 0)
  25862. *outIsPlaying = false;
  25863. if (outTransportStateChanged != 0)
  25864. *outTransportStateChanged = false;
  25865. if (outCurrentSampleInTimeLine != 0)
  25866. *outCurrentSampleInTimeLine = 0;
  25867. if (outIsCycling != 0)
  25868. *outIsCycling = false;
  25869. if (outCycleStartBeat != 0)
  25870. *outCycleStartBeat = 0;
  25871. if (outCycleEndBeat != 0)
  25872. *outCycleEndBeat = 0;
  25873. }
  25874. return noErr;
  25875. }
  25876. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25877. public Timer
  25878. {
  25879. public:
  25880. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25881. : AudioProcessorEditor (&plugin_),
  25882. plugin (plugin_)
  25883. {
  25884. addAndMakeVisible (&wrapper);
  25885. setOpaque (true);
  25886. setVisible (true);
  25887. setSize (100, 100);
  25888. createView (createGenericViewIfNeeded);
  25889. }
  25890. ~AudioUnitPluginWindowCocoa()
  25891. {
  25892. const bool wasValid = isValid();
  25893. wrapper.setView (0);
  25894. if (wasValid)
  25895. plugin.editorBeingDeleted (this);
  25896. }
  25897. bool isValid() const { return wrapper.getView() != 0; }
  25898. void paint (Graphics& g)
  25899. {
  25900. g.fillAll (Colours::white);
  25901. }
  25902. void resized()
  25903. {
  25904. wrapper.setSize (getWidth(), getHeight());
  25905. }
  25906. void timerCallback()
  25907. {
  25908. wrapper.resizeToFitView();
  25909. startTimer (jmin (713, getTimerInterval() + 51));
  25910. }
  25911. void childBoundsChanged (Component* child)
  25912. {
  25913. setSize (wrapper.getWidth(), wrapper.getHeight());
  25914. startTimer (70);
  25915. }
  25916. private:
  25917. AudioUnitPluginInstance& plugin;
  25918. NSViewComponent wrapper;
  25919. bool createView (const bool createGenericViewIfNeeded)
  25920. {
  25921. NSView* pluginView = 0;
  25922. UInt32 dataSize = 0;
  25923. Boolean isWritable = false;
  25924. AudioUnitInitialize (plugin.audioUnit);
  25925. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25926. 0, &dataSize, &isWritable) == noErr
  25927. && dataSize != 0
  25928. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25929. 0, &dataSize, &isWritable) == noErr)
  25930. {
  25931. HeapBlock <AudioUnitCocoaViewInfo> info;
  25932. info.calloc (dataSize, 1);
  25933. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25934. 0, info, &dataSize) == noErr)
  25935. {
  25936. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25937. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25938. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25939. Class viewClass = [viewBundle classNamed: viewClassName];
  25940. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25941. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25942. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25943. {
  25944. id factory = [[[viewClass alloc] init] autorelease];
  25945. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25946. withSize: NSMakeSize (getWidth(), getHeight())];
  25947. }
  25948. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25949. CFRelease (info->mCocoaAUViewClass[i]);
  25950. CFRelease (info->mCocoaAUViewBundleLocation);
  25951. }
  25952. }
  25953. if (createGenericViewIfNeeded && (pluginView == 0))
  25954. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25955. wrapper.setView (pluginView);
  25956. if (pluginView != 0)
  25957. {
  25958. timerCallback();
  25959. startTimer (70);
  25960. }
  25961. return pluginView != 0;
  25962. }
  25963. };
  25964. #if JUCE_SUPPORT_CARBON
  25965. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25966. {
  25967. public:
  25968. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25969. : AudioProcessorEditor (&plugin_),
  25970. plugin (plugin_),
  25971. viewComponent (0)
  25972. {
  25973. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25974. setOpaque (true);
  25975. setVisible (true);
  25976. setSize (400, 300);
  25977. ComponentDescription viewList [16];
  25978. UInt32 viewListSize = sizeof (viewList);
  25979. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25980. 0, &viewList, &viewListSize);
  25981. componentRecord = FindNextComponent (0, &viewList[0]);
  25982. }
  25983. ~AudioUnitPluginWindowCarbon()
  25984. {
  25985. innerWrapper = 0;
  25986. if (isValid())
  25987. plugin.editorBeingDeleted (this);
  25988. }
  25989. bool isValid() const throw() { return componentRecord != 0; }
  25990. void paint (Graphics& g)
  25991. {
  25992. g.fillAll (Colours::black);
  25993. }
  25994. void resized()
  25995. {
  25996. innerWrapper->setSize (getWidth(), getHeight());
  25997. }
  25998. bool keyStateChanged (bool)
  25999. {
  26000. return false;
  26001. }
  26002. bool keyPressed (const KeyPress&)
  26003. {
  26004. return false;
  26005. }
  26006. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  26007. AudioUnitCarbonView getViewComponent()
  26008. {
  26009. if (viewComponent == 0 && componentRecord != 0)
  26010. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  26011. return viewComponent;
  26012. }
  26013. void closeViewComponent()
  26014. {
  26015. if (viewComponent != 0)
  26016. {
  26017. log ("Closing AU GUI: " + plugin.getName());
  26018. CloseComponent (viewComponent);
  26019. viewComponent = 0;
  26020. }
  26021. }
  26022. private:
  26023. AudioUnitPluginInstance& plugin;
  26024. ComponentRecord* componentRecord;
  26025. AudioUnitCarbonView viewComponent;
  26026. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26027. {
  26028. public:
  26029. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  26030. : owner (owner_)
  26031. {
  26032. }
  26033. ~InnerWrapperComponent()
  26034. {
  26035. deleteWindow();
  26036. }
  26037. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26038. {
  26039. log ("Opening AU GUI: " + owner->plugin.getName());
  26040. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  26041. if (viewComponent == 0)
  26042. return 0;
  26043. Float32Point pos = { 0, 0 };
  26044. Float32Point size = { 250, 200 };
  26045. HIViewRef pluginView = 0;
  26046. AudioUnitCarbonViewCreate (viewComponent,
  26047. owner->getAudioUnit(),
  26048. windowRef,
  26049. rootView,
  26050. &pos,
  26051. &size,
  26052. (ControlRef*) &pluginView);
  26053. return pluginView;
  26054. }
  26055. void removeView (HIViewRef)
  26056. {
  26057. owner->closeViewComponent();
  26058. }
  26059. private:
  26060. AudioUnitPluginWindowCarbon* const owner;
  26061. };
  26062. friend class InnerWrapperComponent;
  26063. ScopedPointer<InnerWrapperComponent> innerWrapper;
  26064. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  26065. };
  26066. #endif
  26067. bool AudioUnitPluginInstance::hasEditor() const
  26068. {
  26069. return true;
  26070. }
  26071. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26072. {
  26073. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26074. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26075. w = 0;
  26076. #if JUCE_SUPPORT_CARBON
  26077. if (w == 0)
  26078. {
  26079. w = new AudioUnitPluginWindowCarbon (*this);
  26080. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26081. w = 0;
  26082. }
  26083. #endif
  26084. if (w == 0)
  26085. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26086. return w.release();
  26087. }
  26088. const String AudioUnitPluginInstance::getCategory() const
  26089. {
  26090. const char* result = 0;
  26091. switch (componentDesc.componentType)
  26092. {
  26093. case kAudioUnitType_Effect:
  26094. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  26095. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  26096. case kAudioUnitType_Generator: result = "Generator"; break;
  26097. case kAudioUnitType_Panner: result = "Panner"; break;
  26098. default: break;
  26099. }
  26100. return result;
  26101. }
  26102. int AudioUnitPluginInstance::getNumParameters()
  26103. {
  26104. return parameterIds.size();
  26105. }
  26106. float AudioUnitPluginInstance::getParameter (int index)
  26107. {
  26108. const ScopedLock sl (lock);
  26109. Float32 value = 0.0f;
  26110. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  26111. {
  26112. AudioUnitGetParameter (audioUnit,
  26113. (UInt32) parameterIds.getUnchecked (index),
  26114. kAudioUnitScope_Global, 0,
  26115. &value);
  26116. }
  26117. return value;
  26118. }
  26119. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26120. {
  26121. const ScopedLock sl (lock);
  26122. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  26123. {
  26124. AudioUnitSetParameter (audioUnit,
  26125. (UInt32) parameterIds.getUnchecked (index),
  26126. kAudioUnitScope_Global, 0,
  26127. newValue, 0);
  26128. }
  26129. }
  26130. const String AudioUnitPluginInstance::getParameterName (int index)
  26131. {
  26132. AudioUnitParameterInfo info;
  26133. zerostruct (info);
  26134. UInt32 sz = sizeof (info);
  26135. String name;
  26136. if (AudioUnitGetProperty (audioUnit,
  26137. kAudioUnitProperty_ParameterInfo,
  26138. kAudioUnitScope_Global,
  26139. parameterIds [index], &info, &sz) == noErr)
  26140. {
  26141. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26142. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26143. else
  26144. name = String (info.name, sizeof (info.name));
  26145. }
  26146. return name;
  26147. }
  26148. const String AudioUnitPluginInstance::getParameterText (int index)
  26149. {
  26150. return String (getParameter (index));
  26151. }
  26152. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26153. {
  26154. AudioUnitParameterInfo info;
  26155. UInt32 sz = sizeof (info);
  26156. if (AudioUnitGetProperty (audioUnit,
  26157. kAudioUnitProperty_ParameterInfo,
  26158. kAudioUnitScope_Global,
  26159. parameterIds [index], &info, &sz) == noErr)
  26160. {
  26161. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26162. }
  26163. return true;
  26164. }
  26165. int AudioUnitPluginInstance::getNumPrograms()
  26166. {
  26167. CFArrayRef presets;
  26168. UInt32 sz = sizeof (CFArrayRef);
  26169. int num = 0;
  26170. if (AudioUnitGetProperty (audioUnit,
  26171. kAudioUnitProperty_FactoryPresets,
  26172. kAudioUnitScope_Global,
  26173. 0, &presets, &sz) == noErr)
  26174. {
  26175. num = (int) CFArrayGetCount (presets);
  26176. CFRelease (presets);
  26177. }
  26178. return num;
  26179. }
  26180. int AudioUnitPluginInstance::getCurrentProgram()
  26181. {
  26182. AUPreset current;
  26183. current.presetNumber = 0;
  26184. UInt32 sz = sizeof (AUPreset);
  26185. AudioUnitGetProperty (audioUnit,
  26186. kAudioUnitProperty_FactoryPresets,
  26187. kAudioUnitScope_Global,
  26188. 0, &current, &sz);
  26189. return current.presetNumber;
  26190. }
  26191. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26192. {
  26193. AUPreset current;
  26194. current.presetNumber = newIndex;
  26195. current.presetName = 0;
  26196. AudioUnitSetProperty (audioUnit,
  26197. kAudioUnitProperty_FactoryPresets,
  26198. kAudioUnitScope_Global,
  26199. 0, &current, sizeof (AUPreset));
  26200. }
  26201. const String AudioUnitPluginInstance::getProgramName (int index)
  26202. {
  26203. String s;
  26204. CFArrayRef presets;
  26205. UInt32 sz = sizeof (CFArrayRef);
  26206. if (AudioUnitGetProperty (audioUnit,
  26207. kAudioUnitProperty_FactoryPresets,
  26208. kAudioUnitScope_Global,
  26209. 0, &presets, &sz) == noErr)
  26210. {
  26211. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26212. {
  26213. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26214. if (p != 0 && p->presetNumber == index)
  26215. {
  26216. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26217. break;
  26218. }
  26219. }
  26220. CFRelease (presets);
  26221. }
  26222. return s;
  26223. }
  26224. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26225. {
  26226. jassertfalse; // xxx not implemented!
  26227. }
  26228. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26229. {
  26230. if (isPositiveAndBelow (index, getNumInputChannels()))
  26231. return "Input " + String (index + 1);
  26232. return String::empty;
  26233. }
  26234. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26235. {
  26236. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26237. return false;
  26238. return true;
  26239. }
  26240. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26241. {
  26242. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26243. return "Output " + String (index + 1);
  26244. return String::empty;
  26245. }
  26246. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26247. {
  26248. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26249. return false;
  26250. return true;
  26251. }
  26252. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26253. {
  26254. getCurrentProgramStateInformation (destData);
  26255. }
  26256. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26257. {
  26258. CFPropertyListRef propertyList = 0;
  26259. UInt32 sz = sizeof (CFPropertyListRef);
  26260. if (AudioUnitGetProperty (audioUnit,
  26261. kAudioUnitProperty_ClassInfo,
  26262. kAudioUnitScope_Global,
  26263. 0, &propertyList, &sz) == noErr)
  26264. {
  26265. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26266. CFWriteStreamOpen (stream);
  26267. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26268. CFWriteStreamClose (stream);
  26269. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26270. destData.setSize (bytesWritten);
  26271. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26272. CFRelease (data);
  26273. CFRelease (stream);
  26274. CFRelease (propertyList);
  26275. }
  26276. }
  26277. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26278. {
  26279. setCurrentProgramStateInformation (data, sizeInBytes);
  26280. }
  26281. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26282. {
  26283. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26284. (const UInt8*) data,
  26285. sizeInBytes,
  26286. kCFAllocatorNull);
  26287. CFReadStreamOpen (stream);
  26288. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26289. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26290. stream,
  26291. 0,
  26292. kCFPropertyListImmutable,
  26293. &format,
  26294. 0);
  26295. CFRelease (stream);
  26296. if (propertyList != 0)
  26297. AudioUnitSetProperty (audioUnit,
  26298. kAudioUnitProperty_ClassInfo,
  26299. kAudioUnitScope_Global,
  26300. 0, &propertyList, sizeof (propertyList));
  26301. }
  26302. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26303. {
  26304. }
  26305. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26306. {
  26307. }
  26308. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26309. const String& fileOrIdentifier)
  26310. {
  26311. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26312. return;
  26313. PluginDescription desc;
  26314. desc.fileOrIdentifier = fileOrIdentifier;
  26315. desc.uid = 0;
  26316. try
  26317. {
  26318. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26319. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26320. if (auInstance != 0)
  26321. {
  26322. auInstance->fillInPluginDescription (desc);
  26323. results.add (new PluginDescription (desc));
  26324. }
  26325. }
  26326. catch (...)
  26327. {
  26328. // crashed while loading...
  26329. }
  26330. }
  26331. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26332. {
  26333. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26334. {
  26335. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26336. if (result->audioUnit != 0)
  26337. {
  26338. result->initialise();
  26339. return result.release();
  26340. }
  26341. }
  26342. return 0;
  26343. }
  26344. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26345. const bool /*recursive*/)
  26346. {
  26347. StringArray result;
  26348. ComponentRecord* comp = 0;
  26349. ComponentDescription desc;
  26350. zerostruct (desc);
  26351. for (;;)
  26352. {
  26353. zerostruct (desc);
  26354. comp = FindNextComponent (comp, &desc);
  26355. if (comp == 0)
  26356. break;
  26357. GetComponentInfo (comp, &desc, 0, 0, 0);
  26358. if (desc.componentType == kAudioUnitType_MusicDevice
  26359. || desc.componentType == kAudioUnitType_MusicEffect
  26360. || desc.componentType == kAudioUnitType_Effect
  26361. || desc.componentType == kAudioUnitType_Generator
  26362. || desc.componentType == kAudioUnitType_Panner)
  26363. {
  26364. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26365. DBG (s);
  26366. result.add (s);
  26367. }
  26368. }
  26369. return result;
  26370. }
  26371. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26372. {
  26373. ComponentDescription desc;
  26374. String name, version, manufacturer;
  26375. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26376. return FindNextComponent (0, &desc) != 0;
  26377. const File f (fileOrIdentifier);
  26378. return f.hasFileExtension (".component")
  26379. && f.isDirectory();
  26380. }
  26381. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26382. {
  26383. ComponentDescription desc;
  26384. String name, version, manufacturer;
  26385. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26386. if (name.isEmpty())
  26387. name = fileOrIdentifier;
  26388. return name;
  26389. }
  26390. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26391. {
  26392. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26393. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26394. else
  26395. return File (desc.fileOrIdentifier).exists();
  26396. }
  26397. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26398. {
  26399. return FileSearchPath ("/(Default AudioUnit locations)");
  26400. }
  26401. #endif
  26402. END_JUCE_NAMESPACE
  26403. #undef log
  26404. #endif
  26405. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26406. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26407. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26408. #define JUCE_MAC_VST_INCLUDED 1
  26409. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26410. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26411. #if JUCE_WINDOWS
  26412. #undef _WIN32_WINNT
  26413. #define _WIN32_WINNT 0x500
  26414. #undef STRICT
  26415. #define STRICT
  26416. #include <windows.h>
  26417. #include <float.h>
  26418. #pragma warning (disable : 4312 4355)
  26419. #elif JUCE_LINUX
  26420. #include <float.h>
  26421. #include <sys/time.h>
  26422. #include <X11/Xlib.h>
  26423. #include <X11/Xutil.h>
  26424. #include <X11/Xatom.h>
  26425. #undef Font
  26426. #undef KeyPress
  26427. #undef Drawable
  26428. #undef Time
  26429. #else
  26430. #include <Cocoa/Cocoa.h>
  26431. #include <Carbon/Carbon.h>
  26432. #endif
  26433. #if ! (JUCE_MAC && JUCE_64BIT)
  26434. BEGIN_JUCE_NAMESPACE
  26435. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26436. #endif
  26437. #undef PRAGMA_ALIGN_SUPPORTED
  26438. #define VST_FORCE_DEPRECATED 0
  26439. #if JUCE_MSVC
  26440. #pragma warning (push)
  26441. #pragma warning (disable: 4996)
  26442. #endif
  26443. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26444. your include path if you want to add VST support.
  26445. If you're not interested in VSTs, you can disable them by changing the
  26446. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26447. */
  26448. #include <pluginterfaces/vst2.x/aeffectx.h>
  26449. #if JUCE_MSVC
  26450. #pragma warning (pop)
  26451. #endif
  26452. #if JUCE_LINUX
  26453. #define Font JUCE_NAMESPACE::Font
  26454. #define KeyPress JUCE_NAMESPACE::KeyPress
  26455. #define Drawable JUCE_NAMESPACE::Drawable
  26456. #define Time JUCE_NAMESPACE::Time
  26457. #endif
  26458. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26459. #ifdef __aeffect__
  26460. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26461. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26462. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26463. events to the list.
  26464. This is used by both the VST hosting code and the plugin wrapper.
  26465. */
  26466. class VSTMidiEventList
  26467. {
  26468. public:
  26469. VSTMidiEventList()
  26470. : numEventsUsed (0), numEventsAllocated (0)
  26471. {
  26472. }
  26473. ~VSTMidiEventList()
  26474. {
  26475. freeEvents();
  26476. }
  26477. void clear()
  26478. {
  26479. numEventsUsed = 0;
  26480. if (events != 0)
  26481. events->numEvents = 0;
  26482. }
  26483. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26484. {
  26485. ensureSize (numEventsUsed + 1);
  26486. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26487. events->numEvents = ++numEventsUsed;
  26488. if (numBytes <= 4)
  26489. {
  26490. if (e->type == kVstSysExType)
  26491. {
  26492. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26493. e->type = kVstMidiType;
  26494. e->byteSize = sizeof (VstMidiEvent);
  26495. e->noteLength = 0;
  26496. e->noteOffset = 0;
  26497. e->detune = 0;
  26498. e->noteOffVelocity = 0;
  26499. }
  26500. e->deltaFrames = frameOffset;
  26501. memcpy (e->midiData, midiData, numBytes);
  26502. }
  26503. else
  26504. {
  26505. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26506. if (se->type == kVstSysExType)
  26507. delete[] se->sysexDump;
  26508. se->sysexDump = new char [numBytes];
  26509. memcpy (se->sysexDump, midiData, numBytes);
  26510. se->type = kVstSysExType;
  26511. se->byteSize = sizeof (VstMidiSysexEvent);
  26512. se->deltaFrames = frameOffset;
  26513. se->flags = 0;
  26514. se->dumpBytes = numBytes;
  26515. se->resvd1 = 0;
  26516. se->resvd2 = 0;
  26517. }
  26518. }
  26519. // Handy method to pull the events out of an event buffer supplied by the host
  26520. // or plugin.
  26521. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26522. {
  26523. for (int i = 0; i < events->numEvents; ++i)
  26524. {
  26525. const VstEvent* const e = events->events[i];
  26526. if (e != 0)
  26527. {
  26528. if (e->type == kVstMidiType)
  26529. {
  26530. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26531. 4, e->deltaFrames);
  26532. }
  26533. else if (e->type == kVstSysExType)
  26534. {
  26535. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26536. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26537. e->deltaFrames);
  26538. }
  26539. }
  26540. }
  26541. }
  26542. void ensureSize (int numEventsNeeded)
  26543. {
  26544. if (numEventsNeeded > numEventsAllocated)
  26545. {
  26546. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26547. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26548. if (events == 0)
  26549. events.calloc (size, 1);
  26550. else
  26551. events.realloc (size, 1);
  26552. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26553. {
  26554. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26555. (int) sizeof (VstMidiSysexEvent)));
  26556. e->type = kVstMidiType;
  26557. e->byteSize = sizeof (VstMidiEvent);
  26558. events->events[i] = (VstEvent*) e;
  26559. }
  26560. numEventsAllocated = numEventsNeeded;
  26561. }
  26562. }
  26563. void freeEvents()
  26564. {
  26565. if (events != 0)
  26566. {
  26567. for (int i = numEventsAllocated; --i >= 0;)
  26568. {
  26569. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26570. if (e->type == kVstSysExType)
  26571. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26572. juce_free (e);
  26573. }
  26574. events.free();
  26575. numEventsUsed = 0;
  26576. numEventsAllocated = 0;
  26577. }
  26578. }
  26579. HeapBlock <VstEvents> events;
  26580. private:
  26581. int numEventsUsed, numEventsAllocated;
  26582. };
  26583. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26584. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26585. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26586. #if ! JUCE_WINDOWS
  26587. static void _fpreset() {}
  26588. static void _clearfp() {}
  26589. #endif
  26590. extern void juce_callAnyTimersSynchronously();
  26591. const int fxbVersionNum = 1;
  26592. struct fxProgram
  26593. {
  26594. long chunkMagic; // 'CcnK'
  26595. long byteSize; // of this chunk, excl. magic + byteSize
  26596. long fxMagic; // 'FxCk'
  26597. long version;
  26598. long fxID; // fx unique id
  26599. long fxVersion;
  26600. long numParams;
  26601. char prgName[28];
  26602. float params[1]; // variable no. of parameters
  26603. };
  26604. struct fxSet
  26605. {
  26606. long chunkMagic; // 'CcnK'
  26607. long byteSize; // of this chunk, excl. magic + byteSize
  26608. long fxMagic; // 'FxBk'
  26609. long version;
  26610. long fxID; // fx unique id
  26611. long fxVersion;
  26612. long numPrograms;
  26613. char future[128];
  26614. fxProgram programs[1]; // variable no. of programs
  26615. };
  26616. struct fxChunkSet
  26617. {
  26618. long chunkMagic; // 'CcnK'
  26619. long byteSize; // of this chunk, excl. magic + byteSize
  26620. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26621. long version;
  26622. long fxID; // fx unique id
  26623. long fxVersion;
  26624. long numPrograms;
  26625. char future[128];
  26626. long chunkSize;
  26627. char chunk[8]; // variable
  26628. };
  26629. struct fxProgramSet
  26630. {
  26631. long chunkMagic; // 'CcnK'
  26632. long byteSize; // of this chunk, excl. magic + byteSize
  26633. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26634. long version;
  26635. long fxID; // fx unique id
  26636. long fxVersion;
  26637. long numPrograms;
  26638. char name[28];
  26639. long chunkSize;
  26640. char chunk[8]; // variable
  26641. };
  26642. namespace
  26643. {
  26644. long vst_swap (const long x) throw()
  26645. {
  26646. #ifdef JUCE_LITTLE_ENDIAN
  26647. return (long) ByteOrder::swap ((uint32) x);
  26648. #else
  26649. return x;
  26650. #endif
  26651. }
  26652. float vst_swapFloat (const float x) throw()
  26653. {
  26654. #ifdef JUCE_LITTLE_ENDIAN
  26655. union { uint32 asInt; float asFloat; } n;
  26656. n.asFloat = x;
  26657. n.asInt = ByteOrder::swap (n.asInt);
  26658. return n.asFloat;
  26659. #else
  26660. return x;
  26661. #endif
  26662. }
  26663. double getVSTHostTimeNanoseconds()
  26664. {
  26665. #if JUCE_WINDOWS
  26666. return timeGetTime() * 1000000.0;
  26667. #elif JUCE_LINUX
  26668. timeval micro;
  26669. gettimeofday (&micro, 0);
  26670. return micro.tv_usec * 1000.0;
  26671. #elif JUCE_MAC
  26672. UnsignedWide micro;
  26673. Microseconds (&micro);
  26674. return micro.lo * 1000.0;
  26675. #endif
  26676. }
  26677. }
  26678. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26679. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26680. static int shellUIDToCreate = 0;
  26681. static int insideVSTCallback = 0;
  26682. class VSTPluginWindow;
  26683. // Change this to disable logging of various VST activities
  26684. #ifndef VST_LOGGING
  26685. #define VST_LOGGING 1
  26686. #endif
  26687. #if VST_LOGGING
  26688. #define log(a) Logger::writeToLog(a);
  26689. #else
  26690. #define log(a)
  26691. #endif
  26692. #if JUCE_MAC && JUCE_PPC
  26693. static void* NewCFMFromMachO (void* const machofp) throw()
  26694. {
  26695. void* result = (void*) new char[8];
  26696. ((void**) result)[0] = machofp;
  26697. ((void**) result)[1] = result;
  26698. return result;
  26699. }
  26700. #endif
  26701. #if JUCE_LINUX
  26702. extern Display* display;
  26703. extern XContext windowHandleXContext;
  26704. typedef void (*EventProcPtr) (XEvent* ev);
  26705. static bool xErrorTriggered;
  26706. namespace
  26707. {
  26708. int temporaryErrorHandler (Display*, XErrorEvent*)
  26709. {
  26710. xErrorTriggered = true;
  26711. return 0;
  26712. }
  26713. int getPropertyFromXWindow (Window handle, Atom atom)
  26714. {
  26715. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26716. xErrorTriggered = false;
  26717. int userSize;
  26718. unsigned long bytes, userCount;
  26719. unsigned char* data;
  26720. Atom userType;
  26721. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26722. &userType, &userSize, &userCount, &bytes, &data);
  26723. XSetErrorHandler (oldErrorHandler);
  26724. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26725. : 0;
  26726. }
  26727. Window getChildWindow (Window windowToCheck)
  26728. {
  26729. Window rootWindow, parentWindow;
  26730. Window* childWindows;
  26731. unsigned int numChildren;
  26732. XQueryTree (display,
  26733. windowToCheck,
  26734. &rootWindow,
  26735. &parentWindow,
  26736. &childWindows,
  26737. &numChildren);
  26738. if (numChildren > 0)
  26739. return childWindows [0];
  26740. return 0;
  26741. }
  26742. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26743. {
  26744. if (e.mods.isLeftButtonDown())
  26745. {
  26746. ev.xbutton.button = Button1;
  26747. ev.xbutton.state |= Button1Mask;
  26748. }
  26749. else if (e.mods.isRightButtonDown())
  26750. {
  26751. ev.xbutton.button = Button3;
  26752. ev.xbutton.state |= Button3Mask;
  26753. }
  26754. else if (e.mods.isMiddleButtonDown())
  26755. {
  26756. ev.xbutton.button = Button2;
  26757. ev.xbutton.state |= Button2Mask;
  26758. }
  26759. }
  26760. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26761. {
  26762. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26763. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26764. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26765. }
  26766. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26767. {
  26768. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26769. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26770. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26771. }
  26772. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26773. {
  26774. if (increment < 0)
  26775. {
  26776. ev.xbutton.button = Button5;
  26777. ev.xbutton.state |= Button5Mask;
  26778. }
  26779. else if (increment > 0)
  26780. {
  26781. ev.xbutton.button = Button4;
  26782. ev.xbutton.state |= Button4Mask;
  26783. }
  26784. }
  26785. }
  26786. #endif
  26787. class ModuleHandle : public ReferenceCountedObject
  26788. {
  26789. public:
  26790. File file;
  26791. MainCall moduleMain;
  26792. String pluginName;
  26793. static Array <ModuleHandle*>& getActiveModules()
  26794. {
  26795. static Array <ModuleHandle*> activeModules;
  26796. return activeModules;
  26797. }
  26798. static ModuleHandle* findOrCreateModule (const File& file)
  26799. {
  26800. for (int i = getActiveModules().size(); --i >= 0;)
  26801. {
  26802. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26803. if (module->file == file)
  26804. return module;
  26805. }
  26806. _fpreset(); // (doesn't do any harm)
  26807. ++insideVSTCallback;
  26808. shellUIDToCreate = 0;
  26809. log ("Attempting to load VST: " + file.getFullPathName());
  26810. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26811. if (! m->open())
  26812. m = 0;
  26813. --insideVSTCallback;
  26814. _fpreset(); // (doesn't do any harm)
  26815. return m.release();
  26816. }
  26817. ModuleHandle (const File& file_)
  26818. : file (file_),
  26819. moduleMain (0),
  26820. #if JUCE_WINDOWS || JUCE_LINUX
  26821. hModule (0)
  26822. #elif JUCE_MAC
  26823. fragId (0),
  26824. resHandle (0),
  26825. bundleRef (0),
  26826. resFileId (0)
  26827. #endif
  26828. {
  26829. getActiveModules().add (this);
  26830. #if JUCE_WINDOWS || JUCE_LINUX
  26831. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26832. #elif JUCE_MAC
  26833. FSRef ref;
  26834. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26835. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26836. #endif
  26837. }
  26838. ~ModuleHandle()
  26839. {
  26840. getActiveModules().removeValue (this);
  26841. close();
  26842. }
  26843. #if JUCE_WINDOWS || JUCE_LINUX
  26844. void* hModule;
  26845. String fullParentDirectoryPathName;
  26846. bool open()
  26847. {
  26848. #if JUCE_WINDOWS
  26849. static bool timePeriodSet = false;
  26850. if (! timePeriodSet)
  26851. {
  26852. timePeriodSet = true;
  26853. timeBeginPeriod (2);
  26854. }
  26855. #endif
  26856. pluginName = file.getFileNameWithoutExtension();
  26857. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26858. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26859. if (moduleMain == 0)
  26860. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26861. return moduleMain != 0;
  26862. }
  26863. void close()
  26864. {
  26865. _fpreset(); // (doesn't do any harm)
  26866. PlatformUtilities::freeDynamicLibrary (hModule);
  26867. }
  26868. void closeEffect (AEffect* eff)
  26869. {
  26870. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26871. }
  26872. #else
  26873. CFragConnectionID fragId;
  26874. Handle resHandle;
  26875. CFBundleRef bundleRef;
  26876. FSSpec parentDirFSSpec;
  26877. short resFileId;
  26878. bool open()
  26879. {
  26880. bool ok = false;
  26881. const String filename (file.getFullPathName());
  26882. if (file.hasFileExtension (".vst"))
  26883. {
  26884. const char* const utf8 = filename.toUTF8();
  26885. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26886. strlen (utf8), file.isDirectory());
  26887. if (url != 0)
  26888. {
  26889. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26890. CFRelease (url);
  26891. if (bundleRef != 0)
  26892. {
  26893. if (CFBundleLoadExecutable (bundleRef))
  26894. {
  26895. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26896. if (moduleMain == 0)
  26897. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26898. if (moduleMain != 0)
  26899. {
  26900. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26901. if (name != 0)
  26902. {
  26903. if (CFGetTypeID (name) == CFStringGetTypeID())
  26904. {
  26905. char buffer[1024];
  26906. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26907. pluginName = buffer;
  26908. }
  26909. }
  26910. if (pluginName.isEmpty())
  26911. pluginName = file.getFileNameWithoutExtension();
  26912. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26913. ok = true;
  26914. }
  26915. }
  26916. if (! ok)
  26917. {
  26918. CFBundleUnloadExecutable (bundleRef);
  26919. CFRelease (bundleRef);
  26920. bundleRef = 0;
  26921. }
  26922. }
  26923. }
  26924. }
  26925. #if JUCE_PPC
  26926. else
  26927. {
  26928. FSRef fn;
  26929. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26930. {
  26931. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26932. if (resFileId != -1)
  26933. {
  26934. const int numEffs = Count1Resources ('aEff');
  26935. for (int i = 0; i < numEffs; ++i)
  26936. {
  26937. resHandle = Get1IndResource ('aEff', i + 1);
  26938. if (resHandle != 0)
  26939. {
  26940. OSType type;
  26941. Str255 name;
  26942. SInt16 id;
  26943. GetResInfo (resHandle, &id, &type, name);
  26944. pluginName = String ((const char*) name + 1, name[0]);
  26945. DetachResource (resHandle);
  26946. HLock (resHandle);
  26947. Ptr ptr;
  26948. Str255 errorText;
  26949. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26950. name, kPrivateCFragCopy,
  26951. &fragId, &ptr, errorText);
  26952. if (err == noErr)
  26953. {
  26954. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26955. ok = true;
  26956. }
  26957. else
  26958. {
  26959. HUnlock (resHandle);
  26960. }
  26961. break;
  26962. }
  26963. }
  26964. if (! ok)
  26965. CloseResFile (resFileId);
  26966. }
  26967. }
  26968. }
  26969. #endif
  26970. return ok;
  26971. }
  26972. void close()
  26973. {
  26974. #if JUCE_PPC
  26975. if (fragId != 0)
  26976. {
  26977. if (moduleMain != 0)
  26978. disposeMachOFromCFM ((void*) moduleMain);
  26979. CloseConnection (&fragId);
  26980. HUnlock (resHandle);
  26981. if (resFileId != 0)
  26982. CloseResFile (resFileId);
  26983. }
  26984. else
  26985. #endif
  26986. if (bundleRef != 0)
  26987. {
  26988. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26989. if (CFGetRetainCount (bundleRef) == 1)
  26990. CFBundleUnloadExecutable (bundleRef);
  26991. if (CFGetRetainCount (bundleRef) > 0)
  26992. CFRelease (bundleRef);
  26993. }
  26994. }
  26995. void closeEffect (AEffect* eff)
  26996. {
  26997. #if JUCE_PPC
  26998. if (fragId != 0)
  26999. {
  27000. Array<void*> thingsToDelete;
  27001. thingsToDelete.add ((void*) eff->dispatcher);
  27002. thingsToDelete.add ((void*) eff->process);
  27003. thingsToDelete.add ((void*) eff->setParameter);
  27004. thingsToDelete.add ((void*) eff->getParameter);
  27005. thingsToDelete.add ((void*) eff->processReplacing);
  27006. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27007. for (int i = thingsToDelete.size(); --i >= 0;)
  27008. disposeMachOFromCFM (thingsToDelete[i]);
  27009. }
  27010. else
  27011. #endif
  27012. {
  27013. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27014. }
  27015. }
  27016. #if JUCE_PPC
  27017. static void* newMachOFromCFM (void* cfmfp)
  27018. {
  27019. if (cfmfp == 0)
  27020. return 0;
  27021. UInt32* const mfp = new UInt32[6];
  27022. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  27023. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  27024. mfp[2] = 0x800c0000;
  27025. mfp[3] = 0x804c0004;
  27026. mfp[4] = 0x7c0903a6;
  27027. mfp[5] = 0x4e800420;
  27028. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  27029. return mfp;
  27030. }
  27031. static void disposeMachOFromCFM (void* ptr)
  27032. {
  27033. delete[] static_cast <UInt32*> (ptr);
  27034. }
  27035. void coerceAEffectFunctionCalls (AEffect* eff)
  27036. {
  27037. if (fragId != 0)
  27038. {
  27039. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  27040. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  27041. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  27042. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  27043. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  27044. }
  27045. }
  27046. #endif
  27047. #endif
  27048. private:
  27049. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  27050. };
  27051. /**
  27052. An instance of a plugin, created by a VSTPluginFormat.
  27053. */
  27054. class VSTPluginInstance : public AudioPluginInstance,
  27055. private Timer,
  27056. private AsyncUpdater
  27057. {
  27058. public:
  27059. ~VSTPluginInstance();
  27060. // AudioPluginInstance methods:
  27061. void fillInPluginDescription (PluginDescription& desc) const
  27062. {
  27063. desc.name = name;
  27064. {
  27065. char buffer [512];
  27066. zerostruct (buffer);
  27067. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27068. desc.descriptiveName = String (buffer).trim();
  27069. if (desc.descriptiveName.isEmpty())
  27070. desc.descriptiveName = name;
  27071. }
  27072. desc.fileOrIdentifier = module->file.getFullPathName();
  27073. desc.uid = getUID();
  27074. desc.lastFileModTime = module->file.getLastModificationTime();
  27075. desc.pluginFormatName = "VST";
  27076. desc.category = getCategory();
  27077. {
  27078. char buffer [kVstMaxVendorStrLen + 8];
  27079. zerostruct (buffer);
  27080. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27081. desc.manufacturerName = buffer;
  27082. }
  27083. desc.version = getVersion();
  27084. desc.numInputChannels = getNumInputChannels();
  27085. desc.numOutputChannels = getNumOutputChannels();
  27086. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27087. }
  27088. void* getPlatformSpecificData() { return effect; }
  27089. const String getName() const { return name; }
  27090. int getUID() const;
  27091. bool acceptsMidi() const { return wantsMidiMessages; }
  27092. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27093. // AudioProcessor methods:
  27094. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27095. void releaseResources();
  27096. void processBlock (AudioSampleBuffer& buffer,
  27097. MidiBuffer& midiMessages);
  27098. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27099. AudioProcessorEditor* createEditor();
  27100. const String getInputChannelName (int index) const;
  27101. bool isInputChannelStereoPair (int index) const;
  27102. const String getOutputChannelName (int index) const;
  27103. bool isOutputChannelStereoPair (int index) const;
  27104. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27105. float getParameter (int index);
  27106. void setParameter (int index, float newValue);
  27107. const String getParameterName (int index);
  27108. const String getParameterText (int index);
  27109. bool isParameterAutomatable (int index) const;
  27110. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27111. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27112. void setCurrentProgram (int index);
  27113. const String getProgramName (int index);
  27114. void changeProgramName (int index, const String& newName);
  27115. void getStateInformation (MemoryBlock& destData);
  27116. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27117. void setStateInformation (const void* data, int sizeInBytes);
  27118. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27119. void timerCallback();
  27120. void handleAsyncUpdate();
  27121. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27122. private:
  27123. friend class VSTPluginWindow;
  27124. friend class VSTPluginFormat;
  27125. AEffect* effect;
  27126. String name;
  27127. CriticalSection lock;
  27128. bool wantsMidiMessages, initialised, isPowerOn;
  27129. mutable StringArray programNames;
  27130. AudioSampleBuffer tempBuffer;
  27131. CriticalSection midiInLock;
  27132. MidiBuffer incomingMidi;
  27133. VSTMidiEventList midiEventsToSend;
  27134. VstTimeInfo vstHostTime;
  27135. ReferenceCountedObjectPtr <ModuleHandle> module;
  27136. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27137. bool restoreProgramSettings (const fxProgram* const prog);
  27138. const String getCurrentProgramName();
  27139. void setParamsInProgramBlock (fxProgram* const prog);
  27140. void updateStoredProgramNames();
  27141. void initialise();
  27142. void handleMidiFromPlugin (const VstEvents* const events);
  27143. void createTempParameterStore (MemoryBlock& dest);
  27144. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27145. const String getParameterLabel (int index) const;
  27146. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27147. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27148. void setChunkData (const char* data, int size, bool isPreset);
  27149. bool loadFromFXBFile (const void* data, int numBytes);
  27150. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27151. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27152. const String getVersion() const;
  27153. const String getCategory() const;
  27154. void setPower (const bool on);
  27155. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  27157. };
  27158. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27159. : effect (0),
  27160. wantsMidiMessages (false),
  27161. initialised (false),
  27162. isPowerOn (false),
  27163. tempBuffer (1, 1),
  27164. module (module_)
  27165. {
  27166. try
  27167. {
  27168. _fpreset();
  27169. ++insideVSTCallback;
  27170. name = module->pluginName;
  27171. log ("Creating VST instance: " + name);
  27172. #if JUCE_MAC
  27173. if (module->resFileId != 0)
  27174. UseResFile (module->resFileId);
  27175. #if JUCE_PPC
  27176. if (module->fragId != 0)
  27177. {
  27178. static void* audioMasterCoerced = 0;
  27179. if (audioMasterCoerced == 0)
  27180. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27181. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27182. }
  27183. else
  27184. #endif
  27185. #endif
  27186. {
  27187. effect = module->moduleMain (&audioMaster);
  27188. }
  27189. --insideVSTCallback;
  27190. if (effect != 0 && effect->magic == kEffectMagic)
  27191. {
  27192. #if JUCE_PPC
  27193. module->coerceAEffectFunctionCalls (effect);
  27194. #endif
  27195. jassert (effect->resvd2 == 0);
  27196. jassert (effect->object != 0);
  27197. _fpreset(); // some dodgy plugs fuck around with this
  27198. }
  27199. else
  27200. {
  27201. effect = 0;
  27202. }
  27203. }
  27204. catch (...)
  27205. {
  27206. --insideVSTCallback;
  27207. }
  27208. }
  27209. VSTPluginInstance::~VSTPluginInstance()
  27210. {
  27211. const ScopedLock sl (lock);
  27212. jassert (insideVSTCallback == 0);
  27213. if (effect != 0 && effect->magic == kEffectMagic)
  27214. {
  27215. try
  27216. {
  27217. #if JUCE_MAC
  27218. if (module->resFileId != 0)
  27219. UseResFile (module->resFileId);
  27220. #endif
  27221. // Must delete any editors before deleting the plugin instance!
  27222. jassert (getActiveEditor() == 0);
  27223. _fpreset(); // some dodgy plugs fuck around with this
  27224. module->closeEffect (effect);
  27225. }
  27226. catch (...)
  27227. {}
  27228. }
  27229. module = 0;
  27230. effect = 0;
  27231. }
  27232. void VSTPluginInstance::initialise()
  27233. {
  27234. if (initialised || effect == 0)
  27235. return;
  27236. log ("Initialising VST: " + module->pluginName);
  27237. initialised = true;
  27238. dispatch (effIdentify, 0, 0, 0, 0);
  27239. if (getSampleRate() > 0)
  27240. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27241. if (getBlockSize() > 0)
  27242. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27243. dispatch (effOpen, 0, 0, 0, 0);
  27244. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27245. getSampleRate(), getBlockSize());
  27246. if (getNumPrograms() > 1)
  27247. setCurrentProgram (0);
  27248. else
  27249. dispatch (effSetProgram, 0, 0, 0, 0);
  27250. int i;
  27251. for (i = effect->numInputs; --i >= 0;)
  27252. dispatch (effConnectInput, i, 1, 0, 0);
  27253. for (i = effect->numOutputs; --i >= 0;)
  27254. dispatch (effConnectOutput, i, 1, 0, 0);
  27255. updateStoredProgramNames();
  27256. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27257. setLatencySamples (effect->initialDelay);
  27258. }
  27259. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27260. int samplesPerBlockExpected)
  27261. {
  27262. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27263. sampleRate_, samplesPerBlockExpected);
  27264. setLatencySamples (effect->initialDelay);
  27265. vstHostTime.tempo = 120.0;
  27266. vstHostTime.timeSigNumerator = 4;
  27267. vstHostTime.timeSigDenominator = 4;
  27268. vstHostTime.sampleRate = sampleRate_;
  27269. vstHostTime.samplePos = 0;
  27270. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27271. initialise();
  27272. if (initialised)
  27273. {
  27274. wantsMidiMessages = wantsMidiMessages
  27275. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27276. if (wantsMidiMessages)
  27277. midiEventsToSend.ensureSize (256);
  27278. else
  27279. midiEventsToSend.freeEvents();
  27280. incomingMidi.clear();
  27281. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27282. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27283. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27284. if (! isPowerOn)
  27285. setPower (true);
  27286. // dodgy hack to force some plugins to initialise the sample rate..
  27287. if ((! hasEditor()) && getNumParameters() > 0)
  27288. {
  27289. const float old = getParameter (0);
  27290. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27291. setParameter (0, old);
  27292. }
  27293. dispatch (effStartProcess, 0, 0, 0, 0);
  27294. }
  27295. }
  27296. void VSTPluginInstance::releaseResources()
  27297. {
  27298. if (initialised)
  27299. {
  27300. dispatch (effStopProcess, 0, 0, 0, 0);
  27301. setPower (false);
  27302. }
  27303. tempBuffer.setSize (1, 1);
  27304. incomingMidi.clear();
  27305. midiEventsToSend.freeEvents();
  27306. }
  27307. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27308. MidiBuffer& midiMessages)
  27309. {
  27310. const int numSamples = buffer.getNumSamples();
  27311. if (initialised)
  27312. {
  27313. AudioPlayHead* playHead = getPlayHead();
  27314. if (playHead != 0)
  27315. {
  27316. AudioPlayHead::CurrentPositionInfo position;
  27317. playHead->getCurrentPosition (position);
  27318. vstHostTime.tempo = position.bpm;
  27319. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27320. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27321. vstHostTime.ppqPos = position.ppqPosition;
  27322. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27323. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27324. if (position.isPlaying)
  27325. vstHostTime.flags |= kVstTransportPlaying;
  27326. else
  27327. vstHostTime.flags &= ~kVstTransportPlaying;
  27328. }
  27329. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27330. if (wantsMidiMessages)
  27331. {
  27332. midiEventsToSend.clear();
  27333. midiEventsToSend.ensureSize (1);
  27334. MidiBuffer::Iterator iter (midiMessages);
  27335. const uint8* midiData;
  27336. int numBytesOfMidiData, samplePosition;
  27337. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27338. {
  27339. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27340. jlimit (0, numSamples - 1, samplePosition));
  27341. }
  27342. try
  27343. {
  27344. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27345. }
  27346. catch (...)
  27347. {}
  27348. }
  27349. _clearfp();
  27350. if ((effect->flags & effFlagsCanReplacing) != 0)
  27351. {
  27352. try
  27353. {
  27354. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27355. }
  27356. catch (...)
  27357. {}
  27358. }
  27359. else
  27360. {
  27361. tempBuffer.setSize (effect->numOutputs, numSamples);
  27362. tempBuffer.clear();
  27363. try
  27364. {
  27365. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27366. }
  27367. catch (...)
  27368. {}
  27369. for (int i = effect->numOutputs; --i >= 0;)
  27370. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27371. }
  27372. }
  27373. else
  27374. {
  27375. // Not initialised, so just bypass..
  27376. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27377. buffer.clear (i, 0, buffer.getNumSamples());
  27378. }
  27379. {
  27380. // copy any incoming midi..
  27381. const ScopedLock sl (midiInLock);
  27382. midiMessages.swapWith (incomingMidi);
  27383. incomingMidi.clear();
  27384. }
  27385. }
  27386. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27387. {
  27388. if (events != 0)
  27389. {
  27390. const ScopedLock sl (midiInLock);
  27391. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27392. }
  27393. }
  27394. static Array <VSTPluginWindow*> activeVSTWindows;
  27395. class VSTPluginWindow : public AudioProcessorEditor,
  27396. #if ! JUCE_MAC
  27397. public ComponentMovementWatcher,
  27398. #endif
  27399. public Timer
  27400. {
  27401. public:
  27402. VSTPluginWindow (VSTPluginInstance& plugin_)
  27403. : AudioProcessorEditor (&plugin_),
  27404. #if ! JUCE_MAC
  27405. ComponentMovementWatcher (this),
  27406. #endif
  27407. plugin (plugin_),
  27408. isOpen (false),
  27409. wasShowing (false),
  27410. pluginRefusesToResize (false),
  27411. pluginWantsKeys (false),
  27412. alreadyInside (false),
  27413. recursiveResize (false)
  27414. {
  27415. #if JUCE_WINDOWS
  27416. sizeCheckCount = 0;
  27417. pluginHWND = 0;
  27418. #elif JUCE_LINUX
  27419. pluginWindow = None;
  27420. pluginProc = None;
  27421. #else
  27422. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27423. #endif
  27424. activeVSTWindows.add (this);
  27425. setSize (1, 1);
  27426. setOpaque (true);
  27427. setVisible (true);
  27428. }
  27429. ~VSTPluginWindow()
  27430. {
  27431. #if JUCE_MAC
  27432. innerWrapper = 0;
  27433. #else
  27434. closePluginWindow();
  27435. #endif
  27436. activeVSTWindows.removeValue (this);
  27437. plugin.editorBeingDeleted (this);
  27438. }
  27439. #if ! JUCE_MAC
  27440. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27441. {
  27442. if (recursiveResize)
  27443. return;
  27444. Component* const topComp = getTopLevelComponent();
  27445. if (topComp->getPeer() != 0)
  27446. {
  27447. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27448. recursiveResize = true;
  27449. #if JUCE_WINDOWS
  27450. if (pluginHWND != 0)
  27451. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27452. #elif JUCE_LINUX
  27453. if (pluginWindow != 0)
  27454. {
  27455. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27456. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27457. XMapRaised (display, pluginWindow);
  27458. }
  27459. #endif
  27460. recursiveResize = false;
  27461. }
  27462. }
  27463. void componentVisibilityChanged (Component&)
  27464. {
  27465. const bool isShowingNow = isShowing();
  27466. if (wasShowing != isShowingNow)
  27467. {
  27468. wasShowing = isShowingNow;
  27469. if (isShowingNow)
  27470. openPluginWindow();
  27471. else
  27472. closePluginWindow();
  27473. }
  27474. componentMovedOrResized (true, true);
  27475. }
  27476. void componentPeerChanged()
  27477. {
  27478. closePluginWindow();
  27479. openPluginWindow();
  27480. }
  27481. #endif
  27482. bool keyStateChanged (bool)
  27483. {
  27484. return pluginWantsKeys;
  27485. }
  27486. bool keyPressed (const KeyPress&)
  27487. {
  27488. return pluginWantsKeys;
  27489. }
  27490. #if JUCE_MAC
  27491. void paint (Graphics& g)
  27492. {
  27493. g.fillAll (Colours::black);
  27494. }
  27495. #else
  27496. void paint (Graphics& g)
  27497. {
  27498. if (isOpen)
  27499. {
  27500. ComponentPeer* const peer = getPeer();
  27501. if (peer != 0)
  27502. {
  27503. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27504. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27505. #if JUCE_LINUX
  27506. if (pluginWindow != 0)
  27507. {
  27508. const Rectangle<int> clip (g.getClipBounds());
  27509. XEvent ev;
  27510. zerostruct (ev);
  27511. ev.xexpose.type = Expose;
  27512. ev.xexpose.display = display;
  27513. ev.xexpose.window = pluginWindow;
  27514. ev.xexpose.x = clip.getX();
  27515. ev.xexpose.y = clip.getY();
  27516. ev.xexpose.width = clip.getWidth();
  27517. ev.xexpose.height = clip.getHeight();
  27518. sendEventToChild (&ev);
  27519. }
  27520. #endif
  27521. }
  27522. }
  27523. else
  27524. {
  27525. g.fillAll (Colours::black);
  27526. }
  27527. }
  27528. #endif
  27529. void timerCallback()
  27530. {
  27531. #if JUCE_WINDOWS
  27532. if (--sizeCheckCount <= 0)
  27533. {
  27534. sizeCheckCount = 10;
  27535. checkPluginWindowSize();
  27536. }
  27537. #endif
  27538. try
  27539. {
  27540. static bool reentrant = false;
  27541. if (! reentrant)
  27542. {
  27543. reentrant = true;
  27544. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27545. reentrant = false;
  27546. }
  27547. }
  27548. catch (...)
  27549. {}
  27550. }
  27551. void mouseDown (const MouseEvent& e)
  27552. {
  27553. #if JUCE_LINUX
  27554. if (pluginWindow == 0)
  27555. return;
  27556. toFront (true);
  27557. XEvent ev;
  27558. zerostruct (ev);
  27559. ev.xbutton.display = display;
  27560. ev.xbutton.type = ButtonPress;
  27561. ev.xbutton.window = pluginWindow;
  27562. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27563. ev.xbutton.time = CurrentTime;
  27564. ev.xbutton.x = e.x;
  27565. ev.xbutton.y = e.y;
  27566. ev.xbutton.x_root = e.getScreenX();
  27567. ev.xbutton.y_root = e.getScreenY();
  27568. translateJuceToXButtonModifiers (e, ev);
  27569. sendEventToChild (&ev);
  27570. #elif JUCE_WINDOWS
  27571. (void) e;
  27572. toFront (true);
  27573. #endif
  27574. }
  27575. void broughtToFront()
  27576. {
  27577. activeVSTWindows.removeValue (this);
  27578. activeVSTWindows.add (this);
  27579. #if JUCE_MAC
  27580. dispatch (effEditTop, 0, 0, 0, 0);
  27581. #endif
  27582. }
  27583. private:
  27584. VSTPluginInstance& plugin;
  27585. bool isOpen, wasShowing, recursiveResize;
  27586. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27587. #if JUCE_WINDOWS
  27588. HWND pluginHWND;
  27589. void* originalWndProc;
  27590. int sizeCheckCount;
  27591. #elif JUCE_LINUX
  27592. Window pluginWindow;
  27593. EventProcPtr pluginProc;
  27594. #endif
  27595. #if JUCE_MAC
  27596. void openPluginWindow (WindowRef parentWindow)
  27597. {
  27598. if (isOpen || parentWindow == 0)
  27599. return;
  27600. isOpen = true;
  27601. ERect* rect = 0;
  27602. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27603. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27604. // do this before and after like in the steinberg example
  27605. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27606. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27607. // Install keyboard hooks
  27608. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27609. // double-check it's not too tiny
  27610. int w = 250, h = 150;
  27611. if (rect != 0)
  27612. {
  27613. w = rect->right - rect->left;
  27614. h = rect->bottom - rect->top;
  27615. if (w == 0 || h == 0)
  27616. {
  27617. w = 250;
  27618. h = 150;
  27619. }
  27620. }
  27621. w = jmax (w, 32);
  27622. h = jmax (h, 32);
  27623. setSize (w, h);
  27624. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27625. repaint();
  27626. }
  27627. #else
  27628. void openPluginWindow()
  27629. {
  27630. if (isOpen || getWindowHandle() == 0)
  27631. return;
  27632. log ("Opening VST UI: " + plugin.name);
  27633. isOpen = true;
  27634. ERect* rect = 0;
  27635. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27636. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27637. // do this before and after like in the steinberg example
  27638. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27639. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27640. // Install keyboard hooks
  27641. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27642. #if JUCE_WINDOWS
  27643. originalWndProc = 0;
  27644. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27645. if (pluginHWND == 0)
  27646. {
  27647. isOpen = false;
  27648. setSize (300, 150);
  27649. return;
  27650. }
  27651. #pragma warning (push)
  27652. #pragma warning (disable: 4244)
  27653. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27654. if (! pluginWantsKeys)
  27655. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27656. #pragma warning (pop)
  27657. int w, h;
  27658. RECT r;
  27659. GetWindowRect (pluginHWND, &r);
  27660. w = r.right - r.left;
  27661. h = r.bottom - r.top;
  27662. if (rect != 0)
  27663. {
  27664. const int rw = rect->right - rect->left;
  27665. const int rh = rect->bottom - rect->top;
  27666. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27667. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27668. {
  27669. // very dodgy logic to decide which size is right.
  27670. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27671. {
  27672. SetWindowPos (pluginHWND, 0,
  27673. 0, 0, rw, rh,
  27674. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27675. GetWindowRect (pluginHWND, &r);
  27676. w = r.right - r.left;
  27677. h = r.bottom - r.top;
  27678. pluginRefusesToResize = (w != rw) || (h != rh);
  27679. w = rw;
  27680. h = rh;
  27681. }
  27682. }
  27683. }
  27684. #elif JUCE_LINUX
  27685. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27686. if (pluginWindow != 0)
  27687. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27688. XInternAtom (display, "_XEventProc", False));
  27689. int w = 250, h = 150;
  27690. if (rect != 0)
  27691. {
  27692. w = rect->right - rect->left;
  27693. h = rect->bottom - rect->top;
  27694. if (w == 0 || h == 0)
  27695. {
  27696. w = 250;
  27697. h = 150;
  27698. }
  27699. }
  27700. if (pluginWindow != 0)
  27701. XMapRaised (display, pluginWindow);
  27702. #endif
  27703. // double-check it's not too tiny
  27704. w = jmax (w, 32);
  27705. h = jmax (h, 32);
  27706. setSize (w, h);
  27707. #if JUCE_WINDOWS
  27708. checkPluginWindowSize();
  27709. #endif
  27710. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27711. repaint();
  27712. }
  27713. #endif
  27714. #if ! JUCE_MAC
  27715. void closePluginWindow()
  27716. {
  27717. if (isOpen)
  27718. {
  27719. log ("Closing VST UI: " + plugin.getName());
  27720. isOpen = false;
  27721. dispatch (effEditClose, 0, 0, 0, 0);
  27722. #if JUCE_WINDOWS
  27723. #pragma warning (push)
  27724. #pragma warning (disable: 4244)
  27725. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27726. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27727. #pragma warning (pop)
  27728. stopTimer();
  27729. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27730. DestroyWindow (pluginHWND);
  27731. pluginHWND = 0;
  27732. #elif JUCE_LINUX
  27733. stopTimer();
  27734. pluginWindow = 0;
  27735. pluginProc = 0;
  27736. #endif
  27737. }
  27738. }
  27739. #endif
  27740. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27741. {
  27742. return plugin.dispatch (opcode, index, value, ptr, opt);
  27743. }
  27744. #if JUCE_WINDOWS
  27745. void checkPluginWindowSize()
  27746. {
  27747. RECT r;
  27748. GetWindowRect (pluginHWND, &r);
  27749. const int w = r.right - r.left;
  27750. const int h = r.bottom - r.top;
  27751. if (isShowing() && w > 0 && h > 0
  27752. && (w != getWidth() || h != getHeight())
  27753. && ! pluginRefusesToResize)
  27754. {
  27755. setSize (w, h);
  27756. sizeCheckCount = 0;
  27757. }
  27758. }
  27759. // hooks to get keyboard events from VST windows..
  27760. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27761. {
  27762. for (int i = activeVSTWindows.size(); --i >= 0;)
  27763. {
  27764. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27765. if (w->pluginHWND == hW)
  27766. {
  27767. if (message == WM_CHAR
  27768. || message == WM_KEYDOWN
  27769. || message == WM_SYSKEYDOWN
  27770. || message == WM_KEYUP
  27771. || message == WM_SYSKEYUP
  27772. || message == WM_APPCOMMAND)
  27773. {
  27774. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27775. message, wParam, lParam);
  27776. }
  27777. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27778. (HWND) w->pluginHWND,
  27779. message,
  27780. wParam,
  27781. lParam);
  27782. }
  27783. }
  27784. return DefWindowProc (hW, message, wParam, lParam);
  27785. }
  27786. #endif
  27787. #if JUCE_LINUX
  27788. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27789. void sendEventToChild (XEvent* event)
  27790. {
  27791. if (pluginProc != 0)
  27792. {
  27793. // if the plugin publishes an event procedure, pass the event directly..
  27794. pluginProc (event);
  27795. }
  27796. else if (pluginWindow != 0)
  27797. {
  27798. // if the plugin has a window, then send the event to the window so that
  27799. // its message thread will pick it up..
  27800. XSendEvent (display, pluginWindow, False, 0L, event);
  27801. XFlush (display);
  27802. }
  27803. }
  27804. void mouseEnter (const MouseEvent& e)
  27805. {
  27806. if (pluginWindow != 0)
  27807. {
  27808. XEvent ev;
  27809. zerostruct (ev);
  27810. ev.xcrossing.display = display;
  27811. ev.xcrossing.type = EnterNotify;
  27812. ev.xcrossing.window = pluginWindow;
  27813. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27814. ev.xcrossing.time = CurrentTime;
  27815. ev.xcrossing.x = e.x;
  27816. ev.xcrossing.y = e.y;
  27817. ev.xcrossing.x_root = e.getScreenX();
  27818. ev.xcrossing.y_root = e.getScreenY();
  27819. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27820. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27821. translateJuceToXCrossingModifiers (e, ev);
  27822. sendEventToChild (&ev);
  27823. }
  27824. }
  27825. void mouseExit (const MouseEvent& e)
  27826. {
  27827. if (pluginWindow != 0)
  27828. {
  27829. XEvent ev;
  27830. zerostruct (ev);
  27831. ev.xcrossing.display = display;
  27832. ev.xcrossing.type = LeaveNotify;
  27833. ev.xcrossing.window = pluginWindow;
  27834. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27835. ev.xcrossing.time = CurrentTime;
  27836. ev.xcrossing.x = e.x;
  27837. ev.xcrossing.y = e.y;
  27838. ev.xcrossing.x_root = e.getScreenX();
  27839. ev.xcrossing.y_root = e.getScreenY();
  27840. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27841. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27842. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27843. translateJuceToXCrossingModifiers (e, ev);
  27844. sendEventToChild (&ev);
  27845. }
  27846. }
  27847. void mouseMove (const MouseEvent& e)
  27848. {
  27849. if (pluginWindow != 0)
  27850. {
  27851. XEvent ev;
  27852. zerostruct (ev);
  27853. ev.xmotion.display = display;
  27854. ev.xmotion.type = MotionNotify;
  27855. ev.xmotion.window = pluginWindow;
  27856. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27857. ev.xmotion.time = CurrentTime;
  27858. ev.xmotion.is_hint = NotifyNormal;
  27859. ev.xmotion.x = e.x;
  27860. ev.xmotion.y = e.y;
  27861. ev.xmotion.x_root = e.getScreenX();
  27862. ev.xmotion.y_root = e.getScreenY();
  27863. sendEventToChild (&ev);
  27864. }
  27865. }
  27866. void mouseDrag (const MouseEvent& e)
  27867. {
  27868. if (pluginWindow != 0)
  27869. {
  27870. XEvent ev;
  27871. zerostruct (ev);
  27872. ev.xmotion.display = display;
  27873. ev.xmotion.type = MotionNotify;
  27874. ev.xmotion.window = pluginWindow;
  27875. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27876. ev.xmotion.time = CurrentTime;
  27877. ev.xmotion.x = e.x ;
  27878. ev.xmotion.y = e.y;
  27879. ev.xmotion.x_root = e.getScreenX();
  27880. ev.xmotion.y_root = e.getScreenY();
  27881. ev.xmotion.is_hint = NotifyNormal;
  27882. translateJuceToXMotionModifiers (e, ev);
  27883. sendEventToChild (&ev);
  27884. }
  27885. }
  27886. void mouseUp (const MouseEvent& e)
  27887. {
  27888. if (pluginWindow != 0)
  27889. {
  27890. XEvent ev;
  27891. zerostruct (ev);
  27892. ev.xbutton.display = display;
  27893. ev.xbutton.type = ButtonRelease;
  27894. ev.xbutton.window = pluginWindow;
  27895. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27896. ev.xbutton.time = CurrentTime;
  27897. ev.xbutton.x = e.x;
  27898. ev.xbutton.y = e.y;
  27899. ev.xbutton.x_root = e.getScreenX();
  27900. ev.xbutton.y_root = e.getScreenY();
  27901. translateJuceToXButtonModifiers (e, ev);
  27902. sendEventToChild (&ev);
  27903. }
  27904. }
  27905. void mouseWheelMove (const MouseEvent& e,
  27906. float incrementX,
  27907. float incrementY)
  27908. {
  27909. if (pluginWindow != 0)
  27910. {
  27911. XEvent ev;
  27912. zerostruct (ev);
  27913. ev.xbutton.display = display;
  27914. ev.xbutton.type = ButtonPress;
  27915. ev.xbutton.window = pluginWindow;
  27916. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27917. ev.xbutton.time = CurrentTime;
  27918. ev.xbutton.x = e.x;
  27919. ev.xbutton.y = e.y;
  27920. ev.xbutton.x_root = e.getScreenX();
  27921. ev.xbutton.y_root = e.getScreenY();
  27922. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27923. sendEventToChild (&ev);
  27924. // TODO - put a usleep here ?
  27925. ev.xbutton.type = ButtonRelease;
  27926. sendEventToChild (&ev);
  27927. }
  27928. }
  27929. #endif
  27930. #if JUCE_MAC
  27931. #if ! JUCE_SUPPORT_CARBON
  27932. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27933. #endif
  27934. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27935. {
  27936. public:
  27937. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27938. : owner (owner_),
  27939. alreadyInside (false)
  27940. {
  27941. }
  27942. ~InnerWrapperComponent()
  27943. {
  27944. deleteWindow();
  27945. }
  27946. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27947. {
  27948. owner->openPluginWindow (windowRef);
  27949. return 0;
  27950. }
  27951. void removeView (HIViewRef)
  27952. {
  27953. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27954. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27955. }
  27956. bool getEmbeddedViewSize (int& w, int& h)
  27957. {
  27958. ERect* rect = 0;
  27959. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27960. w = rect->right - rect->left;
  27961. h = rect->bottom - rect->top;
  27962. return true;
  27963. }
  27964. void mouseDown (int x, int y)
  27965. {
  27966. if (! alreadyInside)
  27967. {
  27968. alreadyInside = true;
  27969. getTopLevelComponent()->toFront (true);
  27970. owner->dispatch (effEditMouse, x, y, 0, 0);
  27971. alreadyInside = false;
  27972. }
  27973. else
  27974. {
  27975. PostEvent (::mouseDown, 0);
  27976. }
  27977. }
  27978. void paint()
  27979. {
  27980. ComponentPeer* const peer = getPeer();
  27981. if (peer != 0)
  27982. {
  27983. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27984. ERect r;
  27985. r.left = pos.getX();
  27986. r.right = r.left + getWidth();
  27987. r.top = pos.getY();
  27988. r.bottom = r.top + getHeight();
  27989. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27990. }
  27991. }
  27992. private:
  27993. VSTPluginWindow* const owner;
  27994. bool alreadyInside;
  27995. };
  27996. friend class InnerWrapperComponent;
  27997. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27998. void resized()
  27999. {
  28000. innerWrapper->setSize (getWidth(), getHeight());
  28001. }
  28002. #endif
  28003. private:
  28004. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  28005. };
  28006. AudioProcessorEditor* VSTPluginInstance::createEditor()
  28007. {
  28008. if (hasEditor())
  28009. return new VSTPluginWindow (*this);
  28010. return 0;
  28011. }
  28012. void VSTPluginInstance::handleAsyncUpdate()
  28013. {
  28014. // indicates that something about the plugin has changed..
  28015. updateHostDisplay();
  28016. }
  28017. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  28018. {
  28019. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  28020. {
  28021. changeProgramName (getCurrentProgram(), prog->prgName);
  28022. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28023. setParameter (i, vst_swapFloat (prog->params[i]));
  28024. return true;
  28025. }
  28026. return false;
  28027. }
  28028. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  28029. const int dataSize)
  28030. {
  28031. if (dataSize < 28)
  28032. return false;
  28033. const fxSet* const set = (const fxSet*) data;
  28034. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  28035. || vst_swap (set->version) > fxbVersionNum)
  28036. return false;
  28037. if (vst_swap (set->fxMagic) == 'FxBk')
  28038. {
  28039. // bank of programs
  28040. if (vst_swap (set->numPrograms) >= 0)
  28041. {
  28042. const int oldProg = getCurrentProgram();
  28043. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  28044. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28045. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  28046. {
  28047. if (i != oldProg)
  28048. {
  28049. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  28050. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28051. return false;
  28052. if (vst_swap (set->numPrograms) > 0)
  28053. setCurrentProgram (i);
  28054. if (! restoreProgramSettings (prog))
  28055. return false;
  28056. }
  28057. }
  28058. if (vst_swap (set->numPrograms) > 0)
  28059. setCurrentProgram (oldProg);
  28060. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28061. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28062. return false;
  28063. if (! restoreProgramSettings (prog))
  28064. return false;
  28065. }
  28066. }
  28067. else if (vst_swap (set->fxMagic) == 'FxCk')
  28068. {
  28069. // single program
  28070. const fxProgram* const prog = (const fxProgram*) data;
  28071. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28072. return false;
  28073. changeProgramName (getCurrentProgram(), prog->prgName);
  28074. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28075. setParameter (i, vst_swapFloat (prog->params[i]));
  28076. }
  28077. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28078. {
  28079. // non-preset chunk
  28080. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28081. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28082. return false;
  28083. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28084. }
  28085. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28086. {
  28087. // preset chunk
  28088. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28089. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28090. return false;
  28091. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28092. changeProgramName (getCurrentProgram(), cset->name);
  28093. }
  28094. else
  28095. {
  28096. return false;
  28097. }
  28098. return true;
  28099. }
  28100. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28101. {
  28102. const int numParams = getNumParameters();
  28103. prog->chunkMagic = vst_swap ('CcnK');
  28104. prog->byteSize = 0;
  28105. prog->fxMagic = vst_swap ('FxCk');
  28106. prog->version = vst_swap (fxbVersionNum);
  28107. prog->fxID = vst_swap (getUID());
  28108. prog->fxVersion = vst_swap (getVersionNumber());
  28109. prog->numParams = vst_swap (numParams);
  28110. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28111. for (int i = 0; i < numParams; ++i)
  28112. prog->params[i] = vst_swapFloat (getParameter (i));
  28113. }
  28114. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28115. {
  28116. const int numPrograms = getNumPrograms();
  28117. const int numParams = getNumParameters();
  28118. if (usesChunks())
  28119. {
  28120. if (isFXB)
  28121. {
  28122. MemoryBlock chunk;
  28123. getChunkData (chunk, false, maxSizeMB);
  28124. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28125. dest.setSize (totalLen, true);
  28126. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28127. set->chunkMagic = vst_swap ('CcnK');
  28128. set->byteSize = 0;
  28129. set->fxMagic = vst_swap ('FBCh');
  28130. set->version = vst_swap (fxbVersionNum);
  28131. set->fxID = vst_swap (getUID());
  28132. set->fxVersion = vst_swap (getVersionNumber());
  28133. set->numPrograms = vst_swap (numPrograms);
  28134. set->chunkSize = vst_swap ((long) chunk.getSize());
  28135. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28136. }
  28137. else
  28138. {
  28139. MemoryBlock chunk;
  28140. getChunkData (chunk, true, maxSizeMB);
  28141. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28142. dest.setSize (totalLen, true);
  28143. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28144. set->chunkMagic = vst_swap ('CcnK');
  28145. set->byteSize = 0;
  28146. set->fxMagic = vst_swap ('FPCh');
  28147. set->version = vst_swap (fxbVersionNum);
  28148. set->fxID = vst_swap (getUID());
  28149. set->fxVersion = vst_swap (getVersionNumber());
  28150. set->numPrograms = vst_swap (numPrograms);
  28151. set->chunkSize = vst_swap ((long) chunk.getSize());
  28152. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28153. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28154. }
  28155. }
  28156. else
  28157. {
  28158. if (isFXB)
  28159. {
  28160. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28161. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28162. dest.setSize (len, true);
  28163. fxSet* const set = (fxSet*) dest.getData();
  28164. set->chunkMagic = vst_swap ('CcnK');
  28165. set->byteSize = 0;
  28166. set->fxMagic = vst_swap ('FxBk');
  28167. set->version = vst_swap (fxbVersionNum);
  28168. set->fxID = vst_swap (getUID());
  28169. set->fxVersion = vst_swap (getVersionNumber());
  28170. set->numPrograms = vst_swap (numPrograms);
  28171. const int oldProgram = getCurrentProgram();
  28172. MemoryBlock oldSettings;
  28173. createTempParameterStore (oldSettings);
  28174. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28175. for (int i = 0; i < numPrograms; ++i)
  28176. {
  28177. if (i != oldProgram)
  28178. {
  28179. setCurrentProgram (i);
  28180. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28181. }
  28182. }
  28183. setCurrentProgram (oldProgram);
  28184. restoreFromTempParameterStore (oldSettings);
  28185. }
  28186. else
  28187. {
  28188. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28189. dest.setSize (totalLen, true);
  28190. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28191. }
  28192. }
  28193. return true;
  28194. }
  28195. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28196. {
  28197. if (usesChunks())
  28198. {
  28199. void* data = 0;
  28200. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28201. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28202. {
  28203. mb.setSize (bytes);
  28204. mb.copyFrom (data, 0, bytes);
  28205. }
  28206. }
  28207. }
  28208. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28209. {
  28210. if (size > 0 && usesChunks())
  28211. {
  28212. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28213. if (! isPreset)
  28214. updateStoredProgramNames();
  28215. }
  28216. }
  28217. void VSTPluginInstance::timerCallback()
  28218. {
  28219. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28220. stopTimer();
  28221. }
  28222. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28223. {
  28224. const ScopedLock sl (lock);
  28225. ++insideVSTCallback;
  28226. int result = 0;
  28227. try
  28228. {
  28229. if (effect != 0)
  28230. {
  28231. #if JUCE_MAC
  28232. if (module->resFileId != 0)
  28233. UseResFile (module->resFileId);
  28234. #endif
  28235. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28236. #if JUCE_MAC
  28237. module->resFileId = CurResFile();
  28238. #endif
  28239. --insideVSTCallback;
  28240. return result;
  28241. }
  28242. }
  28243. catch (...)
  28244. {
  28245. }
  28246. --insideVSTCallback;
  28247. return result;
  28248. }
  28249. namespace
  28250. {
  28251. static const int defaultVSTSampleRateValue = 16384;
  28252. static const int defaultVSTBlockSizeValue = 512;
  28253. // handles non plugin-specific callbacks..
  28254. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28255. {
  28256. (void) index;
  28257. (void) value;
  28258. (void) opt;
  28259. switch (opcode)
  28260. {
  28261. case audioMasterCanDo:
  28262. {
  28263. static const char* canDos[] = { "supplyIdle",
  28264. "sendVstEvents",
  28265. "sendVstMidiEvent",
  28266. "sendVstTimeInfo",
  28267. "receiveVstEvents",
  28268. "receiveVstMidiEvent",
  28269. "supportShell",
  28270. "shellCategory" };
  28271. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28272. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28273. return 1;
  28274. return 0;
  28275. }
  28276. case audioMasterVersion: return 0x2400;
  28277. case audioMasterCurrentId: return shellUIDToCreate;
  28278. case audioMasterGetNumAutomatableParameters: return 0;
  28279. case audioMasterGetAutomationState: return 1;
  28280. case audioMasterGetVendorVersion: return 0x0101;
  28281. case audioMasterGetVendorString:
  28282. case audioMasterGetProductString:
  28283. {
  28284. String hostName ("Juce VST Host");
  28285. if (JUCEApplication::getInstance() != 0)
  28286. hostName = JUCEApplication::getInstance()->getApplicationName();
  28287. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28288. break;
  28289. }
  28290. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28291. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28292. case audioMasterSetOutputSampleRate: return 0;
  28293. default:
  28294. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28295. break;
  28296. }
  28297. return 0;
  28298. }
  28299. }
  28300. // handles callbacks for a specific plugin
  28301. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28302. {
  28303. switch (opcode)
  28304. {
  28305. case audioMasterAutomate:
  28306. sendParamChangeMessageToListeners (index, opt);
  28307. break;
  28308. case audioMasterProcessEvents:
  28309. handleMidiFromPlugin ((const VstEvents*) ptr);
  28310. break;
  28311. case audioMasterGetTime:
  28312. #if JUCE_MSVC
  28313. #pragma warning (push)
  28314. #pragma warning (disable: 4311)
  28315. #endif
  28316. return (VstIntPtr) &vstHostTime;
  28317. #if JUCE_MSVC
  28318. #pragma warning (pop)
  28319. #endif
  28320. break;
  28321. case audioMasterIdle:
  28322. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28323. {
  28324. ++insideVSTCallback;
  28325. #if JUCE_MAC
  28326. if (getActiveEditor() != 0)
  28327. dispatch (effEditIdle, 0, 0, 0, 0);
  28328. #endif
  28329. juce_callAnyTimersSynchronously();
  28330. handleUpdateNowIfNeeded();
  28331. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28332. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28333. --insideVSTCallback;
  28334. }
  28335. break;
  28336. case audioMasterUpdateDisplay:
  28337. triggerAsyncUpdate();
  28338. break;
  28339. case audioMasterTempoAt:
  28340. // returns (10000 * bpm)
  28341. break;
  28342. case audioMasterNeedIdle:
  28343. startTimer (50);
  28344. break;
  28345. case audioMasterSizeWindow:
  28346. if (getActiveEditor() != 0)
  28347. getActiveEditor()->setSize (index, value);
  28348. return 1;
  28349. case audioMasterGetSampleRate:
  28350. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28351. case audioMasterGetBlockSize:
  28352. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28353. case audioMasterWantMidi:
  28354. wantsMidiMessages = true;
  28355. break;
  28356. case audioMasterGetDirectory:
  28357. #if JUCE_MAC
  28358. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28359. #else
  28360. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28361. #endif
  28362. case audioMasterGetAutomationState:
  28363. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28364. break;
  28365. // none of these are handled (yet)..
  28366. case audioMasterBeginEdit:
  28367. case audioMasterEndEdit:
  28368. case audioMasterSetTime:
  28369. case audioMasterPinConnected:
  28370. case audioMasterGetParameterQuantization:
  28371. case audioMasterIOChanged:
  28372. case audioMasterGetInputLatency:
  28373. case audioMasterGetOutputLatency:
  28374. case audioMasterGetPreviousPlug:
  28375. case audioMasterGetNextPlug:
  28376. case audioMasterWillReplaceOrAccumulate:
  28377. case audioMasterGetCurrentProcessLevel:
  28378. case audioMasterOfflineStart:
  28379. case audioMasterOfflineRead:
  28380. case audioMasterOfflineWrite:
  28381. case audioMasterOfflineGetCurrentPass:
  28382. case audioMasterOfflineGetCurrentMetaPass:
  28383. case audioMasterVendorSpecific:
  28384. case audioMasterSetIcon:
  28385. case audioMasterGetLanguage:
  28386. case audioMasterOpenWindow:
  28387. case audioMasterCloseWindow:
  28388. break;
  28389. default:
  28390. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28391. }
  28392. return 0;
  28393. }
  28394. // entry point for all callbacks from the plugin
  28395. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28396. {
  28397. try
  28398. {
  28399. if (effect != 0 && effect->resvd2 != 0)
  28400. {
  28401. return ((VSTPluginInstance*)(effect->resvd2))
  28402. ->handleCallback (opcode, index, value, ptr, opt);
  28403. }
  28404. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28405. }
  28406. catch (...)
  28407. {
  28408. return 0;
  28409. }
  28410. }
  28411. const String VSTPluginInstance::getVersion() const
  28412. {
  28413. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28414. String s;
  28415. if (v == 0 || v == -1)
  28416. v = getVersionNumber();
  28417. if (v != 0)
  28418. {
  28419. int versionBits[4];
  28420. int n = 0;
  28421. while (v != 0)
  28422. {
  28423. versionBits [n++] = (v & 0xff);
  28424. v >>= 8;
  28425. }
  28426. s << 'V';
  28427. while (n > 0)
  28428. {
  28429. s << versionBits [--n];
  28430. if (n > 0)
  28431. s << '.';
  28432. }
  28433. }
  28434. return s;
  28435. }
  28436. int VSTPluginInstance::getUID() const
  28437. {
  28438. int uid = effect != 0 ? effect->uniqueID : 0;
  28439. if (uid == 0)
  28440. uid = module->file.hashCode();
  28441. return uid;
  28442. }
  28443. const String VSTPluginInstance::getCategory() const
  28444. {
  28445. const char* result = 0;
  28446. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28447. {
  28448. case kPlugCategEffect: result = "Effect"; break;
  28449. case kPlugCategSynth: result = "Synth"; break;
  28450. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28451. case kPlugCategMastering: result = "Mastering"; break;
  28452. case kPlugCategSpacializer: result = "Spacial"; break;
  28453. case kPlugCategRoomFx: result = "Reverb"; break;
  28454. case kPlugSurroundFx: result = "Surround"; break;
  28455. case kPlugCategRestoration: result = "Restoration"; break;
  28456. case kPlugCategGenerator: result = "Tone generation"; break;
  28457. default: break;
  28458. }
  28459. return result;
  28460. }
  28461. float VSTPluginInstance::getParameter (int index)
  28462. {
  28463. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28464. {
  28465. try
  28466. {
  28467. const ScopedLock sl (lock);
  28468. return effect->getParameter (effect, index);
  28469. }
  28470. catch (...)
  28471. {
  28472. }
  28473. }
  28474. return 0.0f;
  28475. }
  28476. void VSTPluginInstance::setParameter (int index, float newValue)
  28477. {
  28478. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28479. {
  28480. try
  28481. {
  28482. const ScopedLock sl (lock);
  28483. if (effect->getParameter (effect, index) != newValue)
  28484. effect->setParameter (effect, index, newValue);
  28485. }
  28486. catch (...)
  28487. {
  28488. }
  28489. }
  28490. }
  28491. const String VSTPluginInstance::getParameterName (int index)
  28492. {
  28493. if (effect != 0)
  28494. {
  28495. jassert (index >= 0 && index < effect->numParams);
  28496. char nm [256];
  28497. zerostruct (nm);
  28498. dispatch (effGetParamName, index, 0, nm, 0);
  28499. return String (nm).trim();
  28500. }
  28501. return String::empty;
  28502. }
  28503. const String VSTPluginInstance::getParameterLabel (int index) const
  28504. {
  28505. if (effect != 0)
  28506. {
  28507. jassert (index >= 0 && index < effect->numParams);
  28508. char nm [256];
  28509. zerostruct (nm);
  28510. dispatch (effGetParamLabel, index, 0, nm, 0);
  28511. return String (nm).trim();
  28512. }
  28513. return String::empty;
  28514. }
  28515. const String VSTPluginInstance::getParameterText (int index)
  28516. {
  28517. if (effect != 0)
  28518. {
  28519. jassert (index >= 0 && index < effect->numParams);
  28520. char nm [256];
  28521. zerostruct (nm);
  28522. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28523. return String (nm).trim();
  28524. }
  28525. return String::empty;
  28526. }
  28527. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28528. {
  28529. if (effect != 0)
  28530. {
  28531. jassert (index >= 0 && index < effect->numParams);
  28532. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28533. }
  28534. return false;
  28535. }
  28536. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28537. {
  28538. dest.setSize (64 + 4 * getNumParameters());
  28539. dest.fillWith (0);
  28540. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28541. float* const p = (float*) (((char*) dest.getData()) + 64);
  28542. for (int i = 0; i < getNumParameters(); ++i)
  28543. p[i] = getParameter(i);
  28544. }
  28545. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28546. {
  28547. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28548. float* p = (float*) (((char*) m.getData()) + 64);
  28549. for (int i = 0; i < getNumParameters(); ++i)
  28550. setParameter (i, p[i]);
  28551. }
  28552. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28553. {
  28554. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28555. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28556. }
  28557. const String VSTPluginInstance::getProgramName (int index)
  28558. {
  28559. if (index == getCurrentProgram())
  28560. {
  28561. return getCurrentProgramName();
  28562. }
  28563. else if (effect != 0)
  28564. {
  28565. char nm [256];
  28566. zerostruct (nm);
  28567. if (dispatch (effGetProgramNameIndexed,
  28568. jlimit (0, getNumPrograms(), index),
  28569. -1, nm, 0) != 0)
  28570. {
  28571. return String (nm).trim();
  28572. }
  28573. }
  28574. return programNames [index];
  28575. }
  28576. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28577. {
  28578. if (index == getCurrentProgram())
  28579. {
  28580. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28581. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28582. }
  28583. else
  28584. {
  28585. jassertfalse; // xxx not implemented!
  28586. }
  28587. }
  28588. void VSTPluginInstance::updateStoredProgramNames()
  28589. {
  28590. if (effect != 0 && getNumPrograms() > 0)
  28591. {
  28592. char nm [256];
  28593. zerostruct (nm);
  28594. // only do this if the plugin can't use indexed names..
  28595. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28596. {
  28597. const int oldProgram = getCurrentProgram();
  28598. MemoryBlock oldSettings;
  28599. createTempParameterStore (oldSettings);
  28600. for (int i = 0; i < getNumPrograms(); ++i)
  28601. {
  28602. setCurrentProgram (i);
  28603. getCurrentProgramName(); // (this updates the list)
  28604. }
  28605. setCurrentProgram (oldProgram);
  28606. restoreFromTempParameterStore (oldSettings);
  28607. }
  28608. }
  28609. }
  28610. const String VSTPluginInstance::getCurrentProgramName()
  28611. {
  28612. if (effect != 0)
  28613. {
  28614. char nm [256];
  28615. zerostruct (nm);
  28616. dispatch (effGetProgramName, 0, 0, nm, 0);
  28617. const int index = getCurrentProgram();
  28618. if (programNames[index].isEmpty())
  28619. {
  28620. while (programNames.size() < index)
  28621. programNames.add (String::empty);
  28622. programNames.set (index, String (nm).trim());
  28623. }
  28624. return String (nm).trim();
  28625. }
  28626. return String::empty;
  28627. }
  28628. const String VSTPluginInstance::getInputChannelName (int index) const
  28629. {
  28630. if (index >= 0 && index < getNumInputChannels())
  28631. {
  28632. VstPinProperties pinProps;
  28633. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28634. return String (pinProps.label, sizeof (pinProps.label));
  28635. }
  28636. return String::empty;
  28637. }
  28638. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28639. {
  28640. if (index < 0 || index >= getNumInputChannels())
  28641. return false;
  28642. VstPinProperties pinProps;
  28643. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28644. return (pinProps.flags & kVstPinIsStereo) != 0;
  28645. return true;
  28646. }
  28647. const String VSTPluginInstance::getOutputChannelName (int index) const
  28648. {
  28649. if (index >= 0 && index < getNumOutputChannels())
  28650. {
  28651. VstPinProperties pinProps;
  28652. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28653. return String (pinProps.label, sizeof (pinProps.label));
  28654. }
  28655. return String::empty;
  28656. }
  28657. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28658. {
  28659. if (index < 0 || index >= getNumOutputChannels())
  28660. return false;
  28661. VstPinProperties pinProps;
  28662. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28663. return (pinProps.flags & kVstPinIsStereo) != 0;
  28664. return true;
  28665. }
  28666. void VSTPluginInstance::setPower (const bool on)
  28667. {
  28668. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28669. isPowerOn = on;
  28670. }
  28671. const int defaultMaxSizeMB = 64;
  28672. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28673. {
  28674. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28675. }
  28676. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28677. {
  28678. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28679. }
  28680. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28681. {
  28682. loadFromFXBFile (data, sizeInBytes);
  28683. }
  28684. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28685. {
  28686. loadFromFXBFile (data, sizeInBytes);
  28687. }
  28688. VSTPluginFormat::VSTPluginFormat()
  28689. {
  28690. }
  28691. VSTPluginFormat::~VSTPluginFormat()
  28692. {
  28693. }
  28694. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28695. const String& fileOrIdentifier)
  28696. {
  28697. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28698. return;
  28699. PluginDescription desc;
  28700. desc.fileOrIdentifier = fileOrIdentifier;
  28701. desc.uid = 0;
  28702. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28703. if (instance == 0)
  28704. return;
  28705. try
  28706. {
  28707. #if JUCE_MAC
  28708. if (instance->module->resFileId != 0)
  28709. UseResFile (instance->module->resFileId);
  28710. #endif
  28711. instance->fillInPluginDescription (desc);
  28712. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28713. if (category != kPlugCategShell)
  28714. {
  28715. // Normal plugin...
  28716. results.add (new PluginDescription (desc));
  28717. ++insideVSTCallback;
  28718. instance->dispatch (effOpen, 0, 0, 0, 0);
  28719. --insideVSTCallback;
  28720. }
  28721. else
  28722. {
  28723. // It's a shell plugin, so iterate all the subtypes...
  28724. char shellEffectName [64];
  28725. for (;;)
  28726. {
  28727. zerostruct (shellEffectName);
  28728. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28729. if (uid == 0)
  28730. {
  28731. break;
  28732. }
  28733. else
  28734. {
  28735. desc.uid = uid;
  28736. desc.name = shellEffectName;
  28737. desc.descriptiveName = shellEffectName;
  28738. bool alreadyThere = false;
  28739. for (int i = results.size(); --i >= 0;)
  28740. {
  28741. PluginDescription* const d = results.getUnchecked(i);
  28742. if (d->isDuplicateOf (desc))
  28743. {
  28744. alreadyThere = true;
  28745. break;
  28746. }
  28747. }
  28748. if (! alreadyThere)
  28749. results.add (new PluginDescription (desc));
  28750. }
  28751. }
  28752. }
  28753. }
  28754. catch (...)
  28755. {
  28756. // crashed while loading...
  28757. }
  28758. }
  28759. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28760. {
  28761. ScopedPointer <VSTPluginInstance> result;
  28762. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28763. {
  28764. File file (desc.fileOrIdentifier);
  28765. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28766. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28767. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28768. if (module != 0)
  28769. {
  28770. shellUIDToCreate = desc.uid;
  28771. result = new VSTPluginInstance (module);
  28772. if (result->effect != 0)
  28773. {
  28774. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28775. result->initialise();
  28776. }
  28777. else
  28778. {
  28779. result = 0;
  28780. }
  28781. }
  28782. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28783. }
  28784. return result.release();
  28785. }
  28786. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28787. {
  28788. const File f (fileOrIdentifier);
  28789. #if JUCE_MAC
  28790. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28791. return true;
  28792. #if JUCE_PPC
  28793. FSRef fileRef;
  28794. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28795. {
  28796. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28797. if (resFileId != -1)
  28798. {
  28799. const int numEffects = Count1Resources ('aEff');
  28800. CloseResFile (resFileId);
  28801. if (numEffects > 0)
  28802. return true;
  28803. }
  28804. }
  28805. #endif
  28806. return false;
  28807. #elif JUCE_WINDOWS
  28808. return f.existsAsFile() && f.hasFileExtension (".dll");
  28809. #elif JUCE_LINUX
  28810. return f.existsAsFile() && f.hasFileExtension (".so");
  28811. #endif
  28812. }
  28813. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28814. {
  28815. return fileOrIdentifier;
  28816. }
  28817. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28818. {
  28819. return File (desc.fileOrIdentifier).exists();
  28820. }
  28821. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28822. {
  28823. StringArray results;
  28824. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28825. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28826. return results;
  28827. }
  28828. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28829. {
  28830. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28831. // .component or .vst directories.
  28832. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28833. while (iter.next())
  28834. {
  28835. const File f (iter.getFile());
  28836. bool isPlugin = false;
  28837. if (fileMightContainThisPluginType (f.getFullPathName()))
  28838. {
  28839. isPlugin = true;
  28840. results.add (f.getFullPathName());
  28841. }
  28842. if (recursive && (! isPlugin) && f.isDirectory())
  28843. recursiveFileSearch (results, f, true);
  28844. }
  28845. }
  28846. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28847. {
  28848. #if JUCE_MAC
  28849. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28850. #elif JUCE_WINDOWS
  28851. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28852. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28853. #elif JUCE_LINUX
  28854. return FileSearchPath ("/usr/lib/vst");
  28855. #endif
  28856. }
  28857. END_JUCE_NAMESPACE
  28858. #endif
  28859. #undef log
  28860. #endif
  28861. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28862. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28863. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28864. BEGIN_JUCE_NAMESPACE
  28865. AudioProcessor::AudioProcessor()
  28866. : playHead (0),
  28867. activeEditor (0),
  28868. sampleRate (0),
  28869. blockSize (0),
  28870. numInputChannels (0),
  28871. numOutputChannels (0),
  28872. latencySamples (0),
  28873. suspended (false),
  28874. nonRealtime (false)
  28875. {
  28876. }
  28877. AudioProcessor::~AudioProcessor()
  28878. {
  28879. // ooh, nasty - the editor should have been deleted before the filter
  28880. // that it refers to is deleted..
  28881. jassert (activeEditor == 0);
  28882. #if JUCE_DEBUG
  28883. // This will fail if you've called beginParameterChangeGesture() for one
  28884. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28885. jassert (changingParams.countNumberOfSetBits() == 0);
  28886. #endif
  28887. }
  28888. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28889. {
  28890. playHead = newPlayHead;
  28891. }
  28892. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28893. {
  28894. const ScopedLock sl (listenerLock);
  28895. listeners.addIfNotAlreadyThere (newListener);
  28896. }
  28897. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28898. {
  28899. const ScopedLock sl (listenerLock);
  28900. listeners.removeValue (listenerToRemove);
  28901. }
  28902. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28903. const int numOuts,
  28904. const double sampleRate_,
  28905. const int blockSize_) throw()
  28906. {
  28907. numInputChannels = numIns;
  28908. numOutputChannels = numOuts;
  28909. sampleRate = sampleRate_;
  28910. blockSize = blockSize_;
  28911. }
  28912. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28913. {
  28914. nonRealtime = nonRealtime_;
  28915. }
  28916. void AudioProcessor::setLatencySamples (const int newLatency)
  28917. {
  28918. if (latencySamples != newLatency)
  28919. {
  28920. latencySamples = newLatency;
  28921. updateHostDisplay();
  28922. }
  28923. }
  28924. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28925. const float newValue)
  28926. {
  28927. setParameter (parameterIndex, newValue);
  28928. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28929. }
  28930. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28931. {
  28932. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28933. for (int i = listeners.size(); --i >= 0;)
  28934. {
  28935. AudioProcessorListener* l;
  28936. {
  28937. const ScopedLock sl (listenerLock);
  28938. l = listeners [i];
  28939. }
  28940. if (l != 0)
  28941. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28942. }
  28943. }
  28944. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28945. {
  28946. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28947. #if JUCE_DEBUG
  28948. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28949. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28950. jassert (! changingParams [parameterIndex]);
  28951. changingParams.setBit (parameterIndex);
  28952. #endif
  28953. for (int i = listeners.size(); --i >= 0;)
  28954. {
  28955. AudioProcessorListener* l;
  28956. {
  28957. const ScopedLock sl (listenerLock);
  28958. l = listeners [i];
  28959. }
  28960. if (l != 0)
  28961. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28962. }
  28963. }
  28964. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28965. {
  28966. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28967. #if JUCE_DEBUG
  28968. // This means you've called endParameterChangeGesture without having previously called
  28969. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28970. // calls matched correctly.
  28971. jassert (changingParams [parameterIndex]);
  28972. changingParams.clearBit (parameterIndex);
  28973. #endif
  28974. for (int i = listeners.size(); --i >= 0;)
  28975. {
  28976. AudioProcessorListener* l;
  28977. {
  28978. const ScopedLock sl (listenerLock);
  28979. l = listeners [i];
  28980. }
  28981. if (l != 0)
  28982. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28983. }
  28984. }
  28985. void AudioProcessor::updateHostDisplay()
  28986. {
  28987. for (int i = listeners.size(); --i >= 0;)
  28988. {
  28989. AudioProcessorListener* l;
  28990. {
  28991. const ScopedLock sl (listenerLock);
  28992. l = listeners [i];
  28993. }
  28994. if (l != 0)
  28995. l->audioProcessorChanged (this);
  28996. }
  28997. }
  28998. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28999. {
  29000. return true;
  29001. }
  29002. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  29003. {
  29004. return false;
  29005. }
  29006. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  29007. {
  29008. const ScopedLock sl (callbackLock);
  29009. suspended = shouldBeSuspended;
  29010. }
  29011. void AudioProcessor::reset()
  29012. {
  29013. }
  29014. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  29015. {
  29016. const ScopedLock sl (callbackLock);
  29017. jassert (activeEditor == editor);
  29018. if (activeEditor == editor)
  29019. activeEditor = 0;
  29020. }
  29021. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  29022. {
  29023. if (activeEditor != 0)
  29024. return activeEditor;
  29025. AudioProcessorEditor* const ed = createEditor();
  29026. // You must make your hasEditor() method return a consistent result!
  29027. jassert (hasEditor() == (ed != 0));
  29028. if (ed != 0)
  29029. {
  29030. // you must give your editor comp a size before returning it..
  29031. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  29032. const ScopedLock sl (callbackLock);
  29033. activeEditor = ed;
  29034. }
  29035. return ed;
  29036. }
  29037. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  29038. {
  29039. getStateInformation (destData);
  29040. }
  29041. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  29042. {
  29043. setStateInformation (data, sizeInBytes);
  29044. }
  29045. // magic number to identify memory blocks that we've stored as XML
  29046. const uint32 magicXmlNumber = 0x21324356;
  29047. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  29048. JUCE_NAMESPACE::MemoryBlock& destData)
  29049. {
  29050. const String xmlString (xml.createDocument (String::empty, true, false));
  29051. const int stringLength = xmlString.getNumBytesAsUTF8();
  29052. destData.setSize (stringLength + 10);
  29053. char* const d = static_cast<char*> (destData.getData());
  29054. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  29055. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  29056. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  29057. }
  29058. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  29059. const int sizeInBytes)
  29060. {
  29061. if (sizeInBytes > 8
  29062. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29063. {
  29064. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29065. if (stringLength > 0)
  29066. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29067. jmin ((sizeInBytes - 8), stringLength)));
  29068. }
  29069. return 0;
  29070. }
  29071. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29072. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29073. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29074. {
  29075. return timeInSeconds == other.timeInSeconds
  29076. && ppqPosition == other.ppqPosition
  29077. && editOriginTime == other.editOriginTime
  29078. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29079. && frameRate == other.frameRate
  29080. && isPlaying == other.isPlaying
  29081. && isRecording == other.isRecording
  29082. && bpm == other.bpm
  29083. && timeSigNumerator == other.timeSigNumerator
  29084. && timeSigDenominator == other.timeSigDenominator;
  29085. }
  29086. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29087. {
  29088. return ! operator== (other);
  29089. }
  29090. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29091. {
  29092. zerostruct (*this);
  29093. timeSigNumerator = 4;
  29094. timeSigDenominator = 4;
  29095. bpm = 120;
  29096. }
  29097. END_JUCE_NAMESPACE
  29098. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29099. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29100. BEGIN_JUCE_NAMESPACE
  29101. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29102. : owner (owner_)
  29103. {
  29104. // the filter must be valid..
  29105. jassert (owner != 0);
  29106. }
  29107. AudioProcessorEditor::~AudioProcessorEditor()
  29108. {
  29109. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29110. // filter for some reason..
  29111. jassert (owner->getActiveEditor() != this);
  29112. }
  29113. END_JUCE_NAMESPACE
  29114. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29115. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29116. BEGIN_JUCE_NAMESPACE
  29117. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29118. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29119. : id (id_),
  29120. processor (processor_),
  29121. isPrepared (false)
  29122. {
  29123. jassert (processor_ != 0);
  29124. }
  29125. AudioProcessorGraph::Node::~Node()
  29126. {
  29127. }
  29128. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29129. AudioProcessorGraph* const graph)
  29130. {
  29131. if (! isPrepared)
  29132. {
  29133. isPrepared = true;
  29134. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29135. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29136. if (ioProc != 0)
  29137. ioProc->setParentGraph (graph);
  29138. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29139. processor->getNumOutputChannels(),
  29140. sampleRate, blockSize);
  29141. processor->prepareToPlay (sampleRate, blockSize);
  29142. }
  29143. }
  29144. void AudioProcessorGraph::Node::unprepare()
  29145. {
  29146. if (isPrepared)
  29147. {
  29148. isPrepared = false;
  29149. processor->releaseResources();
  29150. }
  29151. }
  29152. AudioProcessorGraph::AudioProcessorGraph()
  29153. : lastNodeId (0),
  29154. renderingBuffers (1, 1),
  29155. currentAudioOutputBuffer (1, 1)
  29156. {
  29157. }
  29158. AudioProcessorGraph::~AudioProcessorGraph()
  29159. {
  29160. clearRenderingSequence();
  29161. clear();
  29162. }
  29163. const String AudioProcessorGraph::getName() const
  29164. {
  29165. return "Audio Graph";
  29166. }
  29167. void AudioProcessorGraph::clear()
  29168. {
  29169. nodes.clear();
  29170. connections.clear();
  29171. triggerAsyncUpdate();
  29172. }
  29173. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29174. {
  29175. for (int i = nodes.size(); --i >= 0;)
  29176. if (nodes.getUnchecked(i)->id == nodeId)
  29177. return nodes.getUnchecked(i);
  29178. return 0;
  29179. }
  29180. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29181. uint32 nodeId)
  29182. {
  29183. if (newProcessor == 0)
  29184. {
  29185. jassertfalse;
  29186. return 0;
  29187. }
  29188. if (nodeId == 0)
  29189. {
  29190. nodeId = ++lastNodeId;
  29191. }
  29192. else
  29193. {
  29194. // you can't add a node with an id that already exists in the graph..
  29195. jassert (getNodeForId (nodeId) == 0);
  29196. removeNode (nodeId);
  29197. }
  29198. lastNodeId = nodeId;
  29199. Node* const n = new Node (nodeId, newProcessor);
  29200. nodes.add (n);
  29201. triggerAsyncUpdate();
  29202. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29203. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29204. if (ioProc != 0)
  29205. ioProc->setParentGraph (this);
  29206. return n;
  29207. }
  29208. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29209. {
  29210. disconnectNode (nodeId);
  29211. for (int i = nodes.size(); --i >= 0;)
  29212. {
  29213. if (nodes.getUnchecked(i)->id == nodeId)
  29214. {
  29215. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29216. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29217. if (ioProc != 0)
  29218. ioProc->setParentGraph (0);
  29219. nodes.remove (i);
  29220. triggerAsyncUpdate();
  29221. return true;
  29222. }
  29223. }
  29224. return false;
  29225. }
  29226. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29227. const int sourceChannelIndex,
  29228. const uint32 destNodeId,
  29229. const int destChannelIndex) const
  29230. {
  29231. for (int i = connections.size(); --i >= 0;)
  29232. {
  29233. const Connection* const c = connections.getUnchecked(i);
  29234. if (c->sourceNodeId == sourceNodeId
  29235. && c->destNodeId == destNodeId
  29236. && c->sourceChannelIndex == sourceChannelIndex
  29237. && c->destChannelIndex == destChannelIndex)
  29238. {
  29239. return c;
  29240. }
  29241. }
  29242. return 0;
  29243. }
  29244. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29245. const uint32 possibleDestNodeId) const
  29246. {
  29247. for (int i = connections.size(); --i >= 0;)
  29248. {
  29249. const Connection* const c = connections.getUnchecked(i);
  29250. if (c->sourceNodeId == possibleSourceNodeId
  29251. && c->destNodeId == possibleDestNodeId)
  29252. {
  29253. return true;
  29254. }
  29255. }
  29256. return false;
  29257. }
  29258. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29259. const int sourceChannelIndex,
  29260. const uint32 destNodeId,
  29261. const int destChannelIndex) const
  29262. {
  29263. if (sourceChannelIndex < 0
  29264. || destChannelIndex < 0
  29265. || sourceNodeId == destNodeId
  29266. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29267. return false;
  29268. const Node* const source = getNodeForId (sourceNodeId);
  29269. if (source == 0
  29270. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29271. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29272. return false;
  29273. const Node* const dest = getNodeForId (destNodeId);
  29274. if (dest == 0
  29275. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29276. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29277. return false;
  29278. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29279. destNodeId, destChannelIndex) == 0;
  29280. }
  29281. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29282. const int sourceChannelIndex,
  29283. const uint32 destNodeId,
  29284. const int destChannelIndex)
  29285. {
  29286. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29287. return false;
  29288. Connection* const c = new Connection();
  29289. c->sourceNodeId = sourceNodeId;
  29290. c->sourceChannelIndex = sourceChannelIndex;
  29291. c->destNodeId = destNodeId;
  29292. c->destChannelIndex = destChannelIndex;
  29293. connections.add (c);
  29294. triggerAsyncUpdate();
  29295. return true;
  29296. }
  29297. void AudioProcessorGraph::removeConnection (const int index)
  29298. {
  29299. connections.remove (index);
  29300. triggerAsyncUpdate();
  29301. }
  29302. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29303. const uint32 destNodeId, const int destChannelIndex)
  29304. {
  29305. bool doneAnything = false;
  29306. for (int i = connections.size(); --i >= 0;)
  29307. {
  29308. const Connection* const c = connections.getUnchecked(i);
  29309. if (c->sourceNodeId == sourceNodeId
  29310. && c->destNodeId == destNodeId
  29311. && c->sourceChannelIndex == sourceChannelIndex
  29312. && c->destChannelIndex == destChannelIndex)
  29313. {
  29314. removeConnection (i);
  29315. doneAnything = true;
  29316. triggerAsyncUpdate();
  29317. }
  29318. }
  29319. return doneAnything;
  29320. }
  29321. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29322. {
  29323. bool doneAnything = false;
  29324. for (int i = connections.size(); --i >= 0;)
  29325. {
  29326. const Connection* const c = connections.getUnchecked(i);
  29327. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29328. {
  29329. removeConnection (i);
  29330. doneAnything = true;
  29331. triggerAsyncUpdate();
  29332. }
  29333. }
  29334. return doneAnything;
  29335. }
  29336. bool AudioProcessorGraph::removeIllegalConnections()
  29337. {
  29338. bool doneAnything = false;
  29339. for (int i = connections.size(); --i >= 0;)
  29340. {
  29341. const Connection* const c = connections.getUnchecked(i);
  29342. const Node* const source = getNodeForId (c->sourceNodeId);
  29343. const Node* const dest = getNodeForId (c->destNodeId);
  29344. if (source == 0 || dest == 0
  29345. || (c->sourceChannelIndex != midiChannelIndex
  29346. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29347. || (c->sourceChannelIndex == midiChannelIndex
  29348. && ! source->processor->producesMidi())
  29349. || (c->destChannelIndex != midiChannelIndex
  29350. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29351. || (c->destChannelIndex == midiChannelIndex
  29352. && ! dest->processor->acceptsMidi()))
  29353. {
  29354. removeConnection (i);
  29355. doneAnything = true;
  29356. triggerAsyncUpdate();
  29357. }
  29358. }
  29359. return doneAnything;
  29360. }
  29361. namespace GraphRenderingOps
  29362. {
  29363. class AudioGraphRenderingOp
  29364. {
  29365. public:
  29366. AudioGraphRenderingOp() {}
  29367. virtual ~AudioGraphRenderingOp() {}
  29368. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29369. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29370. const int numSamples) = 0;
  29371. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29372. };
  29373. class ClearChannelOp : public AudioGraphRenderingOp
  29374. {
  29375. public:
  29376. ClearChannelOp (const int channelNum_)
  29377. : channelNum (channelNum_)
  29378. {}
  29379. ~ClearChannelOp() {}
  29380. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29381. {
  29382. sharedBufferChans.clear (channelNum, 0, numSamples);
  29383. }
  29384. private:
  29385. const int channelNum;
  29386. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29387. };
  29388. class CopyChannelOp : public AudioGraphRenderingOp
  29389. {
  29390. public:
  29391. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29392. : srcChannelNum (srcChannelNum_),
  29393. dstChannelNum (dstChannelNum_)
  29394. {}
  29395. ~CopyChannelOp() {}
  29396. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29397. {
  29398. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29399. }
  29400. private:
  29401. const int srcChannelNum, dstChannelNum;
  29402. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29403. };
  29404. class AddChannelOp : public AudioGraphRenderingOp
  29405. {
  29406. public:
  29407. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29408. : srcChannelNum (srcChannelNum_),
  29409. dstChannelNum (dstChannelNum_)
  29410. {}
  29411. ~AddChannelOp() {}
  29412. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29413. {
  29414. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29415. }
  29416. private:
  29417. const int srcChannelNum, dstChannelNum;
  29418. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29419. };
  29420. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29421. {
  29422. public:
  29423. ClearMidiBufferOp (const int bufferNum_)
  29424. : bufferNum (bufferNum_)
  29425. {}
  29426. ~ClearMidiBufferOp() {}
  29427. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29428. {
  29429. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29430. }
  29431. private:
  29432. const int bufferNum;
  29433. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29434. };
  29435. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29436. {
  29437. public:
  29438. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29439. : srcBufferNum (srcBufferNum_),
  29440. dstBufferNum (dstBufferNum_)
  29441. {}
  29442. ~CopyMidiBufferOp() {}
  29443. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29444. {
  29445. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29446. }
  29447. private:
  29448. const int srcBufferNum, dstBufferNum;
  29449. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29450. };
  29451. class AddMidiBufferOp : public AudioGraphRenderingOp
  29452. {
  29453. public:
  29454. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29455. : srcBufferNum (srcBufferNum_),
  29456. dstBufferNum (dstBufferNum_)
  29457. {}
  29458. ~AddMidiBufferOp() {}
  29459. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29460. {
  29461. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29462. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29463. }
  29464. private:
  29465. const int srcBufferNum, dstBufferNum;
  29466. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29467. };
  29468. class ProcessBufferOp : public AudioGraphRenderingOp
  29469. {
  29470. public:
  29471. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29472. const Array <int>& audioChannelsToUse_,
  29473. const int totalChans_,
  29474. const int midiBufferToUse_)
  29475. : node (node_),
  29476. processor (node_->getProcessor()),
  29477. audioChannelsToUse (audioChannelsToUse_),
  29478. totalChans (jmax (1, totalChans_)),
  29479. midiBufferToUse (midiBufferToUse_)
  29480. {
  29481. channels.calloc (totalChans);
  29482. while (audioChannelsToUse.size() < totalChans)
  29483. audioChannelsToUse.add (0);
  29484. }
  29485. ~ProcessBufferOp()
  29486. {
  29487. }
  29488. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29489. {
  29490. for (int i = totalChans; --i >= 0;)
  29491. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29492. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29493. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29494. }
  29495. const AudioProcessorGraph::Node::Ptr node;
  29496. AudioProcessor* const processor;
  29497. private:
  29498. Array <int> audioChannelsToUse;
  29499. HeapBlock <float*> channels;
  29500. int totalChans;
  29501. int midiBufferToUse;
  29502. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29503. };
  29504. /** Used to calculate the correct sequence of rendering ops needed, based on
  29505. the best re-use of shared buffers at each stage.
  29506. */
  29507. class RenderingOpSequenceCalculator
  29508. {
  29509. public:
  29510. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29511. const Array<void*>& orderedNodes_,
  29512. Array<void*>& renderingOps)
  29513. : graph (graph_),
  29514. orderedNodes (orderedNodes_)
  29515. {
  29516. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29517. channels.add (0);
  29518. midiNodeIds.add ((uint32) zeroNodeID);
  29519. for (int i = 0; i < orderedNodes.size(); ++i)
  29520. {
  29521. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29522. renderingOps, i);
  29523. markAnyUnusedBuffersAsFree (i);
  29524. }
  29525. }
  29526. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29527. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29528. private:
  29529. AudioProcessorGraph& graph;
  29530. const Array<void*>& orderedNodes;
  29531. Array <int> channels;
  29532. Array <uint32> nodeIds, midiNodeIds;
  29533. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29534. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29535. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29536. Array<void*>& renderingOps,
  29537. const int ourRenderingIndex)
  29538. {
  29539. const int numIns = node->getProcessor()->getNumInputChannels();
  29540. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29541. const int totalChans = jmax (numIns, numOuts);
  29542. Array <int> audioChannelsToUse;
  29543. int midiBufferToUse = -1;
  29544. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29545. {
  29546. // get a list of all the inputs to this node
  29547. Array <int> sourceNodes, sourceOutputChans;
  29548. for (int i = graph.getNumConnections(); --i >= 0;)
  29549. {
  29550. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29551. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29552. {
  29553. sourceNodes.add (c->sourceNodeId);
  29554. sourceOutputChans.add (c->sourceChannelIndex);
  29555. }
  29556. }
  29557. int bufIndex = -1;
  29558. if (sourceNodes.size() == 0)
  29559. {
  29560. // unconnected input channel
  29561. if (inputChan >= numOuts)
  29562. {
  29563. bufIndex = getReadOnlyEmptyBuffer();
  29564. jassert (bufIndex >= 0);
  29565. }
  29566. else
  29567. {
  29568. bufIndex = getFreeBuffer (false);
  29569. renderingOps.add (new ClearChannelOp (bufIndex));
  29570. }
  29571. }
  29572. else if (sourceNodes.size() == 1)
  29573. {
  29574. // channel with a straightforward single input..
  29575. const int srcNode = sourceNodes.getUnchecked(0);
  29576. const int srcChan = sourceOutputChans.getUnchecked(0);
  29577. bufIndex = getBufferContaining (srcNode, srcChan);
  29578. if (bufIndex < 0)
  29579. {
  29580. // if not found, this is probably a feedback loop
  29581. bufIndex = getReadOnlyEmptyBuffer();
  29582. jassert (bufIndex >= 0);
  29583. }
  29584. if (inputChan < numOuts
  29585. && isBufferNeededLater (ourRenderingIndex,
  29586. inputChan,
  29587. srcNode, srcChan))
  29588. {
  29589. // can't mess up this channel because it's needed later by another node, so we
  29590. // need to use a copy of it..
  29591. const int newFreeBuffer = getFreeBuffer (false);
  29592. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29593. bufIndex = newFreeBuffer;
  29594. }
  29595. }
  29596. else
  29597. {
  29598. // channel with a mix of several inputs..
  29599. // try to find a re-usable channel from our inputs..
  29600. int reusableInputIndex = -1;
  29601. for (int i = 0; i < sourceNodes.size(); ++i)
  29602. {
  29603. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29604. sourceOutputChans.getUnchecked(i));
  29605. if (sourceBufIndex >= 0
  29606. && ! isBufferNeededLater (ourRenderingIndex,
  29607. inputChan,
  29608. sourceNodes.getUnchecked(i),
  29609. sourceOutputChans.getUnchecked(i)))
  29610. {
  29611. // we've found one of our input chans that can be re-used..
  29612. reusableInputIndex = i;
  29613. bufIndex = sourceBufIndex;
  29614. break;
  29615. }
  29616. }
  29617. if (reusableInputIndex < 0)
  29618. {
  29619. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29620. bufIndex = getFreeBuffer (false);
  29621. jassert (bufIndex != 0);
  29622. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29623. sourceOutputChans.getUnchecked (0));
  29624. if (srcIndex < 0)
  29625. {
  29626. // if not found, this is probably a feedback loop
  29627. renderingOps.add (new ClearChannelOp (bufIndex));
  29628. }
  29629. else
  29630. {
  29631. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29632. }
  29633. reusableInputIndex = 0;
  29634. }
  29635. for (int j = 0; j < sourceNodes.size(); ++j)
  29636. {
  29637. if (j != reusableInputIndex)
  29638. {
  29639. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29640. sourceOutputChans.getUnchecked(j));
  29641. if (srcIndex >= 0)
  29642. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29643. }
  29644. }
  29645. }
  29646. jassert (bufIndex >= 0);
  29647. audioChannelsToUse.add (bufIndex);
  29648. if (inputChan < numOuts)
  29649. markBufferAsContaining (bufIndex, node->id, inputChan);
  29650. }
  29651. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29652. {
  29653. const int bufIndex = getFreeBuffer (false);
  29654. jassert (bufIndex != 0);
  29655. audioChannelsToUse.add (bufIndex);
  29656. markBufferAsContaining (bufIndex, node->id, outputChan);
  29657. }
  29658. // Now the same thing for midi..
  29659. Array <int> midiSourceNodes;
  29660. for (int i = graph.getNumConnections(); --i >= 0;)
  29661. {
  29662. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29663. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29664. midiSourceNodes.add (c->sourceNodeId);
  29665. }
  29666. if (midiSourceNodes.size() == 0)
  29667. {
  29668. // No midi inputs..
  29669. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29670. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29671. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29672. }
  29673. else if (midiSourceNodes.size() == 1)
  29674. {
  29675. // One midi input..
  29676. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29677. AudioProcessorGraph::midiChannelIndex);
  29678. if (midiBufferToUse >= 0)
  29679. {
  29680. if (isBufferNeededLater (ourRenderingIndex,
  29681. AudioProcessorGraph::midiChannelIndex,
  29682. midiSourceNodes.getUnchecked(0),
  29683. AudioProcessorGraph::midiChannelIndex))
  29684. {
  29685. // can't mess up this channel because it's needed later by another node, so we
  29686. // need to use a copy of it..
  29687. const int newFreeBuffer = getFreeBuffer (true);
  29688. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29689. midiBufferToUse = newFreeBuffer;
  29690. }
  29691. }
  29692. else
  29693. {
  29694. // probably a feedback loop, so just use an empty one..
  29695. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29696. }
  29697. }
  29698. else
  29699. {
  29700. // More than one midi input being mixed..
  29701. int reusableInputIndex = -1;
  29702. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29703. {
  29704. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29705. AudioProcessorGraph::midiChannelIndex);
  29706. if (sourceBufIndex >= 0
  29707. && ! isBufferNeededLater (ourRenderingIndex,
  29708. AudioProcessorGraph::midiChannelIndex,
  29709. midiSourceNodes.getUnchecked(i),
  29710. AudioProcessorGraph::midiChannelIndex))
  29711. {
  29712. // we've found one of our input buffers that can be re-used..
  29713. reusableInputIndex = i;
  29714. midiBufferToUse = sourceBufIndex;
  29715. break;
  29716. }
  29717. }
  29718. if (reusableInputIndex < 0)
  29719. {
  29720. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29721. midiBufferToUse = getFreeBuffer (true);
  29722. jassert (midiBufferToUse >= 0);
  29723. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29724. AudioProcessorGraph::midiChannelIndex);
  29725. if (srcIndex >= 0)
  29726. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29727. else
  29728. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29729. reusableInputIndex = 0;
  29730. }
  29731. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29732. {
  29733. if (j != reusableInputIndex)
  29734. {
  29735. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29736. AudioProcessorGraph::midiChannelIndex);
  29737. if (srcIndex >= 0)
  29738. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29739. }
  29740. }
  29741. }
  29742. if (node->getProcessor()->producesMidi())
  29743. markBufferAsContaining (midiBufferToUse, node->id,
  29744. AudioProcessorGraph::midiChannelIndex);
  29745. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29746. totalChans, midiBufferToUse));
  29747. }
  29748. int getFreeBuffer (const bool forMidi)
  29749. {
  29750. if (forMidi)
  29751. {
  29752. for (int i = 1; i < midiNodeIds.size(); ++i)
  29753. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29754. return i;
  29755. midiNodeIds.add ((uint32) freeNodeID);
  29756. return midiNodeIds.size() - 1;
  29757. }
  29758. else
  29759. {
  29760. for (int i = 1; i < nodeIds.size(); ++i)
  29761. if (nodeIds.getUnchecked(i) == freeNodeID)
  29762. return i;
  29763. nodeIds.add ((uint32) freeNodeID);
  29764. channels.add (0);
  29765. return nodeIds.size() - 1;
  29766. }
  29767. }
  29768. int getReadOnlyEmptyBuffer() const
  29769. {
  29770. return 0;
  29771. }
  29772. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29773. {
  29774. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29775. {
  29776. for (int i = midiNodeIds.size(); --i >= 0;)
  29777. if (midiNodeIds.getUnchecked(i) == nodeId)
  29778. return i;
  29779. }
  29780. else
  29781. {
  29782. for (int i = nodeIds.size(); --i >= 0;)
  29783. if (nodeIds.getUnchecked(i) == nodeId
  29784. && channels.getUnchecked(i) == outputChannel)
  29785. return i;
  29786. }
  29787. return -1;
  29788. }
  29789. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29790. {
  29791. int i;
  29792. for (i = 0; i < nodeIds.size(); ++i)
  29793. {
  29794. if (isNodeBusy (nodeIds.getUnchecked(i))
  29795. && ! isBufferNeededLater (stepIndex, -1,
  29796. nodeIds.getUnchecked(i),
  29797. channels.getUnchecked(i)))
  29798. {
  29799. nodeIds.set (i, (uint32) freeNodeID);
  29800. }
  29801. }
  29802. for (i = 0; i < midiNodeIds.size(); ++i)
  29803. {
  29804. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29805. && ! isBufferNeededLater (stepIndex, -1,
  29806. midiNodeIds.getUnchecked(i),
  29807. AudioProcessorGraph::midiChannelIndex))
  29808. {
  29809. midiNodeIds.set (i, (uint32) freeNodeID);
  29810. }
  29811. }
  29812. }
  29813. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29814. int inputChannelOfIndexToIgnore,
  29815. const uint32 nodeId,
  29816. const int outputChanIndex) const
  29817. {
  29818. while (stepIndexToSearchFrom < orderedNodes.size())
  29819. {
  29820. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29821. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29822. {
  29823. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29824. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29825. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29826. return true;
  29827. }
  29828. else
  29829. {
  29830. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29831. if (i != inputChannelOfIndexToIgnore
  29832. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29833. node->id, i) != 0)
  29834. return true;
  29835. }
  29836. inputChannelOfIndexToIgnore = -1;
  29837. ++stepIndexToSearchFrom;
  29838. }
  29839. return false;
  29840. }
  29841. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29842. {
  29843. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29844. {
  29845. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29846. midiNodeIds.set (bufferNum, nodeId);
  29847. }
  29848. else
  29849. {
  29850. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29851. nodeIds.set (bufferNum, nodeId);
  29852. channels.set (bufferNum, outputIndex);
  29853. }
  29854. }
  29855. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29856. };
  29857. }
  29858. void AudioProcessorGraph::clearRenderingSequence()
  29859. {
  29860. const ScopedLock sl (renderLock);
  29861. for (int i = renderingOps.size(); --i >= 0;)
  29862. {
  29863. GraphRenderingOps::AudioGraphRenderingOp* const r
  29864. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29865. renderingOps.remove (i);
  29866. delete r;
  29867. }
  29868. }
  29869. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29870. const uint32 possibleDestinationId,
  29871. const int recursionCheck) const
  29872. {
  29873. if (recursionCheck > 0)
  29874. {
  29875. for (int i = connections.size(); --i >= 0;)
  29876. {
  29877. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29878. if (c->destNodeId == possibleDestinationId
  29879. && (c->sourceNodeId == possibleInputId
  29880. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29881. return true;
  29882. }
  29883. }
  29884. return false;
  29885. }
  29886. void AudioProcessorGraph::buildRenderingSequence()
  29887. {
  29888. Array<void*> newRenderingOps;
  29889. int numRenderingBuffersNeeded = 2;
  29890. int numMidiBuffersNeeded = 1;
  29891. {
  29892. MessageManagerLock mml;
  29893. Array<void*> orderedNodes;
  29894. int i;
  29895. for (i = 0; i < nodes.size(); ++i)
  29896. {
  29897. Node* const node = nodes.getUnchecked(i);
  29898. node->prepare (getSampleRate(), getBlockSize(), this);
  29899. int j = 0;
  29900. for (; j < orderedNodes.size(); ++j)
  29901. if (isAnInputTo (node->id,
  29902. ((Node*) orderedNodes.getUnchecked (j))->id,
  29903. nodes.size() + 1))
  29904. break;
  29905. orderedNodes.insert (j, node);
  29906. }
  29907. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29908. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29909. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29910. }
  29911. Array<void*> oldRenderingOps (renderingOps);
  29912. {
  29913. // swap over to the new rendering sequence..
  29914. const ScopedLock sl (renderLock);
  29915. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29916. renderingBuffers.clear();
  29917. for (int i = midiBuffers.size(); --i >= 0;)
  29918. midiBuffers.getUnchecked(i)->clear();
  29919. while (midiBuffers.size() < numMidiBuffersNeeded)
  29920. midiBuffers.add (new MidiBuffer());
  29921. renderingOps = newRenderingOps;
  29922. }
  29923. for (int i = oldRenderingOps.size(); --i >= 0;)
  29924. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29925. }
  29926. void AudioProcessorGraph::handleAsyncUpdate()
  29927. {
  29928. buildRenderingSequence();
  29929. }
  29930. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29931. {
  29932. currentAudioInputBuffer = 0;
  29933. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29934. currentMidiInputBuffer = 0;
  29935. currentMidiOutputBuffer.clear();
  29936. clearRenderingSequence();
  29937. buildRenderingSequence();
  29938. }
  29939. void AudioProcessorGraph::releaseResources()
  29940. {
  29941. for (int i = 0; i < nodes.size(); ++i)
  29942. nodes.getUnchecked(i)->unprepare();
  29943. renderingBuffers.setSize (1, 1);
  29944. midiBuffers.clear();
  29945. currentAudioInputBuffer = 0;
  29946. currentAudioOutputBuffer.setSize (1, 1);
  29947. currentMidiInputBuffer = 0;
  29948. currentMidiOutputBuffer.clear();
  29949. }
  29950. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29951. {
  29952. const int numSamples = buffer.getNumSamples();
  29953. const ScopedLock sl (renderLock);
  29954. currentAudioInputBuffer = &buffer;
  29955. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29956. currentAudioOutputBuffer.clear();
  29957. currentMidiInputBuffer = &midiMessages;
  29958. currentMidiOutputBuffer.clear();
  29959. int i;
  29960. for (i = 0; i < renderingOps.size(); ++i)
  29961. {
  29962. GraphRenderingOps::AudioGraphRenderingOp* const op
  29963. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29964. op->perform (renderingBuffers, midiBuffers, numSamples);
  29965. }
  29966. for (i = 0; i < buffer.getNumChannels(); ++i)
  29967. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29968. midiMessages.clear();
  29969. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29970. }
  29971. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29972. {
  29973. return "Input " + String (channelIndex + 1);
  29974. }
  29975. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29976. {
  29977. return "Output " + String (channelIndex + 1);
  29978. }
  29979. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29980. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29981. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29982. bool AudioProcessorGraph::producesMidi() const { return true; }
  29983. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29984. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29985. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29986. : type (type_),
  29987. graph (0)
  29988. {
  29989. }
  29990. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29991. {
  29992. }
  29993. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29994. {
  29995. switch (type)
  29996. {
  29997. case audioOutputNode: return "Audio Output";
  29998. case audioInputNode: return "Audio Input";
  29999. case midiOutputNode: return "Midi Output";
  30000. case midiInputNode: return "Midi Input";
  30001. default: break;
  30002. }
  30003. return String::empty;
  30004. }
  30005. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  30006. {
  30007. d.name = getName();
  30008. d.uid = d.name.hashCode();
  30009. d.category = "I/O devices";
  30010. d.pluginFormatName = "Internal";
  30011. d.manufacturerName = "Raw Material Software";
  30012. d.version = "1.0";
  30013. d.isInstrument = false;
  30014. d.numInputChannels = getNumInputChannels();
  30015. if (type == audioOutputNode && graph != 0)
  30016. d.numInputChannels = graph->getNumInputChannels();
  30017. d.numOutputChannels = getNumOutputChannels();
  30018. if (type == audioInputNode && graph != 0)
  30019. d.numOutputChannels = graph->getNumOutputChannels();
  30020. }
  30021. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  30022. {
  30023. jassert (graph != 0);
  30024. }
  30025. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  30026. {
  30027. }
  30028. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  30029. MidiBuffer& midiMessages)
  30030. {
  30031. jassert (graph != 0);
  30032. switch (type)
  30033. {
  30034. case audioOutputNode:
  30035. {
  30036. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  30037. buffer.getNumChannels()); --i >= 0;)
  30038. {
  30039. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  30040. }
  30041. break;
  30042. }
  30043. case audioInputNode:
  30044. {
  30045. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  30046. buffer.getNumChannels()); --i >= 0;)
  30047. {
  30048. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  30049. }
  30050. break;
  30051. }
  30052. case midiOutputNode:
  30053. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30054. break;
  30055. case midiInputNode:
  30056. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30057. break;
  30058. default:
  30059. break;
  30060. }
  30061. }
  30062. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30063. {
  30064. return type == midiOutputNode;
  30065. }
  30066. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30067. {
  30068. return type == midiInputNode;
  30069. }
  30070. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30071. {
  30072. switch (type)
  30073. {
  30074. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30075. case midiOutputNode: return "Midi Output";
  30076. default: break;
  30077. }
  30078. return String::empty;
  30079. }
  30080. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30081. {
  30082. switch (type)
  30083. {
  30084. case audioInputNode: return "Input " + String (channelIndex + 1);
  30085. case midiInputNode: return "Midi Input";
  30086. default: break;
  30087. }
  30088. return String::empty;
  30089. }
  30090. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30091. {
  30092. return type == audioInputNode || type == audioOutputNode;
  30093. }
  30094. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30095. {
  30096. return isInputChannelStereoPair (index);
  30097. }
  30098. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30099. {
  30100. return type == audioInputNode || type == midiInputNode;
  30101. }
  30102. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30103. {
  30104. return type == audioOutputNode || type == midiOutputNode;
  30105. }
  30106. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30107. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30108. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30109. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30110. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30111. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30112. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30113. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30114. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30115. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30116. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30117. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30118. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30119. {
  30120. }
  30121. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30122. {
  30123. }
  30124. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30125. {
  30126. graph = newGraph;
  30127. if (graph != 0)
  30128. {
  30129. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30130. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30131. getSampleRate(),
  30132. getBlockSize());
  30133. updateHostDisplay();
  30134. }
  30135. }
  30136. END_JUCE_NAMESPACE
  30137. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30138. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30139. BEGIN_JUCE_NAMESPACE
  30140. AudioProcessorPlayer::AudioProcessorPlayer()
  30141. : processor (0),
  30142. sampleRate (0),
  30143. blockSize (0),
  30144. isPrepared (false),
  30145. numInputChans (0),
  30146. numOutputChans (0),
  30147. tempBuffer (1, 1)
  30148. {
  30149. }
  30150. AudioProcessorPlayer::~AudioProcessorPlayer()
  30151. {
  30152. setProcessor (0);
  30153. }
  30154. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30155. {
  30156. if (processor != processorToPlay)
  30157. {
  30158. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30159. {
  30160. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30161. sampleRate, blockSize);
  30162. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30163. }
  30164. AudioProcessor* oldOne;
  30165. {
  30166. const ScopedLock sl (lock);
  30167. oldOne = isPrepared ? processor : 0;
  30168. processor = processorToPlay;
  30169. isPrepared = true;
  30170. }
  30171. if (oldOne != 0)
  30172. oldOne->releaseResources();
  30173. }
  30174. }
  30175. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30176. const int numInputChannels,
  30177. float** const outputChannelData,
  30178. const int numOutputChannels,
  30179. const int numSamples)
  30180. {
  30181. // these should have been prepared by audioDeviceAboutToStart()...
  30182. jassert (sampleRate > 0 && blockSize > 0);
  30183. incomingMidi.clear();
  30184. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30185. int i, totalNumChans = 0;
  30186. if (numInputChannels > numOutputChannels)
  30187. {
  30188. // if there aren't enough output channels for the number of
  30189. // inputs, we need to create some temporary extra ones (can't
  30190. // use the input data in case it gets written to)
  30191. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30192. false, false, true);
  30193. for (i = 0; i < numOutputChannels; ++i)
  30194. {
  30195. channels[totalNumChans] = outputChannelData[i];
  30196. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30197. ++totalNumChans;
  30198. }
  30199. for (i = numOutputChannels; i < numInputChannels; ++i)
  30200. {
  30201. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30202. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30203. ++totalNumChans;
  30204. }
  30205. }
  30206. else
  30207. {
  30208. for (i = 0; i < numInputChannels; ++i)
  30209. {
  30210. channels[totalNumChans] = outputChannelData[i];
  30211. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30212. ++totalNumChans;
  30213. }
  30214. for (i = numInputChannels; i < numOutputChannels; ++i)
  30215. {
  30216. channels[totalNumChans] = outputChannelData[i];
  30217. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30218. ++totalNumChans;
  30219. }
  30220. }
  30221. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30222. const ScopedLock sl (lock);
  30223. if (processor != 0)
  30224. {
  30225. const ScopedLock sl (processor->getCallbackLock());
  30226. if (processor->isSuspended())
  30227. {
  30228. for (i = 0; i < numOutputChannels; ++i)
  30229. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30230. }
  30231. else
  30232. {
  30233. processor->processBlock (buffer, incomingMidi);
  30234. }
  30235. }
  30236. }
  30237. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30238. {
  30239. const ScopedLock sl (lock);
  30240. sampleRate = device->getCurrentSampleRate();
  30241. blockSize = device->getCurrentBufferSizeSamples();
  30242. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30243. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30244. messageCollector.reset (sampleRate);
  30245. zeromem (channels, sizeof (channels));
  30246. if (processor != 0)
  30247. {
  30248. if (isPrepared)
  30249. processor->releaseResources();
  30250. AudioProcessor* const oldProcessor = processor;
  30251. setProcessor (0);
  30252. setProcessor (oldProcessor);
  30253. }
  30254. }
  30255. void AudioProcessorPlayer::audioDeviceStopped()
  30256. {
  30257. const ScopedLock sl (lock);
  30258. if (processor != 0 && isPrepared)
  30259. processor->releaseResources();
  30260. sampleRate = 0.0;
  30261. blockSize = 0;
  30262. isPrepared = false;
  30263. tempBuffer.setSize (1, 1);
  30264. }
  30265. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30266. {
  30267. messageCollector.addMessageToQueue (message);
  30268. }
  30269. END_JUCE_NAMESPACE
  30270. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30271. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30272. BEGIN_JUCE_NAMESPACE
  30273. class ProcessorParameterPropertyComp : public PropertyComponent,
  30274. public AudioProcessorListener,
  30275. public Timer
  30276. {
  30277. public:
  30278. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30279. : PropertyComponent (name),
  30280. owner (owner_),
  30281. index (index_),
  30282. paramHasChanged (false),
  30283. slider (owner_, index_)
  30284. {
  30285. startTimer (100);
  30286. addAndMakeVisible (&slider);
  30287. owner_.addListener (this);
  30288. }
  30289. ~ProcessorParameterPropertyComp()
  30290. {
  30291. owner.removeListener (this);
  30292. }
  30293. void refresh()
  30294. {
  30295. paramHasChanged = false;
  30296. slider.setValue (owner.getParameter (index), false);
  30297. }
  30298. void audioProcessorChanged (AudioProcessor*) {}
  30299. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30300. {
  30301. if (parameterIndex == index)
  30302. paramHasChanged = true;
  30303. }
  30304. void timerCallback()
  30305. {
  30306. if (paramHasChanged)
  30307. {
  30308. refresh();
  30309. startTimer (1000 / 50);
  30310. }
  30311. else
  30312. {
  30313. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30314. }
  30315. }
  30316. private:
  30317. class ParamSlider : public Slider
  30318. {
  30319. public:
  30320. ParamSlider (AudioProcessor& owner_, const int index_)
  30321. : owner (owner_),
  30322. index (index_)
  30323. {
  30324. setRange (0.0, 1.0, 0.0);
  30325. setSliderStyle (Slider::LinearBar);
  30326. setTextBoxIsEditable (false);
  30327. setScrollWheelEnabled (false);
  30328. }
  30329. void valueChanged()
  30330. {
  30331. const float newVal = (float) getValue();
  30332. if (owner.getParameter (index) != newVal)
  30333. owner.setParameter (index, newVal);
  30334. }
  30335. const String getTextFromValue (double /*value*/)
  30336. {
  30337. return owner.getParameterText (index);
  30338. }
  30339. private:
  30340. AudioProcessor& owner;
  30341. const int index;
  30342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30343. };
  30344. AudioProcessor& owner;
  30345. const int index;
  30346. bool volatile paramHasChanged;
  30347. ParamSlider slider;
  30348. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30349. };
  30350. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30351. : AudioProcessorEditor (owner_)
  30352. {
  30353. jassert (owner_ != 0);
  30354. setOpaque (true);
  30355. addAndMakeVisible (&panel);
  30356. Array <PropertyComponent*> params;
  30357. const int numParams = owner_->getNumParameters();
  30358. int totalHeight = 0;
  30359. for (int i = 0; i < numParams; ++i)
  30360. {
  30361. String name (owner_->getParameterName (i));
  30362. if (name.trim().isEmpty())
  30363. name = "Unnamed";
  30364. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30365. params.add (pc);
  30366. totalHeight += pc->getPreferredHeight();
  30367. }
  30368. panel.addProperties (params);
  30369. setSize (400, jlimit (25, 400, totalHeight));
  30370. }
  30371. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30372. {
  30373. }
  30374. void GenericAudioProcessorEditor::paint (Graphics& g)
  30375. {
  30376. g.fillAll (Colours::white);
  30377. }
  30378. void GenericAudioProcessorEditor::resized()
  30379. {
  30380. panel.setBounds (getLocalBounds());
  30381. }
  30382. END_JUCE_NAMESPACE
  30383. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30384. /*** Start of inlined file: juce_Sampler.cpp ***/
  30385. BEGIN_JUCE_NAMESPACE
  30386. SamplerSound::SamplerSound (const String& name_,
  30387. AudioFormatReader& source,
  30388. const BigInteger& midiNotes_,
  30389. const int midiNoteForNormalPitch,
  30390. const double attackTimeSecs,
  30391. const double releaseTimeSecs,
  30392. const double maxSampleLengthSeconds)
  30393. : name (name_),
  30394. midiNotes (midiNotes_),
  30395. midiRootNote (midiNoteForNormalPitch)
  30396. {
  30397. sourceSampleRate = source.sampleRate;
  30398. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30399. {
  30400. length = 0;
  30401. attackSamples = 0;
  30402. releaseSamples = 0;
  30403. }
  30404. else
  30405. {
  30406. length = jmin ((int) source.lengthInSamples,
  30407. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30408. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30409. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30410. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30411. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30412. }
  30413. }
  30414. SamplerSound::~SamplerSound()
  30415. {
  30416. }
  30417. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30418. {
  30419. return midiNotes [midiNoteNumber];
  30420. }
  30421. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30422. {
  30423. return true;
  30424. }
  30425. SamplerVoice::SamplerVoice()
  30426. : pitchRatio (0.0),
  30427. sourceSamplePosition (0.0),
  30428. lgain (0.0f),
  30429. rgain (0.0f),
  30430. isInAttack (false),
  30431. isInRelease (false)
  30432. {
  30433. }
  30434. SamplerVoice::~SamplerVoice()
  30435. {
  30436. }
  30437. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30438. {
  30439. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30440. }
  30441. void SamplerVoice::startNote (const int midiNoteNumber,
  30442. const float velocity,
  30443. SynthesiserSound* s,
  30444. const int /*currentPitchWheelPosition*/)
  30445. {
  30446. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30447. jassert (sound != 0); // this object can only play SamplerSounds!
  30448. if (sound != 0)
  30449. {
  30450. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30451. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30452. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30453. sourceSamplePosition = 0.0;
  30454. lgain = velocity;
  30455. rgain = velocity;
  30456. isInAttack = (sound->attackSamples > 0);
  30457. isInRelease = false;
  30458. if (isInAttack)
  30459. {
  30460. attackReleaseLevel = 0.0f;
  30461. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30462. }
  30463. else
  30464. {
  30465. attackReleaseLevel = 1.0f;
  30466. attackDelta = 0.0f;
  30467. }
  30468. if (sound->releaseSamples > 0)
  30469. {
  30470. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30471. }
  30472. else
  30473. {
  30474. releaseDelta = 0.0f;
  30475. }
  30476. }
  30477. }
  30478. void SamplerVoice::stopNote (const bool allowTailOff)
  30479. {
  30480. if (allowTailOff)
  30481. {
  30482. isInAttack = false;
  30483. isInRelease = true;
  30484. }
  30485. else
  30486. {
  30487. clearCurrentNote();
  30488. }
  30489. }
  30490. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30491. {
  30492. }
  30493. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30494. const int /*newValue*/)
  30495. {
  30496. }
  30497. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30498. {
  30499. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30500. if (playingSound != 0)
  30501. {
  30502. const float* const inL = playingSound->data->getSampleData (0, 0);
  30503. const float* const inR = playingSound->data->getNumChannels() > 1
  30504. ? playingSound->data->getSampleData (1, 0) : 0;
  30505. float* outL = outputBuffer.getSampleData (0, startSample);
  30506. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30507. while (--numSamples >= 0)
  30508. {
  30509. const int pos = (int) sourceSamplePosition;
  30510. const float alpha = (float) (sourceSamplePosition - pos);
  30511. const float invAlpha = 1.0f - alpha;
  30512. // just using a very simple linear interpolation here..
  30513. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30514. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30515. : l;
  30516. l *= lgain;
  30517. r *= rgain;
  30518. if (isInAttack)
  30519. {
  30520. l *= attackReleaseLevel;
  30521. r *= attackReleaseLevel;
  30522. attackReleaseLevel += attackDelta;
  30523. if (attackReleaseLevel >= 1.0f)
  30524. {
  30525. attackReleaseLevel = 1.0f;
  30526. isInAttack = false;
  30527. }
  30528. }
  30529. else if (isInRelease)
  30530. {
  30531. l *= attackReleaseLevel;
  30532. r *= attackReleaseLevel;
  30533. attackReleaseLevel += releaseDelta;
  30534. if (attackReleaseLevel <= 0.0f)
  30535. {
  30536. stopNote (false);
  30537. break;
  30538. }
  30539. }
  30540. if (outR != 0)
  30541. {
  30542. *outL++ += l;
  30543. *outR++ += r;
  30544. }
  30545. else
  30546. {
  30547. *outL++ += (l + r) * 0.5f;
  30548. }
  30549. sourceSamplePosition += pitchRatio;
  30550. if (sourceSamplePosition > playingSound->length)
  30551. {
  30552. stopNote (false);
  30553. break;
  30554. }
  30555. }
  30556. }
  30557. }
  30558. END_JUCE_NAMESPACE
  30559. /*** End of inlined file: juce_Sampler.cpp ***/
  30560. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30561. BEGIN_JUCE_NAMESPACE
  30562. SynthesiserSound::SynthesiserSound()
  30563. {
  30564. }
  30565. SynthesiserSound::~SynthesiserSound()
  30566. {
  30567. }
  30568. SynthesiserVoice::SynthesiserVoice()
  30569. : currentSampleRate (44100.0),
  30570. currentlyPlayingNote (-1),
  30571. noteOnTime (0),
  30572. currentlyPlayingSound (0)
  30573. {
  30574. }
  30575. SynthesiserVoice::~SynthesiserVoice()
  30576. {
  30577. }
  30578. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30579. {
  30580. return currentlyPlayingSound != 0
  30581. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30582. }
  30583. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30584. {
  30585. currentSampleRate = newRate;
  30586. }
  30587. void SynthesiserVoice::clearCurrentNote()
  30588. {
  30589. currentlyPlayingNote = -1;
  30590. currentlyPlayingSound = 0;
  30591. }
  30592. Synthesiser::Synthesiser()
  30593. : sampleRate (0),
  30594. lastNoteOnCounter (0),
  30595. shouldStealNotes (true)
  30596. {
  30597. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30598. lastPitchWheelValues[i] = 0x2000;
  30599. }
  30600. Synthesiser::~Synthesiser()
  30601. {
  30602. }
  30603. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30604. {
  30605. const ScopedLock sl (lock);
  30606. return voices [index];
  30607. }
  30608. void Synthesiser::clearVoices()
  30609. {
  30610. const ScopedLock sl (lock);
  30611. voices.clear();
  30612. }
  30613. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30614. {
  30615. const ScopedLock sl (lock);
  30616. voices.add (newVoice);
  30617. }
  30618. void Synthesiser::removeVoice (const int index)
  30619. {
  30620. const ScopedLock sl (lock);
  30621. voices.remove (index);
  30622. }
  30623. void Synthesiser::clearSounds()
  30624. {
  30625. const ScopedLock sl (lock);
  30626. sounds.clear();
  30627. }
  30628. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30629. {
  30630. const ScopedLock sl (lock);
  30631. sounds.add (newSound);
  30632. }
  30633. void Synthesiser::removeSound (const int index)
  30634. {
  30635. const ScopedLock sl (lock);
  30636. sounds.remove (index);
  30637. }
  30638. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30639. {
  30640. shouldStealNotes = shouldStealNotes_;
  30641. }
  30642. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30643. {
  30644. if (sampleRate != newRate)
  30645. {
  30646. const ScopedLock sl (lock);
  30647. allNotesOff (0, false);
  30648. sampleRate = newRate;
  30649. for (int i = voices.size(); --i >= 0;)
  30650. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30651. }
  30652. }
  30653. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30654. const MidiBuffer& midiData,
  30655. int startSample,
  30656. int numSamples)
  30657. {
  30658. // must set the sample rate before using this!
  30659. jassert (sampleRate != 0);
  30660. const ScopedLock sl (lock);
  30661. MidiBuffer::Iterator midiIterator (midiData);
  30662. midiIterator.setNextSamplePosition (startSample);
  30663. MidiMessage m (0xf4, 0.0);
  30664. while (numSamples > 0)
  30665. {
  30666. int midiEventPos;
  30667. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30668. && midiEventPos < startSample + numSamples;
  30669. const int numThisTime = useEvent ? midiEventPos - startSample
  30670. : numSamples;
  30671. if (numThisTime > 0)
  30672. {
  30673. for (int i = voices.size(); --i >= 0;)
  30674. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30675. }
  30676. if (useEvent)
  30677. {
  30678. if (m.isNoteOn())
  30679. {
  30680. const int channel = m.getChannel();
  30681. noteOn (channel,
  30682. m.getNoteNumber(),
  30683. m.getFloatVelocity());
  30684. }
  30685. else if (m.isNoteOff())
  30686. {
  30687. noteOff (m.getChannel(),
  30688. m.getNoteNumber(),
  30689. true);
  30690. }
  30691. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30692. {
  30693. allNotesOff (m.getChannel(), true);
  30694. }
  30695. else if (m.isPitchWheel())
  30696. {
  30697. const int channel = m.getChannel();
  30698. const int wheelPos = m.getPitchWheelValue();
  30699. lastPitchWheelValues [channel - 1] = wheelPos;
  30700. handlePitchWheel (channel, wheelPos);
  30701. }
  30702. else if (m.isController())
  30703. {
  30704. handleController (m.getChannel(),
  30705. m.getControllerNumber(),
  30706. m.getControllerValue());
  30707. }
  30708. }
  30709. startSample += numThisTime;
  30710. numSamples -= numThisTime;
  30711. }
  30712. }
  30713. void Synthesiser::noteOn (const int midiChannel,
  30714. const int midiNoteNumber,
  30715. const float velocity)
  30716. {
  30717. const ScopedLock sl (lock);
  30718. for (int i = sounds.size(); --i >= 0;)
  30719. {
  30720. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30721. if (sound->appliesToNote (midiNoteNumber)
  30722. && sound->appliesToChannel (midiChannel))
  30723. {
  30724. startVoice (findFreeVoice (sound, shouldStealNotes),
  30725. sound, midiChannel, midiNoteNumber, velocity);
  30726. }
  30727. }
  30728. }
  30729. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30730. SynthesiserSound* const sound,
  30731. const int midiChannel,
  30732. const int midiNoteNumber,
  30733. const float velocity)
  30734. {
  30735. if (voice != 0 && sound != 0)
  30736. {
  30737. if (voice->currentlyPlayingSound != 0)
  30738. voice->stopNote (false);
  30739. voice->startNote (midiNoteNumber,
  30740. velocity,
  30741. sound,
  30742. lastPitchWheelValues [midiChannel - 1]);
  30743. voice->currentlyPlayingNote = midiNoteNumber;
  30744. voice->noteOnTime = ++lastNoteOnCounter;
  30745. voice->currentlyPlayingSound = sound;
  30746. }
  30747. }
  30748. void Synthesiser::noteOff (const int midiChannel,
  30749. const int midiNoteNumber,
  30750. const bool allowTailOff)
  30751. {
  30752. const ScopedLock sl (lock);
  30753. for (int i = voices.size(); --i >= 0;)
  30754. {
  30755. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30756. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30757. {
  30758. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30759. if (sound != 0
  30760. && sound->appliesToNote (midiNoteNumber)
  30761. && sound->appliesToChannel (midiChannel))
  30762. {
  30763. voice->stopNote (allowTailOff);
  30764. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30765. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30766. }
  30767. }
  30768. }
  30769. }
  30770. void Synthesiser::allNotesOff (const int midiChannel,
  30771. const bool allowTailOff)
  30772. {
  30773. const ScopedLock sl (lock);
  30774. for (int i = voices.size(); --i >= 0;)
  30775. {
  30776. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30777. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30778. voice->stopNote (allowTailOff);
  30779. }
  30780. }
  30781. void Synthesiser::handlePitchWheel (const int midiChannel,
  30782. const int wheelValue)
  30783. {
  30784. const ScopedLock sl (lock);
  30785. for (int i = voices.size(); --i >= 0;)
  30786. {
  30787. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30788. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30789. {
  30790. voice->pitchWheelMoved (wheelValue);
  30791. }
  30792. }
  30793. }
  30794. void Synthesiser::handleController (const int midiChannel,
  30795. const int controllerNumber,
  30796. const int controllerValue)
  30797. {
  30798. const ScopedLock sl (lock);
  30799. for (int i = voices.size(); --i >= 0;)
  30800. {
  30801. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30802. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30803. voice->controllerMoved (controllerNumber, controllerValue);
  30804. }
  30805. }
  30806. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30807. const bool stealIfNoneAvailable) const
  30808. {
  30809. const ScopedLock sl (lock);
  30810. for (int i = voices.size(); --i >= 0;)
  30811. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30812. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30813. return voices.getUnchecked (i);
  30814. if (stealIfNoneAvailable)
  30815. {
  30816. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30817. SynthesiserVoice* oldest = 0;
  30818. for (int i = voices.size(); --i >= 0;)
  30819. {
  30820. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30821. if (voice->canPlaySound (soundToPlay)
  30822. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30823. oldest = voice;
  30824. }
  30825. jassert (oldest != 0);
  30826. return oldest;
  30827. }
  30828. return 0;
  30829. }
  30830. END_JUCE_NAMESPACE
  30831. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30832. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30833. BEGIN_JUCE_NAMESPACE
  30834. // special message of our own with a string in it
  30835. class ActionMessage : public Message
  30836. {
  30837. public:
  30838. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30839. : message (messageText)
  30840. {
  30841. pointerParameter = listener_;
  30842. }
  30843. const String message;
  30844. private:
  30845. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30846. };
  30847. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30848. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30849. {
  30850. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30851. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30852. if (owner->actionListeners.contains (target))
  30853. target->actionListenerCallback (am.message);
  30854. }
  30855. ActionBroadcaster::ActionBroadcaster()
  30856. {
  30857. // are you trying to create this object before or after juce has been intialised??
  30858. jassert (MessageManager::instance != 0);
  30859. callback.owner = this;
  30860. }
  30861. ActionBroadcaster::~ActionBroadcaster()
  30862. {
  30863. // all event-based objects must be deleted BEFORE juce is shut down!
  30864. jassert (MessageManager::instance != 0);
  30865. }
  30866. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30867. {
  30868. const ScopedLock sl (actionListenerLock);
  30869. if (listener != 0)
  30870. actionListeners.add (listener);
  30871. }
  30872. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30873. {
  30874. const ScopedLock sl (actionListenerLock);
  30875. actionListeners.removeValue (listener);
  30876. }
  30877. void ActionBroadcaster::removeAllActionListeners()
  30878. {
  30879. const ScopedLock sl (actionListenerLock);
  30880. actionListeners.clear();
  30881. }
  30882. void ActionBroadcaster::sendActionMessage (const String& message) const
  30883. {
  30884. const ScopedLock sl (actionListenerLock);
  30885. for (int i = actionListeners.size(); --i >= 0;)
  30886. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30887. }
  30888. END_JUCE_NAMESPACE
  30889. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30890. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30891. BEGIN_JUCE_NAMESPACE
  30892. class AsyncUpdater::AsyncUpdaterMessage : public CallbackMessage
  30893. {
  30894. public:
  30895. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30896. : owner (owner_)
  30897. {
  30898. }
  30899. void messageCallback()
  30900. {
  30901. if (owner.pendingMessage.compareAndSetBool (0, this))
  30902. owner.handleAsyncUpdate();
  30903. }
  30904. AsyncUpdater& owner;
  30905. };
  30906. AsyncUpdater::AsyncUpdater() throw()
  30907. {
  30908. }
  30909. AsyncUpdater::~AsyncUpdater()
  30910. {
  30911. // You're deleting this object with a background thread while there's an update
  30912. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30913. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30914. // deleting this object, or find some other way to avoid such a race condition.
  30915. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30916. pendingMessage = 0;
  30917. }
  30918. void AsyncUpdater::triggerAsyncUpdate()
  30919. {
  30920. if (pendingMessage.value == 0)
  30921. {
  30922. ScopedPointer<AsyncUpdaterMessage> pending (new AsyncUpdaterMessage (*this));
  30923. if (pendingMessage.compareAndSetBool (pending, 0))
  30924. pending.release()->post();
  30925. }
  30926. }
  30927. void AsyncUpdater::cancelPendingUpdate() throw()
  30928. {
  30929. pendingMessage = 0;
  30930. }
  30931. void AsyncUpdater::handleUpdateNowIfNeeded()
  30932. {
  30933. // This can only be called by the event thread.
  30934. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30935. if (pendingMessage.exchange (0) != 0)
  30936. handleAsyncUpdate();
  30937. }
  30938. bool AsyncUpdater::isUpdatePending() const throw()
  30939. {
  30940. return pendingMessage.value != 0;
  30941. }
  30942. END_JUCE_NAMESPACE
  30943. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30944. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30945. BEGIN_JUCE_NAMESPACE
  30946. ChangeBroadcaster::ChangeBroadcaster() throw()
  30947. {
  30948. // are you trying to create this object before or after juce has been intialised??
  30949. jassert (MessageManager::instance != 0);
  30950. callback.owner = this;
  30951. }
  30952. ChangeBroadcaster::~ChangeBroadcaster()
  30953. {
  30954. // all event-based objects must be deleted BEFORE juce is shut down!
  30955. jassert (MessageManager::instance != 0);
  30956. }
  30957. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30958. {
  30959. // Listeners can only be safely added when the event thread is locked
  30960. // You can use a MessageManagerLock if you need to call this from another thread.
  30961. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30962. changeListeners.add (listener);
  30963. }
  30964. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30965. {
  30966. // Listeners can only be safely added when the event thread is locked
  30967. // You can use a MessageManagerLock if you need to call this from another thread.
  30968. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30969. changeListeners.remove (listener);
  30970. }
  30971. void ChangeBroadcaster::removeAllChangeListeners()
  30972. {
  30973. // Listeners can only be safely added when the event thread is locked
  30974. // You can use a MessageManagerLock if you need to call this from another thread.
  30975. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30976. changeListeners.clear();
  30977. }
  30978. void ChangeBroadcaster::sendChangeMessage()
  30979. {
  30980. if (changeListeners.size() > 0)
  30981. callback.triggerAsyncUpdate();
  30982. }
  30983. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30984. {
  30985. // This can only be called by the event thread.
  30986. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30987. callback.cancelPendingUpdate();
  30988. callListeners();
  30989. }
  30990. void ChangeBroadcaster::dispatchPendingMessages()
  30991. {
  30992. callback.handleUpdateNowIfNeeded();
  30993. }
  30994. void ChangeBroadcaster::callListeners()
  30995. {
  30996. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30997. }
  30998. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30999. : owner (0)
  31000. {
  31001. }
  31002. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  31003. {
  31004. jassert (owner != 0);
  31005. owner->callListeners();
  31006. }
  31007. END_JUCE_NAMESPACE
  31008. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  31009. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  31010. BEGIN_JUCE_NAMESPACE
  31011. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  31012. const uint32 magicMessageHeaderNumber)
  31013. : Thread ("Juce IPC connection"),
  31014. callbackConnectionState (false),
  31015. useMessageThread (callbacksOnMessageThread),
  31016. magicMessageHeader (magicMessageHeaderNumber),
  31017. pipeReceiveMessageTimeout (-1)
  31018. {
  31019. }
  31020. InterprocessConnection::~InterprocessConnection()
  31021. {
  31022. callbackConnectionState = false;
  31023. disconnect();
  31024. }
  31025. bool InterprocessConnection::connectToSocket (const String& hostName,
  31026. const int portNumber,
  31027. const int timeOutMillisecs)
  31028. {
  31029. disconnect();
  31030. const ScopedLock sl (pipeAndSocketLock);
  31031. socket = new StreamingSocket();
  31032. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31033. {
  31034. connectionMadeInt();
  31035. startThread();
  31036. return true;
  31037. }
  31038. else
  31039. {
  31040. socket = 0;
  31041. return false;
  31042. }
  31043. }
  31044. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31045. const int pipeReceiveMessageTimeoutMs)
  31046. {
  31047. disconnect();
  31048. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31049. if (newPipe->openExisting (pipeName))
  31050. {
  31051. const ScopedLock sl (pipeAndSocketLock);
  31052. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31053. initialiseWithPipe (newPipe.release());
  31054. return true;
  31055. }
  31056. return false;
  31057. }
  31058. bool InterprocessConnection::createPipe (const String& pipeName,
  31059. const int pipeReceiveMessageTimeoutMs)
  31060. {
  31061. disconnect();
  31062. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31063. if (newPipe->createNewPipe (pipeName))
  31064. {
  31065. const ScopedLock sl (pipeAndSocketLock);
  31066. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31067. initialiseWithPipe (newPipe.release());
  31068. return true;
  31069. }
  31070. return false;
  31071. }
  31072. void InterprocessConnection::disconnect()
  31073. {
  31074. if (socket != 0)
  31075. socket->close();
  31076. if (pipe != 0)
  31077. {
  31078. pipe->cancelPendingReads();
  31079. pipe->close();
  31080. }
  31081. stopThread (4000);
  31082. {
  31083. const ScopedLock sl (pipeAndSocketLock);
  31084. socket = 0;
  31085. pipe = 0;
  31086. }
  31087. connectionLostInt();
  31088. }
  31089. bool InterprocessConnection::isConnected() const
  31090. {
  31091. const ScopedLock sl (pipeAndSocketLock);
  31092. return ((socket != 0 && socket->isConnected())
  31093. || (pipe != 0 && pipe->isOpen()))
  31094. && isThreadRunning();
  31095. }
  31096. const String InterprocessConnection::getConnectedHostName() const
  31097. {
  31098. if (pipe != 0)
  31099. {
  31100. return "localhost";
  31101. }
  31102. else if (socket != 0)
  31103. {
  31104. if (! socket->isLocal())
  31105. return socket->getHostName();
  31106. return "localhost";
  31107. }
  31108. return String::empty;
  31109. }
  31110. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31111. {
  31112. uint32 messageHeader[2];
  31113. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31114. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31115. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31116. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31117. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31118. size_t bytesWritten = 0;
  31119. const ScopedLock sl (pipeAndSocketLock);
  31120. if (socket != 0)
  31121. {
  31122. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31123. }
  31124. else if (pipe != 0)
  31125. {
  31126. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31127. }
  31128. if (bytesWritten < 0)
  31129. {
  31130. // error..
  31131. return false;
  31132. }
  31133. return (bytesWritten == messageData.getSize());
  31134. }
  31135. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31136. {
  31137. jassert (socket == 0);
  31138. socket = socket_;
  31139. connectionMadeInt();
  31140. startThread();
  31141. }
  31142. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31143. {
  31144. jassert (pipe == 0);
  31145. pipe = pipe_;
  31146. connectionMadeInt();
  31147. startThread();
  31148. }
  31149. const int messageMagicNumber = 0xb734128b;
  31150. void InterprocessConnection::handleMessage (const Message& message)
  31151. {
  31152. if (message.intParameter1 == messageMagicNumber)
  31153. {
  31154. switch (message.intParameter2)
  31155. {
  31156. case 0:
  31157. {
  31158. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31159. messageReceived (*data);
  31160. break;
  31161. }
  31162. case 1:
  31163. connectionMade();
  31164. break;
  31165. case 2:
  31166. connectionLost();
  31167. break;
  31168. }
  31169. }
  31170. }
  31171. void InterprocessConnection::connectionMadeInt()
  31172. {
  31173. if (! callbackConnectionState)
  31174. {
  31175. callbackConnectionState = true;
  31176. if (useMessageThread)
  31177. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31178. else
  31179. connectionMade();
  31180. }
  31181. }
  31182. void InterprocessConnection::connectionLostInt()
  31183. {
  31184. if (callbackConnectionState)
  31185. {
  31186. callbackConnectionState = false;
  31187. if (useMessageThread)
  31188. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31189. else
  31190. connectionLost();
  31191. }
  31192. }
  31193. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31194. {
  31195. jassert (callbackConnectionState);
  31196. if (useMessageThread)
  31197. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31198. else
  31199. messageReceived (data);
  31200. }
  31201. bool InterprocessConnection::readNextMessageInt()
  31202. {
  31203. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31204. uint32 messageHeader[2];
  31205. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31206. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31207. if (bytes == sizeof (messageHeader)
  31208. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31209. {
  31210. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31211. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31212. {
  31213. MemoryBlock messageData (bytesInMessage, true);
  31214. int bytesRead = 0;
  31215. while (bytesInMessage > 0)
  31216. {
  31217. if (threadShouldExit())
  31218. return false;
  31219. const int numThisTime = jmin (bytesInMessage, 65536);
  31220. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31221. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31222. if (bytesIn <= 0)
  31223. break;
  31224. bytesRead += bytesIn;
  31225. bytesInMessage -= bytesIn;
  31226. }
  31227. if (bytesRead >= 0)
  31228. deliverDataInt (messageData);
  31229. }
  31230. }
  31231. else if (bytes < 0)
  31232. {
  31233. {
  31234. const ScopedLock sl (pipeAndSocketLock);
  31235. socket = 0;
  31236. }
  31237. connectionLostInt();
  31238. return false;
  31239. }
  31240. return true;
  31241. }
  31242. void InterprocessConnection::run()
  31243. {
  31244. while (! threadShouldExit())
  31245. {
  31246. if (socket != 0)
  31247. {
  31248. const int ready = socket->waitUntilReady (true, 0);
  31249. if (ready < 0)
  31250. {
  31251. {
  31252. const ScopedLock sl (pipeAndSocketLock);
  31253. socket = 0;
  31254. }
  31255. connectionLostInt();
  31256. break;
  31257. }
  31258. else if (ready > 0)
  31259. {
  31260. if (! readNextMessageInt())
  31261. break;
  31262. }
  31263. else
  31264. {
  31265. Thread::sleep (2);
  31266. }
  31267. }
  31268. else if (pipe != 0)
  31269. {
  31270. if (! pipe->isOpen())
  31271. {
  31272. {
  31273. const ScopedLock sl (pipeAndSocketLock);
  31274. pipe = 0;
  31275. }
  31276. connectionLostInt();
  31277. break;
  31278. }
  31279. else
  31280. {
  31281. if (! readNextMessageInt())
  31282. break;
  31283. }
  31284. }
  31285. else
  31286. {
  31287. break;
  31288. }
  31289. }
  31290. }
  31291. END_JUCE_NAMESPACE
  31292. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31293. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31294. BEGIN_JUCE_NAMESPACE
  31295. InterprocessConnectionServer::InterprocessConnectionServer()
  31296. : Thread ("Juce IPC server")
  31297. {
  31298. }
  31299. InterprocessConnectionServer::~InterprocessConnectionServer()
  31300. {
  31301. stop();
  31302. }
  31303. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31304. {
  31305. stop();
  31306. socket = new StreamingSocket();
  31307. if (socket->createListener (portNumber))
  31308. {
  31309. startThread();
  31310. return true;
  31311. }
  31312. socket = 0;
  31313. return false;
  31314. }
  31315. void InterprocessConnectionServer::stop()
  31316. {
  31317. signalThreadShouldExit();
  31318. if (socket != 0)
  31319. socket->close();
  31320. stopThread (4000);
  31321. socket = 0;
  31322. }
  31323. void InterprocessConnectionServer::run()
  31324. {
  31325. while ((! threadShouldExit()) && socket != 0)
  31326. {
  31327. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31328. if (clientSocket != 0)
  31329. {
  31330. InterprocessConnection* newConnection = createConnectionObject();
  31331. if (newConnection != 0)
  31332. newConnection->initialiseWithSocket (clientSocket.release());
  31333. }
  31334. }
  31335. }
  31336. END_JUCE_NAMESPACE
  31337. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31338. /*** Start of inlined file: juce_Message.cpp ***/
  31339. BEGIN_JUCE_NAMESPACE
  31340. Message::Message() throw()
  31341. : intParameter1 (0),
  31342. intParameter2 (0),
  31343. intParameter3 (0),
  31344. pointerParameter (0),
  31345. messageRecipient (0)
  31346. {
  31347. }
  31348. Message::Message (const int intParameter1_,
  31349. const int intParameter2_,
  31350. const int intParameter3_,
  31351. void* const pointerParameter_) throw()
  31352. : intParameter1 (intParameter1_),
  31353. intParameter2 (intParameter2_),
  31354. intParameter3 (intParameter3_),
  31355. pointerParameter (pointerParameter_),
  31356. messageRecipient (0)
  31357. {
  31358. }
  31359. Message::~Message()
  31360. {
  31361. }
  31362. END_JUCE_NAMESPACE
  31363. /*** End of inlined file: juce_Message.cpp ***/
  31364. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31365. BEGIN_JUCE_NAMESPACE
  31366. MessageListener::MessageListener() throw()
  31367. {
  31368. // are you trying to create a messagelistener before or after juce has been intialised??
  31369. jassert (MessageManager::instance != 0);
  31370. if (MessageManager::instance != 0)
  31371. MessageManager::instance->messageListeners.add (this);
  31372. }
  31373. MessageListener::~MessageListener()
  31374. {
  31375. if (MessageManager::instance != 0)
  31376. MessageManager::instance->messageListeners.removeValue (this);
  31377. }
  31378. void MessageListener::postMessage (Message* const message) const throw()
  31379. {
  31380. message->messageRecipient = const_cast <MessageListener*> (this);
  31381. if (MessageManager::instance == 0)
  31382. MessageManager::getInstance();
  31383. MessageManager::instance->postMessageToQueue (message);
  31384. }
  31385. bool MessageListener::isValidMessageListener() const throw()
  31386. {
  31387. return (MessageManager::instance != 0)
  31388. && MessageManager::instance->messageListeners.contains (this);
  31389. }
  31390. END_JUCE_NAMESPACE
  31391. /*** End of inlined file: juce_MessageListener.cpp ***/
  31392. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31393. BEGIN_JUCE_NAMESPACE
  31394. // platform-specific functions..
  31395. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31396. bool juce_postMessageToSystemQueue (Message* message);
  31397. MessageManager* MessageManager::instance = 0;
  31398. static const int quitMessageId = 0xfffff321;
  31399. MessageManager::MessageManager() throw()
  31400. : quitMessagePosted (false),
  31401. quitMessageReceived (false),
  31402. threadWithLock (0)
  31403. {
  31404. messageThreadId = Thread::getCurrentThreadId();
  31405. if (JUCEApplication::isStandaloneApp())
  31406. Thread::setCurrentThreadName ("Juce Message Thread");
  31407. }
  31408. MessageManager::~MessageManager() throw()
  31409. {
  31410. broadcaster = 0;
  31411. doPlatformSpecificShutdown();
  31412. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31413. jassert (messageListeners.size() == 0);
  31414. jassert (instance == this);
  31415. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31416. }
  31417. MessageManager* MessageManager::getInstance() throw()
  31418. {
  31419. if (instance == 0)
  31420. {
  31421. instance = new MessageManager();
  31422. doPlatformSpecificInitialisation();
  31423. }
  31424. return instance;
  31425. }
  31426. void MessageManager::postMessageToQueue (Message* const message)
  31427. {
  31428. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31429. delete message;
  31430. }
  31431. CallbackMessage::CallbackMessage() throw() {}
  31432. CallbackMessage::~CallbackMessage() {}
  31433. void CallbackMessage::post()
  31434. {
  31435. if (MessageManager::instance != 0)
  31436. MessageManager::instance->postMessageToQueue (this);
  31437. }
  31438. // not for public use..
  31439. void MessageManager::deliverMessage (Message* const message)
  31440. {
  31441. JUCE_TRY
  31442. {
  31443. const ScopedPointer <Message> messageDeleter (message);
  31444. MessageListener* const recipient = message->messageRecipient;
  31445. if (recipient == 0)
  31446. {
  31447. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31448. if (callbackMessage != 0)
  31449. {
  31450. callbackMessage->messageCallback();
  31451. }
  31452. else if (message->intParameter1 == quitMessageId)
  31453. {
  31454. quitMessageReceived = true;
  31455. }
  31456. }
  31457. else if (messageListeners.contains (recipient))
  31458. {
  31459. recipient->handleMessage (*message);
  31460. }
  31461. }
  31462. JUCE_CATCH_EXCEPTION
  31463. }
  31464. #if ! (JUCE_MAC || JUCE_IOS)
  31465. void MessageManager::runDispatchLoop()
  31466. {
  31467. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31468. runDispatchLoopUntil (-1);
  31469. }
  31470. void MessageManager::stopDispatchLoop()
  31471. {
  31472. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31473. quitMessagePosted = true;
  31474. }
  31475. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31476. {
  31477. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31478. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31479. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31480. && ! quitMessageReceived)
  31481. {
  31482. JUCE_TRY
  31483. {
  31484. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31485. {
  31486. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31487. if (msToWait > 0)
  31488. Thread::sleep (jmin (5, msToWait));
  31489. }
  31490. }
  31491. JUCE_CATCH_EXCEPTION
  31492. }
  31493. return ! quitMessageReceived;
  31494. }
  31495. #endif
  31496. void MessageManager::deliverBroadcastMessage (const String& value)
  31497. {
  31498. if (broadcaster != 0)
  31499. broadcaster->sendActionMessage (value);
  31500. }
  31501. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31502. {
  31503. if (broadcaster == 0)
  31504. broadcaster = new ActionBroadcaster();
  31505. broadcaster->addActionListener (listener);
  31506. }
  31507. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31508. {
  31509. if (broadcaster != 0)
  31510. broadcaster->removeActionListener (listener);
  31511. }
  31512. bool MessageManager::isThisTheMessageThread() const throw()
  31513. {
  31514. return Thread::getCurrentThreadId() == messageThreadId;
  31515. }
  31516. void MessageManager::setCurrentThreadAsMessageThread()
  31517. {
  31518. if (messageThreadId != Thread::getCurrentThreadId())
  31519. {
  31520. messageThreadId = Thread::getCurrentThreadId();
  31521. // This is needed on windows to make sure the message window is created by this thread
  31522. doPlatformSpecificShutdown();
  31523. doPlatformSpecificInitialisation();
  31524. }
  31525. }
  31526. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31527. {
  31528. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31529. return thisThread == messageThreadId || thisThread == threadWithLock;
  31530. }
  31531. /* The only safe way to lock the message thread while another thread does
  31532. some work is by posting a special message, whose purpose is to tie up the event
  31533. loop until the other thread has finished its business.
  31534. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31535. get locked before making an event callback, because if the same OS lock gets indirectly
  31536. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31537. in Cocoa).
  31538. */
  31539. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31540. {
  31541. public:
  31542. SharedEvents() {}
  31543. /* This class just holds a couple of events to communicate between the BlockingMessage
  31544. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31545. this shared data must be kept in a separate, ref-counted container. */
  31546. WaitableEvent lockedEvent, releaseEvent;
  31547. private:
  31548. JUCE_DECLARE_NON_COPYABLE (SharedEvents);
  31549. };
  31550. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31551. {
  31552. public:
  31553. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31554. void messageCallback()
  31555. {
  31556. events->lockedEvent.signal();
  31557. events->releaseEvent.wait();
  31558. }
  31559. private:
  31560. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31561. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31562. };
  31563. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31564. : sharedEvents (0),
  31565. locked (false)
  31566. {
  31567. init (threadToCheck, 0);
  31568. }
  31569. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31570. : sharedEvents (0),
  31571. locked (false)
  31572. {
  31573. init (0, jobToCheckForExitSignal);
  31574. }
  31575. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31576. {
  31577. if (MessageManager::instance != 0)
  31578. {
  31579. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31580. {
  31581. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31582. }
  31583. else
  31584. {
  31585. if (threadToCheck == 0 && job == 0)
  31586. {
  31587. MessageManager::instance->lockingLock.enter();
  31588. }
  31589. else
  31590. {
  31591. while (! MessageManager::instance->lockingLock.tryEnter())
  31592. {
  31593. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31594. || (job != 0 && job->shouldExit()))
  31595. return;
  31596. Thread::sleep (1);
  31597. }
  31598. }
  31599. sharedEvents = new SharedEvents();
  31600. sharedEvents->incReferenceCount();
  31601. (new BlockingMessage (sharedEvents))->post();
  31602. while (! sharedEvents->lockedEvent.wait (50))
  31603. {
  31604. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31605. || (job != 0 && job->shouldExit()))
  31606. {
  31607. sharedEvents->releaseEvent.signal();
  31608. sharedEvents->decReferenceCount();
  31609. sharedEvents = 0;
  31610. MessageManager::instance->lockingLock.exit();
  31611. return;
  31612. }
  31613. }
  31614. jassert (MessageManager::instance->threadWithLock == 0);
  31615. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31616. locked = true;
  31617. }
  31618. }
  31619. }
  31620. MessageManagerLock::~MessageManagerLock() throw()
  31621. {
  31622. if (sharedEvents != 0)
  31623. {
  31624. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31625. sharedEvents->releaseEvent.signal();
  31626. sharedEvents->decReferenceCount();
  31627. if (MessageManager::instance != 0)
  31628. {
  31629. MessageManager::instance->threadWithLock = 0;
  31630. MessageManager::instance->lockingLock.exit();
  31631. }
  31632. }
  31633. }
  31634. END_JUCE_NAMESPACE
  31635. /*** End of inlined file: juce_MessageManager.cpp ***/
  31636. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31637. BEGIN_JUCE_NAMESPACE
  31638. class MultiTimer::MultiTimerCallback : public Timer
  31639. {
  31640. public:
  31641. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31642. : timerId (timerId_),
  31643. owner (owner_)
  31644. {
  31645. }
  31646. ~MultiTimerCallback()
  31647. {
  31648. }
  31649. void timerCallback()
  31650. {
  31651. owner.timerCallback (timerId);
  31652. }
  31653. const int timerId;
  31654. private:
  31655. MultiTimer& owner;
  31656. };
  31657. MultiTimer::MultiTimer() throw()
  31658. {
  31659. }
  31660. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31661. {
  31662. }
  31663. MultiTimer::~MultiTimer()
  31664. {
  31665. const ScopedLock sl (timerListLock);
  31666. timers.clear();
  31667. }
  31668. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31669. {
  31670. const ScopedLock sl (timerListLock);
  31671. for (int i = timers.size(); --i >= 0;)
  31672. {
  31673. MultiTimerCallback* const t = timers.getUnchecked(i);
  31674. if (t->timerId == timerId)
  31675. {
  31676. t->startTimer (intervalInMilliseconds);
  31677. return;
  31678. }
  31679. }
  31680. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31681. timers.add (newTimer);
  31682. newTimer->startTimer (intervalInMilliseconds);
  31683. }
  31684. void MultiTimer::stopTimer (const int timerId) throw()
  31685. {
  31686. const ScopedLock sl (timerListLock);
  31687. for (int i = timers.size(); --i >= 0;)
  31688. {
  31689. MultiTimerCallback* const t = timers.getUnchecked(i);
  31690. if (t->timerId == timerId)
  31691. t->stopTimer();
  31692. }
  31693. }
  31694. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31695. {
  31696. const ScopedLock sl (timerListLock);
  31697. for (int i = timers.size(); --i >= 0;)
  31698. {
  31699. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31700. if (t->timerId == timerId)
  31701. return t->isTimerRunning();
  31702. }
  31703. return false;
  31704. }
  31705. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31706. {
  31707. const ScopedLock sl (timerListLock);
  31708. for (int i = timers.size(); --i >= 0;)
  31709. {
  31710. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31711. if (t->timerId == timerId)
  31712. return t->getTimerInterval();
  31713. }
  31714. return 0;
  31715. }
  31716. END_JUCE_NAMESPACE
  31717. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31718. /*** Start of inlined file: juce_Timer.cpp ***/
  31719. BEGIN_JUCE_NAMESPACE
  31720. class InternalTimerThread : private Thread,
  31721. private MessageListener,
  31722. private DeletedAtShutdown,
  31723. private AsyncUpdater
  31724. {
  31725. public:
  31726. InternalTimerThread()
  31727. : Thread ("Juce Timer"),
  31728. firstTimer (0),
  31729. callbackNeeded (0)
  31730. {
  31731. triggerAsyncUpdate();
  31732. }
  31733. ~InternalTimerThread() throw()
  31734. {
  31735. stopThread (4000);
  31736. jassert (instance == this || instance == 0);
  31737. if (instance == this)
  31738. instance = 0;
  31739. }
  31740. void run()
  31741. {
  31742. uint32 lastTime = Time::getMillisecondCounter();
  31743. while (! threadShouldExit())
  31744. {
  31745. const uint32 now = Time::getMillisecondCounter();
  31746. if (now <= lastTime)
  31747. {
  31748. wait (2);
  31749. continue;
  31750. }
  31751. const int elapsed = now - lastTime;
  31752. lastTime = now;
  31753. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31754. if (timeUntilFirstTimer <= 0)
  31755. {
  31756. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31757. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31758. but if it fails it means the message-thread changed the value from under us so at least
  31759. some processing is happenening and we can just loop around and try again
  31760. */
  31761. if (callbackNeeded.compareAndSetBool (1, 0))
  31762. {
  31763. postMessage (new Message());
  31764. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31765. when the app has a modal loop), so this is how long to wait before assuming the
  31766. message has been lost and trying again.
  31767. */
  31768. const uint32 messageDeliveryTimeout = now + 2000;
  31769. while (callbackNeeded.get() != 0)
  31770. {
  31771. wait (4);
  31772. if (threadShouldExit())
  31773. return;
  31774. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31775. break;
  31776. }
  31777. }
  31778. }
  31779. else
  31780. {
  31781. // don't wait for too long because running this loop also helps keep the
  31782. // Time::getApproximateMillisecondTimer value stay up-to-date
  31783. wait (jlimit (1, 50, timeUntilFirstTimer));
  31784. }
  31785. }
  31786. }
  31787. void callTimers()
  31788. {
  31789. const ScopedLock sl (lock);
  31790. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31791. {
  31792. Timer* const t = firstTimer;
  31793. t->countdownMs = t->periodMs;
  31794. removeTimer (t);
  31795. addTimer (t);
  31796. const ScopedUnlock ul (lock);
  31797. JUCE_TRY
  31798. {
  31799. t->timerCallback();
  31800. }
  31801. JUCE_CATCH_EXCEPTION
  31802. }
  31803. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31804. before the boolean is set. This set should never fail since if it was false in the first place,
  31805. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31806. get a message then the value is true and the other thread can only set it to true again and
  31807. we will get another callback to set it to false.
  31808. */
  31809. callbackNeeded.set (0);
  31810. }
  31811. void handleMessage (const Message&)
  31812. {
  31813. callTimers();
  31814. }
  31815. void callTimersSynchronously()
  31816. {
  31817. if (! isThreadRunning())
  31818. {
  31819. // (This is relied on by some plugins in cases where the MM has
  31820. // had to restart and the async callback never started)
  31821. cancelPendingUpdate();
  31822. triggerAsyncUpdate();
  31823. }
  31824. callTimers();
  31825. }
  31826. static void callAnyTimersSynchronously()
  31827. {
  31828. if (InternalTimerThread::instance != 0)
  31829. InternalTimerThread::instance->callTimersSynchronously();
  31830. }
  31831. static inline void add (Timer* const tim) throw()
  31832. {
  31833. if (instance == 0)
  31834. instance = new InternalTimerThread();
  31835. const ScopedLock sl (instance->lock);
  31836. instance->addTimer (tim);
  31837. }
  31838. static inline void remove (Timer* const tim) throw()
  31839. {
  31840. if (instance != 0)
  31841. {
  31842. const ScopedLock sl (instance->lock);
  31843. instance->removeTimer (tim);
  31844. }
  31845. }
  31846. static inline void resetCounter (Timer* const tim,
  31847. const int newCounter) throw()
  31848. {
  31849. if (instance != 0)
  31850. {
  31851. tim->countdownMs = newCounter;
  31852. tim->periodMs = newCounter;
  31853. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31854. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31855. {
  31856. const ScopedLock sl (instance->lock);
  31857. instance->removeTimer (tim);
  31858. instance->addTimer (tim);
  31859. }
  31860. }
  31861. }
  31862. private:
  31863. friend class Timer;
  31864. static InternalTimerThread* instance;
  31865. static CriticalSection lock;
  31866. Timer* volatile firstTimer;
  31867. Atomic <int> callbackNeeded;
  31868. void addTimer (Timer* const t) throw()
  31869. {
  31870. #if JUCE_DEBUG
  31871. Timer* tt = firstTimer;
  31872. while (tt != 0)
  31873. {
  31874. // trying to add a timer that's already here - shouldn't get to this point,
  31875. // so if you get this assertion, let me know!
  31876. jassert (tt != t);
  31877. tt = tt->next;
  31878. }
  31879. jassert (t->previous == 0 && t->next == 0);
  31880. #endif
  31881. Timer* i = firstTimer;
  31882. if (i == 0 || i->countdownMs > t->countdownMs)
  31883. {
  31884. t->next = firstTimer;
  31885. firstTimer = t;
  31886. }
  31887. else
  31888. {
  31889. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31890. i = i->next;
  31891. jassert (i != 0);
  31892. t->next = i->next;
  31893. t->previous = i;
  31894. i->next = t;
  31895. }
  31896. if (t->next != 0)
  31897. t->next->previous = t;
  31898. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31899. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31900. notify();
  31901. }
  31902. void removeTimer (Timer* const t) throw()
  31903. {
  31904. #if JUCE_DEBUG
  31905. Timer* tt = firstTimer;
  31906. bool found = false;
  31907. while (tt != 0)
  31908. {
  31909. if (tt == t)
  31910. {
  31911. found = true;
  31912. break;
  31913. }
  31914. tt = tt->next;
  31915. }
  31916. // trying to remove a timer that's not here - shouldn't get to this point,
  31917. // so if you get this assertion, let me know!
  31918. jassert (found);
  31919. #endif
  31920. if (t->previous != 0)
  31921. {
  31922. jassert (firstTimer != t);
  31923. t->previous->next = t->next;
  31924. }
  31925. else
  31926. {
  31927. jassert (firstTimer == t);
  31928. firstTimer = t->next;
  31929. }
  31930. if (t->next != 0)
  31931. t->next->previous = t->previous;
  31932. t->next = 0;
  31933. t->previous = 0;
  31934. }
  31935. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31936. {
  31937. const ScopedLock sl (lock);
  31938. for (Timer* t = firstTimer; t != 0; t = t->next)
  31939. t->countdownMs -= numMillisecsElapsed;
  31940. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31941. }
  31942. void handleAsyncUpdate()
  31943. {
  31944. startThread (7);
  31945. }
  31946. JUCE_DECLARE_NON_COPYABLE (InternalTimerThread);
  31947. };
  31948. InternalTimerThread* InternalTimerThread::instance = 0;
  31949. CriticalSection InternalTimerThread::lock;
  31950. void juce_callAnyTimersSynchronously()
  31951. {
  31952. InternalTimerThread::callAnyTimersSynchronously();
  31953. }
  31954. #if JUCE_DEBUG
  31955. static SortedSet <Timer*> activeTimers;
  31956. #endif
  31957. Timer::Timer() throw()
  31958. : countdownMs (0),
  31959. periodMs (0),
  31960. previous (0),
  31961. next (0)
  31962. {
  31963. #if JUCE_DEBUG
  31964. activeTimers.add (this);
  31965. #endif
  31966. }
  31967. Timer::Timer (const Timer&) throw()
  31968. : countdownMs (0),
  31969. periodMs (0),
  31970. previous (0),
  31971. next (0)
  31972. {
  31973. #if JUCE_DEBUG
  31974. activeTimers.add (this);
  31975. #endif
  31976. }
  31977. Timer::~Timer()
  31978. {
  31979. stopTimer();
  31980. #if JUCE_DEBUG
  31981. activeTimers.removeValue (this);
  31982. #endif
  31983. }
  31984. void Timer::startTimer (const int interval) throw()
  31985. {
  31986. const ScopedLock sl (InternalTimerThread::lock);
  31987. #if JUCE_DEBUG
  31988. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31989. jassert (activeTimers.contains (this));
  31990. #endif
  31991. if (periodMs == 0)
  31992. {
  31993. countdownMs = interval;
  31994. periodMs = jmax (1, interval);
  31995. InternalTimerThread::add (this);
  31996. }
  31997. else
  31998. {
  31999. InternalTimerThread::resetCounter (this, interval);
  32000. }
  32001. }
  32002. void Timer::stopTimer() throw()
  32003. {
  32004. const ScopedLock sl (InternalTimerThread::lock);
  32005. #if JUCE_DEBUG
  32006. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32007. jassert (activeTimers.contains (this));
  32008. #endif
  32009. if (periodMs > 0)
  32010. {
  32011. InternalTimerThread::remove (this);
  32012. periodMs = 0;
  32013. }
  32014. }
  32015. END_JUCE_NAMESPACE
  32016. /*** End of inlined file: juce_Timer.cpp ***/
  32017. #endif
  32018. #if JUCE_BUILD_GUI
  32019. /*** Start of inlined file: juce_Component.cpp ***/
  32020. BEGIN_JUCE_NAMESPACE
  32021. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32022. Component* Component::currentlyFocusedComponent = 0;
  32023. class Component::MouseListenerList
  32024. {
  32025. public:
  32026. MouseListenerList()
  32027. : numDeepMouseListeners (0)
  32028. {
  32029. }
  32030. ~MouseListenerList()
  32031. {
  32032. }
  32033. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  32034. {
  32035. if (! listeners.contains (newListener))
  32036. {
  32037. if (wantsEventsForAllNestedChildComponents)
  32038. {
  32039. listeners.insert (0, newListener);
  32040. ++numDeepMouseListeners;
  32041. }
  32042. else
  32043. {
  32044. listeners.add (newListener);
  32045. }
  32046. }
  32047. }
  32048. void removeListener (MouseListener* const listenerToRemove)
  32049. {
  32050. const int index = listeners.indexOf (listenerToRemove);
  32051. if (index >= 0)
  32052. {
  32053. if (index < numDeepMouseListeners)
  32054. --numDeepMouseListeners;
  32055. listeners.remove (index);
  32056. }
  32057. }
  32058. static void sendMouseEvent (Component* comp, BailOutChecker& checker,
  32059. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  32060. {
  32061. if (checker.shouldBailOut())
  32062. return;
  32063. {
  32064. MouseListenerList* const list = comp->mouseListeners_;
  32065. if (list != 0)
  32066. {
  32067. for (int i = list->listeners.size(); --i >= 0;)
  32068. {
  32069. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32070. if (checker.shouldBailOut())
  32071. return;
  32072. i = jmin (i, list->listeners.size());
  32073. }
  32074. }
  32075. }
  32076. Component* p = comp->parentComponent_;
  32077. while (p != 0)
  32078. {
  32079. MouseListenerList* const list = p->mouseListeners_;
  32080. if (list != 0 && list->numDeepMouseListeners > 0)
  32081. {
  32082. BailOutChecker checker2 (comp, p);
  32083. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32084. {
  32085. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32086. if (checker2.shouldBailOut())
  32087. return;
  32088. i = jmin (i, list->numDeepMouseListeners);
  32089. }
  32090. }
  32091. p = p->parentComponent_;
  32092. }
  32093. }
  32094. static void sendWheelEvent (Component* comp, BailOutChecker& checker, const MouseEvent& e,
  32095. const float wheelIncrementX, const float wheelIncrementY)
  32096. {
  32097. if (checker.shouldBailOut())
  32098. return;
  32099. {
  32100. MouseListenerList* const list = comp->mouseListeners_;
  32101. if (list != 0)
  32102. {
  32103. for (int i = list->listeners.size(); --i >= 0;)
  32104. {
  32105. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32106. if (checker.shouldBailOut())
  32107. return;
  32108. i = jmin (i, list->listeners.size());
  32109. }
  32110. }
  32111. }
  32112. Component* p = comp->parentComponent_;
  32113. while (p != 0)
  32114. {
  32115. MouseListenerList* const list = p->mouseListeners_;
  32116. if (list != 0 && list->numDeepMouseListeners > 0)
  32117. {
  32118. BailOutChecker checker2 (comp, p);
  32119. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32120. {
  32121. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32122. if (checker2.shouldBailOut())
  32123. return;
  32124. i = jmin (i, list->numDeepMouseListeners);
  32125. }
  32126. }
  32127. p = p->parentComponent_;
  32128. }
  32129. }
  32130. private:
  32131. Array <MouseListener*> listeners;
  32132. int numDeepMouseListeners;
  32133. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  32134. };
  32135. class Component::ComponentHelpers
  32136. {
  32137. public:
  32138. static void* runModalLoopCallback (void* userData)
  32139. {
  32140. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32141. }
  32142. static const Identifier getColourPropertyId (const int colourId)
  32143. {
  32144. String s;
  32145. s.preallocateStorage (18);
  32146. s << "jcclr_" << String::toHexString (colourId);
  32147. return s;
  32148. }
  32149. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  32150. {
  32151. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  32152. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  32153. && comp.hitTest (localPoint.getX(), localPoint.getY());
  32154. }
  32155. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  32156. {
  32157. if (comp.affineTransform_ == 0)
  32158. return pointInParentSpace - comp.getPosition();
  32159. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform_->inverted()).toInt() - comp.getPosition();
  32160. }
  32161. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  32162. {
  32163. if (comp.affineTransform_ == 0)
  32164. return areaInParentSpace - comp.getPosition();
  32165. return areaInParentSpace.toFloat().transformed (comp.affineTransform_->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  32166. }
  32167. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  32168. {
  32169. if (comp.affineTransform_ == 0)
  32170. return pointInLocalSpace + comp.getPosition();
  32171. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform_).toInt();
  32172. }
  32173. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  32174. {
  32175. if (comp.affineTransform_ == 0)
  32176. return areaInLocalSpace + comp.getPosition();
  32177. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform_).getSmallestIntegerContainer();
  32178. }
  32179. template <typename Type>
  32180. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  32181. {
  32182. const Component* const directParent = target.getParentComponent();
  32183. jassert (directParent != 0);
  32184. if (directParent == parent)
  32185. return convertFromParentSpace (target, coordInParent);
  32186. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  32187. }
  32188. template <typename Type>
  32189. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  32190. {
  32191. while (source != 0)
  32192. {
  32193. if (source == target)
  32194. return p;
  32195. if (source->isParentOf (target))
  32196. return convertFromDistantParentSpace (source, *target, p);
  32197. if (source->isOnDesktop())
  32198. {
  32199. p = source->getPeer()->localToGlobal (p);
  32200. source = 0;
  32201. }
  32202. else
  32203. {
  32204. p = convertToParentSpace (*source, p);
  32205. source = source->getParentComponent();
  32206. }
  32207. }
  32208. jassert (source == 0);
  32209. if (target == 0)
  32210. return p;
  32211. const Component* const topLevelComp = target->getTopLevelComponent();
  32212. if (topLevelComp->isOnDesktop())
  32213. p = topLevelComp->getPeer()->globalToLocal (p);
  32214. else
  32215. p = convertFromParentSpace (*topLevelComp, p);
  32216. if (topLevelComp == target)
  32217. return p;
  32218. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32219. }
  32220. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32221. {
  32222. Rectangle<int> r (comp.getLocalBounds());
  32223. Component* const p = comp.getParentComponent();
  32224. if (p != 0)
  32225. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32226. return r;
  32227. }
  32228. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32229. {
  32230. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32231. {
  32232. const Component& child = *comp.childComponentList_.getUnchecked(i);
  32233. if (child.isVisible() && ! child.isTransformed())
  32234. {
  32235. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds_));
  32236. if (! newClip.isEmpty())
  32237. {
  32238. if (child.isOpaque())
  32239. {
  32240. g.excludeClipRegion (newClip + delta);
  32241. }
  32242. else
  32243. {
  32244. const Point<int> childPos (child.getPosition());
  32245. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32246. }
  32247. }
  32248. }
  32249. }
  32250. }
  32251. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32252. const Point<int>& delta,
  32253. const Rectangle<int>& clipRect,
  32254. const Component* const compToAvoid)
  32255. {
  32256. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32257. {
  32258. const Component* const c = comp.childComponentList_.getUnchecked(i);
  32259. if (c != compToAvoid && c->isVisible())
  32260. {
  32261. if (c->isOpaque())
  32262. {
  32263. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32264. childBounds.translate (delta.getX(), delta.getY());
  32265. result.subtract (childBounds);
  32266. }
  32267. else
  32268. {
  32269. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32270. newClip.translate (-c->getX(), -c->getY());
  32271. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32272. newClip, compToAvoid);
  32273. }
  32274. }
  32275. }
  32276. }
  32277. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32278. {
  32279. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32280. : Desktop::getInstance().getMainMonitorArea();
  32281. }
  32282. };
  32283. Component::Component()
  32284. : parentComponent_ (0),
  32285. lookAndFeel_ (0),
  32286. effect_ (0),
  32287. bufferedImage_ (0),
  32288. componentFlags_ (0),
  32289. componentTransparency (0)
  32290. {
  32291. }
  32292. Component::Component (const String& name)
  32293. : componentName_ (name),
  32294. parentComponent_ (0),
  32295. lookAndFeel_ (0),
  32296. effect_ (0),
  32297. bufferedImage_ (0),
  32298. componentFlags_ (0),
  32299. componentTransparency (0)
  32300. {
  32301. }
  32302. Component::~Component()
  32303. {
  32304. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32305. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32306. #endif
  32307. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32308. if (parentComponent_ != 0)
  32309. {
  32310. parentComponent_->removeChildComponent (this);
  32311. }
  32312. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32313. {
  32314. giveAwayFocus();
  32315. }
  32316. if (flags.hasHeavyweightPeerFlag)
  32317. removeFromDesktop();
  32318. for (int i = childComponentList_.size(); --i >= 0;)
  32319. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32320. }
  32321. void Component::setName (const String& name)
  32322. {
  32323. // if component methods are being called from threads other than the message
  32324. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32325. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32326. if (componentName_ != name)
  32327. {
  32328. componentName_ = name;
  32329. if (flags.hasHeavyweightPeerFlag)
  32330. {
  32331. ComponentPeer* const peer = getPeer();
  32332. jassert (peer != 0);
  32333. if (peer != 0)
  32334. peer->setTitle (name);
  32335. }
  32336. BailOutChecker checker (this);
  32337. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32338. }
  32339. }
  32340. void Component::setVisible (bool shouldBeVisible)
  32341. {
  32342. if (flags.visibleFlag != shouldBeVisible)
  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. SafePointer<Component> safePointer (this);
  32348. flags.visibleFlag = shouldBeVisible;
  32349. internalRepaint (0, 0, getWidth(), getHeight());
  32350. sendFakeMouseMove();
  32351. if (! shouldBeVisible)
  32352. {
  32353. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32354. {
  32355. if (parentComponent_ != 0)
  32356. parentComponent_->grabKeyboardFocus();
  32357. else
  32358. giveAwayFocus();
  32359. }
  32360. }
  32361. if (safePointer != 0)
  32362. {
  32363. sendVisibilityChangeMessage();
  32364. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32365. {
  32366. ComponentPeer* const peer = getPeer();
  32367. jassert (peer != 0);
  32368. if (peer != 0)
  32369. {
  32370. peer->setVisible (shouldBeVisible);
  32371. internalHierarchyChanged();
  32372. }
  32373. }
  32374. }
  32375. }
  32376. }
  32377. void Component::visibilityChanged()
  32378. {
  32379. }
  32380. void Component::sendVisibilityChangeMessage()
  32381. {
  32382. BailOutChecker checker (this);
  32383. visibilityChanged();
  32384. if (! checker.shouldBailOut())
  32385. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32386. }
  32387. bool Component::isShowing() const
  32388. {
  32389. if (flags.visibleFlag)
  32390. {
  32391. if (parentComponent_ != 0)
  32392. {
  32393. return parentComponent_->isShowing();
  32394. }
  32395. else
  32396. {
  32397. const ComponentPeer* const peer = getPeer();
  32398. return peer != 0 && ! peer->isMinimised();
  32399. }
  32400. }
  32401. return false;
  32402. }
  32403. void* Component::getWindowHandle() const
  32404. {
  32405. const ComponentPeer* const peer = getPeer();
  32406. if (peer != 0)
  32407. return peer->getNativeHandle();
  32408. return 0;
  32409. }
  32410. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32411. {
  32412. // if component methods are being called from threads other than the message
  32413. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32414. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32415. if (isOpaque())
  32416. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32417. else
  32418. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32419. int currentStyleFlags = 0;
  32420. // don't use getPeer(), so that we only get the peer that's specifically
  32421. // for this comp, and not for one of its parents.
  32422. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32423. if (peer != 0)
  32424. currentStyleFlags = peer->getStyleFlags();
  32425. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32426. {
  32427. SafePointer<Component> safePointer (this);
  32428. #if JUCE_LINUX
  32429. // it's wise to give the component a non-zero size before
  32430. // putting it on the desktop, as X windows get confused by this, and
  32431. // a (1, 1) minimum size is enforced here.
  32432. setSize (jmax (1, getWidth()),
  32433. jmax (1, getHeight()));
  32434. #endif
  32435. const Point<int> topLeft (getScreenPosition());
  32436. bool wasFullscreen = false;
  32437. bool wasMinimised = false;
  32438. ComponentBoundsConstrainer* currentConstainer = 0;
  32439. Rectangle<int> oldNonFullScreenBounds;
  32440. if (peer != 0)
  32441. {
  32442. wasFullscreen = peer->isFullScreen();
  32443. wasMinimised = peer->isMinimised();
  32444. currentConstainer = peer->getConstrainer();
  32445. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32446. removeFromDesktop();
  32447. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32448. }
  32449. if (parentComponent_ != 0)
  32450. parentComponent_->removeChildComponent (this);
  32451. if (safePointer != 0)
  32452. {
  32453. flags.hasHeavyweightPeerFlag = true;
  32454. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32455. Desktop::getInstance().addDesktopComponent (this);
  32456. bounds_.setPosition (topLeft);
  32457. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32458. peer->setVisible (isVisible());
  32459. if (wasFullscreen)
  32460. {
  32461. peer->setFullScreen (true);
  32462. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32463. }
  32464. if (wasMinimised)
  32465. peer->setMinimised (true);
  32466. if (isAlwaysOnTop())
  32467. peer->setAlwaysOnTop (true);
  32468. peer->setConstrainer (currentConstainer);
  32469. repaint();
  32470. }
  32471. internalHierarchyChanged();
  32472. }
  32473. }
  32474. void Component::removeFromDesktop()
  32475. {
  32476. // if component methods are being called from threads other than the message
  32477. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32478. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32479. if (flags.hasHeavyweightPeerFlag)
  32480. {
  32481. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32482. flags.hasHeavyweightPeerFlag = false;
  32483. jassert (peer != 0);
  32484. delete peer;
  32485. Desktop::getInstance().removeDesktopComponent (this);
  32486. }
  32487. }
  32488. bool Component::isOnDesktop() const throw()
  32489. {
  32490. return flags.hasHeavyweightPeerFlag;
  32491. }
  32492. void Component::userTriedToCloseWindow()
  32493. {
  32494. /* This means that the user's trying to get rid of your window with the 'close window' system
  32495. menu option (on windows) or possibly the task manager - you should really handle this
  32496. and delete or hide your component in an appropriate way.
  32497. If you want to ignore the event and don't want to trigger this assertion, just override
  32498. this method and do nothing.
  32499. */
  32500. jassertfalse;
  32501. }
  32502. void Component::minimisationStateChanged (bool)
  32503. {
  32504. }
  32505. void Component::setOpaque (const bool shouldBeOpaque)
  32506. {
  32507. if (shouldBeOpaque != flags.opaqueFlag)
  32508. {
  32509. flags.opaqueFlag = shouldBeOpaque;
  32510. if (flags.hasHeavyweightPeerFlag)
  32511. {
  32512. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32513. if (peer != 0)
  32514. {
  32515. // to make it recreate the heavyweight window
  32516. addToDesktop (peer->getStyleFlags());
  32517. }
  32518. }
  32519. repaint();
  32520. }
  32521. }
  32522. bool Component::isOpaque() const throw()
  32523. {
  32524. return flags.opaqueFlag;
  32525. }
  32526. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32527. {
  32528. if (shouldBeBuffered != flags.bufferToImageFlag)
  32529. {
  32530. bufferedImage_ = Image::null;
  32531. flags.bufferToImageFlag = shouldBeBuffered;
  32532. }
  32533. }
  32534. void Component::toFront (const bool setAsForeground)
  32535. {
  32536. // if component methods are being called from threads other than the message
  32537. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32538. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32539. if (flags.hasHeavyweightPeerFlag)
  32540. {
  32541. ComponentPeer* const peer = getPeer();
  32542. if (peer != 0)
  32543. {
  32544. peer->toFront (setAsForeground);
  32545. if (setAsForeground && ! hasKeyboardFocus (true))
  32546. grabKeyboardFocus();
  32547. }
  32548. }
  32549. else if (parentComponent_ != 0)
  32550. {
  32551. Array<Component*>& childList = parentComponent_->childComponentList_;
  32552. if (childList.getLast() != this)
  32553. {
  32554. const int index = childList.indexOf (this);
  32555. if (index >= 0)
  32556. {
  32557. int insertIndex = -1;
  32558. if (! flags.alwaysOnTopFlag)
  32559. {
  32560. insertIndex = childList.size() - 1;
  32561. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32562. --insertIndex;
  32563. }
  32564. if (index != insertIndex)
  32565. {
  32566. childList.move (index, insertIndex);
  32567. sendFakeMouseMove();
  32568. repaintParent();
  32569. }
  32570. }
  32571. }
  32572. if (setAsForeground)
  32573. {
  32574. internalBroughtToFront();
  32575. grabKeyboardFocus();
  32576. }
  32577. }
  32578. }
  32579. void Component::toBehind (Component* const other)
  32580. {
  32581. if (other != 0 && other != this)
  32582. {
  32583. // the two components must belong to the same parent..
  32584. jassert (parentComponent_ == other->parentComponent_);
  32585. if (parentComponent_ != 0)
  32586. {
  32587. Array<Component*>& childList = parentComponent_->childComponentList_;
  32588. const int index = childList.indexOf (this);
  32589. if (index >= 0 && childList [index + 1] != other)
  32590. {
  32591. int otherIndex = childList.indexOf (other);
  32592. if (otherIndex >= 0)
  32593. {
  32594. if (index < otherIndex)
  32595. --otherIndex;
  32596. childList.move (index, otherIndex);
  32597. sendFakeMouseMove();
  32598. repaintParent();
  32599. }
  32600. }
  32601. }
  32602. else if (isOnDesktop())
  32603. {
  32604. jassert (other->isOnDesktop());
  32605. if (other->isOnDesktop())
  32606. {
  32607. ComponentPeer* const us = getPeer();
  32608. ComponentPeer* const them = other->getPeer();
  32609. jassert (us != 0 && them != 0);
  32610. if (us != 0 && them != 0)
  32611. us->toBehind (them);
  32612. }
  32613. }
  32614. }
  32615. }
  32616. void Component::toBack()
  32617. {
  32618. Array<Component*>& childList = parentComponent_->childComponentList_;
  32619. if (isOnDesktop())
  32620. {
  32621. jassertfalse; //xxx need to add this to native window
  32622. }
  32623. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32624. {
  32625. const int index = childList.indexOf (this);
  32626. if (index > 0)
  32627. {
  32628. int insertIndex = 0;
  32629. if (flags.alwaysOnTopFlag)
  32630. {
  32631. while (insertIndex < childList.size()
  32632. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32633. {
  32634. ++insertIndex;
  32635. }
  32636. }
  32637. if (index != insertIndex)
  32638. {
  32639. childList.move (index, insertIndex);
  32640. sendFakeMouseMove();
  32641. repaintParent();
  32642. }
  32643. }
  32644. }
  32645. }
  32646. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32647. {
  32648. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32649. {
  32650. flags.alwaysOnTopFlag = shouldStayOnTop;
  32651. if (isOnDesktop())
  32652. {
  32653. ComponentPeer* const peer = getPeer();
  32654. jassert (peer != 0);
  32655. if (peer != 0)
  32656. {
  32657. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32658. {
  32659. // some kinds of peer can't change their always-on-top status, so
  32660. // for these, we'll need to create a new window
  32661. const int oldFlags = peer->getStyleFlags();
  32662. removeFromDesktop();
  32663. addToDesktop (oldFlags);
  32664. }
  32665. }
  32666. }
  32667. if (shouldStayOnTop)
  32668. toFront (false);
  32669. internalHierarchyChanged();
  32670. }
  32671. }
  32672. bool Component::isAlwaysOnTop() const throw()
  32673. {
  32674. return flags.alwaysOnTopFlag;
  32675. }
  32676. int Component::proportionOfWidth (const float proportion) const throw()
  32677. {
  32678. return roundToInt (proportion * bounds_.getWidth());
  32679. }
  32680. int Component::proportionOfHeight (const float proportion) const throw()
  32681. {
  32682. return roundToInt (proportion * bounds_.getHeight());
  32683. }
  32684. int Component::getParentWidth() const throw()
  32685. {
  32686. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32687. : getParentMonitorArea().getWidth();
  32688. }
  32689. int Component::getParentHeight() const throw()
  32690. {
  32691. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32692. : getParentMonitorArea().getHeight();
  32693. }
  32694. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32695. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32696. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32697. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32698. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32699. {
  32700. return ComponentHelpers::convertCoordinate (this, source, point);
  32701. }
  32702. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32703. {
  32704. return ComponentHelpers::convertCoordinate (this, source, area);
  32705. }
  32706. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32707. {
  32708. return ComponentHelpers::convertCoordinate (0, this, point);
  32709. }
  32710. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32711. {
  32712. return ComponentHelpers::convertCoordinate (0, this, area);
  32713. }
  32714. /* Deprecated methods... */
  32715. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32716. {
  32717. return localPointToGlobal (relativePosition);
  32718. }
  32719. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32720. {
  32721. return getLocalPoint (0, screenPosition);
  32722. }
  32723. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32724. {
  32725. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32726. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32727. }
  32728. void Component::setBounds (const int x, const int y, int w, int h)
  32729. {
  32730. // if component methods are being called from threads other than the message
  32731. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32732. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32733. if (w < 0) w = 0;
  32734. if (h < 0) h = 0;
  32735. const bool wasResized = (getWidth() != w || getHeight() != h);
  32736. const bool wasMoved = (getX() != x || getY() != y);
  32737. #if JUCE_DEBUG
  32738. // It's a very bad idea to try to resize a window during its paint() method!
  32739. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32740. #endif
  32741. if (wasMoved || wasResized)
  32742. {
  32743. const bool showing = isShowing();
  32744. if (showing)
  32745. {
  32746. // send a fake mouse move to trigger enter/exit messages if needed..
  32747. sendFakeMouseMove();
  32748. if (! flags.hasHeavyweightPeerFlag)
  32749. repaintParent();
  32750. }
  32751. bounds_.setBounds (x, y, w, h);
  32752. if (showing)
  32753. {
  32754. if (wasResized)
  32755. repaint();
  32756. else if (! flags.hasHeavyweightPeerFlag)
  32757. repaintParent();
  32758. }
  32759. if (flags.hasHeavyweightPeerFlag)
  32760. {
  32761. ComponentPeer* const peer = getPeer();
  32762. if (peer != 0)
  32763. {
  32764. if (wasMoved && wasResized)
  32765. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32766. else if (wasMoved)
  32767. peer->setPosition (getX(), getY());
  32768. else if (wasResized)
  32769. peer->setSize (getWidth(), getHeight());
  32770. }
  32771. }
  32772. sendMovedResizedMessages (wasMoved, wasResized);
  32773. }
  32774. }
  32775. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32776. {
  32777. JUCE_TRY
  32778. {
  32779. if (wasMoved)
  32780. moved();
  32781. if (wasResized)
  32782. {
  32783. resized();
  32784. for (int i = childComponentList_.size(); --i >= 0;)
  32785. {
  32786. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32787. i = jmin (i, childComponentList_.size());
  32788. }
  32789. }
  32790. BailOutChecker checker (this);
  32791. if (parentComponent_ != 0)
  32792. parentComponent_->childBoundsChanged (this);
  32793. if (! checker.shouldBailOut())
  32794. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32795. *this, wasMoved, wasResized);
  32796. }
  32797. JUCE_CATCH_EXCEPTION
  32798. }
  32799. void Component::setSize (const int w, const int h)
  32800. {
  32801. setBounds (getX(), getY(), w, h);
  32802. }
  32803. void Component::setTopLeftPosition (const int x, const int y)
  32804. {
  32805. setBounds (x, y, getWidth(), getHeight());
  32806. }
  32807. void Component::setTopRightPosition (const int x, const int y)
  32808. {
  32809. setTopLeftPosition (x - getWidth(), y);
  32810. }
  32811. void Component::setBounds (const Rectangle<int>& r)
  32812. {
  32813. setBounds (r.getX(),
  32814. r.getY(),
  32815. r.getWidth(),
  32816. r.getHeight());
  32817. }
  32818. void Component::setBoundsRelative (const float x, const float y,
  32819. const float w, const float h)
  32820. {
  32821. const int pw = getParentWidth();
  32822. const int ph = getParentHeight();
  32823. setBounds (roundToInt (x * pw),
  32824. roundToInt (y * ph),
  32825. roundToInt (w * pw),
  32826. roundToInt (h * ph));
  32827. }
  32828. void Component::setCentrePosition (const int x, const int y)
  32829. {
  32830. setTopLeftPosition (x - getWidth() / 2,
  32831. y - getHeight() / 2);
  32832. }
  32833. void Component::setCentreRelative (const float x, const float y)
  32834. {
  32835. setCentrePosition (roundToInt (getParentWidth() * x),
  32836. roundToInt (getParentHeight() * y));
  32837. }
  32838. void Component::centreWithSize (const int width, const int height)
  32839. {
  32840. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32841. setBounds (parentArea.getCentreX() - width / 2,
  32842. parentArea.getCentreY() - height / 2,
  32843. width, height);
  32844. }
  32845. void Component::setBoundsInset (const BorderSize& borders)
  32846. {
  32847. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32848. }
  32849. void Component::setBoundsToFit (int x, int y, int width, int height,
  32850. const Justification& justification,
  32851. const bool onlyReduceInSize)
  32852. {
  32853. // it's no good calling this method unless both the component and
  32854. // target rectangle have a finite size.
  32855. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32856. if (getWidth() > 0 && getHeight() > 0
  32857. && width > 0 && height > 0)
  32858. {
  32859. int newW, newH;
  32860. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32861. {
  32862. newW = getWidth();
  32863. newH = getHeight();
  32864. }
  32865. else
  32866. {
  32867. const double imageRatio = getHeight() / (double) getWidth();
  32868. const double targetRatio = height / (double) width;
  32869. if (imageRatio <= targetRatio)
  32870. {
  32871. newW = width;
  32872. newH = jmin (height, roundToInt (newW * imageRatio));
  32873. }
  32874. else
  32875. {
  32876. newH = height;
  32877. newW = jmin (width, roundToInt (newH / imageRatio));
  32878. }
  32879. }
  32880. if (newW > 0 && newH > 0)
  32881. {
  32882. int newX, newY;
  32883. justification.applyToRectangle (newX, newY, newW, newH,
  32884. x, y, width, height);
  32885. setBounds (newX, newY, newW, newH);
  32886. }
  32887. }
  32888. }
  32889. bool Component::isTransformed() const throw()
  32890. {
  32891. return affineTransform_ != 0;
  32892. }
  32893. void Component::setTransform (const AffineTransform& newTransform)
  32894. {
  32895. // If you pass in a transform with no inverse, the component will have no dimensions,
  32896. // and there will be all sorts of maths errors when converting coordinates.
  32897. jassert (! newTransform.isSingularity());
  32898. if (newTransform.isIdentity())
  32899. {
  32900. if (affineTransform_ != 0)
  32901. {
  32902. repaint();
  32903. affineTransform_ = 0;
  32904. repaint();
  32905. sendMovedResizedMessages (false, false);
  32906. }
  32907. }
  32908. else if (affineTransform_ == 0)
  32909. {
  32910. repaint();
  32911. affineTransform_ = new AffineTransform (newTransform);
  32912. repaint();
  32913. sendMovedResizedMessages (false, false);
  32914. }
  32915. else if (*affineTransform_ != newTransform)
  32916. {
  32917. repaint();
  32918. *affineTransform_ = newTransform;
  32919. repaint();
  32920. sendMovedResizedMessages (false, false);
  32921. }
  32922. }
  32923. const AffineTransform Component::getTransform() const
  32924. {
  32925. return affineTransform_ != 0 ? *affineTransform_ : AffineTransform::identity;
  32926. }
  32927. bool Component::hitTest (int x, int y)
  32928. {
  32929. if (! flags.ignoresMouseClicksFlag)
  32930. return true;
  32931. if (flags.allowChildMouseClicksFlag)
  32932. {
  32933. for (int i = getNumChildComponents(); --i >= 0;)
  32934. {
  32935. Component& child = *getChildComponent (i);
  32936. if (child.isVisible()
  32937. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32938. return true;
  32939. }
  32940. }
  32941. return false;
  32942. }
  32943. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32944. const bool allowClicksOnChildComponents) throw()
  32945. {
  32946. flags.ignoresMouseClicksFlag = ! allowClicks;
  32947. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32948. }
  32949. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32950. bool& allowsClicksOnChildComponents) const throw()
  32951. {
  32952. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32953. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32954. }
  32955. bool Component::contains (const Point<int>& point)
  32956. {
  32957. if (ComponentHelpers::hitTest (*this, point))
  32958. {
  32959. if (parentComponent_ != 0)
  32960. {
  32961. return parentComponent_->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32962. }
  32963. else if (flags.hasHeavyweightPeerFlag)
  32964. {
  32965. const ComponentPeer* const peer = getPeer();
  32966. if (peer != 0)
  32967. return peer->contains (point, true);
  32968. }
  32969. }
  32970. return false;
  32971. }
  32972. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32973. {
  32974. if (! contains (point))
  32975. return false;
  32976. Component* const top = getTopLevelComponent();
  32977. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32978. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32979. }
  32980. Component* Component::getComponentAt (const Point<int>& position)
  32981. {
  32982. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32983. {
  32984. for (int i = childComponentList_.size(); --i >= 0;)
  32985. {
  32986. Component* child = childComponentList_.getUnchecked(i);
  32987. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32988. if (child != 0)
  32989. return child;
  32990. }
  32991. return this;
  32992. }
  32993. return 0;
  32994. }
  32995. Component* Component::getComponentAt (const int x, const int y)
  32996. {
  32997. return getComponentAt (Point<int> (x, y));
  32998. }
  32999. void Component::addChildComponent (Component* const child, int zOrder)
  33000. {
  33001. // if component methods are being called from threads other than the message
  33002. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33003. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33004. if (child != 0 && child->parentComponent_ != this)
  33005. {
  33006. if (child->parentComponent_ != 0)
  33007. child->parentComponent_->removeChildComponent (child);
  33008. else
  33009. child->removeFromDesktop();
  33010. child->parentComponent_ = this;
  33011. if (child->isVisible())
  33012. child->repaintParent();
  33013. if (! child->isAlwaysOnTop())
  33014. {
  33015. if (zOrder < 0 || zOrder > childComponentList_.size())
  33016. zOrder = childComponentList_.size();
  33017. while (zOrder > 0)
  33018. {
  33019. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  33020. break;
  33021. --zOrder;
  33022. }
  33023. }
  33024. childComponentList_.insert (zOrder, child);
  33025. child->internalHierarchyChanged();
  33026. internalChildrenChanged();
  33027. }
  33028. }
  33029. void Component::addAndMakeVisible (Component* const child, int zOrder)
  33030. {
  33031. if (child != 0)
  33032. {
  33033. child->setVisible (true);
  33034. addChildComponent (child, zOrder);
  33035. }
  33036. }
  33037. void Component::removeChildComponent (Component* const child)
  33038. {
  33039. removeChildComponent (childComponentList_.indexOf (child));
  33040. }
  33041. Component* Component::removeChildComponent (const int index)
  33042. {
  33043. // if component methods are being called from threads other than the message
  33044. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33045. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33046. Component* const child = childComponentList_ [index];
  33047. if (child != 0)
  33048. {
  33049. const bool childShowing = child->isShowing();
  33050. if (childShowing)
  33051. {
  33052. sendFakeMouseMove();
  33053. child->repaintParent();
  33054. }
  33055. childComponentList_.remove (index);
  33056. child->parentComponent_ = 0;
  33057. // (NB: there are obscure situations where a childShowing = false, but it still has the focus)
  33058. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  33059. {
  33060. SafePointer<Component> thisPointer (this);
  33061. giveAwayFocus();
  33062. if (thisPointer == 0)
  33063. return child;
  33064. if (childShowing)
  33065. grabKeyboardFocus();
  33066. }
  33067. child->internalHierarchyChanged();
  33068. internalChildrenChanged();
  33069. }
  33070. return child;
  33071. }
  33072. void Component::removeAllChildren()
  33073. {
  33074. while (childComponentList_.size() > 0)
  33075. removeChildComponent (childComponentList_.size() - 1);
  33076. }
  33077. void Component::deleteAllChildren()
  33078. {
  33079. while (childComponentList_.size() > 0)
  33080. delete (removeChildComponent (childComponentList_.size() - 1));
  33081. }
  33082. int Component::getNumChildComponents() const throw()
  33083. {
  33084. return childComponentList_.size();
  33085. }
  33086. Component* Component::getChildComponent (const int index) const throw()
  33087. {
  33088. return childComponentList_ [index];
  33089. }
  33090. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33091. {
  33092. return childComponentList_.indexOf (const_cast <Component*> (child));
  33093. }
  33094. Component* Component::getTopLevelComponent() const throw()
  33095. {
  33096. const Component* comp = this;
  33097. while (comp->parentComponent_ != 0)
  33098. comp = comp->parentComponent_;
  33099. return const_cast <Component*> (comp);
  33100. }
  33101. bool Component::isParentOf (const Component* possibleChild) const throw()
  33102. {
  33103. while (possibleChild != 0)
  33104. {
  33105. possibleChild = possibleChild->parentComponent_;
  33106. if (possibleChild == this)
  33107. return true;
  33108. }
  33109. return false;
  33110. }
  33111. void Component::parentHierarchyChanged()
  33112. {
  33113. }
  33114. void Component::childrenChanged()
  33115. {
  33116. }
  33117. void Component::internalChildrenChanged()
  33118. {
  33119. if (componentListeners.isEmpty())
  33120. {
  33121. childrenChanged();
  33122. }
  33123. else
  33124. {
  33125. BailOutChecker checker (this);
  33126. childrenChanged();
  33127. if (! checker.shouldBailOut())
  33128. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33129. }
  33130. }
  33131. void Component::internalHierarchyChanged()
  33132. {
  33133. BailOutChecker checker (this);
  33134. parentHierarchyChanged();
  33135. if (checker.shouldBailOut())
  33136. return;
  33137. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33138. if (checker.shouldBailOut())
  33139. return;
  33140. for (int i = childComponentList_.size(); --i >= 0;)
  33141. {
  33142. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33143. if (checker.shouldBailOut())
  33144. {
  33145. // you really shouldn't delete the parent component during a callback telling you
  33146. // that it's changed..
  33147. jassertfalse;
  33148. return;
  33149. }
  33150. i = jmin (i, childComponentList_.size());
  33151. }
  33152. }
  33153. int Component::runModalLoop()
  33154. {
  33155. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33156. {
  33157. // use a callback so this can be called from non-gui threads
  33158. return (int) (pointer_sized_int) MessageManager::getInstance()
  33159. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  33160. }
  33161. if (! isCurrentlyModal())
  33162. enterModalState (true);
  33163. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33164. }
  33165. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33166. {
  33167. // if component methods are being called from threads other than the message
  33168. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33169. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33170. // Check for an attempt to make a component modal when it already is!
  33171. // This can cause nasty problems..
  33172. jassert (! flags.currentlyModalFlag);
  33173. if (! isCurrentlyModal())
  33174. {
  33175. ModalComponentManager::getInstance()->startModal (this, callback);
  33176. flags.currentlyModalFlag = true;
  33177. setVisible (true);
  33178. if (takeKeyboardFocus_)
  33179. grabKeyboardFocus();
  33180. }
  33181. }
  33182. void Component::exitModalState (const int returnValue)
  33183. {
  33184. if (isCurrentlyModal())
  33185. {
  33186. if (MessageManager::getInstance()->isThisTheMessageThread())
  33187. {
  33188. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33189. flags.currentlyModalFlag = false;
  33190. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33191. }
  33192. else
  33193. {
  33194. class ExitModalStateMessage : public CallbackMessage
  33195. {
  33196. public:
  33197. ExitModalStateMessage (Component* const target_, const int result_)
  33198. : target (target_), result (result_) {}
  33199. void messageCallback()
  33200. {
  33201. if (target.getComponent() != 0) // (getComponent() required for VS2003 bug)
  33202. target->exitModalState (result);
  33203. }
  33204. private:
  33205. Component::SafePointer<Component> target;
  33206. int result;
  33207. };
  33208. (new ExitModalStateMessage (this, returnValue))->post();
  33209. }
  33210. }
  33211. }
  33212. bool Component::isCurrentlyModal() const throw()
  33213. {
  33214. return flags.currentlyModalFlag
  33215. && getCurrentlyModalComponent() == this;
  33216. }
  33217. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33218. {
  33219. Component* const mc = getCurrentlyModalComponent();
  33220. return mc != 0
  33221. && mc != this
  33222. && (! mc->isParentOf (this))
  33223. && ! mc->canModalEventBeSentToComponent (this);
  33224. }
  33225. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33226. {
  33227. return ModalComponentManager::getInstance()->getNumModalComponents();
  33228. }
  33229. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33230. {
  33231. return ModalComponentManager::getInstance()->getModalComponent (index);
  33232. }
  33233. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33234. {
  33235. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33236. }
  33237. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33238. {
  33239. return flags.bringToFrontOnClickFlag;
  33240. }
  33241. void Component::setMouseCursor (const MouseCursor& cursor)
  33242. {
  33243. if (cursor_ != cursor)
  33244. {
  33245. cursor_ = cursor;
  33246. if (flags.visibleFlag)
  33247. updateMouseCursor();
  33248. }
  33249. }
  33250. const MouseCursor Component::getMouseCursor()
  33251. {
  33252. return cursor_;
  33253. }
  33254. void Component::updateMouseCursor() const
  33255. {
  33256. sendFakeMouseMove();
  33257. }
  33258. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33259. {
  33260. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33261. }
  33262. void Component::setAlpha (const float newAlpha)
  33263. {
  33264. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33265. if (componentTransparency != newIntAlpha)
  33266. {
  33267. componentTransparency = newIntAlpha;
  33268. if (flags.hasHeavyweightPeerFlag)
  33269. {
  33270. ComponentPeer* const peer = getPeer();
  33271. if (peer != 0)
  33272. peer->setAlpha (newAlpha);
  33273. }
  33274. else
  33275. {
  33276. repaint();
  33277. }
  33278. }
  33279. }
  33280. float Component::getAlpha() const
  33281. {
  33282. return (255 - componentTransparency) / 255.0f;
  33283. }
  33284. void Component::repaintParent()
  33285. {
  33286. if (flags.visibleFlag)
  33287. internalRepaint (0, 0, getWidth(), getHeight());
  33288. }
  33289. void Component::repaint()
  33290. {
  33291. repaint (0, 0, getWidth(), getHeight());
  33292. }
  33293. void Component::repaint (const int x, const int y,
  33294. const int w, const int h)
  33295. {
  33296. bufferedImage_ = Image::null;
  33297. if (flags.visibleFlag)
  33298. internalRepaint (x, y, w, h);
  33299. }
  33300. void Component::repaint (const Rectangle<int>& area)
  33301. {
  33302. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33303. }
  33304. void Component::internalRepaint (int x, int y, int w, int h)
  33305. {
  33306. // if component methods are being called from threads other than the message
  33307. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33308. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33309. if (x < 0)
  33310. {
  33311. w += x;
  33312. x = 0;
  33313. }
  33314. if (x + w > getWidth())
  33315. w = getWidth() - x;
  33316. if (w > 0)
  33317. {
  33318. if (y < 0)
  33319. {
  33320. h += y;
  33321. y = 0;
  33322. }
  33323. if (y + h > getHeight())
  33324. h = getHeight() - y;
  33325. if (h > 0)
  33326. {
  33327. if (parentComponent_ != 0)
  33328. {
  33329. if (parentComponent_->flags.visibleFlag)
  33330. {
  33331. if (affineTransform_ == 0)
  33332. {
  33333. parentComponent_->internalRepaint (x + getX(), y + getY(), w, h);
  33334. }
  33335. else
  33336. {
  33337. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33338. parentComponent_->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33339. }
  33340. }
  33341. }
  33342. else if (flags.hasHeavyweightPeerFlag)
  33343. {
  33344. ComponentPeer* const peer = getPeer();
  33345. if (peer != 0)
  33346. peer->repaint (Rectangle<int> (x, y, w, h));
  33347. }
  33348. }
  33349. }
  33350. }
  33351. void Component::paintComponent (Graphics& g)
  33352. {
  33353. if (flags.bufferToImageFlag)
  33354. {
  33355. if (bufferedImage_.isNull())
  33356. {
  33357. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33358. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33359. Graphics imG (bufferedImage_);
  33360. paint (imG);
  33361. }
  33362. g.setColour (Colours::black.withAlpha (getAlpha()));
  33363. g.drawImageAt (bufferedImage_, 0, 0);
  33364. }
  33365. else
  33366. {
  33367. paint (g);
  33368. }
  33369. }
  33370. void Component::paintWithinParentContext (Graphics& g)
  33371. {
  33372. g.setOrigin (getX(), getY());
  33373. paintEntireComponent (g, false);
  33374. }
  33375. void Component::paintComponentAndChildren (Graphics& g)
  33376. {
  33377. const Rectangle<int> clipBounds (g.getClipBounds());
  33378. if (flags.dontClipGraphicsFlag)
  33379. {
  33380. paintComponent (g);
  33381. }
  33382. else
  33383. {
  33384. g.saveState();
  33385. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33386. if (! g.isClipEmpty())
  33387. paintComponent (g);
  33388. g.restoreState();
  33389. }
  33390. for (int i = 0; i < childComponentList_.size(); ++i)
  33391. {
  33392. Component& child = *childComponentList_.getUnchecked (i);
  33393. if (child.isVisible())
  33394. {
  33395. if (child.affineTransform_ != 0)
  33396. {
  33397. g.saveState();
  33398. g.addTransform (*child.affineTransform_);
  33399. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33400. child.paintWithinParentContext (g);
  33401. g.restoreState();
  33402. }
  33403. else if (clipBounds.intersects (child.getBounds()))
  33404. {
  33405. g.saveState();
  33406. if (child.flags.dontClipGraphicsFlag)
  33407. {
  33408. child.paintWithinParentContext (g);
  33409. }
  33410. else if (g.reduceClipRegion (child.getBounds()))
  33411. {
  33412. bool nothingClipped = true;
  33413. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33414. {
  33415. const Component& sibling = *childComponentList_.getUnchecked (j);
  33416. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform_ == 0)
  33417. {
  33418. nothingClipped = false;
  33419. g.excludeClipRegion (sibling.getBounds());
  33420. }
  33421. }
  33422. if (nothingClipped || ! g.isClipEmpty())
  33423. child.paintWithinParentContext (g);
  33424. }
  33425. g.restoreState();
  33426. }
  33427. }
  33428. }
  33429. g.saveState();
  33430. paintOverChildren (g);
  33431. g.restoreState();
  33432. }
  33433. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33434. {
  33435. jassert (! g.isClipEmpty());
  33436. #if JUCE_DEBUG
  33437. flags.isInsidePaintCall = true;
  33438. #endif
  33439. if (effect_ != 0)
  33440. {
  33441. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33442. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33443. {
  33444. Graphics g2 (effectImage);
  33445. paintComponentAndChildren (g2);
  33446. }
  33447. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33448. }
  33449. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33450. {
  33451. if (componentTransparency < 255)
  33452. {
  33453. g.beginTransparencyLayer (getAlpha());
  33454. paintComponentAndChildren (g);
  33455. g.endTransparencyLayer();
  33456. }
  33457. }
  33458. else
  33459. {
  33460. paintComponentAndChildren (g);
  33461. }
  33462. #if JUCE_DEBUG
  33463. flags.isInsidePaintCall = false;
  33464. #endif
  33465. }
  33466. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33467. {
  33468. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33469. }
  33470. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33471. const bool clipImageToComponentBounds)
  33472. {
  33473. Rectangle<int> r (areaToGrab);
  33474. if (clipImageToComponentBounds)
  33475. r = r.getIntersection (getLocalBounds());
  33476. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33477. jmax (1, r.getWidth()),
  33478. jmax (1, r.getHeight()),
  33479. true);
  33480. Graphics imageContext (componentImage);
  33481. imageContext.setOrigin (-r.getX(), -r.getY());
  33482. paintEntireComponent (imageContext, true);
  33483. return componentImage;
  33484. }
  33485. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33486. {
  33487. if (effect_ != effect)
  33488. {
  33489. effect_ = effect;
  33490. repaint();
  33491. }
  33492. }
  33493. LookAndFeel& Component::getLookAndFeel() const throw()
  33494. {
  33495. const Component* c = this;
  33496. do
  33497. {
  33498. if (c->lookAndFeel_ != 0)
  33499. return *(c->lookAndFeel_);
  33500. c = c->parentComponent_;
  33501. }
  33502. while (c != 0);
  33503. return LookAndFeel::getDefaultLookAndFeel();
  33504. }
  33505. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33506. {
  33507. if (lookAndFeel_ != newLookAndFeel)
  33508. {
  33509. lookAndFeel_ = newLookAndFeel;
  33510. sendLookAndFeelChange();
  33511. }
  33512. }
  33513. void Component::lookAndFeelChanged()
  33514. {
  33515. }
  33516. void Component::sendLookAndFeelChange()
  33517. {
  33518. repaint();
  33519. SafePointer<Component> safePointer (this);
  33520. lookAndFeelChanged();
  33521. if (safePointer != 0)
  33522. {
  33523. for (int i = childComponentList_.size(); --i >= 0;)
  33524. {
  33525. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33526. if (safePointer == 0)
  33527. return;
  33528. i = jmin (i, childComponentList_.size());
  33529. }
  33530. }
  33531. }
  33532. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33533. {
  33534. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33535. if (v != 0)
  33536. return Colour ((int) *v);
  33537. if (inheritFromParent && parentComponent_ != 0)
  33538. return parentComponent_->findColour (colourId, true);
  33539. return getLookAndFeel().findColour (colourId);
  33540. }
  33541. bool Component::isColourSpecified (const int colourId) const
  33542. {
  33543. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33544. }
  33545. void Component::removeColour (const int colourId)
  33546. {
  33547. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33548. colourChanged();
  33549. }
  33550. void Component::setColour (const int colourId, const Colour& colour)
  33551. {
  33552. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33553. colourChanged();
  33554. }
  33555. void Component::copyAllExplicitColoursTo (Component& target) const
  33556. {
  33557. bool changed = false;
  33558. for (int i = properties.size(); --i >= 0;)
  33559. {
  33560. const Identifier name (properties.getName(i));
  33561. if (name.toString().startsWith ("jcclr_"))
  33562. if (target.properties.set (name, properties [name]))
  33563. changed = true;
  33564. }
  33565. if (changed)
  33566. target.colourChanged();
  33567. }
  33568. void Component::colourChanged()
  33569. {
  33570. }
  33571. const Rectangle<int> Component::getLocalBounds() const throw()
  33572. {
  33573. return Rectangle<int> (getWidth(), getHeight());
  33574. }
  33575. const Rectangle<int> Component::getBoundsInParent() const throw()
  33576. {
  33577. return affineTransform_ == 0 ? bounds_
  33578. : bounds_.toFloat().transformed (*affineTransform_).getSmallestIntegerContainer();
  33579. }
  33580. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33581. {
  33582. result.clear();
  33583. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33584. if (! unclipped.isEmpty())
  33585. {
  33586. result.add (unclipped);
  33587. if (includeSiblings)
  33588. {
  33589. const Component* const c = getTopLevelComponent();
  33590. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33591. c->getLocalBounds(), this);
  33592. }
  33593. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33594. result.consolidate();
  33595. }
  33596. }
  33597. void Component::mouseEnter (const MouseEvent&)
  33598. {
  33599. // base class does nothing
  33600. }
  33601. void Component::mouseExit (const MouseEvent&)
  33602. {
  33603. // base class does nothing
  33604. }
  33605. void Component::mouseDown (const MouseEvent&)
  33606. {
  33607. // base class does nothing
  33608. }
  33609. void Component::mouseUp (const MouseEvent&)
  33610. {
  33611. // base class does nothing
  33612. }
  33613. void Component::mouseDrag (const MouseEvent&)
  33614. {
  33615. // base class does nothing
  33616. }
  33617. void Component::mouseMove (const MouseEvent&)
  33618. {
  33619. // base class does nothing
  33620. }
  33621. void Component::mouseDoubleClick (const MouseEvent&)
  33622. {
  33623. // base class does nothing
  33624. }
  33625. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33626. {
  33627. // the base class just passes this event up to its parent..
  33628. if (parentComponent_ != 0)
  33629. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33630. wheelIncrementX, wheelIncrementY);
  33631. }
  33632. void Component::resized()
  33633. {
  33634. // base class does nothing
  33635. }
  33636. void Component::moved()
  33637. {
  33638. // base class does nothing
  33639. }
  33640. void Component::childBoundsChanged (Component*)
  33641. {
  33642. // base class does nothing
  33643. }
  33644. void Component::parentSizeChanged()
  33645. {
  33646. // base class does nothing
  33647. }
  33648. void Component::addComponentListener (ComponentListener* const newListener)
  33649. {
  33650. componentListeners.add (newListener);
  33651. }
  33652. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33653. {
  33654. componentListeners.remove (listenerToRemove);
  33655. }
  33656. void Component::inputAttemptWhenModal()
  33657. {
  33658. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33659. getLookAndFeel().playAlertSound();
  33660. }
  33661. bool Component::canModalEventBeSentToComponent (const Component*)
  33662. {
  33663. return false;
  33664. }
  33665. void Component::internalModalInputAttempt()
  33666. {
  33667. Component* const current = getCurrentlyModalComponent();
  33668. if (current != 0)
  33669. current->inputAttemptWhenModal();
  33670. }
  33671. void Component::paint (Graphics&)
  33672. {
  33673. // all painting is done in the subclasses
  33674. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33675. }
  33676. void Component::paintOverChildren (Graphics&)
  33677. {
  33678. // all painting is done in the subclasses
  33679. }
  33680. void Component::postCommandMessage (const int commandId)
  33681. {
  33682. class CustomCommandMessage : public CallbackMessage
  33683. {
  33684. public:
  33685. CustomCommandMessage (Component* const target_, const int commandId_)
  33686. : target (target_), commandId (commandId_) {}
  33687. void messageCallback()
  33688. {
  33689. if (target != 0)
  33690. target->handleCommandMessage (commandId);
  33691. }
  33692. private:
  33693. Component::SafePointer<Component> target;
  33694. int commandId;
  33695. };
  33696. (new CustomCommandMessage (this, commandId))->post();
  33697. }
  33698. void Component::handleCommandMessage (int)
  33699. {
  33700. // used by subclasses
  33701. }
  33702. void Component::addMouseListener (MouseListener* const newListener,
  33703. const bool wantsEventsForAllNestedChildComponents)
  33704. {
  33705. // if component methods are being called from threads other than the message
  33706. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33707. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33708. // If you register a component as a mouselistener for itself, it'll receive all the events
  33709. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33710. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33711. if (mouseListeners_ == 0)
  33712. mouseListeners_ = new MouseListenerList();
  33713. mouseListeners_->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33714. }
  33715. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33716. {
  33717. // if component methods are being called from threads other than the message
  33718. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33719. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33720. if (mouseListeners_ != 0)
  33721. mouseListeners_->removeListener (listenerToRemove);
  33722. }
  33723. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33724. {
  33725. if (isCurrentlyBlockedByAnotherModalComponent())
  33726. {
  33727. // if something else is modal, always just show a normal mouse cursor
  33728. source.showMouseCursor (MouseCursor::NormalCursor);
  33729. return;
  33730. }
  33731. if (! flags.mouseInsideFlag)
  33732. {
  33733. flags.mouseInsideFlag = true;
  33734. flags.mouseOverFlag = true;
  33735. flags.mouseDownFlag = false;
  33736. BailOutChecker checker (this);
  33737. if (flags.repaintOnMouseActivityFlag)
  33738. repaint();
  33739. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33740. this, this, time, relativePos, time, 0, false);
  33741. mouseEnter (me);
  33742. if (checker.shouldBailOut())
  33743. return;
  33744. Desktop& desktop = Desktop::getInstance();
  33745. desktop.resetTimer();
  33746. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33747. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseEnter, me);
  33748. }
  33749. }
  33750. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33751. {
  33752. BailOutChecker checker (this);
  33753. if (flags.mouseDownFlag)
  33754. {
  33755. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33756. if (checker.shouldBailOut())
  33757. return;
  33758. }
  33759. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33760. {
  33761. flags.mouseInsideFlag = false;
  33762. flags.mouseOverFlag = false;
  33763. flags.mouseDownFlag = false;
  33764. if (flags.repaintOnMouseActivityFlag)
  33765. repaint();
  33766. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33767. this, this, time, relativePos, time, 0, false);
  33768. mouseExit (me);
  33769. if (checker.shouldBailOut())
  33770. return;
  33771. Desktop& desktop = Desktop::getInstance();
  33772. desktop.resetTimer();
  33773. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33774. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseExit, me);
  33775. }
  33776. }
  33777. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33778. {
  33779. Desktop& desktop = Desktop::getInstance();
  33780. BailOutChecker checker (this);
  33781. if (isCurrentlyBlockedByAnotherModalComponent())
  33782. {
  33783. internalModalInputAttempt();
  33784. if (checker.shouldBailOut())
  33785. return;
  33786. // If processing the input attempt has exited the modal loop, we'll allow the event
  33787. // to be delivered..
  33788. if (isCurrentlyBlockedByAnotherModalComponent())
  33789. {
  33790. // allow blocked mouse-events to go to global listeners..
  33791. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33792. this, this, time, relativePos, time,
  33793. source.getNumberOfMultipleClicks(), false);
  33794. desktop.resetTimer();
  33795. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33796. return;
  33797. }
  33798. }
  33799. {
  33800. Component* c = this;
  33801. while (c != 0)
  33802. {
  33803. if (c->isBroughtToFrontOnMouseClick())
  33804. {
  33805. c->toFront (true);
  33806. if (checker.shouldBailOut())
  33807. return;
  33808. }
  33809. c = c->parentComponent_;
  33810. }
  33811. }
  33812. if (! flags.dontFocusOnMouseClickFlag)
  33813. {
  33814. grabFocusInternal (focusChangedByMouseClick);
  33815. if (checker.shouldBailOut())
  33816. return;
  33817. }
  33818. flags.mouseDownFlag = true;
  33819. flags.mouseOverFlag = true;
  33820. if (flags.repaintOnMouseActivityFlag)
  33821. repaint();
  33822. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33823. this, this, time, relativePos, time,
  33824. source.getNumberOfMultipleClicks(), false);
  33825. mouseDown (me);
  33826. if (checker.shouldBailOut())
  33827. return;
  33828. desktop.resetTimer();
  33829. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33830. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDown, me);
  33831. }
  33832. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33833. {
  33834. if (flags.mouseDownFlag)
  33835. {
  33836. flags.mouseDownFlag = false;
  33837. BailOutChecker checker (this);
  33838. if (flags.repaintOnMouseActivityFlag)
  33839. repaint();
  33840. const MouseEvent me (source, relativePos,
  33841. oldModifiers, this, this, time,
  33842. getLocalPoint (0, source.getLastMouseDownPosition()),
  33843. source.getLastMouseDownTime(),
  33844. source.getNumberOfMultipleClicks(),
  33845. source.hasMouseMovedSignificantlySincePressed());
  33846. mouseUp (me);
  33847. if (checker.shouldBailOut())
  33848. return;
  33849. Desktop& desktop = Desktop::getInstance();
  33850. desktop.resetTimer();
  33851. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33852. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseUp, me);
  33853. if (checker.shouldBailOut())
  33854. return;
  33855. // check for double-click
  33856. if (me.getNumberOfClicks() >= 2)
  33857. {
  33858. mouseDoubleClick (me);
  33859. if (checker.shouldBailOut())
  33860. return;
  33861. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33862. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDoubleClick, me);
  33863. }
  33864. }
  33865. }
  33866. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33867. {
  33868. if (flags.mouseDownFlag)
  33869. {
  33870. flags.mouseOverFlag = reallyContains (relativePos, false);
  33871. BailOutChecker checker (this);
  33872. const MouseEvent me (source, relativePos,
  33873. source.getCurrentModifiers(), this, this, time,
  33874. getLocalPoint (0, source.getLastMouseDownPosition()),
  33875. source.getLastMouseDownTime(),
  33876. source.getNumberOfMultipleClicks(),
  33877. source.hasMouseMovedSignificantlySincePressed());
  33878. mouseDrag (me);
  33879. if (checker.shouldBailOut())
  33880. return;
  33881. Desktop& desktop = Desktop::getInstance();
  33882. desktop.resetTimer();
  33883. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33884. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDrag, me);
  33885. }
  33886. }
  33887. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33888. {
  33889. Desktop& desktop = Desktop::getInstance();
  33890. BailOutChecker checker (this);
  33891. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33892. this, this, time, relativePos, time, 0, false);
  33893. if (isCurrentlyBlockedByAnotherModalComponent())
  33894. {
  33895. // allow blocked mouse-events to go to global listeners..
  33896. desktop.sendMouseMove();
  33897. }
  33898. else
  33899. {
  33900. flags.mouseOverFlag = true;
  33901. mouseMove (me);
  33902. if (checker.shouldBailOut())
  33903. return;
  33904. desktop.resetTimer();
  33905. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33906. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseMove, me);
  33907. }
  33908. }
  33909. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33910. const Time& time, const float amountX, const float amountY)
  33911. {
  33912. Desktop& desktop = Desktop::getInstance();
  33913. BailOutChecker checker (this);
  33914. const float wheelIncrementX = amountX / 256.0f;
  33915. const float wheelIncrementY = amountY / 256.0f;
  33916. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33917. this, this, time, relativePos, time, 0, false);
  33918. if (isCurrentlyBlockedByAnotherModalComponent())
  33919. {
  33920. // allow blocked mouse-events to go to global listeners..
  33921. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33922. }
  33923. else
  33924. {
  33925. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33926. if (checker.shouldBailOut())
  33927. return;
  33928. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33929. MouseListenerList::sendWheelEvent (this, checker, me, wheelIncrementX, wheelIncrementY);
  33930. }
  33931. }
  33932. void Component::sendFakeMouseMove() const
  33933. {
  33934. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33935. if (! mainMouse.isDragging())
  33936. mainMouse.triggerFakeMove();
  33937. }
  33938. void Component::beginDragAutoRepeat (const int interval)
  33939. {
  33940. Desktop::getInstance().beginDragAutoRepeat (interval);
  33941. }
  33942. void Component::broughtToFront()
  33943. {
  33944. }
  33945. void Component::internalBroughtToFront()
  33946. {
  33947. if (flags.hasHeavyweightPeerFlag)
  33948. Desktop::getInstance().componentBroughtToFront (this);
  33949. BailOutChecker checker (this);
  33950. broughtToFront();
  33951. if (checker.shouldBailOut())
  33952. return;
  33953. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33954. if (checker.shouldBailOut())
  33955. return;
  33956. // When brought to the front and there's a modal component blocking this one,
  33957. // we need to bring the modal one to the front instead..
  33958. Component* const cm = getCurrentlyModalComponent();
  33959. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33960. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33961. }
  33962. void Component::focusGained (FocusChangeType)
  33963. {
  33964. // base class does nothing
  33965. }
  33966. void Component::internalFocusGain (const FocusChangeType cause)
  33967. {
  33968. SafePointer<Component> safePointer (this);
  33969. focusGained (cause);
  33970. if (safePointer != 0)
  33971. internalChildFocusChange (cause);
  33972. }
  33973. void Component::focusLost (FocusChangeType)
  33974. {
  33975. // base class does nothing
  33976. }
  33977. void Component::internalFocusLoss (const FocusChangeType cause)
  33978. {
  33979. SafePointer<Component> safePointer (this);
  33980. focusLost (focusChangedDirectly);
  33981. if (safePointer != 0)
  33982. internalChildFocusChange (cause);
  33983. }
  33984. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33985. {
  33986. // base class does nothing
  33987. }
  33988. void Component::internalChildFocusChange (FocusChangeType cause)
  33989. {
  33990. const bool childIsNowFocused = hasKeyboardFocus (true);
  33991. if (flags.childCompFocusedFlag != childIsNowFocused)
  33992. {
  33993. flags.childCompFocusedFlag = childIsNowFocused;
  33994. SafePointer<Component> safePointer (this);
  33995. focusOfChildComponentChanged (cause);
  33996. if (safePointer == 0)
  33997. return;
  33998. }
  33999. if (parentComponent_ != 0)
  34000. parentComponent_->internalChildFocusChange (cause);
  34001. }
  34002. bool Component::isEnabled() const throw()
  34003. {
  34004. return (! flags.isDisabledFlag)
  34005. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34006. }
  34007. void Component::setEnabled (const bool shouldBeEnabled)
  34008. {
  34009. if (flags.isDisabledFlag == shouldBeEnabled)
  34010. {
  34011. flags.isDisabledFlag = ! shouldBeEnabled;
  34012. // if any parent components are disabled, setting our flag won't make a difference,
  34013. // so no need to send a change message
  34014. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34015. sendEnablementChangeMessage();
  34016. }
  34017. }
  34018. void Component::sendEnablementChangeMessage()
  34019. {
  34020. SafePointer<Component> safePointer (this);
  34021. enablementChanged();
  34022. if (safePointer == 0)
  34023. return;
  34024. for (int i = getNumChildComponents(); --i >= 0;)
  34025. {
  34026. Component* const c = getChildComponent (i);
  34027. if (c != 0)
  34028. {
  34029. c->sendEnablementChangeMessage();
  34030. if (safePointer == 0)
  34031. return;
  34032. }
  34033. }
  34034. }
  34035. void Component::enablementChanged()
  34036. {
  34037. }
  34038. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34039. {
  34040. flags.wantsFocusFlag = wantsFocus;
  34041. }
  34042. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34043. {
  34044. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34045. }
  34046. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34047. {
  34048. return ! flags.dontFocusOnMouseClickFlag;
  34049. }
  34050. bool Component::getWantsKeyboardFocus() const throw()
  34051. {
  34052. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34053. }
  34054. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34055. {
  34056. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34057. }
  34058. bool Component::isFocusContainer() const throw()
  34059. {
  34060. return flags.isFocusContainerFlag;
  34061. }
  34062. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34063. int Component::getExplicitFocusOrder() const
  34064. {
  34065. return properties [juce_explicitFocusOrderId];
  34066. }
  34067. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34068. {
  34069. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34070. }
  34071. KeyboardFocusTraverser* Component::createFocusTraverser()
  34072. {
  34073. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34074. return new KeyboardFocusTraverser();
  34075. return parentComponent_->createFocusTraverser();
  34076. }
  34077. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34078. {
  34079. // give the focus to this component
  34080. if (currentlyFocusedComponent != this)
  34081. {
  34082. JUCE_TRY
  34083. {
  34084. // get the focus onto our desktop window
  34085. ComponentPeer* const peer = getPeer();
  34086. if (peer != 0)
  34087. {
  34088. SafePointer<Component> safePointer (this);
  34089. peer->grabFocus();
  34090. if (peer->isFocused() && currentlyFocusedComponent != this)
  34091. {
  34092. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34093. currentlyFocusedComponent = this;
  34094. Desktop::getInstance().triggerFocusCallback();
  34095. // call this after setting currentlyFocusedComponent so that the one that's
  34096. // losing it has a chance to see where focus is going
  34097. if (componentLosingFocus != 0)
  34098. componentLosingFocus->internalFocusLoss (cause);
  34099. if (currentlyFocusedComponent == this)
  34100. {
  34101. focusGained (cause);
  34102. if (safePointer != 0)
  34103. internalChildFocusChange (cause);
  34104. }
  34105. }
  34106. }
  34107. }
  34108. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34109. catch (const std::exception& e)
  34110. {
  34111. currentlyFocusedComponent = 0;
  34112. Desktop::getInstance().triggerFocusCallback();
  34113. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34114. }
  34115. catch (...)
  34116. {
  34117. currentlyFocusedComponent = 0;
  34118. Desktop::getInstance().triggerFocusCallback();
  34119. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34120. }
  34121. #endif
  34122. }
  34123. }
  34124. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34125. {
  34126. if (isShowing())
  34127. {
  34128. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34129. {
  34130. takeKeyboardFocus (cause);
  34131. }
  34132. else
  34133. {
  34134. if (isParentOf (currentlyFocusedComponent)
  34135. && currentlyFocusedComponent->isShowing())
  34136. {
  34137. // do nothing if the focused component is actually a child of ours..
  34138. }
  34139. else
  34140. {
  34141. // find the default child component..
  34142. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34143. if (traverser != 0)
  34144. {
  34145. Component* const defaultComp = traverser->getDefaultComponent (this);
  34146. traverser = 0;
  34147. if (defaultComp != 0)
  34148. {
  34149. defaultComp->grabFocusInternal (cause, false);
  34150. return;
  34151. }
  34152. }
  34153. if (canTryParent && parentComponent_ != 0)
  34154. {
  34155. // if no children want it and we're allowed to try our parent comp,
  34156. // then pass up to parent, which will try our siblings.
  34157. parentComponent_->grabFocusInternal (cause, true);
  34158. }
  34159. }
  34160. }
  34161. }
  34162. }
  34163. void Component::grabKeyboardFocus()
  34164. {
  34165. // if component methods are being called from threads other than the message
  34166. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34167. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34168. grabFocusInternal (focusChangedDirectly);
  34169. }
  34170. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34171. {
  34172. // if component methods are being called from threads other than the message
  34173. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34174. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34175. if (parentComponent_ != 0)
  34176. {
  34177. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34178. if (traverser != 0)
  34179. {
  34180. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34181. : traverser->getPreviousComponent (this);
  34182. traverser = 0;
  34183. if (nextComp != 0)
  34184. {
  34185. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34186. {
  34187. SafePointer<Component> nextCompPointer (nextComp);
  34188. internalModalInputAttempt();
  34189. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34190. return;
  34191. }
  34192. nextComp->grabFocusInternal (focusChangedByTabKey);
  34193. return;
  34194. }
  34195. }
  34196. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34197. }
  34198. }
  34199. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34200. {
  34201. return (currentlyFocusedComponent == this)
  34202. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34203. }
  34204. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34205. {
  34206. return currentlyFocusedComponent;
  34207. }
  34208. void Component::giveAwayFocus()
  34209. {
  34210. Component* const componentLosingFocus = currentlyFocusedComponent;
  34211. currentlyFocusedComponent = 0;
  34212. if (componentLosingFocus != 0)
  34213. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34214. Desktop::getInstance().triggerFocusCallback();
  34215. }
  34216. bool Component::isMouseOver (const bool includeChildren) const
  34217. {
  34218. if (flags.mouseOverFlag)
  34219. return true;
  34220. if (includeChildren)
  34221. {
  34222. Desktop& desktop = Desktop::getInstance();
  34223. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34224. {
  34225. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34226. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34227. return true;
  34228. }
  34229. }
  34230. return false;
  34231. }
  34232. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34233. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34234. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34235. {
  34236. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34237. }
  34238. const Point<int> Component::getMouseXYRelative() const
  34239. {
  34240. return getLocalPoint (0, Desktop::getMousePosition());
  34241. }
  34242. const Rectangle<int> Component::getParentMonitorArea() const
  34243. {
  34244. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34245. }
  34246. void Component::addKeyListener (KeyListener* const newListener)
  34247. {
  34248. if (keyListeners_ == 0)
  34249. keyListeners_ = new Array <KeyListener*>();
  34250. keyListeners_->addIfNotAlreadyThere (newListener);
  34251. }
  34252. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34253. {
  34254. if (keyListeners_ != 0)
  34255. keyListeners_->removeValue (listenerToRemove);
  34256. }
  34257. bool Component::keyPressed (const KeyPress&)
  34258. {
  34259. return false;
  34260. }
  34261. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34262. {
  34263. return false;
  34264. }
  34265. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34266. {
  34267. if (parentComponent_ != 0)
  34268. parentComponent_->modifierKeysChanged (modifiers);
  34269. }
  34270. void Component::internalModifierKeysChanged()
  34271. {
  34272. sendFakeMouseMove();
  34273. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34274. }
  34275. ComponentPeer* Component::getPeer() const
  34276. {
  34277. if (flags.hasHeavyweightPeerFlag)
  34278. return ComponentPeer::getPeerFor (this);
  34279. else if (parentComponent_ == 0)
  34280. return 0;
  34281. return parentComponent_->getPeer();
  34282. }
  34283. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34284. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34285. {
  34286. jassert (component1 != 0);
  34287. }
  34288. bool Component::BailOutChecker::shouldBailOut() const throw()
  34289. {
  34290. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34291. }
  34292. END_JUCE_NAMESPACE
  34293. /*** End of inlined file: juce_Component.cpp ***/
  34294. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34295. BEGIN_JUCE_NAMESPACE
  34296. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34297. void ComponentListener::componentBroughtToFront (Component&) {}
  34298. void ComponentListener::componentVisibilityChanged (Component&) {}
  34299. void ComponentListener::componentChildrenChanged (Component&) {}
  34300. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34301. void ComponentListener::componentNameChanged (Component&) {}
  34302. void ComponentListener::componentBeingDeleted (Component&) {}
  34303. END_JUCE_NAMESPACE
  34304. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34305. /*** Start of inlined file: juce_Desktop.cpp ***/
  34306. BEGIN_JUCE_NAMESPACE
  34307. Desktop::Desktop()
  34308. : mouseClickCounter (0),
  34309. kioskModeComponent (0),
  34310. allowedOrientations (allOrientations)
  34311. {
  34312. createMouseInputSources();
  34313. refreshMonitorSizes();
  34314. }
  34315. Desktop::~Desktop()
  34316. {
  34317. jassert (instance == this);
  34318. instance = 0;
  34319. // doh! If you don't delete all your windows before exiting, you're going to
  34320. // be leaking memory!
  34321. jassert (desktopComponents.size() == 0);
  34322. }
  34323. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34324. {
  34325. if (instance == 0)
  34326. instance = new Desktop();
  34327. return *instance;
  34328. }
  34329. Desktop* Desktop::instance = 0;
  34330. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34331. const bool clipToWorkArea);
  34332. void Desktop::refreshMonitorSizes()
  34333. {
  34334. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34335. oldClipped.swapWithArray (monitorCoordsClipped);
  34336. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34337. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34338. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34339. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34340. if (oldClipped != monitorCoordsClipped
  34341. || oldUnclipped != monitorCoordsUnclipped)
  34342. {
  34343. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34344. {
  34345. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34346. if (p != 0)
  34347. p->handleScreenSizeChange();
  34348. }
  34349. }
  34350. }
  34351. int Desktop::getNumDisplayMonitors() const throw()
  34352. {
  34353. return monitorCoordsClipped.size();
  34354. }
  34355. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34356. {
  34357. return clippedToWorkArea ? monitorCoordsClipped [index]
  34358. : monitorCoordsUnclipped [index];
  34359. }
  34360. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34361. {
  34362. RectangleList rl;
  34363. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34364. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34365. return rl;
  34366. }
  34367. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34368. {
  34369. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34370. }
  34371. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34372. {
  34373. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34374. double bestDistance = 1.0e10;
  34375. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34376. {
  34377. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34378. if (rect.contains (position))
  34379. return rect;
  34380. const double distance = rect.getCentre().getDistanceFrom (position);
  34381. if (distance < bestDistance)
  34382. {
  34383. bestDistance = distance;
  34384. best = rect;
  34385. }
  34386. }
  34387. return best;
  34388. }
  34389. int Desktop::getNumComponents() const throw()
  34390. {
  34391. return desktopComponents.size();
  34392. }
  34393. Component* Desktop::getComponent (const int index) const throw()
  34394. {
  34395. return desktopComponents [index];
  34396. }
  34397. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34398. {
  34399. for (int i = desktopComponents.size(); --i >= 0;)
  34400. {
  34401. Component* const c = desktopComponents.getUnchecked(i);
  34402. if (c->isVisible())
  34403. {
  34404. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34405. if (c->contains (relative))
  34406. return c->getComponentAt (relative);
  34407. }
  34408. }
  34409. return 0;
  34410. }
  34411. void Desktop::addDesktopComponent (Component* const c)
  34412. {
  34413. jassert (c != 0);
  34414. jassert (! desktopComponents.contains (c));
  34415. desktopComponents.addIfNotAlreadyThere (c);
  34416. }
  34417. void Desktop::removeDesktopComponent (Component* const c)
  34418. {
  34419. desktopComponents.removeValue (c);
  34420. }
  34421. void Desktop::componentBroughtToFront (Component* const c)
  34422. {
  34423. const int index = desktopComponents.indexOf (c);
  34424. jassert (index >= 0);
  34425. if (index >= 0)
  34426. {
  34427. int newIndex = -1;
  34428. if (! c->isAlwaysOnTop())
  34429. {
  34430. newIndex = desktopComponents.size();
  34431. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34432. --newIndex;
  34433. --newIndex;
  34434. }
  34435. desktopComponents.move (index, newIndex);
  34436. }
  34437. }
  34438. const Point<int> Desktop::getMousePosition()
  34439. {
  34440. return getInstance().getMainMouseSource().getScreenPosition();
  34441. }
  34442. const Point<int> Desktop::getLastMouseDownPosition()
  34443. {
  34444. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34445. }
  34446. int Desktop::getMouseButtonClickCounter()
  34447. {
  34448. return getInstance().mouseClickCounter;
  34449. }
  34450. void Desktop::incrementMouseClickCounter() throw()
  34451. {
  34452. ++mouseClickCounter;
  34453. }
  34454. int Desktop::getNumDraggingMouseSources() const throw()
  34455. {
  34456. int num = 0;
  34457. for (int i = mouseSources.size(); --i >= 0;)
  34458. if (mouseSources.getUnchecked(i)->isDragging())
  34459. ++num;
  34460. return num;
  34461. }
  34462. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34463. {
  34464. int num = 0;
  34465. for (int i = mouseSources.size(); --i >= 0;)
  34466. {
  34467. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34468. if (mi->isDragging())
  34469. {
  34470. if (index == num)
  34471. return mi;
  34472. ++num;
  34473. }
  34474. }
  34475. return 0;
  34476. }
  34477. class MouseDragAutoRepeater : public Timer
  34478. {
  34479. public:
  34480. MouseDragAutoRepeater() {}
  34481. void timerCallback()
  34482. {
  34483. Desktop& desktop = Desktop::getInstance();
  34484. int numMiceDown = 0;
  34485. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34486. {
  34487. MouseInputSource* const source = desktop.getMouseSource(i);
  34488. if (source->isDragging())
  34489. {
  34490. source->triggerFakeMove();
  34491. ++numMiceDown;
  34492. }
  34493. }
  34494. if (numMiceDown == 0)
  34495. desktop.beginDragAutoRepeat (0);
  34496. }
  34497. private:
  34498. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34499. };
  34500. void Desktop::beginDragAutoRepeat (const int interval)
  34501. {
  34502. if (interval > 0)
  34503. {
  34504. if (dragRepeater == 0)
  34505. dragRepeater = new MouseDragAutoRepeater();
  34506. if (dragRepeater->getTimerInterval() != interval)
  34507. dragRepeater->startTimer (interval);
  34508. }
  34509. else
  34510. {
  34511. dragRepeater = 0;
  34512. }
  34513. }
  34514. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34515. {
  34516. focusListeners.add (listener);
  34517. }
  34518. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34519. {
  34520. focusListeners.remove (listener);
  34521. }
  34522. void Desktop::triggerFocusCallback()
  34523. {
  34524. triggerAsyncUpdate();
  34525. }
  34526. void Desktop::handleAsyncUpdate()
  34527. {
  34528. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34529. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34530. Component::SafePointer<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34531. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34532. }
  34533. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34534. {
  34535. mouseListeners.add (listener);
  34536. resetTimer();
  34537. }
  34538. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34539. {
  34540. mouseListeners.remove (listener);
  34541. resetTimer();
  34542. }
  34543. void Desktop::timerCallback()
  34544. {
  34545. if (lastFakeMouseMove != getMousePosition())
  34546. sendMouseMove();
  34547. }
  34548. void Desktop::sendMouseMove()
  34549. {
  34550. if (! mouseListeners.isEmpty())
  34551. {
  34552. startTimer (20);
  34553. lastFakeMouseMove = getMousePosition();
  34554. Component* const target = findComponentAt (lastFakeMouseMove);
  34555. if (target != 0)
  34556. {
  34557. Component::BailOutChecker checker (target);
  34558. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34559. const Time now (Time::getCurrentTime());
  34560. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34561. target, target, now, pos, now, 0, false);
  34562. if (me.mods.isAnyMouseButtonDown())
  34563. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34564. else
  34565. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34566. }
  34567. }
  34568. }
  34569. void Desktop::resetTimer()
  34570. {
  34571. if (mouseListeners.size() == 0)
  34572. stopTimer();
  34573. else
  34574. startTimer (100);
  34575. lastFakeMouseMove = getMousePosition();
  34576. }
  34577. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34578. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34579. {
  34580. if (kioskModeComponent != componentToUse)
  34581. {
  34582. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34583. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34584. if (kioskModeComponent != 0)
  34585. {
  34586. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34587. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34588. }
  34589. kioskModeComponent = componentToUse;
  34590. if (kioskModeComponent != 0)
  34591. {
  34592. // Only components that are already on the desktop can be put into kiosk mode!
  34593. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34594. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34595. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34596. }
  34597. }
  34598. }
  34599. void Desktop::setOrientationsEnabled (const int newOrientations)
  34600. {
  34601. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34602. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34603. allowedOrientations = newOrientations;
  34604. }
  34605. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34606. {
  34607. // Make sure you only pass one valid flag in here...
  34608. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34609. return (allowedOrientations & orientation) != 0;
  34610. }
  34611. END_JUCE_NAMESPACE
  34612. /*** End of inlined file: juce_Desktop.cpp ***/
  34613. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34614. BEGIN_JUCE_NAMESPACE
  34615. class ModalComponentManager::ModalItem : public ComponentListener
  34616. {
  34617. public:
  34618. ModalItem (Component* const comp, Callback* const callback)
  34619. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34620. {
  34621. if (callback != 0)
  34622. callbacks.add (callback);
  34623. jassert (comp != 0);
  34624. component->addComponentListener (this);
  34625. }
  34626. ~ModalItem()
  34627. {
  34628. if (! isDeleted)
  34629. component->removeComponentListener (this);
  34630. }
  34631. void componentBeingDeleted (Component&)
  34632. {
  34633. isDeleted = true;
  34634. cancel();
  34635. }
  34636. void componentVisibilityChanged (Component&)
  34637. {
  34638. if (! component->isShowing())
  34639. cancel();
  34640. }
  34641. void componentParentHierarchyChanged (Component&)
  34642. {
  34643. if (! component->isShowing())
  34644. cancel();
  34645. }
  34646. void cancel()
  34647. {
  34648. if (isActive)
  34649. {
  34650. isActive = false;
  34651. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34652. }
  34653. }
  34654. Component* component;
  34655. OwnedArray<Callback> callbacks;
  34656. int returnValue;
  34657. bool isActive, isDeleted;
  34658. private:
  34659. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34660. };
  34661. ModalComponentManager::ModalComponentManager()
  34662. {
  34663. }
  34664. ModalComponentManager::~ModalComponentManager()
  34665. {
  34666. clearSingletonInstance();
  34667. }
  34668. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34669. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34670. {
  34671. if (component != 0)
  34672. stack.add (new ModalItem (component, callback));
  34673. }
  34674. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34675. {
  34676. if (callback != 0)
  34677. {
  34678. ScopedPointer<Callback> callbackDeleter (callback);
  34679. for (int i = stack.size(); --i >= 0;)
  34680. {
  34681. ModalItem* const item = stack.getUnchecked(i);
  34682. if (item->component == component)
  34683. {
  34684. item->callbacks.add (callback);
  34685. callbackDeleter.release();
  34686. break;
  34687. }
  34688. }
  34689. }
  34690. }
  34691. void ModalComponentManager::endModal (Component* component)
  34692. {
  34693. for (int i = stack.size(); --i >= 0;)
  34694. {
  34695. ModalItem* const item = stack.getUnchecked(i);
  34696. if (item->component == component)
  34697. item->cancel();
  34698. }
  34699. }
  34700. void ModalComponentManager::endModal (Component* component, int returnValue)
  34701. {
  34702. for (int i = stack.size(); --i >= 0;)
  34703. {
  34704. ModalItem* const item = stack.getUnchecked(i);
  34705. if (item->component == component)
  34706. {
  34707. item->returnValue = returnValue;
  34708. item->cancel();
  34709. }
  34710. }
  34711. }
  34712. int ModalComponentManager::getNumModalComponents() const
  34713. {
  34714. int n = 0;
  34715. for (int i = 0; i < stack.size(); ++i)
  34716. if (stack.getUnchecked(i)->isActive)
  34717. ++n;
  34718. return n;
  34719. }
  34720. Component* ModalComponentManager::getModalComponent (const int index) const
  34721. {
  34722. int n = 0;
  34723. for (int i = stack.size(); --i >= 0;)
  34724. {
  34725. const ModalItem* const item = stack.getUnchecked(i);
  34726. if (item->isActive)
  34727. if (n++ == index)
  34728. return item->component;
  34729. }
  34730. return 0;
  34731. }
  34732. bool ModalComponentManager::isModal (Component* const comp) const
  34733. {
  34734. for (int i = stack.size(); --i >= 0;)
  34735. {
  34736. const ModalItem* const item = stack.getUnchecked(i);
  34737. if (item->isActive && item->component == comp)
  34738. return true;
  34739. }
  34740. return false;
  34741. }
  34742. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34743. {
  34744. return comp == getModalComponent (0);
  34745. }
  34746. void ModalComponentManager::handleAsyncUpdate()
  34747. {
  34748. for (int i = stack.size(); --i >= 0;)
  34749. {
  34750. const ModalItem* const item = stack.getUnchecked(i);
  34751. if (! item->isActive)
  34752. {
  34753. for (int j = item->callbacks.size(); --j >= 0;)
  34754. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34755. stack.remove (i);
  34756. }
  34757. }
  34758. }
  34759. void ModalComponentManager::bringModalComponentsToFront()
  34760. {
  34761. ComponentPeer* lastOne = 0;
  34762. for (int i = 0; i < getNumModalComponents(); ++i)
  34763. {
  34764. Component* const c = getModalComponent (i);
  34765. if (c == 0)
  34766. break;
  34767. ComponentPeer* peer = c->getPeer();
  34768. if (peer != 0 && peer != lastOne)
  34769. {
  34770. if (lastOne == 0)
  34771. {
  34772. peer->toFront (true);
  34773. peer->grabFocus();
  34774. }
  34775. else
  34776. peer->toBehind (lastOne);
  34777. lastOne = peer;
  34778. }
  34779. }
  34780. }
  34781. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34782. {
  34783. public:
  34784. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34785. ~ReturnValueRetriever() {}
  34786. void modalStateFinished (int returnValue)
  34787. {
  34788. finished = true;
  34789. value = returnValue;
  34790. }
  34791. private:
  34792. int& value;
  34793. bool& finished;
  34794. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34795. };
  34796. int ModalComponentManager::runEventLoopForCurrentComponent()
  34797. {
  34798. // This can only be run from the message thread!
  34799. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34800. Component* currentlyModal = getModalComponent (0);
  34801. if (currentlyModal == 0)
  34802. return 0;
  34803. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34804. int returnValue = 0;
  34805. bool finished = false;
  34806. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34807. JUCE_TRY
  34808. {
  34809. while (! finished)
  34810. {
  34811. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34812. break;
  34813. }
  34814. }
  34815. JUCE_CATCH_EXCEPTION
  34816. if (prevFocused != 0)
  34817. prevFocused->grabKeyboardFocus();
  34818. return returnValue;
  34819. }
  34820. END_JUCE_NAMESPACE
  34821. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34822. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34823. BEGIN_JUCE_NAMESPACE
  34824. ArrowButton::ArrowButton (const String& name,
  34825. float arrowDirectionInRadians,
  34826. const Colour& arrowColour)
  34827. : Button (name),
  34828. colour (arrowColour)
  34829. {
  34830. path.lineTo (0.0f, 1.0f);
  34831. path.lineTo (1.0f, 0.5f);
  34832. path.closeSubPath();
  34833. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34834. 0.5f, 0.5f));
  34835. setComponentEffect (&shadow);
  34836. buttonStateChanged();
  34837. }
  34838. ArrowButton::~ArrowButton()
  34839. {
  34840. }
  34841. void ArrowButton::paintButton (Graphics& g,
  34842. bool /*isMouseOverButton*/,
  34843. bool /*isButtonDown*/)
  34844. {
  34845. g.setColour (colour);
  34846. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34847. (float) offset,
  34848. (float) (getWidth() - 3),
  34849. (float) (getHeight() - 3),
  34850. false));
  34851. }
  34852. void ArrowButton::buttonStateChanged()
  34853. {
  34854. offset = (isDown()) ? 1 : 0;
  34855. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34856. 0.3f, -1, 0);
  34857. }
  34858. END_JUCE_NAMESPACE
  34859. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34860. /*** Start of inlined file: juce_Button.cpp ***/
  34861. BEGIN_JUCE_NAMESPACE
  34862. class Button::RepeatTimer : public Timer
  34863. {
  34864. public:
  34865. RepeatTimer (Button& owner_) : owner (owner_) {}
  34866. void timerCallback() { owner.repeatTimerCallback(); }
  34867. private:
  34868. Button& owner;
  34869. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34870. };
  34871. Button::Button (const String& name)
  34872. : Component (name),
  34873. text (name),
  34874. buttonPressTime (0),
  34875. lastRepeatTime (0),
  34876. commandManagerToUse (0),
  34877. autoRepeatDelay (-1),
  34878. autoRepeatSpeed (0),
  34879. autoRepeatMinimumDelay (-1),
  34880. radioGroupId (0),
  34881. commandID (0),
  34882. connectedEdgeFlags (0),
  34883. buttonState (buttonNormal),
  34884. lastToggleState (false),
  34885. clickTogglesState (false),
  34886. needsToRelease (false),
  34887. needsRepainting (false),
  34888. isKeyDown (false),
  34889. triggerOnMouseDown (false),
  34890. generateTooltip (false)
  34891. {
  34892. setWantsKeyboardFocus (true);
  34893. isOn.addListener (this);
  34894. }
  34895. Button::~Button()
  34896. {
  34897. isOn.removeListener (this);
  34898. if (commandManagerToUse != 0)
  34899. commandManagerToUse->removeListener (this);
  34900. repeatTimer = 0;
  34901. clearShortcuts();
  34902. }
  34903. void Button::setButtonText (const String& newText)
  34904. {
  34905. if (text != newText)
  34906. {
  34907. text = newText;
  34908. repaint();
  34909. }
  34910. }
  34911. void Button::setTooltip (const String& newTooltip)
  34912. {
  34913. SettableTooltipClient::setTooltip (newTooltip);
  34914. generateTooltip = false;
  34915. }
  34916. const String Button::getTooltip()
  34917. {
  34918. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34919. {
  34920. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34921. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34922. for (int i = 0; i < keyPresses.size(); ++i)
  34923. {
  34924. const String key (keyPresses.getReference(i).getTextDescription());
  34925. tt << " [";
  34926. if (key.length() == 1)
  34927. tt << TRANS("shortcut") << ": '" << key << "']";
  34928. else
  34929. tt << key << ']';
  34930. }
  34931. return tt;
  34932. }
  34933. return SettableTooltipClient::getTooltip();
  34934. }
  34935. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34936. {
  34937. if (connectedEdgeFlags != connectedEdgeFlags_)
  34938. {
  34939. connectedEdgeFlags = connectedEdgeFlags_;
  34940. repaint();
  34941. }
  34942. }
  34943. void Button::setToggleState (const bool shouldBeOn,
  34944. const bool sendChangeNotification)
  34945. {
  34946. if (shouldBeOn != lastToggleState)
  34947. {
  34948. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34949. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34950. lastToggleState = shouldBeOn;
  34951. repaint();
  34952. if (sendChangeNotification)
  34953. {
  34954. Component::SafePointer<Component> deletionWatcher (this);
  34955. sendClickMessage (ModifierKeys());
  34956. if (deletionWatcher == 0)
  34957. return;
  34958. }
  34959. if (lastToggleState)
  34960. turnOffOtherButtonsInGroup (sendChangeNotification);
  34961. }
  34962. }
  34963. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34964. {
  34965. clickTogglesState = shouldToggle;
  34966. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34967. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34968. // it is that this button represents, and the button will update its state to reflect this
  34969. // in the applicationCommandListChanged() method.
  34970. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34971. }
  34972. bool Button::getClickingTogglesState() const throw()
  34973. {
  34974. return clickTogglesState;
  34975. }
  34976. void Button::valueChanged (Value& value)
  34977. {
  34978. if (value.refersToSameSourceAs (isOn))
  34979. setToggleState (isOn.getValue(), true);
  34980. }
  34981. void Button::setRadioGroupId (const int newGroupId)
  34982. {
  34983. if (radioGroupId != newGroupId)
  34984. {
  34985. radioGroupId = newGroupId;
  34986. if (lastToggleState)
  34987. turnOffOtherButtonsInGroup (true);
  34988. }
  34989. }
  34990. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34991. {
  34992. Component* const p = getParentComponent();
  34993. if (p != 0 && radioGroupId != 0)
  34994. {
  34995. Component::SafePointer<Component> deletionWatcher (this);
  34996. for (int i = p->getNumChildComponents(); --i >= 0;)
  34997. {
  34998. Component* const c = p->getChildComponent (i);
  34999. if (c != this)
  35000. {
  35001. Button* const b = dynamic_cast <Button*> (c);
  35002. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35003. {
  35004. b->setToggleState (false, sendChangeNotification);
  35005. if (deletionWatcher == 0)
  35006. return;
  35007. }
  35008. }
  35009. }
  35010. }
  35011. }
  35012. void Button::enablementChanged()
  35013. {
  35014. updateState();
  35015. repaint();
  35016. }
  35017. Button::ButtonState Button::updateState()
  35018. {
  35019. return updateState (isMouseOver (true), isMouseButtonDown());
  35020. }
  35021. Button::ButtonState Button::updateState (const bool over, const bool down)
  35022. {
  35023. ButtonState newState = buttonNormal;
  35024. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35025. {
  35026. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35027. newState = buttonDown;
  35028. else if (over)
  35029. newState = buttonOver;
  35030. }
  35031. setState (newState);
  35032. return newState;
  35033. }
  35034. void Button::setState (const ButtonState newState)
  35035. {
  35036. if (buttonState != newState)
  35037. {
  35038. buttonState = newState;
  35039. repaint();
  35040. if (buttonState == buttonDown)
  35041. {
  35042. buttonPressTime = Time::getApproximateMillisecondCounter();
  35043. lastRepeatTime = 0;
  35044. }
  35045. sendStateMessage();
  35046. }
  35047. }
  35048. bool Button::isDown() const throw()
  35049. {
  35050. return buttonState == buttonDown;
  35051. }
  35052. bool Button::isOver() const throw()
  35053. {
  35054. return buttonState != buttonNormal;
  35055. }
  35056. void Button::buttonStateChanged()
  35057. {
  35058. }
  35059. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35060. {
  35061. const uint32 now = Time::getApproximateMillisecondCounter();
  35062. return now > buttonPressTime ? now - buttonPressTime : 0;
  35063. }
  35064. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35065. {
  35066. triggerOnMouseDown = isTriggeredOnMouseDown;
  35067. }
  35068. void Button::clicked()
  35069. {
  35070. }
  35071. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35072. {
  35073. clicked();
  35074. }
  35075. static const int clickMessageId = 0x2f3f4f99;
  35076. void Button::triggerClick()
  35077. {
  35078. postCommandMessage (clickMessageId);
  35079. }
  35080. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35081. {
  35082. if (clickTogglesState)
  35083. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35084. sendClickMessage (modifiers);
  35085. }
  35086. void Button::flashButtonState()
  35087. {
  35088. if (isEnabled())
  35089. {
  35090. needsToRelease = true;
  35091. setState (buttonDown);
  35092. getRepeatTimer().startTimer (100);
  35093. }
  35094. }
  35095. void Button::handleCommandMessage (int commandId)
  35096. {
  35097. if (commandId == clickMessageId)
  35098. {
  35099. if (isEnabled())
  35100. {
  35101. flashButtonState();
  35102. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35103. }
  35104. }
  35105. else
  35106. {
  35107. Component::handleCommandMessage (commandId);
  35108. }
  35109. }
  35110. void Button::addButtonListener (ButtonListener* const newListener)
  35111. {
  35112. buttonListeners.add (newListener);
  35113. }
  35114. void Button::removeButtonListener (ButtonListener* const listener)
  35115. {
  35116. buttonListeners.remove (listener);
  35117. }
  35118. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35119. {
  35120. Component::BailOutChecker checker (this);
  35121. if (commandManagerToUse != 0 && commandID != 0)
  35122. {
  35123. ApplicationCommandTarget::InvocationInfo info (commandID);
  35124. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35125. info.originatingComponent = this;
  35126. commandManagerToUse->invoke (info, true);
  35127. }
  35128. clicked (modifiers);
  35129. if (! checker.shouldBailOut())
  35130. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35131. }
  35132. void Button::sendStateMessage()
  35133. {
  35134. Component::BailOutChecker checker (this);
  35135. buttonStateChanged();
  35136. if (! checker.shouldBailOut())
  35137. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35138. }
  35139. void Button::paint (Graphics& g)
  35140. {
  35141. if (needsToRelease && isEnabled())
  35142. {
  35143. needsToRelease = false;
  35144. needsRepainting = true;
  35145. }
  35146. paintButton (g, isOver(), isDown());
  35147. }
  35148. void Button::mouseEnter (const MouseEvent&)
  35149. {
  35150. updateState (true, false);
  35151. }
  35152. void Button::mouseExit (const MouseEvent&)
  35153. {
  35154. updateState (false, false);
  35155. }
  35156. void Button::mouseDown (const MouseEvent& e)
  35157. {
  35158. updateState (true, true);
  35159. if (isDown())
  35160. {
  35161. if (autoRepeatDelay >= 0)
  35162. getRepeatTimer().startTimer (autoRepeatDelay);
  35163. if (triggerOnMouseDown)
  35164. internalClickCallback (e.mods);
  35165. }
  35166. }
  35167. void Button::mouseUp (const MouseEvent& e)
  35168. {
  35169. const bool wasDown = isDown();
  35170. updateState (isMouseOver(), false);
  35171. if (wasDown && isOver() && ! triggerOnMouseDown)
  35172. internalClickCallback (e.mods);
  35173. }
  35174. void Button::mouseDrag (const MouseEvent&)
  35175. {
  35176. const ButtonState oldState = buttonState;
  35177. updateState (isMouseOver(), true);
  35178. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35179. getRepeatTimer().startTimer (autoRepeatSpeed);
  35180. }
  35181. void Button::focusGained (FocusChangeType)
  35182. {
  35183. updateState();
  35184. repaint();
  35185. }
  35186. void Button::focusLost (FocusChangeType)
  35187. {
  35188. updateState();
  35189. repaint();
  35190. }
  35191. void Button::visibilityChanged()
  35192. {
  35193. needsToRelease = false;
  35194. updateState();
  35195. }
  35196. void Button::parentHierarchyChanged()
  35197. {
  35198. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35199. if (newKeySource != keySource.getComponent())
  35200. {
  35201. if (keySource != 0)
  35202. keySource->removeKeyListener (this);
  35203. keySource = newKeySource;
  35204. if (keySource != 0)
  35205. keySource->addKeyListener (this);
  35206. }
  35207. }
  35208. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35209. const int commandID_,
  35210. const bool generateTooltip_)
  35211. {
  35212. commandID = commandID_;
  35213. generateTooltip = generateTooltip_;
  35214. if (commandManagerToUse != commandManagerToUse_)
  35215. {
  35216. if (commandManagerToUse != 0)
  35217. commandManagerToUse->removeListener (this);
  35218. commandManagerToUse = commandManagerToUse_;
  35219. if (commandManagerToUse != 0)
  35220. commandManagerToUse->addListener (this);
  35221. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35222. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35223. // it is that this button represents, and the button will update its state to reflect this
  35224. // in the applicationCommandListChanged() method.
  35225. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35226. }
  35227. if (commandManagerToUse != 0)
  35228. applicationCommandListChanged();
  35229. else
  35230. setEnabled (true);
  35231. }
  35232. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35233. {
  35234. if (info.commandID == commandID
  35235. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35236. {
  35237. flashButtonState();
  35238. }
  35239. }
  35240. void Button::applicationCommandListChanged()
  35241. {
  35242. if (commandManagerToUse != 0)
  35243. {
  35244. ApplicationCommandInfo info (0);
  35245. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35246. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35247. if (target != 0)
  35248. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35249. }
  35250. }
  35251. void Button::addShortcut (const KeyPress& key)
  35252. {
  35253. if (key.isValid())
  35254. {
  35255. jassert (! isRegisteredForShortcut (key)); // already registered!
  35256. shortcuts.add (key);
  35257. parentHierarchyChanged();
  35258. }
  35259. }
  35260. void Button::clearShortcuts()
  35261. {
  35262. shortcuts.clear();
  35263. parentHierarchyChanged();
  35264. }
  35265. bool Button::isShortcutPressed() const
  35266. {
  35267. if (! isCurrentlyBlockedByAnotherModalComponent())
  35268. {
  35269. for (int i = shortcuts.size(); --i >= 0;)
  35270. if (shortcuts.getReference(i).isCurrentlyDown())
  35271. return true;
  35272. }
  35273. return false;
  35274. }
  35275. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35276. {
  35277. for (int i = shortcuts.size(); --i >= 0;)
  35278. if (key == shortcuts.getReference(i))
  35279. return true;
  35280. return false;
  35281. }
  35282. bool Button::keyStateChanged (const bool, Component*)
  35283. {
  35284. if (! isEnabled())
  35285. return false;
  35286. const bool wasDown = isKeyDown;
  35287. isKeyDown = isShortcutPressed();
  35288. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35289. getRepeatTimer().startTimer (autoRepeatDelay);
  35290. updateState();
  35291. if (isEnabled() && wasDown && ! isKeyDown)
  35292. {
  35293. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35294. // (return immediately - this button may now have been deleted)
  35295. return true;
  35296. }
  35297. return wasDown || isKeyDown;
  35298. }
  35299. bool Button::keyPressed (const KeyPress&, Component*)
  35300. {
  35301. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35302. return isShortcutPressed();
  35303. }
  35304. bool Button::keyPressed (const KeyPress& key)
  35305. {
  35306. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35307. {
  35308. triggerClick();
  35309. return true;
  35310. }
  35311. return false;
  35312. }
  35313. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35314. const int repeatMillisecs,
  35315. const int minimumDelayInMillisecs) throw()
  35316. {
  35317. autoRepeatDelay = initialDelayMillisecs;
  35318. autoRepeatSpeed = repeatMillisecs;
  35319. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35320. }
  35321. void Button::repeatTimerCallback()
  35322. {
  35323. if (needsRepainting)
  35324. {
  35325. getRepeatTimer().stopTimer();
  35326. updateState();
  35327. needsRepainting = false;
  35328. }
  35329. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35330. {
  35331. int repeatSpeed = autoRepeatSpeed;
  35332. if (autoRepeatMinimumDelay >= 0)
  35333. {
  35334. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35335. timeHeldDown *= timeHeldDown;
  35336. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35337. }
  35338. repeatSpeed = jmax (1, repeatSpeed);
  35339. const uint32 now = Time::getMillisecondCounter();
  35340. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35341. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35342. repeatSpeed = jmax (1, repeatSpeed / 2);
  35343. lastRepeatTime = now;
  35344. getRepeatTimer().startTimer (repeatSpeed);
  35345. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35346. }
  35347. else if (! needsToRelease)
  35348. {
  35349. getRepeatTimer().stopTimer();
  35350. }
  35351. }
  35352. Button::RepeatTimer& Button::getRepeatTimer()
  35353. {
  35354. if (repeatTimer == 0)
  35355. repeatTimer = new RepeatTimer (*this);
  35356. return *repeatTimer;
  35357. }
  35358. END_JUCE_NAMESPACE
  35359. /*** End of inlined file: juce_Button.cpp ***/
  35360. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35361. BEGIN_JUCE_NAMESPACE
  35362. DrawableButton::DrawableButton (const String& name,
  35363. const DrawableButton::ButtonStyle buttonStyle)
  35364. : Button (name),
  35365. style (buttonStyle),
  35366. currentImage (0),
  35367. edgeIndent (3)
  35368. {
  35369. if (buttonStyle == ImageOnButtonBackground)
  35370. {
  35371. backgroundOff = Colour (0xffbbbbff);
  35372. backgroundOn = Colour (0xff3333ff);
  35373. }
  35374. else
  35375. {
  35376. backgroundOff = Colours::transparentBlack;
  35377. backgroundOn = Colour (0xaabbbbff);
  35378. }
  35379. }
  35380. DrawableButton::~DrawableButton()
  35381. {
  35382. }
  35383. void DrawableButton::setImages (const Drawable* normal,
  35384. const Drawable* over,
  35385. const Drawable* down,
  35386. const Drawable* disabled,
  35387. const Drawable* normalOn,
  35388. const Drawable* overOn,
  35389. const Drawable* downOn,
  35390. const Drawable* disabledOn)
  35391. {
  35392. jassert (normal != 0); // you really need to give it at least a normal image..
  35393. if (normal != 0) normalImage = normal->createCopy();
  35394. if (over != 0) overImage = over->createCopy();
  35395. if (down != 0) downImage = down->createCopy();
  35396. if (disabled != 0) disabledImage = disabled->createCopy();
  35397. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35398. if (overOn != 0) overImageOn = overOn->createCopy();
  35399. if (downOn != 0) downImageOn = downOn->createCopy();
  35400. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35401. buttonStateChanged();
  35402. }
  35403. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35404. {
  35405. if (style != newStyle)
  35406. {
  35407. style = newStyle;
  35408. buttonStateChanged();
  35409. }
  35410. }
  35411. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35412. const Colour& toggledOnColour)
  35413. {
  35414. if (backgroundOff != toggledOffColour
  35415. || backgroundOn != toggledOnColour)
  35416. {
  35417. backgroundOff = toggledOffColour;
  35418. backgroundOn = toggledOnColour;
  35419. repaint();
  35420. }
  35421. }
  35422. const Colour& DrawableButton::getBackgroundColour() const throw()
  35423. {
  35424. return getToggleState() ? backgroundOn
  35425. : backgroundOff;
  35426. }
  35427. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35428. {
  35429. edgeIndent = numPixelsIndent;
  35430. repaint();
  35431. resized();
  35432. }
  35433. void DrawableButton::resized()
  35434. {
  35435. Button::resized();
  35436. if (style == ImageRaw)
  35437. {
  35438. currentImage->setOriginWithOriginalSize (Point<float>());
  35439. }
  35440. else if (currentImage != 0)
  35441. {
  35442. Rectangle<int> imageSpace;
  35443. if (style == ImageOnButtonBackground)
  35444. {
  35445. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35446. }
  35447. else
  35448. {
  35449. const int textH = (style == ImageAboveTextLabel)
  35450. ? jmin (16, proportionOfHeight (0.25f))
  35451. : 0;
  35452. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35453. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35454. imageSpace.setBounds (indentX, indentY,
  35455. getWidth() - indentX * 2,
  35456. getHeight() - indentY * 2 - textH);
  35457. }
  35458. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35459. }
  35460. }
  35461. void DrawableButton::buttonStateChanged()
  35462. {
  35463. repaint();
  35464. Drawable* imageToDraw = 0;
  35465. float opacity = 1.0f;
  35466. if (isEnabled())
  35467. {
  35468. imageToDraw = getCurrentImage();
  35469. }
  35470. else
  35471. {
  35472. imageToDraw = getToggleState() ? disabledImageOn
  35473. : disabledImage;
  35474. if (imageToDraw == 0)
  35475. {
  35476. opacity = 0.4f;
  35477. imageToDraw = getNormalImage();
  35478. }
  35479. }
  35480. if (imageToDraw != currentImage)
  35481. {
  35482. removeChildComponent (currentImage);
  35483. currentImage = imageToDraw;
  35484. if (currentImage != 0)
  35485. {
  35486. addAndMakeVisible (currentImage);
  35487. DrawableButton::resized();
  35488. }
  35489. }
  35490. if (currentImage != 0)
  35491. currentImage->setAlpha (opacity);
  35492. }
  35493. void DrawableButton::paintButton (Graphics& g,
  35494. bool isMouseOverButton,
  35495. bool isButtonDown)
  35496. {
  35497. if (style == ImageOnButtonBackground)
  35498. {
  35499. getLookAndFeel().drawButtonBackground (g, *this,
  35500. getBackgroundColour(),
  35501. isMouseOverButton,
  35502. isButtonDown);
  35503. }
  35504. else
  35505. {
  35506. g.fillAll (getBackgroundColour());
  35507. const int textH = (style == ImageAboveTextLabel)
  35508. ? jmin (16, proportionOfHeight (0.25f))
  35509. : 0;
  35510. if (textH > 0)
  35511. {
  35512. g.setFont ((float) textH);
  35513. g.setColour (findColour (DrawableButton::textColourId)
  35514. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35515. g.drawFittedText (getButtonText(),
  35516. 2, getHeight() - textH - 1,
  35517. getWidth() - 4, textH,
  35518. Justification::centred, 1);
  35519. }
  35520. }
  35521. }
  35522. Drawable* DrawableButton::getCurrentImage() const throw()
  35523. {
  35524. if (isDown())
  35525. return getDownImage();
  35526. if (isOver())
  35527. return getOverImage();
  35528. return getNormalImage();
  35529. }
  35530. Drawable* DrawableButton::getNormalImage() const throw()
  35531. {
  35532. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35533. : normalImage;
  35534. }
  35535. Drawable* DrawableButton::getOverImage() const throw()
  35536. {
  35537. Drawable* d = normalImage;
  35538. if (getToggleState())
  35539. {
  35540. if (overImageOn != 0)
  35541. d = overImageOn;
  35542. else if (normalImageOn != 0)
  35543. d = normalImageOn;
  35544. else if (overImage != 0)
  35545. d = overImage;
  35546. }
  35547. else
  35548. {
  35549. if (overImage != 0)
  35550. d = overImage;
  35551. }
  35552. return d;
  35553. }
  35554. Drawable* DrawableButton::getDownImage() const throw()
  35555. {
  35556. Drawable* d = normalImage;
  35557. if (getToggleState())
  35558. {
  35559. if (downImageOn != 0)
  35560. d = downImageOn;
  35561. else if (overImageOn != 0)
  35562. d = overImageOn;
  35563. else if (normalImageOn != 0)
  35564. d = normalImageOn;
  35565. else if (downImage != 0)
  35566. d = downImage;
  35567. else
  35568. d = getOverImage();
  35569. }
  35570. else
  35571. {
  35572. if (downImage != 0)
  35573. d = downImage;
  35574. else
  35575. d = getOverImage();
  35576. }
  35577. return d;
  35578. }
  35579. END_JUCE_NAMESPACE
  35580. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35581. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35582. BEGIN_JUCE_NAMESPACE
  35583. HyperlinkButton::HyperlinkButton (const String& linkText,
  35584. const URL& linkURL)
  35585. : Button (linkText),
  35586. url (linkURL),
  35587. font (14.0f, Font::underlined),
  35588. resizeFont (true),
  35589. justification (Justification::centred)
  35590. {
  35591. setMouseCursor (MouseCursor::PointingHandCursor);
  35592. setTooltip (linkURL.toString (false));
  35593. }
  35594. HyperlinkButton::~HyperlinkButton()
  35595. {
  35596. }
  35597. void HyperlinkButton::setFont (const Font& newFont,
  35598. const bool resizeToMatchComponentHeight,
  35599. const Justification& justificationType)
  35600. {
  35601. font = newFont;
  35602. resizeFont = resizeToMatchComponentHeight;
  35603. justification = justificationType;
  35604. repaint();
  35605. }
  35606. void HyperlinkButton::setURL (const URL& newURL) throw()
  35607. {
  35608. url = newURL;
  35609. setTooltip (newURL.toString (false));
  35610. }
  35611. const Font HyperlinkButton::getFontToUse() const
  35612. {
  35613. Font f (font);
  35614. if (resizeFont)
  35615. f.setHeight (getHeight() * 0.7f);
  35616. return f;
  35617. }
  35618. void HyperlinkButton::changeWidthToFitText()
  35619. {
  35620. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35621. }
  35622. void HyperlinkButton::colourChanged()
  35623. {
  35624. repaint();
  35625. }
  35626. void HyperlinkButton::clicked()
  35627. {
  35628. if (url.isWellFormed())
  35629. url.launchInDefaultBrowser();
  35630. }
  35631. void HyperlinkButton::paintButton (Graphics& g,
  35632. bool isMouseOverButton,
  35633. bool isButtonDown)
  35634. {
  35635. const Colour textColour (findColour (textColourId));
  35636. if (isEnabled())
  35637. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35638. : textColour);
  35639. else
  35640. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35641. g.setFont (getFontToUse());
  35642. g.drawText (getButtonText(),
  35643. 2, 0, getWidth() - 2, getHeight(),
  35644. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35645. true);
  35646. }
  35647. END_JUCE_NAMESPACE
  35648. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35649. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35650. BEGIN_JUCE_NAMESPACE
  35651. ImageButton::ImageButton (const String& text_)
  35652. : Button (text_),
  35653. scaleImageToFit (true),
  35654. preserveProportions (true),
  35655. alphaThreshold (0),
  35656. imageX (0),
  35657. imageY (0),
  35658. imageW (0),
  35659. imageH (0),
  35660. normalImage (0),
  35661. overImage (0),
  35662. downImage (0)
  35663. {
  35664. }
  35665. ImageButton::~ImageButton()
  35666. {
  35667. }
  35668. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35669. const bool rescaleImagesWhenButtonSizeChanges,
  35670. const bool preserveImageProportions,
  35671. const Image& normalImage_,
  35672. const float imageOpacityWhenNormal,
  35673. const Colour& overlayColourWhenNormal,
  35674. const Image& overImage_,
  35675. const float imageOpacityWhenOver,
  35676. const Colour& overlayColourWhenOver,
  35677. const Image& downImage_,
  35678. const float imageOpacityWhenDown,
  35679. const Colour& overlayColourWhenDown,
  35680. const float hitTestAlphaThreshold)
  35681. {
  35682. normalImage = normalImage_;
  35683. overImage = overImage_;
  35684. downImage = downImage_;
  35685. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35686. {
  35687. imageW = normalImage.getWidth();
  35688. imageH = normalImage.getHeight();
  35689. setSize (imageW, imageH);
  35690. }
  35691. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35692. preserveProportions = preserveImageProportions;
  35693. normalOpacity = imageOpacityWhenNormal;
  35694. normalOverlay = overlayColourWhenNormal;
  35695. overOpacity = imageOpacityWhenOver;
  35696. overOverlay = overlayColourWhenOver;
  35697. downOpacity = imageOpacityWhenDown;
  35698. downOverlay = overlayColourWhenDown;
  35699. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35700. repaint();
  35701. }
  35702. const Image ImageButton::getCurrentImage() const
  35703. {
  35704. if (isDown() || getToggleState())
  35705. return getDownImage();
  35706. if (isOver())
  35707. return getOverImage();
  35708. return getNormalImage();
  35709. }
  35710. const Image ImageButton::getNormalImage() const
  35711. {
  35712. return normalImage;
  35713. }
  35714. const Image ImageButton::getOverImage() const
  35715. {
  35716. return overImage.isValid() ? overImage
  35717. : normalImage;
  35718. }
  35719. const Image ImageButton::getDownImage() const
  35720. {
  35721. return downImage.isValid() ? downImage
  35722. : getOverImage();
  35723. }
  35724. void ImageButton::paintButton (Graphics& g,
  35725. bool isMouseOverButton,
  35726. bool isButtonDown)
  35727. {
  35728. if (! isEnabled())
  35729. {
  35730. isMouseOverButton = false;
  35731. isButtonDown = false;
  35732. }
  35733. Image im (getCurrentImage());
  35734. if (im.isValid())
  35735. {
  35736. const int iw = im.getWidth();
  35737. const int ih = im.getHeight();
  35738. imageW = getWidth();
  35739. imageH = getHeight();
  35740. imageX = (imageW - iw) >> 1;
  35741. imageY = (imageH - ih) >> 1;
  35742. if (scaleImageToFit)
  35743. {
  35744. if (preserveProportions)
  35745. {
  35746. int newW, newH;
  35747. const float imRatio = ih / (float)iw;
  35748. const float destRatio = imageH / (float)imageW;
  35749. if (imRatio > destRatio)
  35750. {
  35751. newW = roundToInt (imageH / imRatio);
  35752. newH = imageH;
  35753. }
  35754. else
  35755. {
  35756. newW = imageW;
  35757. newH = roundToInt (imageW * imRatio);
  35758. }
  35759. imageX = (imageW - newW) / 2;
  35760. imageY = (imageH - newH) / 2;
  35761. imageW = newW;
  35762. imageH = newH;
  35763. }
  35764. else
  35765. {
  35766. imageX = 0;
  35767. imageY = 0;
  35768. }
  35769. }
  35770. if (! scaleImageToFit)
  35771. {
  35772. imageW = iw;
  35773. imageH = ih;
  35774. }
  35775. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35776. isButtonDown ? downOverlay
  35777. : (isMouseOverButton ? overOverlay
  35778. : normalOverlay),
  35779. isButtonDown ? downOpacity
  35780. : (isMouseOverButton ? overOpacity
  35781. : normalOpacity),
  35782. *this);
  35783. }
  35784. }
  35785. bool ImageButton::hitTest (int x, int y)
  35786. {
  35787. if (alphaThreshold == 0)
  35788. return true;
  35789. Image im (getCurrentImage());
  35790. return im.isNull() || (imageW > 0 && imageH > 0
  35791. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35792. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35793. }
  35794. END_JUCE_NAMESPACE
  35795. /*** End of inlined file: juce_ImageButton.cpp ***/
  35796. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35797. BEGIN_JUCE_NAMESPACE
  35798. ShapeButton::ShapeButton (const String& text_,
  35799. const Colour& normalColour_,
  35800. const Colour& overColour_,
  35801. const Colour& downColour_)
  35802. : Button (text_),
  35803. normalColour (normalColour_),
  35804. overColour (overColour_),
  35805. downColour (downColour_),
  35806. maintainShapeProportions (false),
  35807. outlineWidth (0.0f)
  35808. {
  35809. }
  35810. ShapeButton::~ShapeButton()
  35811. {
  35812. }
  35813. void ShapeButton::setColours (const Colour& newNormalColour,
  35814. const Colour& newOverColour,
  35815. const Colour& newDownColour)
  35816. {
  35817. normalColour = newNormalColour;
  35818. overColour = newOverColour;
  35819. downColour = newDownColour;
  35820. }
  35821. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35822. const float newOutlineWidth)
  35823. {
  35824. outlineColour = newOutlineColour;
  35825. outlineWidth = newOutlineWidth;
  35826. }
  35827. void ShapeButton::setShape (const Path& newShape,
  35828. const bool resizeNowToFitThisShape,
  35829. const bool maintainShapeProportions_,
  35830. const bool hasShadow)
  35831. {
  35832. shape = newShape;
  35833. maintainShapeProportions = maintainShapeProportions_;
  35834. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35835. setComponentEffect ((hasShadow) ? &shadow : 0);
  35836. if (resizeNowToFitThisShape)
  35837. {
  35838. Rectangle<float> bounds (shape.getBounds());
  35839. if (hasShadow)
  35840. bounds.expand (4.0f, 4.0f);
  35841. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35842. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35843. 1 + (int) (bounds.getHeight() + outlineWidth));
  35844. }
  35845. }
  35846. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35847. {
  35848. if (! isEnabled())
  35849. {
  35850. isMouseOverButton = false;
  35851. isButtonDown = false;
  35852. }
  35853. g.setColour ((isButtonDown) ? downColour
  35854. : (isMouseOverButton) ? overColour
  35855. : normalColour);
  35856. int w = getWidth();
  35857. int h = getHeight();
  35858. if (getComponentEffect() != 0)
  35859. {
  35860. w -= 4;
  35861. h -= 4;
  35862. }
  35863. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35864. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35865. w - offset - outlineWidth,
  35866. h - offset - outlineWidth,
  35867. maintainShapeProportions));
  35868. g.fillPath (shape, trans);
  35869. if (outlineWidth > 0.0f)
  35870. {
  35871. g.setColour (outlineColour);
  35872. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35873. }
  35874. }
  35875. END_JUCE_NAMESPACE
  35876. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35877. /*** Start of inlined file: juce_TextButton.cpp ***/
  35878. BEGIN_JUCE_NAMESPACE
  35879. TextButton::TextButton (const String& name,
  35880. const String& toolTip)
  35881. : Button (name)
  35882. {
  35883. setTooltip (toolTip);
  35884. }
  35885. TextButton::~TextButton()
  35886. {
  35887. }
  35888. void TextButton::paintButton (Graphics& g,
  35889. bool isMouseOverButton,
  35890. bool isButtonDown)
  35891. {
  35892. getLookAndFeel().drawButtonBackground (g, *this,
  35893. findColour (getToggleState() ? buttonOnColourId
  35894. : buttonColourId),
  35895. isMouseOverButton,
  35896. isButtonDown);
  35897. getLookAndFeel().drawButtonText (g, *this,
  35898. isMouseOverButton,
  35899. isButtonDown);
  35900. }
  35901. void TextButton::colourChanged()
  35902. {
  35903. repaint();
  35904. }
  35905. const Font TextButton::getFont()
  35906. {
  35907. return Font (jmin (15.0f, getHeight() * 0.6f));
  35908. }
  35909. void TextButton::changeWidthToFitText (const int newHeight)
  35910. {
  35911. if (newHeight >= 0)
  35912. setSize (jmax (1, getWidth()), newHeight);
  35913. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35914. getHeight());
  35915. }
  35916. END_JUCE_NAMESPACE
  35917. /*** End of inlined file: juce_TextButton.cpp ***/
  35918. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35919. BEGIN_JUCE_NAMESPACE
  35920. ToggleButton::ToggleButton (const String& buttonText)
  35921. : Button (buttonText)
  35922. {
  35923. setClickingTogglesState (true);
  35924. }
  35925. ToggleButton::~ToggleButton()
  35926. {
  35927. }
  35928. void ToggleButton::paintButton (Graphics& g,
  35929. bool isMouseOverButton,
  35930. bool isButtonDown)
  35931. {
  35932. getLookAndFeel().drawToggleButton (g, *this,
  35933. isMouseOverButton,
  35934. isButtonDown);
  35935. }
  35936. void ToggleButton::changeWidthToFitText()
  35937. {
  35938. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35939. }
  35940. void ToggleButton::colourChanged()
  35941. {
  35942. repaint();
  35943. }
  35944. END_JUCE_NAMESPACE
  35945. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35946. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35947. BEGIN_JUCE_NAMESPACE
  35948. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35949. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35950. : ToolbarItemComponent (itemId_, buttonText, true),
  35951. normalImage (normalImage_),
  35952. toggledOnImage (toggledOnImage_),
  35953. currentImage (0)
  35954. {
  35955. jassert (normalImage_ != 0);
  35956. }
  35957. ToolbarButton::~ToolbarButton()
  35958. {
  35959. }
  35960. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35961. {
  35962. preferredSize = minSize = maxSize = toolbarDepth;
  35963. return true;
  35964. }
  35965. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35966. {
  35967. }
  35968. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35969. {
  35970. buttonStateChanged();
  35971. }
  35972. void ToolbarButton::updateDrawable()
  35973. {
  35974. if (currentImage != 0)
  35975. {
  35976. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35977. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35978. }
  35979. }
  35980. void ToolbarButton::resized()
  35981. {
  35982. ToolbarItemComponent::resized();
  35983. updateDrawable();
  35984. }
  35985. void ToolbarButton::enablementChanged()
  35986. {
  35987. ToolbarItemComponent::enablementChanged();
  35988. updateDrawable();
  35989. }
  35990. void ToolbarButton::buttonStateChanged()
  35991. {
  35992. Drawable* d = normalImage;
  35993. if (getToggleState() && toggledOnImage != 0)
  35994. d = toggledOnImage;
  35995. if (d != currentImage)
  35996. {
  35997. removeChildComponent (currentImage);
  35998. currentImage = d;
  35999. if (d != 0)
  36000. {
  36001. enablementChanged();
  36002. addAndMakeVisible (d);
  36003. updateDrawable();
  36004. }
  36005. }
  36006. }
  36007. END_JUCE_NAMESPACE
  36008. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36009. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36010. BEGIN_JUCE_NAMESPACE
  36011. class CodeDocumentLine
  36012. {
  36013. public:
  36014. CodeDocumentLine (const juce_wchar* const line_,
  36015. const int lineLength_,
  36016. const int numNewLineChars,
  36017. const int lineStartInFile_)
  36018. : line (line_, lineLength_),
  36019. lineStartInFile (lineStartInFile_),
  36020. lineLength (lineLength_),
  36021. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36022. {
  36023. }
  36024. ~CodeDocumentLine()
  36025. {
  36026. }
  36027. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36028. {
  36029. const juce_wchar* const t = text;
  36030. int pos = 0;
  36031. while (t [pos] != 0)
  36032. {
  36033. const int startOfLine = pos;
  36034. int numNewLineChars = 0;
  36035. while (t[pos] != 0)
  36036. {
  36037. if (t[pos] == '\r')
  36038. {
  36039. ++numNewLineChars;
  36040. ++pos;
  36041. if (t[pos] == '\n')
  36042. {
  36043. ++numNewLineChars;
  36044. ++pos;
  36045. }
  36046. break;
  36047. }
  36048. if (t[pos] == '\n')
  36049. {
  36050. ++numNewLineChars;
  36051. ++pos;
  36052. break;
  36053. }
  36054. ++pos;
  36055. }
  36056. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36057. numNewLineChars, startOfLine));
  36058. }
  36059. jassert (pos == text.length());
  36060. }
  36061. bool endsWithLineBreak() const throw()
  36062. {
  36063. return lineLengthWithoutNewLines != lineLength;
  36064. }
  36065. void updateLength() throw()
  36066. {
  36067. lineLengthWithoutNewLines = lineLength = line.length();
  36068. while (lineLengthWithoutNewLines > 0
  36069. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36070. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36071. {
  36072. --lineLengthWithoutNewLines;
  36073. }
  36074. }
  36075. String line;
  36076. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36077. };
  36078. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36079. : document (document_),
  36080. currentLine (document_->lines[0]),
  36081. line (0),
  36082. position (0)
  36083. {
  36084. }
  36085. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36086. : document (other.document),
  36087. currentLine (other.currentLine),
  36088. line (other.line),
  36089. position (other.position)
  36090. {
  36091. }
  36092. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36093. {
  36094. document = other.document;
  36095. currentLine = other.currentLine;
  36096. line = other.line;
  36097. position = other.position;
  36098. return *this;
  36099. }
  36100. CodeDocument::Iterator::~Iterator() throw()
  36101. {
  36102. }
  36103. juce_wchar CodeDocument::Iterator::nextChar()
  36104. {
  36105. if (currentLine == 0)
  36106. return 0;
  36107. jassert (currentLine == document->lines.getUnchecked (line));
  36108. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36109. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36110. {
  36111. ++line;
  36112. currentLine = document->lines [line];
  36113. }
  36114. return result;
  36115. }
  36116. void CodeDocument::Iterator::skip()
  36117. {
  36118. if (currentLine != 0)
  36119. {
  36120. jassert (currentLine == document->lines.getUnchecked (line));
  36121. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36122. {
  36123. ++line;
  36124. currentLine = document->lines [line];
  36125. }
  36126. }
  36127. }
  36128. void CodeDocument::Iterator::skipToEndOfLine()
  36129. {
  36130. if (currentLine != 0)
  36131. {
  36132. jassert (currentLine == document->lines.getUnchecked (line));
  36133. ++line;
  36134. currentLine = document->lines [line];
  36135. if (currentLine != 0)
  36136. position = currentLine->lineStartInFile;
  36137. else
  36138. position = document->getNumCharacters();
  36139. }
  36140. }
  36141. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36142. {
  36143. if (currentLine == 0)
  36144. return 0;
  36145. jassert (currentLine == document->lines.getUnchecked (line));
  36146. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36147. }
  36148. void CodeDocument::Iterator::skipWhitespace()
  36149. {
  36150. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36151. skip();
  36152. }
  36153. bool CodeDocument::Iterator::isEOF() const throw()
  36154. {
  36155. return currentLine == 0;
  36156. }
  36157. CodeDocument::Position::Position() throw()
  36158. : owner (0), characterPos (0), line (0),
  36159. indexInLine (0), positionMaintained (false)
  36160. {
  36161. }
  36162. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36163. const int line_, const int indexInLine_) throw()
  36164. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36165. characterPos (0), line (line_),
  36166. indexInLine (indexInLine_), positionMaintained (false)
  36167. {
  36168. setLineAndIndex (line_, indexInLine_);
  36169. }
  36170. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36171. const int characterPos_) throw()
  36172. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36173. positionMaintained (false)
  36174. {
  36175. setPosition (characterPos_);
  36176. }
  36177. CodeDocument::Position::Position (const Position& other) throw()
  36178. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36179. indexInLine (other.indexInLine), positionMaintained (false)
  36180. {
  36181. jassert (*this == other);
  36182. }
  36183. CodeDocument::Position::~Position()
  36184. {
  36185. setPositionMaintained (false);
  36186. }
  36187. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36188. {
  36189. if (this != &other)
  36190. {
  36191. const bool wasPositionMaintained = positionMaintained;
  36192. if (owner != other.owner)
  36193. setPositionMaintained (false);
  36194. owner = other.owner;
  36195. line = other.line;
  36196. indexInLine = other.indexInLine;
  36197. characterPos = other.characterPos;
  36198. setPositionMaintained (wasPositionMaintained);
  36199. jassert (*this == other);
  36200. }
  36201. return *this;
  36202. }
  36203. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36204. {
  36205. jassert ((characterPos == other.characterPos)
  36206. == (line == other.line && indexInLine == other.indexInLine));
  36207. return characterPos == other.characterPos
  36208. && line == other.line
  36209. && indexInLine == other.indexInLine
  36210. && owner == other.owner;
  36211. }
  36212. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36213. {
  36214. return ! operator== (other);
  36215. }
  36216. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36217. {
  36218. jassert (owner != 0);
  36219. if (owner->lines.size() == 0)
  36220. {
  36221. line = 0;
  36222. indexInLine = 0;
  36223. characterPos = 0;
  36224. }
  36225. else
  36226. {
  36227. if (newLine >= owner->lines.size())
  36228. {
  36229. line = owner->lines.size() - 1;
  36230. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36231. jassert (l != 0);
  36232. indexInLine = l->lineLengthWithoutNewLines;
  36233. characterPos = l->lineStartInFile + indexInLine;
  36234. }
  36235. else
  36236. {
  36237. line = jmax (0, newLine);
  36238. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36239. jassert (l != 0);
  36240. if (l->lineLengthWithoutNewLines > 0)
  36241. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36242. else
  36243. indexInLine = 0;
  36244. characterPos = l->lineStartInFile + indexInLine;
  36245. }
  36246. }
  36247. }
  36248. void CodeDocument::Position::setPosition (const int newPosition)
  36249. {
  36250. jassert (owner != 0);
  36251. line = 0;
  36252. indexInLine = 0;
  36253. characterPos = 0;
  36254. if (newPosition > 0)
  36255. {
  36256. int lineStart = 0;
  36257. int lineEnd = owner->lines.size();
  36258. for (;;)
  36259. {
  36260. if (lineEnd - lineStart < 4)
  36261. {
  36262. for (int i = lineStart; i < lineEnd; ++i)
  36263. {
  36264. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36265. int index = newPosition - l->lineStartInFile;
  36266. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36267. {
  36268. line = i;
  36269. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36270. characterPos = l->lineStartInFile + indexInLine;
  36271. }
  36272. }
  36273. break;
  36274. }
  36275. else
  36276. {
  36277. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36278. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36279. if (newPosition >= mid->lineStartInFile)
  36280. lineStart = midIndex;
  36281. else
  36282. lineEnd = midIndex;
  36283. }
  36284. }
  36285. }
  36286. }
  36287. void CodeDocument::Position::moveBy (int characterDelta)
  36288. {
  36289. jassert (owner != 0);
  36290. if (characterDelta == 1)
  36291. {
  36292. setPosition (getPosition());
  36293. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36294. if (line < owner->lines.size())
  36295. {
  36296. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36297. if (indexInLine + characterDelta < l->lineLength
  36298. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36299. ++characterDelta;
  36300. }
  36301. }
  36302. setPosition (characterPos + characterDelta);
  36303. }
  36304. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36305. {
  36306. CodeDocument::Position p (*this);
  36307. p.moveBy (characterDelta);
  36308. return p;
  36309. }
  36310. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36311. {
  36312. CodeDocument::Position p (*this);
  36313. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36314. return p;
  36315. }
  36316. const juce_wchar CodeDocument::Position::getCharacter() const
  36317. {
  36318. const CodeDocumentLine* const l = owner->lines [line];
  36319. return l == 0 ? 0 : l->line [getIndexInLine()];
  36320. }
  36321. const String CodeDocument::Position::getLineText() const
  36322. {
  36323. const CodeDocumentLine* const l = owner->lines [line];
  36324. return l == 0 ? String::empty : l->line;
  36325. }
  36326. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36327. {
  36328. if (isMaintained != positionMaintained)
  36329. {
  36330. positionMaintained = isMaintained;
  36331. if (owner != 0)
  36332. {
  36333. if (isMaintained)
  36334. {
  36335. jassert (! owner->positionsToMaintain.contains (this));
  36336. owner->positionsToMaintain.add (this);
  36337. }
  36338. else
  36339. {
  36340. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36341. jassert (owner->positionsToMaintain.contains (this));
  36342. owner->positionsToMaintain.removeValue (this);
  36343. }
  36344. }
  36345. }
  36346. }
  36347. CodeDocument::CodeDocument()
  36348. : undoManager (std::numeric_limits<int>::max(), 10000),
  36349. currentActionIndex (0),
  36350. indexOfSavedState (-1),
  36351. maximumLineLength (-1),
  36352. newLineChars ("\r\n")
  36353. {
  36354. }
  36355. CodeDocument::~CodeDocument()
  36356. {
  36357. }
  36358. const String CodeDocument::getAllContent() const
  36359. {
  36360. return getTextBetween (Position (this, 0),
  36361. Position (this, lines.size(), 0));
  36362. }
  36363. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36364. {
  36365. if (end.getPosition() <= start.getPosition())
  36366. return String::empty;
  36367. const int startLine = start.getLineNumber();
  36368. const int endLine = end.getLineNumber();
  36369. if (startLine == endLine)
  36370. {
  36371. CodeDocumentLine* const line = lines [startLine];
  36372. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36373. }
  36374. String result;
  36375. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36376. String::Concatenator concatenator (result);
  36377. const int maxLine = jmin (lines.size() - 1, endLine);
  36378. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36379. {
  36380. const CodeDocumentLine* line = lines.getUnchecked(i);
  36381. int len = line->lineLength;
  36382. if (i == startLine)
  36383. {
  36384. const int index = start.getIndexInLine();
  36385. concatenator.append (line->line.substring (index, len));
  36386. }
  36387. else if (i == endLine)
  36388. {
  36389. len = end.getIndexInLine();
  36390. concatenator.append (line->line.substring (0, len));
  36391. }
  36392. else
  36393. {
  36394. concatenator.append (line->line);
  36395. }
  36396. }
  36397. return result;
  36398. }
  36399. int CodeDocument::getNumCharacters() const throw()
  36400. {
  36401. const CodeDocumentLine* const lastLine = lines.getLast();
  36402. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36403. }
  36404. const String CodeDocument::getLine (const int lineIndex) const throw()
  36405. {
  36406. const CodeDocumentLine* const line = lines [lineIndex];
  36407. return (line == 0) ? String::empty : line->line;
  36408. }
  36409. int CodeDocument::getMaximumLineLength() throw()
  36410. {
  36411. if (maximumLineLength < 0)
  36412. {
  36413. maximumLineLength = 0;
  36414. for (int i = lines.size(); --i >= 0;)
  36415. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36416. }
  36417. return maximumLineLength;
  36418. }
  36419. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36420. {
  36421. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36422. }
  36423. void CodeDocument::insertText (const Position& position, const String& text)
  36424. {
  36425. insert (text, position.getPosition(), true);
  36426. }
  36427. void CodeDocument::replaceAllContent (const String& newContent)
  36428. {
  36429. remove (0, getNumCharacters(), true);
  36430. insert (newContent, 0, true);
  36431. }
  36432. bool CodeDocument::loadFromStream (InputStream& stream)
  36433. {
  36434. replaceAllContent (stream.readEntireStreamAsString());
  36435. setSavePoint();
  36436. clearUndoHistory();
  36437. return true;
  36438. }
  36439. bool CodeDocument::writeToStream (OutputStream& stream)
  36440. {
  36441. for (int i = 0; i < lines.size(); ++i)
  36442. {
  36443. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36444. const char* utf8 = temp.toUTF8();
  36445. if (! stream.write (utf8, (int) strlen (utf8)))
  36446. return false;
  36447. }
  36448. return true;
  36449. }
  36450. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36451. {
  36452. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36453. newLineChars = newLine;
  36454. }
  36455. void CodeDocument::newTransaction()
  36456. {
  36457. undoManager.beginNewTransaction (String::empty);
  36458. }
  36459. void CodeDocument::undo()
  36460. {
  36461. newTransaction();
  36462. undoManager.undo();
  36463. }
  36464. void CodeDocument::redo()
  36465. {
  36466. undoManager.redo();
  36467. }
  36468. void CodeDocument::clearUndoHistory()
  36469. {
  36470. undoManager.clearUndoHistory();
  36471. }
  36472. void CodeDocument::setSavePoint() throw()
  36473. {
  36474. indexOfSavedState = currentActionIndex;
  36475. }
  36476. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36477. {
  36478. return currentActionIndex != indexOfSavedState;
  36479. }
  36480. namespace CodeDocumentHelpers
  36481. {
  36482. int getCharacterType (const juce_wchar character) throw()
  36483. {
  36484. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36485. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36486. }
  36487. }
  36488. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36489. {
  36490. Position p (position);
  36491. const int maxDistance = 256;
  36492. int i = 0;
  36493. while (i < maxDistance
  36494. && CharacterFunctions::isWhitespace (p.getCharacter())
  36495. && (i == 0 || (p.getCharacter() != '\n'
  36496. && p.getCharacter() != '\r')))
  36497. {
  36498. ++i;
  36499. p.moveBy (1);
  36500. }
  36501. if (i == 0)
  36502. {
  36503. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36504. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36505. {
  36506. ++i;
  36507. p.moveBy (1);
  36508. }
  36509. while (i < maxDistance
  36510. && CharacterFunctions::isWhitespace (p.getCharacter())
  36511. && (i == 0 || (p.getCharacter() != '\n'
  36512. && p.getCharacter() != '\r')))
  36513. {
  36514. ++i;
  36515. p.moveBy (1);
  36516. }
  36517. }
  36518. return p;
  36519. }
  36520. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36521. {
  36522. Position p (position);
  36523. const int maxDistance = 256;
  36524. int i = 0;
  36525. bool stoppedAtLineStart = false;
  36526. while (i < maxDistance)
  36527. {
  36528. const juce_wchar c = p.movedBy (-1).getCharacter();
  36529. if (c == '\r' || c == '\n')
  36530. {
  36531. stoppedAtLineStart = true;
  36532. if (i > 0)
  36533. break;
  36534. }
  36535. if (! CharacterFunctions::isWhitespace (c))
  36536. break;
  36537. p.moveBy (-1);
  36538. ++i;
  36539. }
  36540. if (i < maxDistance && ! stoppedAtLineStart)
  36541. {
  36542. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36543. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36544. {
  36545. p.moveBy (-1);
  36546. ++i;
  36547. }
  36548. }
  36549. return p;
  36550. }
  36551. void CodeDocument::checkLastLineStatus()
  36552. {
  36553. while (lines.size() > 0
  36554. && lines.getLast()->lineLength == 0
  36555. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36556. {
  36557. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36558. lines.removeLast();
  36559. }
  36560. const CodeDocumentLine* const lastLine = lines.getLast();
  36561. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36562. {
  36563. // check that there's an empty line at the end if the preceding one ends in a newline..
  36564. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36565. }
  36566. }
  36567. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36568. {
  36569. listeners.add (listener);
  36570. }
  36571. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36572. {
  36573. listeners.remove (listener);
  36574. }
  36575. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36576. {
  36577. Position startPos (this, startLine, 0);
  36578. Position endPos (this, endLine, 0);
  36579. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36580. }
  36581. class CodeDocumentInsertAction : public UndoableAction
  36582. {
  36583. public:
  36584. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36585. : owner (owner_),
  36586. text (text_),
  36587. insertPos (insertPos_)
  36588. {
  36589. }
  36590. bool perform()
  36591. {
  36592. owner.currentActionIndex++;
  36593. owner.insert (text, insertPos, false);
  36594. return true;
  36595. }
  36596. bool undo()
  36597. {
  36598. owner.currentActionIndex--;
  36599. owner.remove (insertPos, insertPos + text.length(), false);
  36600. return true;
  36601. }
  36602. int getSizeInUnits() { return text.length() + 32; }
  36603. private:
  36604. CodeDocument& owner;
  36605. const String text;
  36606. int insertPos;
  36607. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36608. };
  36609. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36610. {
  36611. if (text.isEmpty())
  36612. return;
  36613. if (undoable)
  36614. {
  36615. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36616. }
  36617. else
  36618. {
  36619. Position pos (this, insertPos);
  36620. const int firstAffectedLine = pos.getLineNumber();
  36621. int lastAffectedLine = firstAffectedLine + 1;
  36622. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36623. String textInsideOriginalLine (text);
  36624. if (firstLine != 0)
  36625. {
  36626. const int index = pos.getIndexInLine();
  36627. textInsideOriginalLine = firstLine->line.substring (0, index)
  36628. + textInsideOriginalLine
  36629. + firstLine->line.substring (index);
  36630. }
  36631. maximumLineLength = -1;
  36632. Array <CodeDocumentLine*> newLines;
  36633. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36634. jassert (newLines.size() > 0);
  36635. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36636. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36637. lines.set (firstAffectedLine, newFirstLine);
  36638. if (newLines.size() > 1)
  36639. {
  36640. for (int i = 1; i < newLines.size(); ++i)
  36641. {
  36642. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36643. lines.insert (firstAffectedLine + i, l);
  36644. }
  36645. lastAffectedLine = lines.size();
  36646. }
  36647. int i, lineStart = newFirstLine->lineStartInFile;
  36648. for (i = firstAffectedLine; i < lines.size(); ++i)
  36649. {
  36650. CodeDocumentLine* const l = lines.getUnchecked (i);
  36651. l->lineStartInFile = lineStart;
  36652. lineStart += l->lineLength;
  36653. }
  36654. checkLastLineStatus();
  36655. const int newTextLength = text.length();
  36656. for (i = 0; i < positionsToMaintain.size(); ++i)
  36657. {
  36658. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36659. if (p->getPosition() >= insertPos)
  36660. p->setPosition (p->getPosition() + newTextLength);
  36661. }
  36662. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36663. }
  36664. }
  36665. class CodeDocumentDeleteAction : public UndoableAction
  36666. {
  36667. public:
  36668. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36669. : owner (owner_),
  36670. startPos (startPos_),
  36671. endPos (endPos_)
  36672. {
  36673. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36674. CodeDocument::Position (&owner, endPos));
  36675. }
  36676. bool perform()
  36677. {
  36678. owner.currentActionIndex++;
  36679. owner.remove (startPos, endPos, false);
  36680. return true;
  36681. }
  36682. bool undo()
  36683. {
  36684. owner.currentActionIndex--;
  36685. owner.insert (removedText, startPos, false);
  36686. return true;
  36687. }
  36688. int getSizeInUnits() { return removedText.length() + 32; }
  36689. private:
  36690. CodeDocument& owner;
  36691. int startPos, endPos;
  36692. String removedText;
  36693. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36694. };
  36695. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36696. {
  36697. if (endPos <= startPos)
  36698. return;
  36699. if (undoable)
  36700. {
  36701. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36702. }
  36703. else
  36704. {
  36705. Position startPosition (this, startPos);
  36706. Position endPosition (this, endPos);
  36707. maximumLineLength = -1;
  36708. const int firstAffectedLine = startPosition.getLineNumber();
  36709. const int endLine = endPosition.getLineNumber();
  36710. int lastAffectedLine = firstAffectedLine + 1;
  36711. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36712. if (firstAffectedLine == endLine)
  36713. {
  36714. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36715. + firstLine->line.substring (endPosition.getIndexInLine());
  36716. firstLine->updateLength();
  36717. }
  36718. else
  36719. {
  36720. lastAffectedLine = lines.size();
  36721. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36722. jassert (lastLine != 0);
  36723. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36724. + lastLine->line.substring (endPosition.getIndexInLine());
  36725. firstLine->updateLength();
  36726. int numLinesToRemove = endLine - firstAffectedLine;
  36727. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36728. }
  36729. int i;
  36730. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36731. {
  36732. CodeDocumentLine* const l = lines.getUnchecked (i);
  36733. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36734. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36735. }
  36736. checkLastLineStatus();
  36737. const int totalChars = getNumCharacters();
  36738. for (i = 0; i < positionsToMaintain.size(); ++i)
  36739. {
  36740. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36741. if (p->getPosition() > startPosition.getPosition())
  36742. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36743. if (p->getPosition() > totalChars)
  36744. p->setPosition (totalChars);
  36745. }
  36746. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36747. }
  36748. }
  36749. END_JUCE_NAMESPACE
  36750. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36751. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36752. BEGIN_JUCE_NAMESPACE
  36753. class CodeEditorComponent::CaretComponent : public Component,
  36754. public Timer
  36755. {
  36756. public:
  36757. CaretComponent (CodeEditorComponent& owner_)
  36758. : owner (owner_)
  36759. {
  36760. setAlwaysOnTop (true);
  36761. setInterceptsMouseClicks (false, false);
  36762. }
  36763. void paint (Graphics& g)
  36764. {
  36765. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36766. }
  36767. void timerCallback()
  36768. {
  36769. setVisible (shouldBeShown() && ! isVisible());
  36770. }
  36771. void updatePosition()
  36772. {
  36773. startTimer (400);
  36774. setVisible (shouldBeShown());
  36775. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36776. }
  36777. private:
  36778. CodeEditorComponent& owner;
  36779. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36780. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36781. };
  36782. class CodeEditorComponent::CodeEditorLine
  36783. {
  36784. public:
  36785. CodeEditorLine() throw()
  36786. : highlightColumnStart (0), highlightColumnEnd (0)
  36787. {
  36788. }
  36789. bool update (CodeDocument& document, int lineNum,
  36790. CodeDocument::Iterator& source,
  36791. CodeTokeniser* analyser, const int spacesPerTab,
  36792. const CodeDocument::Position& selectionStart,
  36793. const CodeDocument::Position& selectionEnd)
  36794. {
  36795. Array <SyntaxToken> newTokens;
  36796. newTokens.ensureStorageAllocated (8);
  36797. if (analyser == 0)
  36798. {
  36799. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36800. }
  36801. else if (lineNum < document.getNumLines())
  36802. {
  36803. const CodeDocument::Position pos (&document, lineNum, 0);
  36804. createTokens (pos.getPosition(), pos.getLineText(),
  36805. source, analyser, newTokens);
  36806. }
  36807. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36808. int newHighlightStart = 0;
  36809. int newHighlightEnd = 0;
  36810. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36811. {
  36812. const String line (document.getLine (lineNum));
  36813. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36814. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36815. line, spacesPerTab);
  36816. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36817. line, spacesPerTab);
  36818. }
  36819. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36820. {
  36821. highlightColumnStart = newHighlightStart;
  36822. highlightColumnEnd = newHighlightEnd;
  36823. }
  36824. else
  36825. {
  36826. if (tokens.size() == newTokens.size())
  36827. {
  36828. bool allTheSame = true;
  36829. for (int i = newTokens.size(); --i >= 0;)
  36830. {
  36831. if (tokens.getReference(i) != newTokens.getReference(i))
  36832. {
  36833. allTheSame = false;
  36834. break;
  36835. }
  36836. }
  36837. if (allTheSame)
  36838. return false;
  36839. }
  36840. }
  36841. tokens.swapWithArray (newTokens);
  36842. return true;
  36843. }
  36844. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36845. float x, const int y, const int baselineOffset, const int lineHeight,
  36846. const Colour& highlightColour) const
  36847. {
  36848. if (highlightColumnStart < highlightColumnEnd)
  36849. {
  36850. g.setColour (highlightColour);
  36851. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36852. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36853. }
  36854. int lastType = std::numeric_limits<int>::min();
  36855. for (int i = 0; i < tokens.size(); ++i)
  36856. {
  36857. SyntaxToken& token = tokens.getReference(i);
  36858. if (lastType != token.tokenType)
  36859. {
  36860. lastType = token.tokenType;
  36861. g.setColour (owner.getColourForTokenType (lastType));
  36862. }
  36863. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36864. if (i < tokens.size() - 1)
  36865. {
  36866. if (token.width < 0)
  36867. token.width = font.getStringWidthFloat (token.text);
  36868. x += token.width;
  36869. }
  36870. }
  36871. }
  36872. private:
  36873. struct SyntaxToken
  36874. {
  36875. SyntaxToken (const String& text_, const int type) throw()
  36876. : text (text_), tokenType (type), width (-1.0f)
  36877. {
  36878. }
  36879. bool operator!= (const SyntaxToken& other) const throw()
  36880. {
  36881. return text != other.text || tokenType != other.tokenType;
  36882. }
  36883. String text;
  36884. int tokenType;
  36885. float width;
  36886. };
  36887. Array <SyntaxToken> tokens;
  36888. int highlightColumnStart, highlightColumnEnd;
  36889. static void createTokens (int startPosition, const String& lineText,
  36890. CodeDocument::Iterator& source,
  36891. CodeTokeniser* analyser,
  36892. Array <SyntaxToken>& newTokens)
  36893. {
  36894. CodeDocument::Iterator lastIterator (source);
  36895. const int lineLength = lineText.length();
  36896. for (;;)
  36897. {
  36898. int tokenType = analyser->readNextToken (source);
  36899. int tokenStart = lastIterator.getPosition();
  36900. int tokenEnd = source.getPosition();
  36901. if (tokenEnd <= tokenStart)
  36902. break;
  36903. tokenEnd -= startPosition;
  36904. if (tokenEnd > 0)
  36905. {
  36906. tokenStart -= startPosition;
  36907. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36908. tokenType));
  36909. if (tokenEnd >= lineLength)
  36910. break;
  36911. }
  36912. lastIterator = source;
  36913. }
  36914. source = lastIterator;
  36915. }
  36916. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36917. {
  36918. int x = 0;
  36919. for (int i = 0; i < tokens.size(); ++i)
  36920. {
  36921. SyntaxToken& t = tokens.getReference(i);
  36922. for (;;)
  36923. {
  36924. int tabPos = t.text.indexOfChar ('\t');
  36925. if (tabPos < 0)
  36926. break;
  36927. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36928. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36929. }
  36930. x += t.text.length();
  36931. }
  36932. }
  36933. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36934. {
  36935. jassert (index <= line.length());
  36936. int col = 0;
  36937. for (int i = 0; i < index; ++i)
  36938. {
  36939. if (line[i] != '\t')
  36940. ++col;
  36941. else
  36942. col += spacesPerTab - (col % spacesPerTab);
  36943. }
  36944. return col;
  36945. }
  36946. };
  36947. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36948. CodeTokeniser* const codeTokeniser_)
  36949. : document (document_),
  36950. firstLineOnScreen (0),
  36951. gutter (5),
  36952. spacesPerTab (4),
  36953. lineHeight (0),
  36954. linesOnScreen (0),
  36955. columnsOnScreen (0),
  36956. scrollbarThickness (16),
  36957. columnToTryToMaintain (-1),
  36958. useSpacesForTabs (false),
  36959. xOffset (0),
  36960. verticalScrollBar (true),
  36961. horizontalScrollBar (false),
  36962. codeTokeniser (codeTokeniser_)
  36963. {
  36964. caretPos = CodeDocument::Position (&document_, 0, 0);
  36965. caretPos.setPositionMaintained (true);
  36966. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36967. selectionStart.setPositionMaintained (true);
  36968. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36969. selectionEnd.setPositionMaintained (true);
  36970. setOpaque (true);
  36971. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36972. setWantsKeyboardFocus (true);
  36973. addAndMakeVisible (&verticalScrollBar);
  36974. verticalScrollBar.setSingleStepSize (1.0);
  36975. addAndMakeVisible (&horizontalScrollBar);
  36976. horizontalScrollBar.setSingleStepSize (1.0);
  36977. addAndMakeVisible (caret = new CaretComponent (*this));
  36978. Font f (12.0f);
  36979. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36980. setFont (f);
  36981. resetToDefaultColours();
  36982. verticalScrollBar.addListener (this);
  36983. horizontalScrollBar.addListener (this);
  36984. document.addListener (this);
  36985. }
  36986. CodeEditorComponent::~CodeEditorComponent()
  36987. {
  36988. document.removeListener (this);
  36989. }
  36990. void CodeEditorComponent::loadContent (const String& newContent)
  36991. {
  36992. clearCachedIterators (0);
  36993. document.replaceAllContent (newContent);
  36994. document.clearUndoHistory();
  36995. document.setSavePoint();
  36996. caretPos.setPosition (0);
  36997. selectionStart.setPosition (0);
  36998. selectionEnd.setPosition (0);
  36999. scrollToLine (0);
  37000. }
  37001. bool CodeEditorComponent::isTextInputActive() const
  37002. {
  37003. return true;
  37004. }
  37005. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37006. const CodeDocument::Position& affectedTextEnd)
  37007. {
  37008. clearCachedIterators (affectedTextStart.getLineNumber());
  37009. triggerAsyncUpdate();
  37010. caret->updatePosition();
  37011. columnToTryToMaintain = -1;
  37012. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37013. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37014. deselectAll();
  37015. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37016. || caretPos.getPosition() < affectedTextStart.getPosition())
  37017. moveCaretTo (affectedTextStart, false);
  37018. updateScrollBars();
  37019. }
  37020. void CodeEditorComponent::resized()
  37021. {
  37022. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37023. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37024. lines.clear();
  37025. rebuildLineTokens();
  37026. caret->updatePosition();
  37027. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37028. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37029. updateScrollBars();
  37030. }
  37031. void CodeEditorComponent::paint (Graphics& g)
  37032. {
  37033. handleUpdateNowIfNeeded();
  37034. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37035. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  37036. g.setFont (font);
  37037. const int baselineOffset = (int) font.getAscent();
  37038. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37039. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37040. const Rectangle<int> clip (g.getClipBounds());
  37041. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37042. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37043. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37044. {
  37045. lines.getUnchecked(j)->draw (*this, g, font,
  37046. (float) (gutter - xOffset * charWidth),
  37047. lineHeight * j, baselineOffset, lineHeight,
  37048. highlightColour);
  37049. }
  37050. }
  37051. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37052. {
  37053. if (scrollbarThickness != thickness)
  37054. {
  37055. scrollbarThickness = thickness;
  37056. resized();
  37057. }
  37058. }
  37059. void CodeEditorComponent::handleAsyncUpdate()
  37060. {
  37061. rebuildLineTokens();
  37062. }
  37063. void CodeEditorComponent::rebuildLineTokens()
  37064. {
  37065. cancelPendingUpdate();
  37066. const int numNeeded = linesOnScreen + 1;
  37067. int minLineToRepaint = numNeeded;
  37068. int maxLineToRepaint = 0;
  37069. if (numNeeded != lines.size())
  37070. {
  37071. lines.clear();
  37072. for (int i = numNeeded; --i >= 0;)
  37073. lines.add (new CodeEditorLine());
  37074. minLineToRepaint = 0;
  37075. maxLineToRepaint = numNeeded;
  37076. }
  37077. jassert (numNeeded == lines.size());
  37078. CodeDocument::Iterator source (&document);
  37079. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37080. for (int i = 0; i < numNeeded; ++i)
  37081. {
  37082. CodeEditorLine* const line = lines.getUnchecked(i);
  37083. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37084. selectionStart, selectionEnd))
  37085. {
  37086. minLineToRepaint = jmin (minLineToRepaint, i);
  37087. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37088. }
  37089. }
  37090. if (minLineToRepaint <= maxLineToRepaint)
  37091. {
  37092. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37093. verticalScrollBar.getX() - gutter,
  37094. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37095. }
  37096. }
  37097. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37098. {
  37099. caretPos = newPos;
  37100. columnToTryToMaintain = -1;
  37101. if (highlighting)
  37102. {
  37103. if (dragType == notDragging)
  37104. {
  37105. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37106. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37107. dragType = draggingSelectionStart;
  37108. else
  37109. dragType = draggingSelectionEnd;
  37110. }
  37111. if (dragType == draggingSelectionStart)
  37112. {
  37113. selectionStart = caretPos;
  37114. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37115. {
  37116. const CodeDocument::Position temp (selectionStart);
  37117. selectionStart = selectionEnd;
  37118. selectionEnd = temp;
  37119. dragType = draggingSelectionEnd;
  37120. }
  37121. }
  37122. else
  37123. {
  37124. selectionEnd = caretPos;
  37125. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37126. {
  37127. const CodeDocument::Position temp (selectionStart);
  37128. selectionStart = selectionEnd;
  37129. selectionEnd = temp;
  37130. dragType = draggingSelectionStart;
  37131. }
  37132. }
  37133. triggerAsyncUpdate();
  37134. }
  37135. else
  37136. {
  37137. deselectAll();
  37138. }
  37139. caret->updatePosition();
  37140. scrollToKeepCaretOnScreen();
  37141. updateScrollBars();
  37142. }
  37143. void CodeEditorComponent::deselectAll()
  37144. {
  37145. if (selectionStart != selectionEnd)
  37146. triggerAsyncUpdate();
  37147. selectionStart = caretPos;
  37148. selectionEnd = caretPos;
  37149. }
  37150. void CodeEditorComponent::updateScrollBars()
  37151. {
  37152. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37153. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37154. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37155. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37156. }
  37157. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37158. {
  37159. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37160. newFirstLineOnScreen);
  37161. if (newFirstLineOnScreen != firstLineOnScreen)
  37162. {
  37163. firstLineOnScreen = newFirstLineOnScreen;
  37164. caret->updatePosition();
  37165. updateCachedIterators (firstLineOnScreen);
  37166. triggerAsyncUpdate();
  37167. }
  37168. }
  37169. void CodeEditorComponent::scrollToColumnInternal (double column)
  37170. {
  37171. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37172. if (xOffset != newOffset)
  37173. {
  37174. xOffset = newOffset;
  37175. caret->updatePosition();
  37176. repaint();
  37177. }
  37178. }
  37179. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37180. {
  37181. scrollToLineInternal (newFirstLineOnScreen);
  37182. updateScrollBars();
  37183. }
  37184. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37185. {
  37186. scrollToColumnInternal (newFirstColumnOnScreen);
  37187. updateScrollBars();
  37188. }
  37189. void CodeEditorComponent::scrollBy (int deltaLines)
  37190. {
  37191. scrollToLine (firstLineOnScreen + deltaLines);
  37192. }
  37193. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37194. {
  37195. if (caretPos.getLineNumber() < firstLineOnScreen)
  37196. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37197. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37198. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37199. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37200. if (column >= xOffset + columnsOnScreen - 1)
  37201. scrollToColumn (column + 1 - columnsOnScreen);
  37202. else if (column < xOffset)
  37203. scrollToColumn (column);
  37204. }
  37205. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37206. {
  37207. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37208. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37209. roundToInt (charWidth),
  37210. lineHeight);
  37211. }
  37212. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37213. {
  37214. const int line = y / lineHeight + firstLineOnScreen;
  37215. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37216. const int index = columnToIndex (line, column);
  37217. return CodeDocument::Position (&document, line, index);
  37218. }
  37219. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37220. {
  37221. document.deleteSection (selectionStart, selectionEnd);
  37222. if (newText.isNotEmpty())
  37223. document.insertText (caretPos, newText);
  37224. scrollToKeepCaretOnScreen();
  37225. }
  37226. void CodeEditorComponent::insertTabAtCaret()
  37227. {
  37228. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37229. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37230. {
  37231. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37232. }
  37233. if (useSpacesForTabs)
  37234. {
  37235. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37236. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37237. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37238. }
  37239. else
  37240. {
  37241. insertTextAtCaret ("\t");
  37242. }
  37243. }
  37244. void CodeEditorComponent::cut()
  37245. {
  37246. insertTextAtCaret (String::empty);
  37247. }
  37248. void CodeEditorComponent::copy()
  37249. {
  37250. newTransaction();
  37251. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37252. if (selection.isNotEmpty())
  37253. SystemClipboard::copyTextToClipboard (selection);
  37254. }
  37255. void CodeEditorComponent::copyThenCut()
  37256. {
  37257. copy();
  37258. cut();
  37259. newTransaction();
  37260. }
  37261. void CodeEditorComponent::paste()
  37262. {
  37263. newTransaction();
  37264. const String clip (SystemClipboard::getTextFromClipboard());
  37265. if (clip.isNotEmpty())
  37266. insertTextAtCaret (clip);
  37267. newTransaction();
  37268. }
  37269. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37270. {
  37271. newTransaction();
  37272. if (moveInWholeWordSteps)
  37273. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37274. else
  37275. moveCaretTo (caretPos.movedBy (-1), selecting);
  37276. }
  37277. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37278. {
  37279. newTransaction();
  37280. if (moveInWholeWordSteps)
  37281. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37282. else
  37283. moveCaretTo (caretPos.movedBy (1), selecting);
  37284. }
  37285. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37286. {
  37287. CodeDocument::Position pos (caretPos);
  37288. const int newLineNum = pos.getLineNumber() + delta;
  37289. if (columnToTryToMaintain < 0)
  37290. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37291. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37292. const int colToMaintain = columnToTryToMaintain;
  37293. moveCaretTo (pos, selecting);
  37294. columnToTryToMaintain = colToMaintain;
  37295. }
  37296. void CodeEditorComponent::cursorDown (const bool selecting)
  37297. {
  37298. newTransaction();
  37299. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37300. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37301. else
  37302. moveLineDelta (1, selecting);
  37303. }
  37304. void CodeEditorComponent::cursorUp (const bool selecting)
  37305. {
  37306. newTransaction();
  37307. if (caretPos.getLineNumber() == 0)
  37308. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37309. else
  37310. moveLineDelta (-1, selecting);
  37311. }
  37312. void CodeEditorComponent::pageDown (const bool selecting)
  37313. {
  37314. newTransaction();
  37315. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37316. moveLineDelta (linesOnScreen, selecting);
  37317. }
  37318. void CodeEditorComponent::pageUp (const bool selecting)
  37319. {
  37320. newTransaction();
  37321. scrollBy (-linesOnScreen);
  37322. moveLineDelta (-linesOnScreen, selecting);
  37323. }
  37324. void CodeEditorComponent::scrollUp()
  37325. {
  37326. newTransaction();
  37327. scrollBy (1);
  37328. if (caretPos.getLineNumber() < firstLineOnScreen)
  37329. moveLineDelta (1, false);
  37330. }
  37331. void CodeEditorComponent::scrollDown()
  37332. {
  37333. newTransaction();
  37334. scrollBy (-1);
  37335. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37336. moveLineDelta (-1, false);
  37337. }
  37338. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37339. {
  37340. newTransaction();
  37341. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37342. }
  37343. namespace CodeEditorHelpers
  37344. {
  37345. int findFirstNonWhitespaceChar (const String& line) throw()
  37346. {
  37347. const int len = line.length();
  37348. for (int i = 0; i < len; ++i)
  37349. if (! CharacterFunctions::isWhitespace (line [i]))
  37350. return i;
  37351. return 0;
  37352. }
  37353. }
  37354. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37355. {
  37356. newTransaction();
  37357. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37358. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37359. index = 0;
  37360. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37361. }
  37362. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37363. {
  37364. newTransaction();
  37365. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37366. }
  37367. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37368. {
  37369. newTransaction();
  37370. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37371. }
  37372. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37373. {
  37374. if (moveInWholeWordSteps)
  37375. {
  37376. cut(); // in case something is already highlighted
  37377. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37378. }
  37379. else
  37380. {
  37381. if (selectionStart == selectionEnd)
  37382. selectionStart.moveBy (-1);
  37383. }
  37384. cut();
  37385. }
  37386. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37387. {
  37388. if (moveInWholeWordSteps)
  37389. {
  37390. cut(); // in case something is already highlighted
  37391. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37392. }
  37393. else
  37394. {
  37395. if (selectionStart == selectionEnd)
  37396. selectionEnd.moveBy (1);
  37397. else
  37398. newTransaction();
  37399. }
  37400. cut();
  37401. }
  37402. void CodeEditorComponent::selectAll()
  37403. {
  37404. newTransaction();
  37405. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37406. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37407. }
  37408. void CodeEditorComponent::undo()
  37409. {
  37410. document.undo();
  37411. scrollToKeepCaretOnScreen();
  37412. }
  37413. void CodeEditorComponent::redo()
  37414. {
  37415. document.redo();
  37416. scrollToKeepCaretOnScreen();
  37417. }
  37418. void CodeEditorComponent::newTransaction()
  37419. {
  37420. document.newTransaction();
  37421. startTimer (600);
  37422. }
  37423. void CodeEditorComponent::timerCallback()
  37424. {
  37425. newTransaction();
  37426. }
  37427. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37428. {
  37429. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37430. }
  37431. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37432. {
  37433. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37434. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37435. }
  37436. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37437. {
  37438. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37439. CodeDocument::Position (&document, range.getEnd()));
  37440. }
  37441. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37442. {
  37443. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37444. const bool shiftDown = key.getModifiers().isShiftDown();
  37445. if (key.isKeyCode (KeyPress::leftKey))
  37446. {
  37447. cursorLeft (moveInWholeWordSteps, shiftDown);
  37448. }
  37449. else if (key.isKeyCode (KeyPress::rightKey))
  37450. {
  37451. cursorRight (moveInWholeWordSteps, shiftDown);
  37452. }
  37453. else if (key.isKeyCode (KeyPress::upKey))
  37454. {
  37455. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37456. scrollDown();
  37457. #if JUCE_MAC
  37458. else if (key.getModifiers().isCommandDown())
  37459. goToStartOfDocument (shiftDown);
  37460. #endif
  37461. else
  37462. cursorUp (shiftDown);
  37463. }
  37464. else if (key.isKeyCode (KeyPress::downKey))
  37465. {
  37466. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37467. scrollUp();
  37468. #if JUCE_MAC
  37469. else if (key.getModifiers().isCommandDown())
  37470. goToEndOfDocument (shiftDown);
  37471. #endif
  37472. else
  37473. cursorDown (shiftDown);
  37474. }
  37475. else if (key.isKeyCode (KeyPress::pageDownKey))
  37476. {
  37477. pageDown (shiftDown);
  37478. }
  37479. else if (key.isKeyCode (KeyPress::pageUpKey))
  37480. {
  37481. pageUp (shiftDown);
  37482. }
  37483. else if (key.isKeyCode (KeyPress::homeKey))
  37484. {
  37485. if (moveInWholeWordSteps)
  37486. goToStartOfDocument (shiftDown);
  37487. else
  37488. goToStartOfLine (shiftDown);
  37489. }
  37490. else if (key.isKeyCode (KeyPress::endKey))
  37491. {
  37492. if (moveInWholeWordSteps)
  37493. goToEndOfDocument (shiftDown);
  37494. else
  37495. goToEndOfLine (shiftDown);
  37496. }
  37497. else if (key.isKeyCode (KeyPress::backspaceKey))
  37498. {
  37499. backspace (moveInWholeWordSteps);
  37500. }
  37501. else if (key.isKeyCode (KeyPress::deleteKey))
  37502. {
  37503. deleteForward (moveInWholeWordSteps);
  37504. }
  37505. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37506. {
  37507. copy();
  37508. }
  37509. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37510. {
  37511. copyThenCut();
  37512. }
  37513. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37514. {
  37515. paste();
  37516. }
  37517. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37518. {
  37519. undo();
  37520. }
  37521. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37522. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37523. {
  37524. redo();
  37525. }
  37526. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37527. {
  37528. selectAll();
  37529. }
  37530. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37531. {
  37532. insertTabAtCaret();
  37533. }
  37534. else if (key == KeyPress::returnKey)
  37535. {
  37536. newTransaction();
  37537. insertTextAtCaret (document.getNewLineCharacters());
  37538. }
  37539. else if (key.isKeyCode (KeyPress::escapeKey))
  37540. {
  37541. newTransaction();
  37542. }
  37543. else if (key.getTextCharacter() >= ' ')
  37544. {
  37545. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37546. }
  37547. else
  37548. {
  37549. return false;
  37550. }
  37551. return true;
  37552. }
  37553. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37554. {
  37555. newTransaction();
  37556. dragType = notDragging;
  37557. if (! e.mods.isPopupMenu())
  37558. {
  37559. beginDragAutoRepeat (100);
  37560. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37561. }
  37562. else
  37563. {
  37564. /*PopupMenu m;
  37565. addPopupMenuItems (m, &e);
  37566. const int result = m.show();
  37567. if (result != 0)
  37568. performPopupMenuAction (result);
  37569. */
  37570. }
  37571. }
  37572. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37573. {
  37574. if (! e.mods.isPopupMenu())
  37575. moveCaretTo (getPositionAt (e.x, e.y), true);
  37576. }
  37577. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37578. {
  37579. newTransaction();
  37580. beginDragAutoRepeat (0);
  37581. dragType = notDragging;
  37582. }
  37583. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37584. {
  37585. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37586. CodeDocument::Position tokenEnd (tokenStart);
  37587. if (e.getNumberOfClicks() > 2)
  37588. {
  37589. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37590. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37591. }
  37592. else
  37593. {
  37594. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37595. tokenEnd.moveBy (1);
  37596. tokenStart = tokenEnd;
  37597. while (tokenStart.getIndexInLine() > 0
  37598. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37599. tokenStart.moveBy (-1);
  37600. }
  37601. moveCaretTo (tokenEnd, false);
  37602. moveCaretTo (tokenStart, true);
  37603. }
  37604. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37605. {
  37606. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37607. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37608. {
  37609. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37610. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37611. }
  37612. else
  37613. {
  37614. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37615. }
  37616. }
  37617. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37618. {
  37619. if (scrollBarThatHasMoved == &verticalScrollBar)
  37620. scrollToLineInternal ((int) newRangeStart);
  37621. else
  37622. scrollToColumnInternal (newRangeStart);
  37623. }
  37624. void CodeEditorComponent::focusGained (FocusChangeType)
  37625. {
  37626. caret->updatePosition();
  37627. }
  37628. void CodeEditorComponent::focusLost (FocusChangeType)
  37629. {
  37630. caret->updatePosition();
  37631. }
  37632. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37633. {
  37634. useSpacesForTabs = insertSpaces;
  37635. if (spacesPerTab != numSpaces)
  37636. {
  37637. spacesPerTab = numSpaces;
  37638. triggerAsyncUpdate();
  37639. }
  37640. }
  37641. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37642. {
  37643. const String line (document.getLine (lineNum));
  37644. jassert (index <= line.length());
  37645. int col = 0;
  37646. for (int i = 0; i < index; ++i)
  37647. {
  37648. if (line[i] != '\t')
  37649. ++col;
  37650. else
  37651. col += getTabSize() - (col % getTabSize());
  37652. }
  37653. return col;
  37654. }
  37655. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37656. {
  37657. const String line (document.getLine (lineNum));
  37658. const int lineLength = line.length();
  37659. int i, col = 0;
  37660. for (i = 0; i < lineLength; ++i)
  37661. {
  37662. if (line[i] != '\t')
  37663. ++col;
  37664. else
  37665. col += getTabSize() - (col % getTabSize());
  37666. if (col > column)
  37667. break;
  37668. }
  37669. return i;
  37670. }
  37671. void CodeEditorComponent::setFont (const Font& newFont)
  37672. {
  37673. font = newFont;
  37674. charWidth = font.getStringWidthFloat ("0");
  37675. lineHeight = roundToInt (font.getHeight());
  37676. resized();
  37677. }
  37678. void CodeEditorComponent::resetToDefaultColours()
  37679. {
  37680. coloursForTokenCategories.clear();
  37681. if (codeTokeniser != 0)
  37682. {
  37683. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37684. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37685. }
  37686. }
  37687. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37688. {
  37689. jassert (tokenType < 256);
  37690. while (coloursForTokenCategories.size() < tokenType)
  37691. coloursForTokenCategories.add (Colours::black);
  37692. coloursForTokenCategories.set (tokenType, colour);
  37693. repaint();
  37694. }
  37695. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37696. {
  37697. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37698. return findColour (CodeEditorComponent::defaultTextColourId);
  37699. return coloursForTokenCategories.getReference (tokenType);
  37700. }
  37701. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37702. {
  37703. int i;
  37704. for (i = cachedIterators.size(); --i >= 0;)
  37705. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37706. break;
  37707. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37708. }
  37709. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37710. {
  37711. const int maxNumCachedPositions = 5000;
  37712. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37713. if (cachedIterators.size() == 0)
  37714. cachedIterators.add (new CodeDocument::Iterator (&document));
  37715. if (codeTokeniser == 0)
  37716. return;
  37717. for (;;)
  37718. {
  37719. CodeDocument::Iterator* last = cachedIterators.getLast();
  37720. if (last->getLine() >= maxLineNum)
  37721. break;
  37722. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37723. cachedIterators.add (t);
  37724. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37725. for (;;)
  37726. {
  37727. codeTokeniser->readNextToken (*t);
  37728. if (t->getLine() >= targetLine)
  37729. break;
  37730. if (t->isEOF())
  37731. return;
  37732. }
  37733. }
  37734. }
  37735. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37736. {
  37737. if (codeTokeniser == 0)
  37738. return;
  37739. for (int i = cachedIterators.size(); --i >= 0;)
  37740. {
  37741. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37742. if (t->getPosition() <= position)
  37743. {
  37744. source = *t;
  37745. break;
  37746. }
  37747. }
  37748. while (source.getPosition() < position)
  37749. {
  37750. const CodeDocument::Iterator original (source);
  37751. codeTokeniser->readNextToken (source);
  37752. if (source.getPosition() > position || source.isEOF())
  37753. {
  37754. source = original;
  37755. break;
  37756. }
  37757. }
  37758. }
  37759. END_JUCE_NAMESPACE
  37760. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37761. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37762. BEGIN_JUCE_NAMESPACE
  37763. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37764. {
  37765. }
  37766. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37767. {
  37768. }
  37769. namespace CppTokeniser
  37770. {
  37771. bool isIdentifierStart (const juce_wchar c) throw()
  37772. {
  37773. return CharacterFunctions::isLetter (c)
  37774. || c == '_' || c == '@';
  37775. }
  37776. bool isIdentifierBody (const juce_wchar c) throw()
  37777. {
  37778. return CharacterFunctions::isLetterOrDigit (c)
  37779. || c == '_' || c == '@';
  37780. }
  37781. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37782. {
  37783. static const juce_wchar* const keywords2Char[] =
  37784. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37785. static const juce_wchar* const keywords3Char[] =
  37786. { 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 };
  37787. static const juce_wchar* const keywords4Char[] =
  37788. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37789. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37790. static const juce_wchar* const keywords5Char[] =
  37791. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37792. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37793. static const juce_wchar* const keywords6Char[] =
  37794. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37795. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37796. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37797. static const juce_wchar* const keywordsOther[] =
  37798. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37799. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37800. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37801. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37802. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37803. const juce_wchar* const* k;
  37804. switch (tokenLength)
  37805. {
  37806. case 2: k = keywords2Char; break;
  37807. case 3: k = keywords3Char; break;
  37808. case 4: k = keywords4Char; break;
  37809. case 5: k = keywords5Char; break;
  37810. case 6: k = keywords6Char; break;
  37811. default:
  37812. if (tokenLength < 2 || tokenLength > 16)
  37813. return false;
  37814. k = keywordsOther;
  37815. break;
  37816. }
  37817. int i = 0;
  37818. while (k[i] != 0)
  37819. {
  37820. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37821. return true;
  37822. ++i;
  37823. }
  37824. return false;
  37825. }
  37826. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37827. {
  37828. int tokenLength = 0;
  37829. juce_wchar possibleIdentifier [19];
  37830. while (isIdentifierBody (source.peekNextChar()))
  37831. {
  37832. const juce_wchar c = source.nextChar();
  37833. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37834. possibleIdentifier [tokenLength] = c;
  37835. ++tokenLength;
  37836. }
  37837. if (tokenLength > 1 && tokenLength <= 16)
  37838. {
  37839. possibleIdentifier [tokenLength] = 0;
  37840. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37841. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37842. }
  37843. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37844. }
  37845. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37846. {
  37847. const juce_wchar c = source.peekNextChar();
  37848. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37849. source.skip();
  37850. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37851. return false;
  37852. return true;
  37853. }
  37854. bool isHexDigit (const juce_wchar c) throw()
  37855. {
  37856. return (c >= '0' && c <= '9')
  37857. || (c >= 'a' && c <= 'f')
  37858. || (c >= 'A' && c <= 'F');
  37859. }
  37860. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37861. {
  37862. if (source.nextChar() != '0')
  37863. return false;
  37864. juce_wchar c = source.nextChar();
  37865. if (c != 'x' && c != 'X')
  37866. return false;
  37867. int numDigits = 0;
  37868. while (isHexDigit (source.peekNextChar()))
  37869. {
  37870. ++numDigits;
  37871. source.skip();
  37872. }
  37873. if (numDigits == 0)
  37874. return false;
  37875. return skipNumberSuffix (source);
  37876. }
  37877. bool isOctalDigit (const juce_wchar c) throw()
  37878. {
  37879. return c >= '0' && c <= '7';
  37880. }
  37881. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37882. {
  37883. if (source.nextChar() != '0')
  37884. return false;
  37885. if (! isOctalDigit (source.nextChar()))
  37886. return false;
  37887. while (isOctalDigit (source.peekNextChar()))
  37888. source.skip();
  37889. return skipNumberSuffix (source);
  37890. }
  37891. bool isDecimalDigit (const juce_wchar c) throw()
  37892. {
  37893. return c >= '0' && c <= '9';
  37894. }
  37895. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37896. {
  37897. int numChars = 0;
  37898. while (isDecimalDigit (source.peekNextChar()))
  37899. {
  37900. ++numChars;
  37901. source.skip();
  37902. }
  37903. if (numChars == 0)
  37904. return false;
  37905. return skipNumberSuffix (source);
  37906. }
  37907. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37908. {
  37909. int numDigits = 0;
  37910. while (isDecimalDigit (source.peekNextChar()))
  37911. {
  37912. source.skip();
  37913. ++numDigits;
  37914. }
  37915. const bool hasPoint = (source.peekNextChar() == '.');
  37916. if (hasPoint)
  37917. {
  37918. source.skip();
  37919. while (isDecimalDigit (source.peekNextChar()))
  37920. {
  37921. source.skip();
  37922. ++numDigits;
  37923. }
  37924. }
  37925. if (numDigits == 0)
  37926. return false;
  37927. juce_wchar c = source.peekNextChar();
  37928. const bool hasExponent = (c == 'e' || c == 'E');
  37929. if (hasExponent)
  37930. {
  37931. source.skip();
  37932. c = source.peekNextChar();
  37933. if (c == '+' || c == '-')
  37934. source.skip();
  37935. int numExpDigits = 0;
  37936. while (isDecimalDigit (source.peekNextChar()))
  37937. {
  37938. source.skip();
  37939. ++numExpDigits;
  37940. }
  37941. if (numExpDigits == 0)
  37942. return false;
  37943. }
  37944. c = source.peekNextChar();
  37945. if (c == 'f' || c == 'F')
  37946. source.skip();
  37947. else if (! (hasExponent || hasPoint))
  37948. return false;
  37949. return true;
  37950. }
  37951. int parseNumber (CodeDocument::Iterator& source)
  37952. {
  37953. const CodeDocument::Iterator original (source);
  37954. if (parseFloatLiteral (source))
  37955. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37956. source = original;
  37957. if (parseHexLiteral (source))
  37958. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37959. source = original;
  37960. if (parseOctalLiteral (source))
  37961. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37962. source = original;
  37963. if (parseDecimalLiteral (source))
  37964. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37965. source = original;
  37966. source.skip();
  37967. return CPlusPlusCodeTokeniser::tokenType_error;
  37968. }
  37969. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37970. {
  37971. const juce_wchar quote = source.nextChar();
  37972. for (;;)
  37973. {
  37974. const juce_wchar c = source.nextChar();
  37975. if (c == quote || c == 0)
  37976. break;
  37977. if (c == '\\')
  37978. source.skip();
  37979. }
  37980. }
  37981. void skipComment (CodeDocument::Iterator& source) throw()
  37982. {
  37983. bool lastWasStar = false;
  37984. for (;;)
  37985. {
  37986. const juce_wchar c = source.nextChar();
  37987. if (c == 0 || (c == '/' && lastWasStar))
  37988. break;
  37989. lastWasStar = (c == '*');
  37990. }
  37991. }
  37992. }
  37993. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37994. {
  37995. int result = tokenType_error;
  37996. source.skipWhitespace();
  37997. juce_wchar firstChar = source.peekNextChar();
  37998. switch (firstChar)
  37999. {
  38000. case 0:
  38001. source.skip();
  38002. break;
  38003. case '0':
  38004. case '1':
  38005. case '2':
  38006. case '3':
  38007. case '4':
  38008. case '5':
  38009. case '6':
  38010. case '7':
  38011. case '8':
  38012. case '9':
  38013. result = CppTokeniser::parseNumber (source);
  38014. break;
  38015. case '.':
  38016. result = CppTokeniser::parseNumber (source);
  38017. if (result == tokenType_error)
  38018. result = tokenType_punctuation;
  38019. break;
  38020. case ',':
  38021. case ';':
  38022. case ':':
  38023. source.skip();
  38024. result = tokenType_punctuation;
  38025. break;
  38026. case '(':
  38027. case ')':
  38028. case '{':
  38029. case '}':
  38030. case '[':
  38031. case ']':
  38032. source.skip();
  38033. result = tokenType_bracket;
  38034. break;
  38035. case '"':
  38036. case '\'':
  38037. CppTokeniser::skipQuotedString (source);
  38038. result = tokenType_stringLiteral;
  38039. break;
  38040. case '+':
  38041. result = tokenType_operator;
  38042. source.skip();
  38043. if (source.peekNextChar() == '+')
  38044. source.skip();
  38045. else if (source.peekNextChar() == '=')
  38046. source.skip();
  38047. break;
  38048. case '-':
  38049. source.skip();
  38050. result = CppTokeniser::parseNumber (source);
  38051. if (result == tokenType_error)
  38052. {
  38053. result = tokenType_operator;
  38054. if (source.peekNextChar() == '-')
  38055. source.skip();
  38056. else if (source.peekNextChar() == '=')
  38057. source.skip();
  38058. }
  38059. break;
  38060. case '*':
  38061. case '%':
  38062. case '=':
  38063. case '!':
  38064. result = tokenType_operator;
  38065. source.skip();
  38066. if (source.peekNextChar() == '=')
  38067. source.skip();
  38068. break;
  38069. case '/':
  38070. result = tokenType_operator;
  38071. source.skip();
  38072. if (source.peekNextChar() == '=')
  38073. {
  38074. source.skip();
  38075. }
  38076. else if (source.peekNextChar() == '/')
  38077. {
  38078. result = tokenType_comment;
  38079. source.skipToEndOfLine();
  38080. }
  38081. else if (source.peekNextChar() == '*')
  38082. {
  38083. source.skip();
  38084. result = tokenType_comment;
  38085. CppTokeniser::skipComment (source);
  38086. }
  38087. break;
  38088. case '?':
  38089. case '~':
  38090. source.skip();
  38091. result = tokenType_operator;
  38092. break;
  38093. case '<':
  38094. source.skip();
  38095. result = tokenType_operator;
  38096. if (source.peekNextChar() == '=')
  38097. {
  38098. source.skip();
  38099. }
  38100. else if (source.peekNextChar() == '<')
  38101. {
  38102. source.skip();
  38103. if (source.peekNextChar() == '=')
  38104. source.skip();
  38105. }
  38106. break;
  38107. case '>':
  38108. source.skip();
  38109. result = tokenType_operator;
  38110. if (source.peekNextChar() == '=')
  38111. {
  38112. source.skip();
  38113. }
  38114. else if (source.peekNextChar() == '<')
  38115. {
  38116. source.skip();
  38117. if (source.peekNextChar() == '=')
  38118. source.skip();
  38119. }
  38120. break;
  38121. case '|':
  38122. source.skip();
  38123. result = tokenType_operator;
  38124. if (source.peekNextChar() == '=')
  38125. {
  38126. source.skip();
  38127. }
  38128. else if (source.peekNextChar() == '|')
  38129. {
  38130. source.skip();
  38131. if (source.peekNextChar() == '=')
  38132. source.skip();
  38133. }
  38134. break;
  38135. case '&':
  38136. source.skip();
  38137. result = tokenType_operator;
  38138. if (source.peekNextChar() == '=')
  38139. {
  38140. source.skip();
  38141. }
  38142. else if (source.peekNextChar() == '&')
  38143. {
  38144. source.skip();
  38145. if (source.peekNextChar() == '=')
  38146. source.skip();
  38147. }
  38148. break;
  38149. case '^':
  38150. source.skip();
  38151. result = tokenType_operator;
  38152. if (source.peekNextChar() == '=')
  38153. {
  38154. source.skip();
  38155. }
  38156. else if (source.peekNextChar() == '^')
  38157. {
  38158. source.skip();
  38159. if (source.peekNextChar() == '=')
  38160. source.skip();
  38161. }
  38162. break;
  38163. case '#':
  38164. result = tokenType_preprocessor;
  38165. source.skipToEndOfLine();
  38166. break;
  38167. default:
  38168. if (CppTokeniser::isIdentifierStart (firstChar))
  38169. result = CppTokeniser::parseIdentifier (source);
  38170. else
  38171. source.skip();
  38172. break;
  38173. }
  38174. return result;
  38175. }
  38176. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38177. {
  38178. const char* const types[] =
  38179. {
  38180. "Error",
  38181. "Comment",
  38182. "C++ keyword",
  38183. "Identifier",
  38184. "Integer literal",
  38185. "Float literal",
  38186. "String literal",
  38187. "Operator",
  38188. "Bracket",
  38189. "Punctuation",
  38190. "Preprocessor line",
  38191. 0
  38192. };
  38193. return StringArray (types);
  38194. }
  38195. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38196. {
  38197. const uint32 colours[] =
  38198. {
  38199. 0xffcc0000, // error
  38200. 0xff00aa00, // comment
  38201. 0xff0000cc, // keyword
  38202. 0xff000000, // identifier
  38203. 0xff880000, // int literal
  38204. 0xff885500, // float literal
  38205. 0xff990099, // string literal
  38206. 0xff225500, // operator
  38207. 0xff000055, // bracket
  38208. 0xff004400, // punctuation
  38209. 0xff660000 // preprocessor
  38210. };
  38211. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38212. return Colour (colours [tokenType]);
  38213. return Colours::black;
  38214. }
  38215. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38216. {
  38217. return CppTokeniser::isReservedKeyword (token, token.length());
  38218. }
  38219. END_JUCE_NAMESPACE
  38220. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38221. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38222. BEGIN_JUCE_NAMESPACE
  38223. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38224. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38225. {
  38226. }
  38227. bool ComboBox::ItemInfo::isSeparator() const throw()
  38228. {
  38229. return name.isEmpty();
  38230. }
  38231. bool ComboBox::ItemInfo::isRealItem() const throw()
  38232. {
  38233. return ! (isHeading || name.isEmpty());
  38234. }
  38235. ComboBox::ComboBox (const String& name)
  38236. : Component (name),
  38237. lastCurrentId (0),
  38238. isButtonDown (false),
  38239. separatorPending (false),
  38240. menuActive (false),
  38241. noChoicesMessage (TRANS("(no choices)"))
  38242. {
  38243. setRepaintsOnMouseActivity (true);
  38244. lookAndFeelChanged();
  38245. currentId.addListener (this);
  38246. }
  38247. ComboBox::~ComboBox()
  38248. {
  38249. currentId.removeListener (this);
  38250. if (menuActive)
  38251. PopupMenu::dismissAllActiveMenus();
  38252. label = 0;
  38253. }
  38254. void ComboBox::setEditableText (const bool isEditable)
  38255. {
  38256. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38257. {
  38258. label->setEditable (isEditable, isEditable, false);
  38259. setWantsKeyboardFocus (! isEditable);
  38260. resized();
  38261. }
  38262. }
  38263. bool ComboBox::isTextEditable() const throw()
  38264. {
  38265. return label->isEditable();
  38266. }
  38267. void ComboBox::setJustificationType (const Justification& justification)
  38268. {
  38269. label->setJustificationType (justification);
  38270. }
  38271. const Justification ComboBox::getJustificationType() const throw()
  38272. {
  38273. return label->getJustificationType();
  38274. }
  38275. void ComboBox::setTooltip (const String& newTooltip)
  38276. {
  38277. SettableTooltipClient::setTooltip (newTooltip);
  38278. label->setTooltip (newTooltip);
  38279. }
  38280. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38281. {
  38282. // you can't add empty strings to the list..
  38283. jassert (newItemText.isNotEmpty());
  38284. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38285. jassert (newItemId != 0);
  38286. // you shouldn't use duplicate item IDs!
  38287. jassert (getItemForId (newItemId) == 0);
  38288. if (newItemText.isNotEmpty() && newItemId != 0)
  38289. {
  38290. if (separatorPending)
  38291. {
  38292. separatorPending = false;
  38293. items.add (new ItemInfo (String::empty, 0, false, false));
  38294. }
  38295. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38296. }
  38297. }
  38298. void ComboBox::addSeparator()
  38299. {
  38300. separatorPending = (items.size() > 0);
  38301. }
  38302. void ComboBox::addSectionHeading (const String& headingName)
  38303. {
  38304. // you can't add empty strings to the list..
  38305. jassert (headingName.isNotEmpty());
  38306. if (headingName.isNotEmpty())
  38307. {
  38308. if (separatorPending)
  38309. {
  38310. separatorPending = false;
  38311. items.add (new ItemInfo (String::empty, 0, false, false));
  38312. }
  38313. items.add (new ItemInfo (headingName, 0, true, true));
  38314. }
  38315. }
  38316. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38317. {
  38318. ItemInfo* const item = getItemForId (itemId);
  38319. if (item != 0)
  38320. item->isEnabled = shouldBeEnabled;
  38321. }
  38322. void ComboBox::changeItemText (const int itemId, const String& newText)
  38323. {
  38324. ItemInfo* const item = getItemForId (itemId);
  38325. jassert (item != 0);
  38326. if (item != 0)
  38327. item->name = newText;
  38328. }
  38329. void ComboBox::clear (const bool dontSendChangeMessage)
  38330. {
  38331. items.clear();
  38332. separatorPending = false;
  38333. if (! label->isEditable())
  38334. setSelectedItemIndex (-1, dontSendChangeMessage);
  38335. }
  38336. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38337. {
  38338. if (itemId != 0)
  38339. {
  38340. for (int i = items.size(); --i >= 0;)
  38341. if (items.getUnchecked(i)->itemId == itemId)
  38342. return items.getUnchecked(i);
  38343. }
  38344. return 0;
  38345. }
  38346. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38347. {
  38348. for (int n = 0, i = 0; i < items.size(); ++i)
  38349. {
  38350. ItemInfo* const item = items.getUnchecked(i);
  38351. if (item->isRealItem())
  38352. if (n++ == index)
  38353. return item;
  38354. }
  38355. return 0;
  38356. }
  38357. int ComboBox::getNumItems() const throw()
  38358. {
  38359. int n = 0;
  38360. for (int i = items.size(); --i >= 0;)
  38361. if (items.getUnchecked(i)->isRealItem())
  38362. ++n;
  38363. return n;
  38364. }
  38365. const String ComboBox::getItemText (const int index) const
  38366. {
  38367. const ItemInfo* const item = getItemForIndex (index);
  38368. return item != 0 ? item->name : String::empty;
  38369. }
  38370. int ComboBox::getItemId (const int index) const throw()
  38371. {
  38372. const ItemInfo* const item = getItemForIndex (index);
  38373. return item != 0 ? item->itemId : 0;
  38374. }
  38375. int ComboBox::indexOfItemId (const int itemId) const throw()
  38376. {
  38377. for (int n = 0, i = 0; i < items.size(); ++i)
  38378. {
  38379. const ItemInfo* const item = items.getUnchecked(i);
  38380. if (item->isRealItem())
  38381. {
  38382. if (item->itemId == itemId)
  38383. return n;
  38384. ++n;
  38385. }
  38386. }
  38387. return -1;
  38388. }
  38389. int ComboBox::getSelectedItemIndex() const
  38390. {
  38391. int index = indexOfItemId (currentId.getValue());
  38392. if (getText() != getItemText (index))
  38393. index = -1;
  38394. return index;
  38395. }
  38396. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38397. {
  38398. setSelectedId (getItemId (index), dontSendChangeMessage);
  38399. }
  38400. int ComboBox::getSelectedId() const throw()
  38401. {
  38402. const ItemInfo* const item = getItemForId (currentId.getValue());
  38403. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38404. }
  38405. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38406. {
  38407. const ItemInfo* const item = getItemForId (newItemId);
  38408. const String newItemText (item != 0 ? item->name : String::empty);
  38409. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38410. {
  38411. if (! dontSendChangeMessage)
  38412. triggerAsyncUpdate();
  38413. label->setText (newItemText, false);
  38414. lastCurrentId = newItemId;
  38415. currentId = newItemId;
  38416. repaint(); // for the benefit of the 'none selected' text
  38417. }
  38418. }
  38419. void ComboBox::valueChanged (Value&)
  38420. {
  38421. if (lastCurrentId != (int) currentId.getValue())
  38422. setSelectedId (currentId.getValue(), false);
  38423. }
  38424. const String ComboBox::getText() const
  38425. {
  38426. return label->getText();
  38427. }
  38428. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38429. {
  38430. for (int i = items.size(); --i >= 0;)
  38431. {
  38432. const ItemInfo* const item = items.getUnchecked(i);
  38433. if (item->isRealItem()
  38434. && item->name == newText)
  38435. {
  38436. setSelectedId (item->itemId, dontSendChangeMessage);
  38437. return;
  38438. }
  38439. }
  38440. lastCurrentId = 0;
  38441. currentId = 0;
  38442. if (label->getText() != newText)
  38443. {
  38444. label->setText (newText, false);
  38445. if (! dontSendChangeMessage)
  38446. triggerAsyncUpdate();
  38447. }
  38448. repaint();
  38449. }
  38450. void ComboBox::showEditor()
  38451. {
  38452. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38453. label->showEditor();
  38454. }
  38455. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38456. {
  38457. if (textWhenNothingSelected != newMessage)
  38458. {
  38459. textWhenNothingSelected = newMessage;
  38460. repaint();
  38461. }
  38462. }
  38463. const String ComboBox::getTextWhenNothingSelected() const
  38464. {
  38465. return textWhenNothingSelected;
  38466. }
  38467. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38468. {
  38469. noChoicesMessage = newMessage;
  38470. }
  38471. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38472. {
  38473. return noChoicesMessage;
  38474. }
  38475. void ComboBox::paint (Graphics& g)
  38476. {
  38477. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38478. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38479. *this);
  38480. if (textWhenNothingSelected.isNotEmpty()
  38481. && label->getText().isEmpty()
  38482. && ! label->isBeingEdited())
  38483. {
  38484. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38485. g.setFont (label->getFont());
  38486. g.drawFittedText (textWhenNothingSelected,
  38487. label->getX() + 2, label->getY() + 1,
  38488. label->getWidth() - 4, label->getHeight() - 2,
  38489. label->getJustificationType(),
  38490. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38491. }
  38492. }
  38493. void ComboBox::resized()
  38494. {
  38495. if (getHeight() > 0 && getWidth() > 0)
  38496. getLookAndFeel().positionComboBoxText (*this, *label);
  38497. }
  38498. void ComboBox::enablementChanged()
  38499. {
  38500. repaint();
  38501. }
  38502. void ComboBox::lookAndFeelChanged()
  38503. {
  38504. repaint();
  38505. {
  38506. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38507. jassert (newLabel != 0);
  38508. if (label != 0)
  38509. {
  38510. newLabel->setEditable (label->isEditable());
  38511. newLabel->setJustificationType (label->getJustificationType());
  38512. newLabel->setTooltip (label->getTooltip());
  38513. newLabel->setText (label->getText(), false);
  38514. }
  38515. label = newLabel;
  38516. }
  38517. addAndMakeVisible (label);
  38518. label->addListener (this);
  38519. label->addMouseListener (this, false);
  38520. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38521. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38522. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38523. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38524. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38525. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38526. resized();
  38527. }
  38528. void ComboBox::colourChanged()
  38529. {
  38530. lookAndFeelChanged();
  38531. }
  38532. bool ComboBox::keyPressed (const KeyPress& key)
  38533. {
  38534. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38535. {
  38536. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38537. return true;
  38538. }
  38539. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38540. {
  38541. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38542. return true;
  38543. }
  38544. else if (key.isKeyCode (KeyPress::returnKey))
  38545. {
  38546. showPopup();
  38547. return true;
  38548. }
  38549. return false;
  38550. }
  38551. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38552. {
  38553. // only forward key events that aren't used by this component
  38554. return isKeyDown
  38555. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38556. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38557. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38558. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38559. }
  38560. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38561. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38562. void ComboBox::labelTextChanged (Label*)
  38563. {
  38564. triggerAsyncUpdate();
  38565. }
  38566. class ComboBox::Callback : public ModalComponentManager::Callback
  38567. {
  38568. public:
  38569. Callback (ComboBox* const box_)
  38570. : box (box_)
  38571. {
  38572. }
  38573. void modalStateFinished (int returnValue)
  38574. {
  38575. if (box != 0)
  38576. {
  38577. box->menuActive = false;
  38578. if (returnValue != 0)
  38579. box->setSelectedId (returnValue);
  38580. }
  38581. }
  38582. private:
  38583. Component::SafePointer<ComboBox> box;
  38584. JUCE_DECLARE_NON_COPYABLE (Callback);
  38585. };
  38586. void ComboBox::showPopup()
  38587. {
  38588. if (! menuActive)
  38589. {
  38590. const int selectedId = getSelectedId();
  38591. PopupMenu menu;
  38592. menu.setLookAndFeel (&getLookAndFeel());
  38593. for (int i = 0; i < items.size(); ++i)
  38594. {
  38595. const ItemInfo* const item = items.getUnchecked(i);
  38596. if (item->isSeparator())
  38597. menu.addSeparator();
  38598. else if (item->isHeading)
  38599. menu.addSectionHeader (item->name);
  38600. else
  38601. menu.addItem (item->itemId, item->name,
  38602. item->isEnabled, item->itemId == selectedId);
  38603. }
  38604. if (items.size() == 0)
  38605. menu.addItem (1, noChoicesMessage, false);
  38606. menuActive = true;
  38607. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38608. new Callback (this));
  38609. }
  38610. }
  38611. void ComboBox::mouseDown (const MouseEvent& e)
  38612. {
  38613. beginDragAutoRepeat (300);
  38614. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38615. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38616. showPopup();
  38617. }
  38618. void ComboBox::mouseDrag (const MouseEvent& e)
  38619. {
  38620. beginDragAutoRepeat (50);
  38621. if (isButtonDown && ! e.mouseWasClicked())
  38622. showPopup();
  38623. }
  38624. void ComboBox::mouseUp (const MouseEvent& e2)
  38625. {
  38626. if (isButtonDown)
  38627. {
  38628. isButtonDown = false;
  38629. repaint();
  38630. const MouseEvent e (e2.getEventRelativeTo (this));
  38631. if (reallyContains (e.getPosition(), true)
  38632. && (e2.eventComponent == this || ! label->isEditable()))
  38633. {
  38634. showPopup();
  38635. }
  38636. }
  38637. }
  38638. void ComboBox::addListener (ComboBoxListener* const listener)
  38639. {
  38640. listeners.add (listener);
  38641. }
  38642. void ComboBox::removeListener (ComboBoxListener* const listener)
  38643. {
  38644. listeners.remove (listener);
  38645. }
  38646. void ComboBox::handleAsyncUpdate()
  38647. {
  38648. Component::BailOutChecker checker (this);
  38649. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38650. }
  38651. END_JUCE_NAMESPACE
  38652. /*** End of inlined file: juce_ComboBox.cpp ***/
  38653. /*** Start of inlined file: juce_Label.cpp ***/
  38654. BEGIN_JUCE_NAMESPACE
  38655. Label::Label (const String& componentName,
  38656. const String& labelText)
  38657. : Component (componentName),
  38658. textValue (labelText),
  38659. lastTextValue (labelText),
  38660. font (15.0f),
  38661. justification (Justification::centredLeft),
  38662. ownerComponent (0),
  38663. horizontalBorderSize (5),
  38664. verticalBorderSize (1),
  38665. minimumHorizontalScale (0.7f),
  38666. editSingleClick (false),
  38667. editDoubleClick (false),
  38668. lossOfFocusDiscardsChanges (false)
  38669. {
  38670. setColour (TextEditor::textColourId, Colours::black);
  38671. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38672. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38673. textValue.addListener (this);
  38674. }
  38675. Label::~Label()
  38676. {
  38677. textValue.removeListener (this);
  38678. if (ownerComponent != 0)
  38679. ownerComponent->removeComponentListener (this);
  38680. editor = 0;
  38681. }
  38682. void Label::setText (const String& newText,
  38683. const bool broadcastChangeMessage)
  38684. {
  38685. hideEditor (true);
  38686. if (lastTextValue != newText)
  38687. {
  38688. lastTextValue = newText;
  38689. textValue = newText;
  38690. repaint();
  38691. textWasChanged();
  38692. if (ownerComponent != 0)
  38693. componentMovedOrResized (*ownerComponent, true, true);
  38694. if (broadcastChangeMessage)
  38695. callChangeListeners();
  38696. }
  38697. }
  38698. const String Label::getText (const bool returnActiveEditorContents) const
  38699. {
  38700. return (returnActiveEditorContents && isBeingEdited())
  38701. ? editor->getText()
  38702. : textValue.toString();
  38703. }
  38704. void Label::valueChanged (Value&)
  38705. {
  38706. if (lastTextValue != textValue.toString())
  38707. setText (textValue.toString(), true);
  38708. }
  38709. void Label::setFont (const Font& newFont)
  38710. {
  38711. if (font != newFont)
  38712. {
  38713. font = newFont;
  38714. repaint();
  38715. }
  38716. }
  38717. const Font& Label::getFont() const throw()
  38718. {
  38719. return font;
  38720. }
  38721. void Label::setEditable (const bool editOnSingleClick,
  38722. const bool editOnDoubleClick,
  38723. const bool lossOfFocusDiscardsChanges_)
  38724. {
  38725. editSingleClick = editOnSingleClick;
  38726. editDoubleClick = editOnDoubleClick;
  38727. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38728. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38729. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38730. }
  38731. void Label::setJustificationType (const Justification& newJustification)
  38732. {
  38733. if (justification != newJustification)
  38734. {
  38735. justification = newJustification;
  38736. repaint();
  38737. }
  38738. }
  38739. void Label::setBorderSize (int h, int v)
  38740. {
  38741. if (horizontalBorderSize != h || verticalBorderSize != v)
  38742. {
  38743. horizontalBorderSize = h;
  38744. verticalBorderSize = v;
  38745. repaint();
  38746. }
  38747. }
  38748. Component* Label::getAttachedComponent() const
  38749. {
  38750. return static_cast<Component*> (ownerComponent);
  38751. }
  38752. void Label::attachToComponent (Component* owner,
  38753. const bool onLeft)
  38754. {
  38755. if (ownerComponent != 0)
  38756. ownerComponent->removeComponentListener (this);
  38757. ownerComponent = owner;
  38758. leftOfOwnerComp = onLeft;
  38759. if (ownerComponent != 0)
  38760. {
  38761. setVisible (owner->isVisible());
  38762. ownerComponent->addComponentListener (this);
  38763. componentParentHierarchyChanged (*ownerComponent);
  38764. componentMovedOrResized (*ownerComponent, true, true);
  38765. }
  38766. }
  38767. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38768. {
  38769. if (leftOfOwnerComp)
  38770. {
  38771. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38772. component.getHeight());
  38773. setTopRightPosition (component.getX(), component.getY());
  38774. }
  38775. else
  38776. {
  38777. setSize (component.getWidth(),
  38778. 8 + roundToInt (getFont().getHeight()));
  38779. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38780. }
  38781. }
  38782. void Label::componentParentHierarchyChanged (Component& component)
  38783. {
  38784. if (component.getParentComponent() != 0)
  38785. component.getParentComponent()->addChildComponent (this);
  38786. }
  38787. void Label::componentVisibilityChanged (Component& component)
  38788. {
  38789. setVisible (component.isVisible());
  38790. }
  38791. void Label::textWasEdited()
  38792. {
  38793. }
  38794. void Label::textWasChanged()
  38795. {
  38796. }
  38797. void Label::showEditor()
  38798. {
  38799. if (editor == 0)
  38800. {
  38801. addAndMakeVisible (editor = createEditorComponent());
  38802. editor->setText (getText(), false);
  38803. editor->addListener (this);
  38804. editor->grabKeyboardFocus();
  38805. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38806. editor->addListener (this);
  38807. resized();
  38808. repaint();
  38809. editorShown (editor);
  38810. enterModalState (false);
  38811. editor->grabKeyboardFocus();
  38812. }
  38813. }
  38814. void Label::editorShown (TextEditor* /*editorComponent*/)
  38815. {
  38816. }
  38817. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38818. {
  38819. }
  38820. bool Label::updateFromTextEditorContents()
  38821. {
  38822. jassert (editor != 0);
  38823. const String newText (editor->getText());
  38824. if (textValue.toString() != newText)
  38825. {
  38826. lastTextValue = newText;
  38827. textValue = newText;
  38828. repaint();
  38829. textWasChanged();
  38830. if (ownerComponent != 0)
  38831. componentMovedOrResized (*ownerComponent, true, true);
  38832. return true;
  38833. }
  38834. return false;
  38835. }
  38836. void Label::hideEditor (const bool discardCurrentEditorContents)
  38837. {
  38838. if (editor != 0)
  38839. {
  38840. Component::SafePointer<Component> deletionChecker (this);
  38841. editorAboutToBeHidden (editor);
  38842. const bool changed = (! discardCurrentEditorContents)
  38843. && updateFromTextEditorContents();
  38844. editor = 0;
  38845. repaint();
  38846. if (changed)
  38847. textWasEdited();
  38848. if (deletionChecker != 0)
  38849. exitModalState (0);
  38850. if (changed && deletionChecker != 0)
  38851. callChangeListeners();
  38852. }
  38853. }
  38854. void Label::inputAttemptWhenModal()
  38855. {
  38856. if (editor != 0)
  38857. {
  38858. if (lossOfFocusDiscardsChanges)
  38859. textEditorEscapeKeyPressed (*editor);
  38860. else
  38861. textEditorReturnKeyPressed (*editor);
  38862. }
  38863. }
  38864. bool Label::isBeingEdited() const throw()
  38865. {
  38866. return editor != 0;
  38867. }
  38868. TextEditor* Label::createEditorComponent()
  38869. {
  38870. TextEditor* const ed = new TextEditor (getName());
  38871. ed->setFont (font);
  38872. // copy these colours from our own settings..
  38873. const int cols[] = { TextEditor::backgroundColourId,
  38874. TextEditor::textColourId,
  38875. TextEditor::highlightColourId,
  38876. TextEditor::highlightedTextColourId,
  38877. TextEditor::caretColourId,
  38878. TextEditor::outlineColourId,
  38879. TextEditor::focusedOutlineColourId,
  38880. TextEditor::shadowColourId };
  38881. for (int i = 0; i < numElementsInArray (cols); ++i)
  38882. ed->setColour (cols[i], findColour (cols[i]));
  38883. return ed;
  38884. }
  38885. void Label::paint (Graphics& g)
  38886. {
  38887. getLookAndFeel().drawLabel (g, *this);
  38888. }
  38889. void Label::mouseUp (const MouseEvent& e)
  38890. {
  38891. if (editSingleClick
  38892. && e.mouseWasClicked()
  38893. && contains (e.getPosition())
  38894. && ! e.mods.isPopupMenu())
  38895. {
  38896. showEditor();
  38897. }
  38898. }
  38899. void Label::mouseDoubleClick (const MouseEvent& e)
  38900. {
  38901. if (editDoubleClick && ! e.mods.isPopupMenu())
  38902. showEditor();
  38903. }
  38904. void Label::resized()
  38905. {
  38906. if (editor != 0)
  38907. editor->setBoundsInset (BorderSize (0));
  38908. }
  38909. void Label::focusGained (FocusChangeType cause)
  38910. {
  38911. if (editSingleClick && cause == focusChangedByTabKey)
  38912. showEditor();
  38913. }
  38914. void Label::enablementChanged()
  38915. {
  38916. repaint();
  38917. }
  38918. void Label::colourChanged()
  38919. {
  38920. repaint();
  38921. }
  38922. void Label::setMinimumHorizontalScale (const float newScale)
  38923. {
  38924. if (minimumHorizontalScale != newScale)
  38925. {
  38926. minimumHorizontalScale = newScale;
  38927. repaint();
  38928. }
  38929. }
  38930. // We'll use a custom focus traverser here to make sure focus goes from the
  38931. // text editor to another component rather than back to the label itself.
  38932. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38933. {
  38934. public:
  38935. LabelKeyboardFocusTraverser() {}
  38936. Component* getNextComponent (Component* current)
  38937. {
  38938. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38939. ? current->getParentComponent() : current);
  38940. }
  38941. Component* getPreviousComponent (Component* current)
  38942. {
  38943. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38944. ? current->getParentComponent() : current);
  38945. }
  38946. };
  38947. KeyboardFocusTraverser* Label::createFocusTraverser()
  38948. {
  38949. return new LabelKeyboardFocusTraverser();
  38950. }
  38951. void Label::addListener (LabelListener* const listener)
  38952. {
  38953. listeners.add (listener);
  38954. }
  38955. void Label::removeListener (LabelListener* const listener)
  38956. {
  38957. listeners.remove (listener);
  38958. }
  38959. void Label::callChangeListeners()
  38960. {
  38961. Component::BailOutChecker checker (this);
  38962. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38963. }
  38964. void Label::textEditorTextChanged (TextEditor& ed)
  38965. {
  38966. if (editor != 0)
  38967. {
  38968. jassert (&ed == editor);
  38969. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38970. {
  38971. if (lossOfFocusDiscardsChanges)
  38972. textEditorEscapeKeyPressed (ed);
  38973. else
  38974. textEditorReturnKeyPressed (ed);
  38975. }
  38976. }
  38977. }
  38978. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38979. {
  38980. if (editor != 0)
  38981. {
  38982. jassert (&ed == editor);
  38983. (void) ed;
  38984. const bool changed = updateFromTextEditorContents();
  38985. hideEditor (true);
  38986. if (changed)
  38987. {
  38988. Component::SafePointer<Component> deletionChecker (this);
  38989. textWasEdited();
  38990. if (deletionChecker != 0)
  38991. callChangeListeners();
  38992. }
  38993. }
  38994. }
  38995. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38996. {
  38997. if (editor != 0)
  38998. {
  38999. jassert (&ed == editor);
  39000. (void) ed;
  39001. editor->setText (textValue.toString(), false);
  39002. hideEditor (true);
  39003. }
  39004. }
  39005. void Label::textEditorFocusLost (TextEditor& ed)
  39006. {
  39007. textEditorTextChanged (ed);
  39008. }
  39009. END_JUCE_NAMESPACE
  39010. /*** End of inlined file: juce_Label.cpp ***/
  39011. /*** Start of inlined file: juce_ListBox.cpp ***/
  39012. BEGIN_JUCE_NAMESPACE
  39013. class ListBoxRowComponent : public Component,
  39014. public TooltipClient
  39015. {
  39016. public:
  39017. ListBoxRowComponent (ListBox& owner_)
  39018. : owner (owner_), row (-1),
  39019. selected (false), isDragging (false), selectRowOnMouseUp (false)
  39020. {
  39021. }
  39022. void paint (Graphics& g)
  39023. {
  39024. if (owner.getModel() != 0)
  39025. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39026. }
  39027. void update (const int row_, const bool selected_)
  39028. {
  39029. if (row != row_ || selected != selected_)
  39030. {
  39031. repaint();
  39032. row = row_;
  39033. selected = selected_;
  39034. }
  39035. if (owner.getModel() != 0)
  39036. {
  39037. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  39038. if (customComponent != 0)
  39039. {
  39040. addAndMakeVisible (customComponent);
  39041. customComponent->setBounds (getLocalBounds());
  39042. }
  39043. }
  39044. }
  39045. void mouseDown (const MouseEvent& e)
  39046. {
  39047. isDragging = false;
  39048. selectRowOnMouseUp = false;
  39049. if (isEnabled())
  39050. {
  39051. if (! selected)
  39052. {
  39053. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39054. if (owner.getModel() != 0)
  39055. owner.getModel()->listBoxItemClicked (row, e);
  39056. }
  39057. else
  39058. {
  39059. selectRowOnMouseUp = true;
  39060. }
  39061. }
  39062. }
  39063. void mouseUp (const MouseEvent& e)
  39064. {
  39065. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39066. {
  39067. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39068. if (owner.getModel() != 0)
  39069. owner.getModel()->listBoxItemClicked (row, e);
  39070. }
  39071. }
  39072. void mouseDoubleClick (const MouseEvent& e)
  39073. {
  39074. if (owner.getModel() != 0 && isEnabled())
  39075. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39076. }
  39077. void mouseDrag (const MouseEvent& e)
  39078. {
  39079. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39080. {
  39081. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39082. if (selectedRows.size() > 0)
  39083. {
  39084. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39085. if (dragDescription.isNotEmpty())
  39086. {
  39087. isDragging = true;
  39088. owner.startDragAndDrop (e, dragDescription);
  39089. }
  39090. }
  39091. }
  39092. }
  39093. void resized()
  39094. {
  39095. if (customComponent != 0)
  39096. customComponent->setBounds (getLocalBounds());
  39097. }
  39098. const String getTooltip()
  39099. {
  39100. if (owner.getModel() != 0)
  39101. return owner.getModel()->getTooltipForRow (row);
  39102. return String::empty;
  39103. }
  39104. ScopedPointer<Component> customComponent;
  39105. private:
  39106. ListBox& owner;
  39107. int row;
  39108. bool selected, isDragging, selectRowOnMouseUp;
  39109. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  39110. };
  39111. class ListViewport : public Viewport
  39112. {
  39113. public:
  39114. ListViewport (ListBox& owner_)
  39115. : owner (owner_)
  39116. {
  39117. setWantsKeyboardFocus (false);
  39118. Component* const content = new Component();
  39119. setViewedComponent (content);
  39120. content->addMouseListener (this, false);
  39121. content->setWantsKeyboardFocus (false);
  39122. }
  39123. ~ListViewport()
  39124. {
  39125. }
  39126. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39127. {
  39128. return rows [row % jmax (1, rows.size())];
  39129. }
  39130. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39131. {
  39132. return (row >= firstIndex && row < firstIndex + rows.size())
  39133. ? getComponentForRow (row) : 0;
  39134. }
  39135. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39136. {
  39137. const int index = getIndexOfChildComponent (rowComponent);
  39138. const int num = rows.size();
  39139. for (int i = num; --i >= 0;)
  39140. if (((firstIndex + i) % jmax (1, num)) == index)
  39141. return firstIndex + i;
  39142. return -1;
  39143. }
  39144. void visibleAreaChanged (int, int, int, int)
  39145. {
  39146. updateVisibleArea (true);
  39147. if (owner.getModel() != 0)
  39148. owner.getModel()->listWasScrolled();
  39149. }
  39150. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39151. {
  39152. hasUpdated = false;
  39153. const int newX = getViewedComponent()->getX();
  39154. int newY = getViewedComponent()->getY();
  39155. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39156. const int newH = owner.totalItems * owner.getRowHeight();
  39157. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39158. newY = getMaximumVisibleHeight() - newH;
  39159. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39160. if (makeSureItUpdatesContent && ! hasUpdated)
  39161. updateContents();
  39162. }
  39163. void updateContents()
  39164. {
  39165. hasUpdated = true;
  39166. const int rowHeight = owner.getRowHeight();
  39167. if (rowHeight > 0)
  39168. {
  39169. const int y = getViewPositionY();
  39170. const int w = getViewedComponent()->getWidth();
  39171. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39172. rows.removeRange (numNeeded, rows.size());
  39173. while (numNeeded > rows.size())
  39174. {
  39175. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39176. rows.add (newRow);
  39177. getViewedComponent()->addAndMakeVisible (newRow);
  39178. }
  39179. firstIndex = y / rowHeight;
  39180. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39181. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39182. for (int i = 0; i < numNeeded; ++i)
  39183. {
  39184. const int row = i + firstIndex;
  39185. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39186. if (rowComp != 0)
  39187. {
  39188. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39189. rowComp->update (row, owner.isRowSelected (row));
  39190. }
  39191. }
  39192. }
  39193. if (owner.headerComponent != 0)
  39194. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39195. owner.outlineThickness,
  39196. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39197. getViewedComponent()->getWidth()),
  39198. owner.headerComponent->getHeight());
  39199. }
  39200. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39201. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39202. {
  39203. hasUpdated = false;
  39204. if (row < firstWholeIndex && ! dontScroll)
  39205. {
  39206. setViewPosition (getViewPositionX(), row * rowHeight);
  39207. }
  39208. else if (row >= lastWholeIndex && ! dontScroll)
  39209. {
  39210. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39211. if (row >= lastRowSelected + rowsOnScreen
  39212. && rowsOnScreen < totalItems - 1
  39213. && ! isMouseClick)
  39214. {
  39215. setViewPosition (getViewPositionX(),
  39216. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39217. }
  39218. else
  39219. {
  39220. setViewPosition (getViewPositionX(),
  39221. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39222. }
  39223. }
  39224. if (! hasUpdated)
  39225. updateContents();
  39226. }
  39227. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39228. {
  39229. if (row < firstWholeIndex)
  39230. {
  39231. setViewPosition (getViewPositionX(), row * rowHeight);
  39232. }
  39233. else if (row >= lastWholeIndex)
  39234. {
  39235. setViewPosition (getViewPositionX(),
  39236. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39237. }
  39238. }
  39239. void paint (Graphics& g)
  39240. {
  39241. if (isOpaque())
  39242. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39243. }
  39244. bool keyPressed (const KeyPress& key)
  39245. {
  39246. if (key.isKeyCode (KeyPress::upKey)
  39247. || key.isKeyCode (KeyPress::downKey)
  39248. || key.isKeyCode (KeyPress::pageUpKey)
  39249. || key.isKeyCode (KeyPress::pageDownKey)
  39250. || key.isKeyCode (KeyPress::homeKey)
  39251. || key.isKeyCode (KeyPress::endKey))
  39252. {
  39253. // we want to avoid these keypresses going to the viewport, and instead allow
  39254. // them to pass up to our listbox..
  39255. return false;
  39256. }
  39257. return Viewport::keyPressed (key);
  39258. }
  39259. private:
  39260. ListBox& owner;
  39261. OwnedArray<ListBoxRowComponent> rows;
  39262. int firstIndex, firstWholeIndex, lastWholeIndex;
  39263. bool hasUpdated;
  39264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39265. };
  39266. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39267. : Component (name),
  39268. model (model_),
  39269. totalItems (0),
  39270. rowHeight (22),
  39271. minimumRowWidth (0),
  39272. outlineThickness (0),
  39273. lastRowSelected (-1),
  39274. mouseMoveSelects (false),
  39275. multipleSelection (false),
  39276. hasDoneInitialUpdate (false)
  39277. {
  39278. addAndMakeVisible (viewport = new ListViewport (*this));
  39279. setWantsKeyboardFocus (true);
  39280. colourChanged();
  39281. }
  39282. ListBox::~ListBox()
  39283. {
  39284. headerComponent = 0;
  39285. viewport = 0;
  39286. }
  39287. void ListBox::setModel (ListBoxModel* const newModel)
  39288. {
  39289. if (model != newModel)
  39290. {
  39291. model = newModel;
  39292. repaint();
  39293. updateContent();
  39294. }
  39295. }
  39296. void ListBox::setMultipleSelectionEnabled (bool b)
  39297. {
  39298. multipleSelection = b;
  39299. }
  39300. void ListBox::setMouseMoveSelectsRows (bool b)
  39301. {
  39302. mouseMoveSelects = b;
  39303. if (b)
  39304. addMouseListener (this, true);
  39305. }
  39306. void ListBox::paint (Graphics& g)
  39307. {
  39308. if (! hasDoneInitialUpdate)
  39309. updateContent();
  39310. g.fillAll (findColour (backgroundColourId));
  39311. }
  39312. void ListBox::paintOverChildren (Graphics& g)
  39313. {
  39314. if (outlineThickness > 0)
  39315. {
  39316. g.setColour (findColour (outlineColourId));
  39317. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39318. }
  39319. }
  39320. void ListBox::resized()
  39321. {
  39322. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39323. outlineThickness,
  39324. outlineThickness,
  39325. outlineThickness));
  39326. viewport->setSingleStepSizes (20, getRowHeight());
  39327. viewport->updateVisibleArea (false);
  39328. }
  39329. void ListBox::visibilityChanged()
  39330. {
  39331. viewport->updateVisibleArea (true);
  39332. }
  39333. Viewport* ListBox::getViewport() const throw()
  39334. {
  39335. return viewport;
  39336. }
  39337. void ListBox::updateContent()
  39338. {
  39339. hasDoneInitialUpdate = true;
  39340. totalItems = (model != 0) ? model->getNumRows() : 0;
  39341. bool selectionChanged = false;
  39342. if (selected [selected.size() - 1] >= totalItems)
  39343. {
  39344. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39345. lastRowSelected = getSelectedRow (0);
  39346. selectionChanged = true;
  39347. }
  39348. viewport->updateVisibleArea (isVisible());
  39349. viewport->resized();
  39350. if (selectionChanged && model != 0)
  39351. model->selectedRowsChanged (lastRowSelected);
  39352. }
  39353. void ListBox::selectRow (const int row,
  39354. bool dontScroll,
  39355. bool deselectOthersFirst)
  39356. {
  39357. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39358. }
  39359. void ListBox::selectRowInternal (const int row,
  39360. bool dontScroll,
  39361. bool deselectOthersFirst,
  39362. bool isMouseClick)
  39363. {
  39364. if (! multipleSelection)
  39365. deselectOthersFirst = true;
  39366. if ((! isRowSelected (row))
  39367. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39368. {
  39369. if (isPositiveAndBelow (row, totalItems))
  39370. {
  39371. if (deselectOthersFirst)
  39372. selected.clear();
  39373. selected.addRange (Range<int> (row, row + 1));
  39374. if (getHeight() == 0 || getWidth() == 0)
  39375. dontScroll = true;
  39376. viewport->selectRow (row, getRowHeight(), dontScroll,
  39377. lastRowSelected, totalItems, isMouseClick);
  39378. lastRowSelected = row;
  39379. model->selectedRowsChanged (row);
  39380. }
  39381. else
  39382. {
  39383. if (deselectOthersFirst)
  39384. deselectAllRows();
  39385. }
  39386. }
  39387. }
  39388. void ListBox::deselectRow (const int row)
  39389. {
  39390. if (selected.contains (row))
  39391. {
  39392. selected.removeRange (Range <int> (row, row + 1));
  39393. if (row == lastRowSelected)
  39394. lastRowSelected = getSelectedRow (0);
  39395. viewport->updateContents();
  39396. model->selectedRowsChanged (lastRowSelected);
  39397. }
  39398. }
  39399. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39400. const bool sendNotificationEventToModel)
  39401. {
  39402. selected = setOfRowsToBeSelected;
  39403. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39404. if (! isRowSelected (lastRowSelected))
  39405. lastRowSelected = getSelectedRow (0);
  39406. viewport->updateContents();
  39407. if ((model != 0) && sendNotificationEventToModel)
  39408. model->selectedRowsChanged (lastRowSelected);
  39409. }
  39410. const SparseSet<int> ListBox::getSelectedRows() const
  39411. {
  39412. return selected;
  39413. }
  39414. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39415. {
  39416. if (multipleSelection && (firstRow != lastRow))
  39417. {
  39418. const int numRows = totalItems - 1;
  39419. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39420. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39421. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39422. jmax (firstRow, lastRow) + 1));
  39423. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39424. }
  39425. selectRowInternal (lastRow, false, false, true);
  39426. }
  39427. void ListBox::flipRowSelection (const int row)
  39428. {
  39429. if (isRowSelected (row))
  39430. deselectRow (row);
  39431. else
  39432. selectRowInternal (row, false, false, true);
  39433. }
  39434. void ListBox::deselectAllRows()
  39435. {
  39436. if (! selected.isEmpty())
  39437. {
  39438. selected.clear();
  39439. lastRowSelected = -1;
  39440. viewport->updateContents();
  39441. if (model != 0)
  39442. model->selectedRowsChanged (lastRowSelected);
  39443. }
  39444. }
  39445. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39446. const ModifierKeys& mods)
  39447. {
  39448. if (multipleSelection && mods.isCommandDown())
  39449. {
  39450. flipRowSelection (row);
  39451. }
  39452. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39453. {
  39454. selectRangeOfRows (lastRowSelected, row);
  39455. }
  39456. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39457. {
  39458. selectRowInternal (row, false, ! (multipleSelection && isRowSelected (row)), true);
  39459. }
  39460. }
  39461. int ListBox::getNumSelectedRows() const
  39462. {
  39463. return selected.size();
  39464. }
  39465. int ListBox::getSelectedRow (const int index) const
  39466. {
  39467. return (isPositiveAndBelow (index, selected.size()))
  39468. ? selected [index] : -1;
  39469. }
  39470. bool ListBox::isRowSelected (const int row) const
  39471. {
  39472. return selected.contains (row);
  39473. }
  39474. int ListBox::getLastRowSelected() const
  39475. {
  39476. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39477. }
  39478. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39479. {
  39480. if (isPositiveAndBelow (x, getWidth()))
  39481. {
  39482. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39483. if (isPositiveAndBelow (row, totalItems))
  39484. return row;
  39485. }
  39486. return -1;
  39487. }
  39488. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39489. {
  39490. if (isPositiveAndBelow (x, getWidth()))
  39491. {
  39492. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39493. return jlimit (0, totalItems, row);
  39494. }
  39495. return -1;
  39496. }
  39497. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39498. {
  39499. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39500. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39501. }
  39502. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39503. {
  39504. return viewport->getRowNumberOfComponent (rowComponent);
  39505. }
  39506. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39507. const bool relativeToComponentTopLeft) const throw()
  39508. {
  39509. int y = viewport->getY() + rowHeight * rowNumber;
  39510. if (relativeToComponentTopLeft)
  39511. y -= viewport->getViewPositionY();
  39512. return Rectangle<int> (viewport->getX(), y,
  39513. viewport->getViewedComponent()->getWidth(), rowHeight);
  39514. }
  39515. void ListBox::setVerticalPosition (const double proportion)
  39516. {
  39517. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39518. viewport->setViewPosition (viewport->getViewPositionX(),
  39519. jmax (0, roundToInt (proportion * offscreen)));
  39520. }
  39521. double ListBox::getVerticalPosition() const
  39522. {
  39523. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39524. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39525. : 0;
  39526. }
  39527. int ListBox::getVisibleRowWidth() const throw()
  39528. {
  39529. return viewport->getViewWidth();
  39530. }
  39531. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39532. {
  39533. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39534. }
  39535. bool ListBox::keyPressed (const KeyPress& key)
  39536. {
  39537. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39538. const bool multiple = multipleSelection
  39539. && (lastRowSelected >= 0)
  39540. && (key.getModifiers().isShiftDown()
  39541. || key.getModifiers().isCtrlDown()
  39542. || key.getModifiers().isCommandDown());
  39543. if (key.isKeyCode (KeyPress::upKey))
  39544. {
  39545. if (multiple)
  39546. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39547. else
  39548. selectRow (jmax (0, lastRowSelected - 1));
  39549. }
  39550. else if (key.isKeyCode (KeyPress::returnKey)
  39551. && isRowSelected (lastRowSelected))
  39552. {
  39553. if (model != 0)
  39554. model->returnKeyPressed (lastRowSelected);
  39555. }
  39556. else if (key.isKeyCode (KeyPress::pageUpKey))
  39557. {
  39558. if (multiple)
  39559. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39560. else
  39561. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39562. }
  39563. else if (key.isKeyCode (KeyPress::pageDownKey))
  39564. {
  39565. if (multiple)
  39566. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39567. else
  39568. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39569. }
  39570. else if (key.isKeyCode (KeyPress::homeKey))
  39571. {
  39572. if (multiple && key.getModifiers().isShiftDown())
  39573. selectRangeOfRows (lastRowSelected, 0);
  39574. else
  39575. selectRow (0);
  39576. }
  39577. else if (key.isKeyCode (KeyPress::endKey))
  39578. {
  39579. if (multiple && key.getModifiers().isShiftDown())
  39580. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39581. else
  39582. selectRow (totalItems - 1);
  39583. }
  39584. else if (key.isKeyCode (KeyPress::downKey))
  39585. {
  39586. if (multiple)
  39587. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39588. else
  39589. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39590. }
  39591. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39592. && isRowSelected (lastRowSelected))
  39593. {
  39594. if (model != 0)
  39595. model->deleteKeyPressed (lastRowSelected);
  39596. }
  39597. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39598. {
  39599. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39600. }
  39601. else
  39602. {
  39603. return false;
  39604. }
  39605. return true;
  39606. }
  39607. bool ListBox::keyStateChanged (const bool isKeyDown)
  39608. {
  39609. return isKeyDown
  39610. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39611. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39612. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39613. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39614. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39615. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39616. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39617. }
  39618. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39619. {
  39620. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39621. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39622. }
  39623. void ListBox::mouseMove (const MouseEvent& e)
  39624. {
  39625. if (mouseMoveSelects)
  39626. {
  39627. const MouseEvent e2 (e.getEventRelativeTo (this));
  39628. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39629. }
  39630. }
  39631. void ListBox::mouseExit (const MouseEvent& e)
  39632. {
  39633. mouseMove (e);
  39634. }
  39635. void ListBox::mouseUp (const MouseEvent& e)
  39636. {
  39637. if (e.mouseWasClicked() && model != 0)
  39638. model->backgroundClicked();
  39639. }
  39640. void ListBox::setRowHeight (const int newHeight)
  39641. {
  39642. rowHeight = jmax (1, newHeight);
  39643. viewport->setSingleStepSizes (20, rowHeight);
  39644. updateContent();
  39645. }
  39646. int ListBox::getNumRowsOnScreen() const throw()
  39647. {
  39648. return viewport->getMaximumVisibleHeight() / rowHeight;
  39649. }
  39650. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39651. {
  39652. minimumRowWidth = newMinimumWidth;
  39653. updateContent();
  39654. }
  39655. int ListBox::getVisibleContentWidth() const throw()
  39656. {
  39657. return viewport->getMaximumVisibleWidth();
  39658. }
  39659. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39660. {
  39661. return viewport->getVerticalScrollBar();
  39662. }
  39663. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39664. {
  39665. return viewport->getHorizontalScrollBar();
  39666. }
  39667. void ListBox::colourChanged()
  39668. {
  39669. setOpaque (findColour (backgroundColourId).isOpaque());
  39670. viewport->setOpaque (isOpaque());
  39671. repaint();
  39672. }
  39673. void ListBox::setOutlineThickness (const int outlineThickness_)
  39674. {
  39675. outlineThickness = outlineThickness_;
  39676. resized();
  39677. }
  39678. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39679. {
  39680. if (headerComponent != newHeaderComponent)
  39681. {
  39682. headerComponent = newHeaderComponent;
  39683. addAndMakeVisible (newHeaderComponent);
  39684. ListBox::resized();
  39685. }
  39686. }
  39687. void ListBox::repaintRow (const int rowNumber) throw()
  39688. {
  39689. repaint (getRowPosition (rowNumber, true));
  39690. }
  39691. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39692. {
  39693. Rectangle<int> imageArea;
  39694. const int firstRow = getRowContainingPosition (0, 0);
  39695. int i;
  39696. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39697. {
  39698. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39699. if (rowComp != 0 && isRowSelected (firstRow + i))
  39700. {
  39701. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39702. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39703. imageArea = imageArea.getUnion (rowRect);
  39704. }
  39705. }
  39706. imageArea = imageArea.getIntersection (getLocalBounds());
  39707. imageX = imageArea.getX();
  39708. imageY = imageArea.getY();
  39709. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39710. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39711. {
  39712. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39713. if (rowComp != 0 && isRowSelected (firstRow + i))
  39714. {
  39715. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39716. Graphics g (snapshot);
  39717. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39718. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39719. rowComp->paintEntireComponent (g, false);
  39720. }
  39721. }
  39722. return snapshot;
  39723. }
  39724. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39725. {
  39726. DragAndDropContainer* const dragContainer
  39727. = DragAndDropContainer::findParentDragContainerFor (this);
  39728. if (dragContainer != 0)
  39729. {
  39730. int x, y;
  39731. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39732. dragImage.multiplyAllAlphas (0.6f);
  39733. MouseEvent e2 (e.getEventRelativeTo (this));
  39734. const Point<int> p (x - e2.x, y - e2.y);
  39735. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39736. }
  39737. else
  39738. {
  39739. // to be able to do a drag-and-drop operation, the listbox needs to
  39740. // be inside a component which is also a DragAndDropContainer.
  39741. jassertfalse;
  39742. }
  39743. }
  39744. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39745. {
  39746. (void) existingComponentToUpdate;
  39747. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39748. return 0;
  39749. }
  39750. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39751. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39752. void ListBoxModel::backgroundClicked() {}
  39753. void ListBoxModel::selectedRowsChanged (int) {}
  39754. void ListBoxModel::deleteKeyPressed (int) {}
  39755. void ListBoxModel::returnKeyPressed (int) {}
  39756. void ListBoxModel::listWasScrolled() {}
  39757. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39758. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39759. END_JUCE_NAMESPACE
  39760. /*** End of inlined file: juce_ListBox.cpp ***/
  39761. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39762. BEGIN_JUCE_NAMESPACE
  39763. ProgressBar::ProgressBar (double& progress_)
  39764. : progress (progress_),
  39765. displayPercentage (true),
  39766. lastCallbackTime (0)
  39767. {
  39768. currentValue = jlimit (0.0, 1.0, progress);
  39769. }
  39770. ProgressBar::~ProgressBar()
  39771. {
  39772. }
  39773. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39774. {
  39775. displayPercentage = shouldDisplayPercentage;
  39776. repaint();
  39777. }
  39778. void ProgressBar::setTextToDisplay (const String& text)
  39779. {
  39780. displayPercentage = false;
  39781. displayedMessage = text;
  39782. }
  39783. void ProgressBar::lookAndFeelChanged()
  39784. {
  39785. setOpaque (findColour (backgroundColourId).isOpaque());
  39786. }
  39787. void ProgressBar::colourChanged()
  39788. {
  39789. lookAndFeelChanged();
  39790. }
  39791. void ProgressBar::paint (Graphics& g)
  39792. {
  39793. String text;
  39794. if (displayPercentage)
  39795. {
  39796. if (currentValue >= 0 && currentValue <= 1.0)
  39797. text << roundToInt (currentValue * 100.0) << '%';
  39798. }
  39799. else
  39800. {
  39801. text = displayedMessage;
  39802. }
  39803. getLookAndFeel().drawProgressBar (g, *this,
  39804. getWidth(), getHeight(),
  39805. currentValue, text);
  39806. }
  39807. void ProgressBar::visibilityChanged()
  39808. {
  39809. if (isVisible())
  39810. startTimer (30);
  39811. else
  39812. stopTimer();
  39813. }
  39814. void ProgressBar::timerCallback()
  39815. {
  39816. double newProgress = progress;
  39817. const uint32 now = Time::getMillisecondCounter();
  39818. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39819. lastCallbackTime = now;
  39820. if (currentValue != newProgress
  39821. || newProgress < 0 || newProgress >= 1.0
  39822. || currentMessage != displayedMessage)
  39823. {
  39824. if (currentValue < newProgress
  39825. && newProgress >= 0 && newProgress < 1.0
  39826. && currentValue >= 0 && currentValue < 1.0)
  39827. {
  39828. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39829. newProgress);
  39830. }
  39831. currentValue = newProgress;
  39832. currentMessage = displayedMessage;
  39833. repaint();
  39834. }
  39835. }
  39836. END_JUCE_NAMESPACE
  39837. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39838. /*** Start of inlined file: juce_Slider.cpp ***/
  39839. BEGIN_JUCE_NAMESPACE
  39840. class SliderPopupDisplayComponent : public BubbleComponent
  39841. {
  39842. public:
  39843. SliderPopupDisplayComponent (Slider* const owner_)
  39844. : owner (owner_),
  39845. font (15.0f, Font::bold)
  39846. {
  39847. setAlwaysOnTop (true);
  39848. }
  39849. ~SliderPopupDisplayComponent()
  39850. {
  39851. }
  39852. void paintContent (Graphics& g, int w, int h)
  39853. {
  39854. g.setFont (font);
  39855. g.setColour (Colours::black);
  39856. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39857. }
  39858. void getContentSize (int& w, int& h)
  39859. {
  39860. w = font.getStringWidth (text) + 18;
  39861. h = (int) (font.getHeight() * 1.6f);
  39862. }
  39863. void updatePosition (const String& newText)
  39864. {
  39865. if (text != newText)
  39866. {
  39867. text = newText;
  39868. repaint();
  39869. }
  39870. BubbleComponent::setPosition (owner);
  39871. }
  39872. private:
  39873. Slider* owner;
  39874. Font font;
  39875. String text;
  39876. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39877. };
  39878. Slider::Slider (const String& name)
  39879. : Component (name),
  39880. lastCurrentValue (0),
  39881. lastValueMin (0),
  39882. lastValueMax (0),
  39883. minimum (0),
  39884. maximum (10),
  39885. interval (0),
  39886. skewFactor (1.0),
  39887. velocityModeSensitivity (1.0),
  39888. velocityModeOffset (0.0),
  39889. velocityModeThreshold (1),
  39890. rotaryStart (float_Pi * 1.2f),
  39891. rotaryEnd (float_Pi * 2.8f),
  39892. numDecimalPlaces (7),
  39893. sliderRegionStart (0),
  39894. sliderRegionSize (1),
  39895. sliderBeingDragged (-1),
  39896. pixelsForFullDragExtent (250),
  39897. style (LinearHorizontal),
  39898. textBoxPos (TextBoxLeft),
  39899. textBoxWidth (80),
  39900. textBoxHeight (20),
  39901. incDecButtonMode (incDecButtonsNotDraggable),
  39902. editableText (true),
  39903. doubleClickToValue (false),
  39904. isVelocityBased (false),
  39905. userKeyOverridesVelocity (true),
  39906. rotaryStop (true),
  39907. incDecButtonsSideBySide (false),
  39908. sendChangeOnlyOnRelease (false),
  39909. popupDisplayEnabled (false),
  39910. menuEnabled (false),
  39911. menuShown (false),
  39912. scrollWheelEnabled (true),
  39913. snapsToMousePos (true),
  39914. popupDisplay (0),
  39915. parentForPopupDisplay (0)
  39916. {
  39917. setWantsKeyboardFocus (false);
  39918. setRepaintsOnMouseActivity (true);
  39919. lookAndFeelChanged();
  39920. updateText();
  39921. currentValue.addListener (this);
  39922. valueMin.addListener (this);
  39923. valueMax.addListener (this);
  39924. }
  39925. Slider::~Slider()
  39926. {
  39927. currentValue.removeListener (this);
  39928. valueMin.removeListener (this);
  39929. valueMax.removeListener (this);
  39930. popupDisplay = 0;
  39931. }
  39932. void Slider::handleAsyncUpdate()
  39933. {
  39934. cancelPendingUpdate();
  39935. Component::BailOutChecker checker (this);
  39936. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39937. }
  39938. void Slider::sendDragStart()
  39939. {
  39940. startedDragging();
  39941. Component::BailOutChecker checker (this);
  39942. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39943. }
  39944. void Slider::sendDragEnd()
  39945. {
  39946. stoppedDragging();
  39947. sliderBeingDragged = -1;
  39948. Component::BailOutChecker checker (this);
  39949. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39950. }
  39951. void Slider::addListener (SliderListener* const listener)
  39952. {
  39953. listeners.add (listener);
  39954. }
  39955. void Slider::removeListener (SliderListener* const listener)
  39956. {
  39957. listeners.remove (listener);
  39958. }
  39959. void Slider::setSliderStyle (const SliderStyle newStyle)
  39960. {
  39961. if (style != newStyle)
  39962. {
  39963. style = newStyle;
  39964. repaint();
  39965. lookAndFeelChanged();
  39966. }
  39967. }
  39968. void Slider::setRotaryParameters (const float startAngleRadians,
  39969. const float endAngleRadians,
  39970. const bool stopAtEnd)
  39971. {
  39972. // make sure the values are sensible..
  39973. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39974. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39975. jassert (rotaryStart < rotaryEnd);
  39976. rotaryStart = startAngleRadians;
  39977. rotaryEnd = endAngleRadians;
  39978. rotaryStop = stopAtEnd;
  39979. }
  39980. void Slider::setVelocityBasedMode (const bool velBased)
  39981. {
  39982. isVelocityBased = velBased;
  39983. }
  39984. void Slider::setVelocityModeParameters (const double sensitivity,
  39985. const int threshold,
  39986. const double offset,
  39987. const bool userCanPressKeyToSwapMode)
  39988. {
  39989. jassert (threshold >= 0);
  39990. jassert (sensitivity > 0);
  39991. jassert (offset >= 0);
  39992. velocityModeSensitivity = sensitivity;
  39993. velocityModeOffset = offset;
  39994. velocityModeThreshold = threshold;
  39995. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39996. }
  39997. void Slider::setSkewFactor (const double factor)
  39998. {
  39999. skewFactor = factor;
  40000. }
  40001. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40002. {
  40003. if (maximum > minimum)
  40004. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40005. / (maximum - minimum));
  40006. }
  40007. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40008. {
  40009. jassert (distanceForFullScaleDrag > 0);
  40010. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40011. }
  40012. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40013. {
  40014. if (incDecButtonMode != mode)
  40015. {
  40016. incDecButtonMode = mode;
  40017. lookAndFeelChanged();
  40018. }
  40019. }
  40020. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40021. const bool isReadOnly,
  40022. const int textEntryBoxWidth,
  40023. const int textEntryBoxHeight)
  40024. {
  40025. if (textBoxPos != newPosition
  40026. || editableText != (! isReadOnly)
  40027. || textBoxWidth != textEntryBoxWidth
  40028. || textBoxHeight != textEntryBoxHeight)
  40029. {
  40030. textBoxPos = newPosition;
  40031. editableText = ! isReadOnly;
  40032. textBoxWidth = textEntryBoxWidth;
  40033. textBoxHeight = textEntryBoxHeight;
  40034. repaint();
  40035. lookAndFeelChanged();
  40036. }
  40037. }
  40038. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40039. {
  40040. editableText = shouldBeEditable;
  40041. if (valueBox != 0)
  40042. valueBox->setEditable (shouldBeEditable && isEnabled());
  40043. }
  40044. void Slider::showTextBox()
  40045. {
  40046. jassert (editableText); // this should probably be avoided in read-only sliders.
  40047. if (valueBox != 0)
  40048. valueBox->showEditor();
  40049. }
  40050. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40051. {
  40052. if (valueBox != 0)
  40053. {
  40054. valueBox->hideEditor (discardCurrentEditorContents);
  40055. if (discardCurrentEditorContents)
  40056. updateText();
  40057. }
  40058. }
  40059. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40060. {
  40061. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40062. }
  40063. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40064. {
  40065. snapsToMousePos = shouldSnapToMouse;
  40066. }
  40067. void Slider::setPopupDisplayEnabled (const bool enabled,
  40068. Component* const parentComponentToUse)
  40069. {
  40070. popupDisplayEnabled = enabled;
  40071. parentForPopupDisplay = parentComponentToUse;
  40072. }
  40073. void Slider::colourChanged()
  40074. {
  40075. lookAndFeelChanged();
  40076. }
  40077. void Slider::lookAndFeelChanged()
  40078. {
  40079. LookAndFeel& lf = getLookAndFeel();
  40080. if (textBoxPos != NoTextBox)
  40081. {
  40082. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40083. : getTextFromValue (currentValue.getValue()));
  40084. valueBox = 0;
  40085. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40086. valueBox->setWantsKeyboardFocus (false);
  40087. valueBox->setText (previousTextBoxContent, false);
  40088. valueBox->setEditable (editableText && isEnabled());
  40089. valueBox->addListener (this);
  40090. if (style == LinearBar)
  40091. valueBox->addMouseListener (this, false);
  40092. valueBox->setTooltip (getTooltip());
  40093. }
  40094. else
  40095. {
  40096. valueBox = 0;
  40097. }
  40098. if (style == IncDecButtons)
  40099. {
  40100. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40101. incButton->addButtonListener (this);
  40102. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40103. decButton->addButtonListener (this);
  40104. if (incDecButtonMode != incDecButtonsNotDraggable)
  40105. {
  40106. incButton->addMouseListener (this, false);
  40107. decButton->addMouseListener (this, false);
  40108. }
  40109. else
  40110. {
  40111. incButton->setRepeatSpeed (300, 100, 20);
  40112. incButton->addMouseListener (decButton, false);
  40113. decButton->setRepeatSpeed (300, 100, 20);
  40114. decButton->addMouseListener (incButton, false);
  40115. }
  40116. incButton->setTooltip (getTooltip());
  40117. decButton->setTooltip (getTooltip());
  40118. }
  40119. else
  40120. {
  40121. incButton = 0;
  40122. decButton = 0;
  40123. }
  40124. setComponentEffect (lf.getSliderEffect());
  40125. resized();
  40126. repaint();
  40127. }
  40128. void Slider::setRange (const double newMin,
  40129. const double newMax,
  40130. const double newInt)
  40131. {
  40132. if (minimum != newMin
  40133. || maximum != newMax
  40134. || interval != newInt)
  40135. {
  40136. minimum = newMin;
  40137. maximum = newMax;
  40138. interval = newInt;
  40139. // figure out the number of DPs needed to display all values at this
  40140. // interval setting.
  40141. numDecimalPlaces = 7;
  40142. if (newInt != 0)
  40143. {
  40144. int v = abs ((int) (newInt * 10000000));
  40145. while ((v % 10) == 0)
  40146. {
  40147. --numDecimalPlaces;
  40148. v /= 10;
  40149. }
  40150. }
  40151. // keep the current values inside the new range..
  40152. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40153. {
  40154. setValue (getValue(), false, false);
  40155. }
  40156. else
  40157. {
  40158. setMinValue (getMinValue(), false, false);
  40159. setMaxValue (getMaxValue(), false, false);
  40160. }
  40161. updateText();
  40162. }
  40163. }
  40164. void Slider::triggerChangeMessage (const bool synchronous)
  40165. {
  40166. if (synchronous)
  40167. handleAsyncUpdate();
  40168. else
  40169. triggerAsyncUpdate();
  40170. valueChanged();
  40171. }
  40172. void Slider::valueChanged (Value& value)
  40173. {
  40174. if (value.refersToSameSourceAs (currentValue))
  40175. {
  40176. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40177. setValue (currentValue.getValue(), false, false);
  40178. }
  40179. else if (value.refersToSameSourceAs (valueMin))
  40180. setMinValue (valueMin.getValue(), false, false, true);
  40181. else if (value.refersToSameSourceAs (valueMax))
  40182. setMaxValue (valueMax.getValue(), false, false, true);
  40183. }
  40184. double Slider::getValue() const
  40185. {
  40186. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40187. // methods to get the two values.
  40188. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40189. return currentValue.getValue();
  40190. }
  40191. void Slider::setValue (double newValue,
  40192. const bool sendUpdateMessage,
  40193. const bool sendMessageSynchronously)
  40194. {
  40195. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40196. // methods to set the two values.
  40197. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40198. newValue = constrainedValue (newValue);
  40199. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40200. {
  40201. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40202. newValue = jlimit ((double) valueMin.getValue(),
  40203. (double) valueMax.getValue(),
  40204. newValue);
  40205. }
  40206. if (newValue != lastCurrentValue)
  40207. {
  40208. if (valueBox != 0)
  40209. valueBox->hideEditor (true);
  40210. lastCurrentValue = newValue;
  40211. currentValue = newValue;
  40212. updateText();
  40213. repaint();
  40214. if (popupDisplay != 0)
  40215. {
  40216. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40217. ->updatePosition (getTextFromValue (newValue));
  40218. popupDisplay->repaint();
  40219. }
  40220. if (sendUpdateMessage)
  40221. triggerChangeMessage (sendMessageSynchronously);
  40222. }
  40223. }
  40224. double Slider::getMinValue() const
  40225. {
  40226. // The minimum value only applies to sliders that are in two- or three-value mode.
  40227. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40228. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40229. return valueMin.getValue();
  40230. }
  40231. double Slider::getMaxValue() const
  40232. {
  40233. // The maximum value only applies to sliders that are in two- or three-value mode.
  40234. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40235. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40236. return valueMax.getValue();
  40237. }
  40238. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40239. {
  40240. // The minimum value only applies to sliders that are in two- or three-value mode.
  40241. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40242. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40243. newValue = constrainedValue (newValue);
  40244. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40245. {
  40246. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40247. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40248. newValue = jmin ((double) valueMax.getValue(), newValue);
  40249. }
  40250. else
  40251. {
  40252. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40253. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40254. newValue = jmin (lastCurrentValue, newValue);
  40255. }
  40256. if (lastValueMin != newValue)
  40257. {
  40258. lastValueMin = newValue;
  40259. valueMin = newValue;
  40260. repaint();
  40261. if (popupDisplay != 0)
  40262. {
  40263. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40264. ->updatePosition (getTextFromValue (newValue));
  40265. popupDisplay->repaint();
  40266. }
  40267. if (sendUpdateMessage)
  40268. triggerChangeMessage (sendMessageSynchronously);
  40269. }
  40270. }
  40271. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40272. {
  40273. // The maximum value only applies to sliders that are in two- or three-value mode.
  40274. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40275. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40276. newValue = constrainedValue (newValue);
  40277. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40278. {
  40279. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40280. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40281. newValue = jmax ((double) valueMin.getValue(), newValue);
  40282. }
  40283. else
  40284. {
  40285. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40286. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40287. newValue = jmax (lastCurrentValue, newValue);
  40288. }
  40289. if (lastValueMax != newValue)
  40290. {
  40291. lastValueMax = newValue;
  40292. valueMax = newValue;
  40293. repaint();
  40294. if (popupDisplay != 0)
  40295. {
  40296. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40297. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40298. popupDisplay->repaint();
  40299. }
  40300. if (sendUpdateMessage)
  40301. triggerChangeMessage (sendMessageSynchronously);
  40302. }
  40303. }
  40304. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40305. const double valueToSetOnDoubleClick)
  40306. {
  40307. doubleClickToValue = isDoubleClickEnabled;
  40308. doubleClickReturnValue = valueToSetOnDoubleClick;
  40309. }
  40310. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40311. {
  40312. isEnabled_ = doubleClickToValue;
  40313. return doubleClickReturnValue;
  40314. }
  40315. void Slider::updateText()
  40316. {
  40317. if (valueBox != 0)
  40318. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40319. }
  40320. void Slider::setTextValueSuffix (const String& suffix)
  40321. {
  40322. if (textSuffix != suffix)
  40323. {
  40324. textSuffix = suffix;
  40325. updateText();
  40326. }
  40327. }
  40328. const String Slider::getTextValueSuffix() const
  40329. {
  40330. return textSuffix;
  40331. }
  40332. const String Slider::getTextFromValue (double v)
  40333. {
  40334. if (getNumDecimalPlacesToDisplay() > 0)
  40335. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40336. else
  40337. return String (roundToInt (v)) + getTextValueSuffix();
  40338. }
  40339. double Slider::getValueFromText (const String& text)
  40340. {
  40341. String t (text.trimStart());
  40342. if (t.endsWith (textSuffix))
  40343. t = t.substring (0, t.length() - textSuffix.length());
  40344. while (t.startsWithChar ('+'))
  40345. t = t.substring (1).trimStart();
  40346. return t.initialSectionContainingOnly ("0123456789.,-")
  40347. .getDoubleValue();
  40348. }
  40349. double Slider::proportionOfLengthToValue (double proportion)
  40350. {
  40351. if (skewFactor != 1.0 && proportion > 0.0)
  40352. proportion = exp (log (proportion) / skewFactor);
  40353. return minimum + (maximum - minimum) * proportion;
  40354. }
  40355. double Slider::valueToProportionOfLength (double value)
  40356. {
  40357. const double n = (value - minimum) / (maximum - minimum);
  40358. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40359. }
  40360. double Slider::snapValue (double attemptedValue, const bool)
  40361. {
  40362. return attemptedValue;
  40363. }
  40364. void Slider::startedDragging()
  40365. {
  40366. }
  40367. void Slider::stoppedDragging()
  40368. {
  40369. }
  40370. void Slider::valueChanged()
  40371. {
  40372. }
  40373. void Slider::enablementChanged()
  40374. {
  40375. repaint();
  40376. }
  40377. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40378. {
  40379. menuEnabled = menuEnabled_;
  40380. }
  40381. void Slider::setScrollWheelEnabled (const bool enabled)
  40382. {
  40383. scrollWheelEnabled = enabled;
  40384. }
  40385. void Slider::labelTextChanged (Label* label)
  40386. {
  40387. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40388. if (newValue != (double) currentValue.getValue())
  40389. {
  40390. sendDragStart();
  40391. setValue (newValue, true, true);
  40392. sendDragEnd();
  40393. }
  40394. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40395. }
  40396. void Slider::buttonClicked (Button* button)
  40397. {
  40398. if (style == IncDecButtons)
  40399. {
  40400. sendDragStart();
  40401. if (button == incButton)
  40402. setValue (snapValue (getValue() + interval, false), true, true);
  40403. else if (button == decButton)
  40404. setValue (snapValue (getValue() - interval, false), true, true);
  40405. sendDragEnd();
  40406. }
  40407. }
  40408. double Slider::constrainedValue (double value) const
  40409. {
  40410. if (interval > 0)
  40411. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40412. if (value <= minimum || maximum <= minimum)
  40413. value = minimum;
  40414. else if (value >= maximum)
  40415. value = maximum;
  40416. return value;
  40417. }
  40418. float Slider::getLinearSliderPos (const double value)
  40419. {
  40420. double sliderPosProportional;
  40421. if (maximum > minimum)
  40422. {
  40423. if (value < minimum)
  40424. {
  40425. sliderPosProportional = 0.0;
  40426. }
  40427. else if (value > maximum)
  40428. {
  40429. sliderPosProportional = 1.0;
  40430. }
  40431. else
  40432. {
  40433. sliderPosProportional = valueToProportionOfLength (value);
  40434. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40435. }
  40436. }
  40437. else
  40438. {
  40439. sliderPosProportional = 0.5;
  40440. }
  40441. if (isVertical() || style == IncDecButtons)
  40442. sliderPosProportional = 1.0 - sliderPosProportional;
  40443. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40444. }
  40445. bool Slider::isHorizontal() const
  40446. {
  40447. return style == LinearHorizontal
  40448. || style == LinearBar
  40449. || style == TwoValueHorizontal
  40450. || style == ThreeValueHorizontal;
  40451. }
  40452. bool Slider::isVertical() const
  40453. {
  40454. return style == LinearVertical
  40455. || style == TwoValueVertical
  40456. || style == ThreeValueVertical;
  40457. }
  40458. bool Slider::incDecDragDirectionIsHorizontal() const
  40459. {
  40460. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40461. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40462. }
  40463. float Slider::getPositionOfValue (const double value)
  40464. {
  40465. if (isHorizontal() || isVertical())
  40466. {
  40467. return getLinearSliderPos (value);
  40468. }
  40469. else
  40470. {
  40471. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40472. return 0.0f;
  40473. }
  40474. }
  40475. void Slider::paint (Graphics& g)
  40476. {
  40477. if (style != IncDecButtons)
  40478. {
  40479. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40480. {
  40481. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40482. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40483. getLookAndFeel().drawRotarySlider (g,
  40484. sliderRect.getX(),
  40485. sliderRect.getY(),
  40486. sliderRect.getWidth(),
  40487. sliderRect.getHeight(),
  40488. sliderPos,
  40489. rotaryStart, rotaryEnd,
  40490. *this);
  40491. }
  40492. else
  40493. {
  40494. getLookAndFeel().drawLinearSlider (g,
  40495. sliderRect.getX(),
  40496. sliderRect.getY(),
  40497. sliderRect.getWidth(),
  40498. sliderRect.getHeight(),
  40499. getLinearSliderPos (lastCurrentValue),
  40500. getLinearSliderPos (lastValueMin),
  40501. getLinearSliderPos (lastValueMax),
  40502. style,
  40503. *this);
  40504. }
  40505. if (style == LinearBar && valueBox == 0)
  40506. {
  40507. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40508. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40509. }
  40510. }
  40511. }
  40512. void Slider::resized()
  40513. {
  40514. int minXSpace = 0;
  40515. int minYSpace = 0;
  40516. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40517. minXSpace = 30;
  40518. else
  40519. minYSpace = 15;
  40520. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40521. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40522. if (style == LinearBar)
  40523. {
  40524. if (valueBox != 0)
  40525. valueBox->setBounds (getLocalBounds());
  40526. }
  40527. else
  40528. {
  40529. if (textBoxPos == NoTextBox)
  40530. {
  40531. sliderRect = getLocalBounds();
  40532. }
  40533. else if (textBoxPos == TextBoxLeft)
  40534. {
  40535. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40536. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40537. }
  40538. else if (textBoxPos == TextBoxRight)
  40539. {
  40540. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40541. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40542. }
  40543. else if (textBoxPos == TextBoxAbove)
  40544. {
  40545. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40546. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40547. }
  40548. else if (textBoxPos == TextBoxBelow)
  40549. {
  40550. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40551. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40552. }
  40553. }
  40554. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40555. if (style == LinearBar)
  40556. {
  40557. const int barIndent = 1;
  40558. sliderRegionStart = barIndent;
  40559. sliderRegionSize = getWidth() - barIndent * 2;
  40560. sliderRect.setBounds (sliderRegionStart, barIndent,
  40561. sliderRegionSize, getHeight() - barIndent * 2);
  40562. }
  40563. else if (isHorizontal())
  40564. {
  40565. sliderRegionStart = sliderRect.getX() + indent;
  40566. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40567. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40568. sliderRegionSize, sliderRect.getHeight());
  40569. }
  40570. else if (isVertical())
  40571. {
  40572. sliderRegionStart = sliderRect.getY() + indent;
  40573. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40574. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40575. sliderRect.getWidth(), sliderRegionSize);
  40576. }
  40577. else
  40578. {
  40579. sliderRegionStart = 0;
  40580. sliderRegionSize = 100;
  40581. }
  40582. if (style == IncDecButtons)
  40583. {
  40584. Rectangle<int> buttonRect (sliderRect);
  40585. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40586. buttonRect.expand (-2, 0);
  40587. else
  40588. buttonRect.expand (0, -2);
  40589. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40590. if (incDecButtonsSideBySide)
  40591. {
  40592. decButton->setBounds (buttonRect.getX(),
  40593. buttonRect.getY(),
  40594. buttonRect.getWidth() / 2,
  40595. buttonRect.getHeight());
  40596. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40597. incButton->setBounds (buttonRect.getCentreX(),
  40598. buttonRect.getY(),
  40599. buttonRect.getWidth() / 2,
  40600. buttonRect.getHeight());
  40601. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40602. }
  40603. else
  40604. {
  40605. incButton->setBounds (buttonRect.getX(),
  40606. buttonRect.getY(),
  40607. buttonRect.getWidth(),
  40608. buttonRect.getHeight() / 2);
  40609. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40610. decButton->setBounds (buttonRect.getX(),
  40611. buttonRect.getCentreY(),
  40612. buttonRect.getWidth(),
  40613. buttonRect.getHeight() / 2);
  40614. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40615. }
  40616. }
  40617. }
  40618. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40619. {
  40620. repaint();
  40621. }
  40622. void Slider::mouseDown (const MouseEvent& e)
  40623. {
  40624. mouseWasHidden = false;
  40625. incDecDragged = false;
  40626. mouseXWhenLastDragged = e.x;
  40627. mouseYWhenLastDragged = e.y;
  40628. mouseDragStartX = e.getMouseDownX();
  40629. mouseDragStartY = e.getMouseDownY();
  40630. if (isEnabled())
  40631. {
  40632. if (e.mods.isPopupMenu() && menuEnabled)
  40633. {
  40634. menuShown = true;
  40635. PopupMenu m;
  40636. m.setLookAndFeel (&getLookAndFeel());
  40637. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40638. m.addSeparator();
  40639. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40640. {
  40641. PopupMenu rotaryMenu;
  40642. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40643. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40644. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40645. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40646. }
  40647. const int r = m.show();
  40648. if (r == 1)
  40649. {
  40650. setVelocityBasedMode (! isVelocityBased);
  40651. }
  40652. else if (r == 2)
  40653. {
  40654. setSliderStyle (Rotary);
  40655. }
  40656. else if (r == 3)
  40657. {
  40658. setSliderStyle (RotaryHorizontalDrag);
  40659. }
  40660. else if (r == 4)
  40661. {
  40662. setSliderStyle (RotaryVerticalDrag);
  40663. }
  40664. }
  40665. else if (maximum > minimum)
  40666. {
  40667. menuShown = false;
  40668. if (valueBox != 0)
  40669. valueBox->hideEditor (true);
  40670. sliderBeingDragged = 0;
  40671. if (style == TwoValueHorizontal
  40672. || style == TwoValueVertical
  40673. || style == ThreeValueHorizontal
  40674. || style == ThreeValueVertical)
  40675. {
  40676. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40677. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40678. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40679. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40680. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40681. {
  40682. if (maxPosDistance <= minPosDistance)
  40683. sliderBeingDragged = 2;
  40684. else
  40685. sliderBeingDragged = 1;
  40686. }
  40687. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40688. {
  40689. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40690. sliderBeingDragged = 1;
  40691. else if (normalPosDistance >= maxPosDistance)
  40692. sliderBeingDragged = 2;
  40693. }
  40694. }
  40695. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40696. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40697. * valueToProportionOfLength (currentValue.getValue());
  40698. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40699. : ((sliderBeingDragged == 1) ? valueMin
  40700. : currentValue)).getValue();
  40701. valueOnMouseDown = valueWhenLastDragged;
  40702. if (popupDisplayEnabled)
  40703. {
  40704. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40705. popupDisplay = popup;
  40706. if (parentForPopupDisplay != 0)
  40707. {
  40708. parentForPopupDisplay->addChildComponent (popup);
  40709. }
  40710. else
  40711. {
  40712. popup->addToDesktop (0);
  40713. }
  40714. popup->setVisible (true);
  40715. }
  40716. sendDragStart();
  40717. mouseDrag (e);
  40718. }
  40719. }
  40720. }
  40721. void Slider::mouseUp (const MouseEvent&)
  40722. {
  40723. if (isEnabled()
  40724. && (! menuShown)
  40725. && (maximum > minimum)
  40726. && (style != IncDecButtons || incDecDragged))
  40727. {
  40728. restoreMouseIfHidden();
  40729. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40730. triggerChangeMessage (false);
  40731. sendDragEnd();
  40732. popupDisplay = 0;
  40733. if (style == IncDecButtons)
  40734. {
  40735. incButton->setState (Button::buttonNormal);
  40736. decButton->setState (Button::buttonNormal);
  40737. }
  40738. }
  40739. }
  40740. void Slider::restoreMouseIfHidden()
  40741. {
  40742. if (mouseWasHidden)
  40743. {
  40744. mouseWasHidden = false;
  40745. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40746. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40747. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40748. : ((sliderBeingDragged == 1) ? getMinValue()
  40749. : (double) currentValue.getValue());
  40750. Point<int> mousePos;
  40751. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40752. {
  40753. mousePos = Desktop::getLastMouseDownPosition();
  40754. if (style == RotaryHorizontalDrag)
  40755. {
  40756. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40757. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40758. }
  40759. else
  40760. {
  40761. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40762. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40763. }
  40764. }
  40765. else
  40766. {
  40767. const int pixelPos = (int) getLinearSliderPos (pos);
  40768. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40769. isVertical() ? pixelPos : (getHeight() / 2)));
  40770. }
  40771. Desktop::setMousePosition (mousePos);
  40772. }
  40773. }
  40774. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40775. {
  40776. if (isEnabled()
  40777. && style != IncDecButtons
  40778. && style != Rotary
  40779. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40780. {
  40781. restoreMouseIfHidden();
  40782. }
  40783. }
  40784. namespace SliderHelpers
  40785. {
  40786. double smallestAngleBetween (double a1, double a2) throw()
  40787. {
  40788. return jmin (std::abs (a1 - a2),
  40789. std::abs (a1 + double_Pi * 2.0 - a2),
  40790. std::abs (a2 + double_Pi * 2.0 - a1));
  40791. }
  40792. }
  40793. void Slider::mouseDrag (const MouseEvent& e)
  40794. {
  40795. if (isEnabled()
  40796. && (! menuShown)
  40797. && (maximum > minimum))
  40798. {
  40799. if (style == Rotary)
  40800. {
  40801. int dx = e.x - sliderRect.getCentreX();
  40802. int dy = e.y - sliderRect.getCentreY();
  40803. if (dx * dx + dy * dy > 25)
  40804. {
  40805. double angle = std::atan2 ((double) dx, (double) -dy);
  40806. while (angle < 0.0)
  40807. angle += double_Pi * 2.0;
  40808. if (rotaryStop && ! e.mouseWasClicked())
  40809. {
  40810. if (std::abs (angle - lastAngle) > double_Pi)
  40811. {
  40812. if (angle >= lastAngle)
  40813. angle -= double_Pi * 2.0;
  40814. else
  40815. angle += double_Pi * 2.0;
  40816. }
  40817. if (angle >= lastAngle)
  40818. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40819. else
  40820. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40821. }
  40822. else
  40823. {
  40824. while (angle < rotaryStart)
  40825. angle += double_Pi * 2.0;
  40826. if (angle > rotaryEnd)
  40827. {
  40828. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40829. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40830. angle = rotaryStart;
  40831. else
  40832. angle = rotaryEnd;
  40833. }
  40834. }
  40835. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40836. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40837. lastAngle = angle;
  40838. }
  40839. }
  40840. else
  40841. {
  40842. if (style == LinearBar && e.mouseWasClicked()
  40843. && valueBox != 0 && valueBox->isEditable())
  40844. return;
  40845. if (style == IncDecButtons && ! incDecDragged)
  40846. {
  40847. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40848. return;
  40849. incDecDragged = true;
  40850. mouseDragStartX = e.x;
  40851. mouseDragStartY = e.y;
  40852. }
  40853. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40854. : false))
  40855. || ((maximum - minimum) / sliderRegionSize < interval))
  40856. {
  40857. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40858. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40859. if (style == RotaryHorizontalDrag
  40860. || style == RotaryVerticalDrag
  40861. || style == IncDecButtons
  40862. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40863. && ! snapsToMousePos))
  40864. {
  40865. const int mouseDiff = (style == RotaryHorizontalDrag
  40866. || style == LinearHorizontal
  40867. || style == LinearBar
  40868. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40869. ? e.x - mouseDragStartX
  40870. : mouseDragStartY - e.y;
  40871. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40872. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40873. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40874. if (style == IncDecButtons)
  40875. {
  40876. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40877. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40878. }
  40879. }
  40880. else
  40881. {
  40882. if (isVertical())
  40883. scaledMousePos = 1.0 - scaledMousePos;
  40884. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40885. }
  40886. }
  40887. else
  40888. {
  40889. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40890. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40891. ? e.x - mouseXWhenLastDragged
  40892. : e.y - mouseYWhenLastDragged;
  40893. const double maxSpeed = jmax (200, sliderRegionSize);
  40894. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40895. if (speed != 0)
  40896. {
  40897. speed = 0.2 * velocityModeSensitivity
  40898. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40899. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40900. / maxSpeed))));
  40901. if (mouseDiff < 0)
  40902. speed = -speed;
  40903. if (isVertical() || style == RotaryVerticalDrag
  40904. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40905. speed = -speed;
  40906. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40907. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40908. e.source.enableUnboundedMouseMovement (true, false);
  40909. mouseWasHidden = true;
  40910. }
  40911. }
  40912. }
  40913. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40914. if (sliderBeingDragged == 0)
  40915. {
  40916. setValue (snapValue (valueWhenLastDragged, true),
  40917. ! sendChangeOnlyOnRelease, true);
  40918. }
  40919. else if (sliderBeingDragged == 1)
  40920. {
  40921. setMinValue (snapValue (valueWhenLastDragged, true),
  40922. ! sendChangeOnlyOnRelease, false, true);
  40923. if (e.mods.isShiftDown())
  40924. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40925. else
  40926. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40927. }
  40928. else
  40929. {
  40930. jassert (sliderBeingDragged == 2);
  40931. setMaxValue (snapValue (valueWhenLastDragged, true),
  40932. ! sendChangeOnlyOnRelease, false, true);
  40933. if (e.mods.isShiftDown())
  40934. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40935. else
  40936. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40937. }
  40938. mouseXWhenLastDragged = e.x;
  40939. mouseYWhenLastDragged = e.y;
  40940. }
  40941. }
  40942. void Slider::mouseDoubleClick (const MouseEvent&)
  40943. {
  40944. if (doubleClickToValue
  40945. && isEnabled()
  40946. && style != IncDecButtons
  40947. && minimum <= doubleClickReturnValue
  40948. && maximum >= doubleClickReturnValue)
  40949. {
  40950. sendDragStart();
  40951. setValue (doubleClickReturnValue, true, true);
  40952. sendDragEnd();
  40953. }
  40954. }
  40955. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40956. {
  40957. if (scrollWheelEnabled && isEnabled()
  40958. && style != TwoValueHorizontal
  40959. && style != TwoValueVertical)
  40960. {
  40961. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40962. {
  40963. if (valueBox != 0)
  40964. valueBox->hideEditor (false);
  40965. const double value = (double) currentValue.getValue();
  40966. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40967. const double currentPos = valueToProportionOfLength (value);
  40968. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40969. double delta = (newValue != value)
  40970. ? jmax (std::abs (newValue - value), interval) : 0;
  40971. if (value > newValue)
  40972. delta = -delta;
  40973. sendDragStart();
  40974. setValue (snapValue (value + delta, false), true, true);
  40975. sendDragEnd();
  40976. }
  40977. }
  40978. else
  40979. {
  40980. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40981. }
  40982. }
  40983. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40984. {
  40985. }
  40986. void SliderListener::sliderDragEnded (Slider*)
  40987. {
  40988. }
  40989. END_JUCE_NAMESPACE
  40990. /*** End of inlined file: juce_Slider.cpp ***/
  40991. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40992. BEGIN_JUCE_NAMESPACE
  40993. class DragOverlayComp : public Component
  40994. {
  40995. public:
  40996. DragOverlayComp (const Image& image_)
  40997. : image (image_)
  40998. {
  40999. image.duplicateIfShared();
  41000. image.multiplyAllAlphas (0.8f);
  41001. setAlwaysOnTop (true);
  41002. }
  41003. void paint (Graphics& g)
  41004. {
  41005. g.drawImageAt (image, 0, 0);
  41006. }
  41007. private:
  41008. Image image;
  41009. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  41010. };
  41011. TableHeaderComponent::TableHeaderComponent()
  41012. : columnsChanged (false),
  41013. columnsResized (false),
  41014. sortChanged (false),
  41015. menuActive (true),
  41016. stretchToFit (false),
  41017. columnIdBeingResized (0),
  41018. columnIdBeingDragged (0),
  41019. columnIdUnderMouse (0),
  41020. lastDeliberateWidth (0)
  41021. {
  41022. }
  41023. TableHeaderComponent::~TableHeaderComponent()
  41024. {
  41025. dragOverlayComp = 0;
  41026. }
  41027. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41028. {
  41029. menuActive = hasMenu;
  41030. }
  41031. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41032. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41033. {
  41034. if (onlyCountVisibleColumns)
  41035. {
  41036. int num = 0;
  41037. for (int i = columns.size(); --i >= 0;)
  41038. if (columns.getUnchecked(i)->isVisible())
  41039. ++num;
  41040. return num;
  41041. }
  41042. else
  41043. {
  41044. return columns.size();
  41045. }
  41046. }
  41047. const String TableHeaderComponent::getColumnName (const int columnId) const
  41048. {
  41049. const ColumnInfo* const ci = getInfoForId (columnId);
  41050. return ci != 0 ? ci->name : String::empty;
  41051. }
  41052. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41053. {
  41054. ColumnInfo* const ci = getInfoForId (columnId);
  41055. if (ci != 0 && ci->name != newName)
  41056. {
  41057. ci->name = newName;
  41058. sendColumnsChanged();
  41059. }
  41060. }
  41061. void TableHeaderComponent::addColumn (const String& columnName,
  41062. const int columnId,
  41063. const int width,
  41064. const int minimumWidth,
  41065. const int maximumWidth,
  41066. const int propertyFlags,
  41067. const int insertIndex)
  41068. {
  41069. // can't have a duplicate or null ID!
  41070. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41071. jassert (width > 0);
  41072. ColumnInfo* const ci = new ColumnInfo();
  41073. ci->name = columnName;
  41074. ci->id = columnId;
  41075. ci->width = width;
  41076. ci->lastDeliberateWidth = width;
  41077. ci->minimumWidth = minimumWidth;
  41078. ci->maximumWidth = maximumWidth;
  41079. if (ci->maximumWidth < 0)
  41080. ci->maximumWidth = std::numeric_limits<int>::max();
  41081. jassert (ci->maximumWidth >= ci->minimumWidth);
  41082. ci->propertyFlags = propertyFlags;
  41083. columns.insert (insertIndex, ci);
  41084. sendColumnsChanged();
  41085. }
  41086. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41087. {
  41088. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41089. if (index >= 0)
  41090. {
  41091. columns.remove (index);
  41092. sortChanged = true;
  41093. sendColumnsChanged();
  41094. }
  41095. }
  41096. void TableHeaderComponent::removeAllColumns()
  41097. {
  41098. if (columns.size() > 0)
  41099. {
  41100. columns.clear();
  41101. sendColumnsChanged();
  41102. }
  41103. }
  41104. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41105. {
  41106. const int currentIndex = getIndexOfColumnId (columnId, false);
  41107. newIndex = visibleIndexToTotalIndex (newIndex);
  41108. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41109. {
  41110. columns.move (currentIndex, newIndex);
  41111. sendColumnsChanged();
  41112. }
  41113. }
  41114. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41115. {
  41116. const ColumnInfo* const ci = getInfoForId (columnId);
  41117. return ci != 0 ? ci->width : 0;
  41118. }
  41119. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41120. {
  41121. ColumnInfo* const ci = getInfoForId (columnId);
  41122. if (ci != 0 && ci->width != newWidth)
  41123. {
  41124. const int numColumns = getNumColumns (true);
  41125. ci->lastDeliberateWidth = ci->width
  41126. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41127. if (stretchToFit)
  41128. {
  41129. const int index = getIndexOfColumnId (columnId, true) + 1;
  41130. if (isPositiveAndBelow (index, numColumns))
  41131. {
  41132. const int x = getColumnPosition (index).getX();
  41133. if (lastDeliberateWidth == 0)
  41134. lastDeliberateWidth = getTotalWidth();
  41135. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41136. }
  41137. }
  41138. repaint();
  41139. columnsResized = true;
  41140. triggerAsyncUpdate();
  41141. }
  41142. }
  41143. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41144. {
  41145. int n = 0;
  41146. for (int i = 0; i < columns.size(); ++i)
  41147. {
  41148. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41149. {
  41150. if (columns.getUnchecked(i)->id == columnId)
  41151. return n;
  41152. ++n;
  41153. }
  41154. }
  41155. return -1;
  41156. }
  41157. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41158. {
  41159. if (onlyCountVisibleColumns)
  41160. index = visibleIndexToTotalIndex (index);
  41161. const ColumnInfo* const ci = columns [index];
  41162. return (ci != 0) ? ci->id : 0;
  41163. }
  41164. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41165. {
  41166. int x = 0, width = 0, n = 0;
  41167. for (int i = 0; i < columns.size(); ++i)
  41168. {
  41169. x += width;
  41170. if (columns.getUnchecked(i)->isVisible())
  41171. {
  41172. width = columns.getUnchecked(i)->width;
  41173. if (n++ == index)
  41174. break;
  41175. }
  41176. else
  41177. {
  41178. width = 0;
  41179. }
  41180. }
  41181. return Rectangle<int> (x, 0, width, getHeight());
  41182. }
  41183. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41184. {
  41185. if (xToFind >= 0)
  41186. {
  41187. int x = 0;
  41188. for (int i = 0; i < columns.size(); ++i)
  41189. {
  41190. const ColumnInfo* const ci = columns.getUnchecked(i);
  41191. if (ci->isVisible())
  41192. {
  41193. x += ci->width;
  41194. if (xToFind < x)
  41195. return ci->id;
  41196. }
  41197. }
  41198. }
  41199. return 0;
  41200. }
  41201. int TableHeaderComponent::getTotalWidth() const
  41202. {
  41203. int w = 0;
  41204. for (int i = columns.size(); --i >= 0;)
  41205. if (columns.getUnchecked(i)->isVisible())
  41206. w += columns.getUnchecked(i)->width;
  41207. return w;
  41208. }
  41209. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41210. {
  41211. stretchToFit = shouldStretchToFit;
  41212. lastDeliberateWidth = getTotalWidth();
  41213. resized();
  41214. }
  41215. bool TableHeaderComponent::isStretchToFitActive() const
  41216. {
  41217. return stretchToFit;
  41218. }
  41219. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41220. {
  41221. if (stretchToFit && getWidth() > 0
  41222. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41223. {
  41224. lastDeliberateWidth = targetTotalWidth;
  41225. resizeColumnsToFit (0, targetTotalWidth);
  41226. }
  41227. }
  41228. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41229. {
  41230. targetTotalWidth = jmax (targetTotalWidth, 0);
  41231. StretchableObjectResizer sor;
  41232. int i;
  41233. for (i = firstColumnIndex; i < columns.size(); ++i)
  41234. {
  41235. ColumnInfo* const ci = columns.getUnchecked(i);
  41236. if (ci->isVisible())
  41237. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41238. }
  41239. sor.resizeToFit (targetTotalWidth);
  41240. int visIndex = 0;
  41241. for (i = firstColumnIndex; i < columns.size(); ++i)
  41242. {
  41243. ColumnInfo* const ci = columns.getUnchecked(i);
  41244. if (ci->isVisible())
  41245. {
  41246. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41247. (int) std::floor (sor.getItemSize (visIndex++)));
  41248. if (newWidth != ci->width)
  41249. {
  41250. ci->width = newWidth;
  41251. repaint();
  41252. columnsResized = true;
  41253. triggerAsyncUpdate();
  41254. }
  41255. }
  41256. }
  41257. }
  41258. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41259. {
  41260. ColumnInfo* const ci = getInfoForId (columnId);
  41261. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41262. {
  41263. if (shouldBeVisible)
  41264. ci->propertyFlags |= visible;
  41265. else
  41266. ci->propertyFlags &= ~visible;
  41267. sendColumnsChanged();
  41268. resized();
  41269. }
  41270. }
  41271. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41272. {
  41273. const ColumnInfo* const ci = getInfoForId (columnId);
  41274. return ci != 0 && ci->isVisible();
  41275. }
  41276. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41277. {
  41278. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41279. {
  41280. for (int i = columns.size(); --i >= 0;)
  41281. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41282. ColumnInfo* const ci = getInfoForId (columnId);
  41283. if (ci != 0)
  41284. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41285. reSortTable();
  41286. }
  41287. }
  41288. int TableHeaderComponent::getSortColumnId() const
  41289. {
  41290. for (int i = columns.size(); --i >= 0;)
  41291. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41292. return columns.getUnchecked(i)->id;
  41293. return 0;
  41294. }
  41295. bool TableHeaderComponent::isSortedForwards() const
  41296. {
  41297. for (int i = columns.size(); --i >= 0;)
  41298. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41299. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41300. return true;
  41301. }
  41302. void TableHeaderComponent::reSortTable()
  41303. {
  41304. sortChanged = true;
  41305. repaint();
  41306. triggerAsyncUpdate();
  41307. }
  41308. const String TableHeaderComponent::toString() const
  41309. {
  41310. String s;
  41311. XmlElement doc ("TABLELAYOUT");
  41312. doc.setAttribute ("sortedCol", getSortColumnId());
  41313. doc.setAttribute ("sortForwards", isSortedForwards());
  41314. for (int i = 0; i < columns.size(); ++i)
  41315. {
  41316. const ColumnInfo* const ci = columns.getUnchecked (i);
  41317. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41318. e->setAttribute ("id", ci->id);
  41319. e->setAttribute ("visible", ci->isVisible());
  41320. e->setAttribute ("width", ci->width);
  41321. }
  41322. return doc.createDocument (String::empty, true, false);
  41323. }
  41324. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41325. {
  41326. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41327. int index = 0;
  41328. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41329. {
  41330. forEachXmlChildElement (*storedXml, col)
  41331. {
  41332. const int tabId = col->getIntAttribute ("id");
  41333. ColumnInfo* const ci = getInfoForId (tabId);
  41334. if (ci != 0)
  41335. {
  41336. columns.move (columns.indexOf (ci), index);
  41337. ci->width = col->getIntAttribute ("width");
  41338. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41339. }
  41340. ++index;
  41341. }
  41342. columnsResized = true;
  41343. sendColumnsChanged();
  41344. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41345. storedXml->getBoolAttribute ("sortForwards", true));
  41346. }
  41347. }
  41348. void TableHeaderComponent::addListener (Listener* const newListener)
  41349. {
  41350. listeners.addIfNotAlreadyThere (newListener);
  41351. }
  41352. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41353. {
  41354. listeners.removeValue (listenerToRemove);
  41355. }
  41356. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41357. {
  41358. const ColumnInfo* const ci = getInfoForId (columnId);
  41359. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41360. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41361. }
  41362. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41363. {
  41364. for (int i = 0; i < columns.size(); ++i)
  41365. {
  41366. const ColumnInfo* const ci = columns.getUnchecked(i);
  41367. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41368. menu.addItem (ci->id, ci->name,
  41369. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41370. isColumnVisible (ci->id));
  41371. }
  41372. }
  41373. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41374. {
  41375. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41376. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41377. }
  41378. void TableHeaderComponent::paint (Graphics& g)
  41379. {
  41380. LookAndFeel& lf = getLookAndFeel();
  41381. lf.drawTableHeaderBackground (g, *this);
  41382. const Rectangle<int> clip (g.getClipBounds());
  41383. int x = 0;
  41384. for (int i = 0; i < columns.size(); ++i)
  41385. {
  41386. const ColumnInfo* const ci = columns.getUnchecked(i);
  41387. if (ci->isVisible())
  41388. {
  41389. if (x + ci->width > clip.getX()
  41390. && (ci->id != columnIdBeingDragged
  41391. || dragOverlayComp == 0
  41392. || ! dragOverlayComp->isVisible()))
  41393. {
  41394. Graphics::ScopedSaveState ss (g);
  41395. g.setOrigin (x, 0);
  41396. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41397. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41398. ci->id == columnIdUnderMouse,
  41399. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41400. ci->propertyFlags);
  41401. }
  41402. x += ci->width;
  41403. if (x >= clip.getRight())
  41404. break;
  41405. }
  41406. }
  41407. }
  41408. void TableHeaderComponent::resized()
  41409. {
  41410. }
  41411. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41412. {
  41413. updateColumnUnderMouse (e.x, e.y);
  41414. }
  41415. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41416. {
  41417. updateColumnUnderMouse (e.x, e.y);
  41418. }
  41419. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41420. {
  41421. updateColumnUnderMouse (e.x, e.y);
  41422. }
  41423. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41424. {
  41425. repaint();
  41426. columnIdBeingResized = 0;
  41427. columnIdBeingDragged = 0;
  41428. if (columnIdUnderMouse != 0)
  41429. {
  41430. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41431. if (e.mods.isPopupMenu())
  41432. columnClicked (columnIdUnderMouse, e.mods);
  41433. }
  41434. if (menuActive && e.mods.isPopupMenu())
  41435. showColumnChooserMenu (columnIdUnderMouse);
  41436. }
  41437. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41438. {
  41439. if (columnIdBeingResized == 0
  41440. && columnIdBeingDragged == 0
  41441. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41442. {
  41443. dragOverlayComp = 0;
  41444. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41445. if (columnIdBeingResized != 0)
  41446. {
  41447. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41448. initialColumnWidth = ci->width;
  41449. }
  41450. else
  41451. {
  41452. beginDrag (e);
  41453. }
  41454. }
  41455. if (columnIdBeingResized != 0)
  41456. {
  41457. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41458. if (ci != 0)
  41459. {
  41460. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41461. initialColumnWidth + e.getDistanceFromDragStartX());
  41462. if (stretchToFit)
  41463. {
  41464. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41465. int minWidthOnRight = 0;
  41466. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41467. if (columns.getUnchecked (i)->isVisible())
  41468. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41469. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41470. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41471. }
  41472. setColumnWidth (columnIdBeingResized, w);
  41473. }
  41474. }
  41475. else if (columnIdBeingDragged != 0)
  41476. {
  41477. if (e.y >= -50 && e.y < getHeight() + 50)
  41478. {
  41479. if (dragOverlayComp != 0)
  41480. {
  41481. dragOverlayComp->setVisible (true);
  41482. dragOverlayComp->setBounds (jlimit (0,
  41483. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41484. e.x - draggingColumnOffset),
  41485. 0,
  41486. dragOverlayComp->getWidth(),
  41487. getHeight());
  41488. for (int i = columns.size(); --i >= 0;)
  41489. {
  41490. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41491. int newIndex = currentIndex;
  41492. if (newIndex > 0)
  41493. {
  41494. // if the previous column isn't draggable, we can't move our column
  41495. // past it, because that'd change the undraggable column's position..
  41496. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41497. if ((previous->propertyFlags & draggable) != 0)
  41498. {
  41499. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41500. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41501. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41502. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41503. {
  41504. --newIndex;
  41505. }
  41506. }
  41507. }
  41508. if (newIndex < columns.size() - 1)
  41509. {
  41510. // if the next column isn't draggable, we can't move our column
  41511. // past it, because that'd change the undraggable column's position..
  41512. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41513. if ((nextCol->propertyFlags & draggable) != 0)
  41514. {
  41515. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41516. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41517. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41518. > abs (dragOverlayComp->getRight() - rightOfNext))
  41519. {
  41520. ++newIndex;
  41521. }
  41522. }
  41523. }
  41524. if (newIndex != currentIndex)
  41525. moveColumn (columnIdBeingDragged, newIndex);
  41526. else
  41527. break;
  41528. }
  41529. }
  41530. }
  41531. else
  41532. {
  41533. endDrag (draggingColumnOriginalIndex);
  41534. }
  41535. }
  41536. }
  41537. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41538. {
  41539. if (columnIdBeingDragged == 0)
  41540. {
  41541. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41542. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41543. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41544. {
  41545. columnIdBeingDragged = 0;
  41546. }
  41547. else
  41548. {
  41549. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41550. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41551. const int temp = columnIdBeingDragged;
  41552. columnIdBeingDragged = 0;
  41553. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41554. columnIdBeingDragged = temp;
  41555. dragOverlayComp->setBounds (columnRect);
  41556. for (int i = listeners.size(); --i >= 0;)
  41557. {
  41558. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41559. i = jmin (i, listeners.size() - 1);
  41560. }
  41561. }
  41562. }
  41563. }
  41564. void TableHeaderComponent::endDrag (const int finalIndex)
  41565. {
  41566. if (columnIdBeingDragged != 0)
  41567. {
  41568. moveColumn (columnIdBeingDragged, finalIndex);
  41569. columnIdBeingDragged = 0;
  41570. repaint();
  41571. for (int i = listeners.size(); --i >= 0;)
  41572. {
  41573. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41574. i = jmin (i, listeners.size() - 1);
  41575. }
  41576. }
  41577. }
  41578. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41579. {
  41580. mouseDrag (e);
  41581. for (int i = columns.size(); --i >= 0;)
  41582. if (columns.getUnchecked (i)->isVisible())
  41583. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41584. columnIdBeingResized = 0;
  41585. repaint();
  41586. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41587. updateColumnUnderMouse (e.x, e.y);
  41588. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41589. columnClicked (columnIdUnderMouse, e.mods);
  41590. dragOverlayComp = 0;
  41591. }
  41592. const MouseCursor TableHeaderComponent::getMouseCursor()
  41593. {
  41594. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41595. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41596. return Component::getMouseCursor();
  41597. }
  41598. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41599. {
  41600. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41601. }
  41602. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41603. {
  41604. for (int i = columns.size(); --i >= 0;)
  41605. if (columns.getUnchecked(i)->id == id)
  41606. return columns.getUnchecked(i);
  41607. return 0;
  41608. }
  41609. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41610. {
  41611. int n = 0;
  41612. for (int i = 0; i < columns.size(); ++i)
  41613. {
  41614. if (columns.getUnchecked(i)->isVisible())
  41615. {
  41616. if (n == visibleIndex)
  41617. return i;
  41618. ++n;
  41619. }
  41620. }
  41621. return -1;
  41622. }
  41623. void TableHeaderComponent::sendColumnsChanged()
  41624. {
  41625. if (stretchToFit && lastDeliberateWidth > 0)
  41626. resizeAllColumnsToFit (lastDeliberateWidth);
  41627. repaint();
  41628. columnsChanged = true;
  41629. triggerAsyncUpdate();
  41630. }
  41631. void TableHeaderComponent::handleAsyncUpdate()
  41632. {
  41633. const bool changed = columnsChanged || sortChanged;
  41634. const bool sized = columnsResized || changed;
  41635. const bool sorted = sortChanged;
  41636. columnsChanged = false;
  41637. columnsResized = false;
  41638. sortChanged = false;
  41639. if (sorted)
  41640. {
  41641. for (int i = listeners.size(); --i >= 0;)
  41642. {
  41643. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41644. i = jmin (i, listeners.size() - 1);
  41645. }
  41646. }
  41647. if (changed)
  41648. {
  41649. for (int i = listeners.size(); --i >= 0;)
  41650. {
  41651. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41652. i = jmin (i, listeners.size() - 1);
  41653. }
  41654. }
  41655. if (sized)
  41656. {
  41657. for (int i = listeners.size(); --i >= 0;)
  41658. {
  41659. listeners.getUnchecked(i)->tableColumnsResized (this);
  41660. i = jmin (i, listeners.size() - 1);
  41661. }
  41662. }
  41663. }
  41664. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41665. {
  41666. if (isPositiveAndBelow (mouseX, getWidth()))
  41667. {
  41668. const int draggableDistance = 3;
  41669. int x = 0;
  41670. for (int i = 0; i < columns.size(); ++i)
  41671. {
  41672. const ColumnInfo* const ci = columns.getUnchecked(i);
  41673. if (ci->isVisible())
  41674. {
  41675. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41676. && (ci->propertyFlags & resizable) != 0)
  41677. return ci->id;
  41678. x += ci->width;
  41679. }
  41680. }
  41681. }
  41682. return 0;
  41683. }
  41684. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41685. {
  41686. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41687. ? getColumnIdAtX (x) : 0;
  41688. if (newCol != columnIdUnderMouse)
  41689. {
  41690. columnIdUnderMouse = newCol;
  41691. repaint();
  41692. }
  41693. }
  41694. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41695. {
  41696. PopupMenu m;
  41697. addMenuItems (m, columnIdClicked);
  41698. if (m.getNumItems() > 0)
  41699. {
  41700. m.setLookAndFeel (&getLookAndFeel());
  41701. const int result = m.show();
  41702. if (result != 0)
  41703. reactToMenuItem (result, columnIdClicked);
  41704. }
  41705. }
  41706. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41707. {
  41708. }
  41709. END_JUCE_NAMESPACE
  41710. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41711. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41712. BEGIN_JUCE_NAMESPACE
  41713. class TableListRowComp : public Component,
  41714. public TooltipClient
  41715. {
  41716. public:
  41717. TableListRowComp (TableListBox& owner_)
  41718. : owner (owner_), row (-1), isSelected (false)
  41719. {
  41720. }
  41721. void paint (Graphics& g)
  41722. {
  41723. TableListBoxModel* const model = owner.getModel();
  41724. if (model != 0)
  41725. {
  41726. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41727. const TableHeaderComponent& header = owner.getHeader();
  41728. const int numColumns = header.getNumColumns (true);
  41729. for (int i = 0; i < numColumns; ++i)
  41730. {
  41731. if (columnComponents[i] == 0)
  41732. {
  41733. const int columnId = header.getColumnIdOfIndex (i, true);
  41734. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41735. Graphics::ScopedSaveState ss (g);
  41736. g.reduceClipRegion (columnRect);
  41737. g.setOrigin (columnRect.getX(), 0);
  41738. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41739. }
  41740. }
  41741. }
  41742. }
  41743. void update (const int newRow, const bool isNowSelected)
  41744. {
  41745. jassert (newRow >= 0);
  41746. if (newRow != row || isNowSelected != isSelected)
  41747. {
  41748. row = newRow;
  41749. isSelected = isNowSelected;
  41750. repaint();
  41751. }
  41752. TableListBoxModel* const model = owner.getModel();
  41753. if (model != 0 && row < owner.getNumRows())
  41754. {
  41755. const Identifier columnProperty ("_tableColumnId");
  41756. const int numColumns = owner.getHeader().getNumColumns (true);
  41757. for (int i = 0; i < numColumns; ++i)
  41758. {
  41759. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41760. Component* comp = columnComponents[i];
  41761. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41762. {
  41763. columnComponents.set (i, 0);
  41764. comp = 0;
  41765. }
  41766. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41767. columnComponents.set (i, comp, false);
  41768. if (comp != 0)
  41769. {
  41770. comp->getProperties().set (columnProperty, columnId);
  41771. addAndMakeVisible (comp);
  41772. resizeCustomComp (i);
  41773. }
  41774. }
  41775. columnComponents.removeRange (numColumns, columnComponents.size());
  41776. }
  41777. else
  41778. {
  41779. columnComponents.clear();
  41780. }
  41781. }
  41782. void resized()
  41783. {
  41784. for (int i = columnComponents.size(); --i >= 0;)
  41785. resizeCustomComp (i);
  41786. }
  41787. void resizeCustomComp (const int index)
  41788. {
  41789. Component* const c = columnComponents.getUnchecked (index);
  41790. if (c != 0)
  41791. c->setBounds (owner.getHeader().getColumnPosition (index)
  41792. .withY (0).withHeight (getHeight()));
  41793. }
  41794. void mouseDown (const MouseEvent& e)
  41795. {
  41796. isDragging = false;
  41797. selectRowOnMouseUp = false;
  41798. if (isEnabled())
  41799. {
  41800. if (! isSelected)
  41801. {
  41802. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41803. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41804. if (columnId != 0 && owner.getModel() != 0)
  41805. owner.getModel()->cellClicked (row, columnId, e);
  41806. }
  41807. else
  41808. {
  41809. selectRowOnMouseUp = true;
  41810. }
  41811. }
  41812. }
  41813. void mouseDrag (const MouseEvent& e)
  41814. {
  41815. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41816. {
  41817. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41818. if (selectedRows.size() > 0)
  41819. {
  41820. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41821. if (dragDescription.isNotEmpty())
  41822. {
  41823. isDragging = true;
  41824. owner.startDragAndDrop (e, dragDescription);
  41825. }
  41826. }
  41827. }
  41828. }
  41829. void mouseUp (const MouseEvent& e)
  41830. {
  41831. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41832. {
  41833. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41834. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41835. if (columnId != 0 && owner.getModel() != 0)
  41836. owner.getModel()->cellClicked (row, columnId, e);
  41837. }
  41838. }
  41839. void mouseDoubleClick (const MouseEvent& e)
  41840. {
  41841. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41842. if (columnId != 0 && owner.getModel() != 0)
  41843. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41844. }
  41845. const String getTooltip()
  41846. {
  41847. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41848. if (columnId != 0 && owner.getModel() != 0)
  41849. return owner.getModel()->getCellTooltip (row, columnId);
  41850. return String::empty;
  41851. }
  41852. Component* findChildComponentForColumn (const int columnId) const
  41853. {
  41854. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41855. }
  41856. private:
  41857. TableListBox& owner;
  41858. OwnedArray<Component> columnComponents;
  41859. int row;
  41860. bool isSelected, isDragging, selectRowOnMouseUp;
  41861. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41862. };
  41863. class TableListBoxHeader : public TableHeaderComponent
  41864. {
  41865. public:
  41866. TableListBoxHeader (TableListBox& owner_)
  41867. : owner (owner_)
  41868. {
  41869. }
  41870. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41871. {
  41872. if (owner.isAutoSizeMenuOptionShown())
  41873. {
  41874. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41875. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41876. menu.addSeparator();
  41877. }
  41878. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41879. }
  41880. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41881. {
  41882. switch (menuReturnId)
  41883. {
  41884. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41885. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41886. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41887. }
  41888. }
  41889. private:
  41890. TableListBox& owner;
  41891. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41892. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41893. };
  41894. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41895. : ListBox (name, 0),
  41896. model (model_),
  41897. autoSizeOptionsShown (true)
  41898. {
  41899. ListBox::model = this;
  41900. header = new TableListBoxHeader (*this);
  41901. header->setSize (100, 28);
  41902. header->addListener (this);
  41903. setHeaderComponent (header);
  41904. }
  41905. TableListBox::~TableListBox()
  41906. {
  41907. header = 0;
  41908. }
  41909. void TableListBox::setModel (TableListBoxModel* const newModel)
  41910. {
  41911. if (model != newModel)
  41912. {
  41913. model = newModel;
  41914. updateContent();
  41915. }
  41916. }
  41917. int TableListBox::getHeaderHeight() const
  41918. {
  41919. return header->getHeight();
  41920. }
  41921. void TableListBox::setHeaderHeight (const int newHeight)
  41922. {
  41923. header->setSize (header->getWidth(), newHeight);
  41924. resized();
  41925. }
  41926. void TableListBox::autoSizeColumn (const int columnId)
  41927. {
  41928. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41929. if (width > 0)
  41930. header->setColumnWidth (columnId, width);
  41931. }
  41932. void TableListBox::autoSizeAllColumns()
  41933. {
  41934. for (int i = 0; i < header->getNumColumns (true); ++i)
  41935. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41936. }
  41937. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41938. {
  41939. autoSizeOptionsShown = shouldBeShown;
  41940. }
  41941. bool TableListBox::isAutoSizeMenuOptionShown() const
  41942. {
  41943. return autoSizeOptionsShown;
  41944. }
  41945. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41946. const bool relativeToComponentTopLeft) const
  41947. {
  41948. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41949. if (relativeToComponentTopLeft)
  41950. headerCell.translate (header->getX(), 0);
  41951. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41952. .withX (headerCell.getX())
  41953. .withWidth (headerCell.getWidth());
  41954. }
  41955. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41956. {
  41957. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41958. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41959. }
  41960. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41961. {
  41962. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41963. if (scrollbar != 0)
  41964. {
  41965. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41966. double x = scrollbar->getCurrentRangeStart();
  41967. const double w = scrollbar->getCurrentRangeSize();
  41968. if (pos.getX() < x)
  41969. x = pos.getX();
  41970. else if (pos.getRight() > x + w)
  41971. x += jmax (0.0, pos.getRight() - (x + w));
  41972. scrollbar->setCurrentRangeStart (x);
  41973. }
  41974. }
  41975. int TableListBox::getNumRows()
  41976. {
  41977. return model != 0 ? model->getNumRows() : 0;
  41978. }
  41979. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41980. {
  41981. }
  41982. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41983. {
  41984. if (existingComponentToUpdate == 0)
  41985. existingComponentToUpdate = new TableListRowComp (*this);
  41986. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41987. return existingComponentToUpdate;
  41988. }
  41989. void TableListBox::selectedRowsChanged (int row)
  41990. {
  41991. if (model != 0)
  41992. model->selectedRowsChanged (row);
  41993. }
  41994. void TableListBox::deleteKeyPressed (int row)
  41995. {
  41996. if (model != 0)
  41997. model->deleteKeyPressed (row);
  41998. }
  41999. void TableListBox::returnKeyPressed (int row)
  42000. {
  42001. if (model != 0)
  42002. model->returnKeyPressed (row);
  42003. }
  42004. void TableListBox::backgroundClicked()
  42005. {
  42006. if (model != 0)
  42007. model->backgroundClicked();
  42008. }
  42009. void TableListBox::listWasScrolled()
  42010. {
  42011. if (model != 0)
  42012. model->listWasScrolled();
  42013. }
  42014. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42015. {
  42016. setMinimumContentWidth (header->getTotalWidth());
  42017. repaint();
  42018. updateColumnComponents();
  42019. }
  42020. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42021. {
  42022. setMinimumContentWidth (header->getTotalWidth());
  42023. repaint();
  42024. updateColumnComponents();
  42025. }
  42026. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42027. {
  42028. if (model != 0)
  42029. model->sortOrderChanged (header->getSortColumnId(),
  42030. header->isSortedForwards());
  42031. }
  42032. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42033. {
  42034. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42035. repaint();
  42036. }
  42037. void TableListBox::resized()
  42038. {
  42039. ListBox::resized();
  42040. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42041. setMinimumContentWidth (header->getTotalWidth());
  42042. }
  42043. void TableListBox::updateColumnComponents() const
  42044. {
  42045. const int firstRow = getRowContainingPosition (0, 0);
  42046. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42047. {
  42048. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42049. if (rowComp != 0)
  42050. rowComp->resized();
  42051. }
  42052. }
  42053. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  42054. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  42055. void TableListBoxModel::backgroundClicked() {}
  42056. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  42057. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  42058. void TableListBoxModel::selectedRowsChanged (int) {}
  42059. void TableListBoxModel::deleteKeyPressed (int) {}
  42060. void TableListBoxModel::returnKeyPressed (int) {}
  42061. void TableListBoxModel::listWasScrolled() {}
  42062. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  42063. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  42064. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42065. {
  42066. (void) existingComponentToUpdate;
  42067. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42068. return 0;
  42069. }
  42070. END_JUCE_NAMESPACE
  42071. /*** End of inlined file: juce_TableListBox.cpp ***/
  42072. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42073. BEGIN_JUCE_NAMESPACE
  42074. // a word or space that can't be broken down any further
  42075. struct TextAtom
  42076. {
  42077. String atomText;
  42078. float width;
  42079. int numChars;
  42080. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42081. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42082. const String getText (const juce_wchar passwordCharacter) const
  42083. {
  42084. if (passwordCharacter == 0)
  42085. return atomText;
  42086. else
  42087. return String::repeatedString (String::charToString (passwordCharacter),
  42088. atomText.length());
  42089. }
  42090. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42091. {
  42092. if (passwordCharacter == 0)
  42093. return atomText.substring (0, numChars);
  42094. else if (isNewLine())
  42095. return String::empty;
  42096. else
  42097. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42098. }
  42099. };
  42100. // a run of text with a single font and colour
  42101. class TextEditor::UniformTextSection
  42102. {
  42103. public:
  42104. UniformTextSection (const String& text,
  42105. const Font& font_,
  42106. const Colour& colour_,
  42107. const juce_wchar passwordCharacter)
  42108. : font (font_),
  42109. colour (colour_)
  42110. {
  42111. initialiseAtoms (text, passwordCharacter);
  42112. }
  42113. UniformTextSection (const UniformTextSection& other)
  42114. : font (other.font),
  42115. colour (other.colour)
  42116. {
  42117. atoms.ensureStorageAllocated (other.atoms.size());
  42118. for (int i = 0; i < other.atoms.size(); ++i)
  42119. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42120. }
  42121. ~UniformTextSection()
  42122. {
  42123. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42124. }
  42125. void clear()
  42126. {
  42127. for (int i = atoms.size(); --i >= 0;)
  42128. delete getAtom(i);
  42129. atoms.clear();
  42130. }
  42131. int getNumAtoms() const
  42132. {
  42133. return atoms.size();
  42134. }
  42135. TextAtom* getAtom (const int index) const throw()
  42136. {
  42137. return atoms.getUnchecked (index);
  42138. }
  42139. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42140. {
  42141. if (other.atoms.size() > 0)
  42142. {
  42143. TextAtom* const lastAtom = atoms.getLast();
  42144. int i = 0;
  42145. if (lastAtom != 0)
  42146. {
  42147. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42148. {
  42149. TextAtom* const first = other.getAtom(0);
  42150. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42151. {
  42152. lastAtom->atomText += first->atomText;
  42153. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42154. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42155. delete first;
  42156. ++i;
  42157. }
  42158. }
  42159. }
  42160. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42161. while (i < other.atoms.size())
  42162. {
  42163. atoms.add (other.getAtom(i));
  42164. ++i;
  42165. }
  42166. }
  42167. }
  42168. UniformTextSection* split (const int indexToBreakAt,
  42169. const juce_wchar passwordCharacter)
  42170. {
  42171. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42172. font, colour,
  42173. passwordCharacter);
  42174. int index = 0;
  42175. for (int i = 0; i < atoms.size(); ++i)
  42176. {
  42177. TextAtom* const atom = getAtom(i);
  42178. const int nextIndex = index + atom->numChars;
  42179. if (index == indexToBreakAt)
  42180. {
  42181. int j;
  42182. for (j = i; j < atoms.size(); ++j)
  42183. section2->atoms.add (getAtom (j));
  42184. for (j = atoms.size(); --j >= i;)
  42185. atoms.remove (j);
  42186. break;
  42187. }
  42188. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42189. {
  42190. TextAtom* const secondAtom = new TextAtom();
  42191. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42192. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42193. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42194. section2->atoms.add (secondAtom);
  42195. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42196. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42197. atom->numChars = (uint16) (indexToBreakAt - index);
  42198. int j;
  42199. for (j = i + 1; j < atoms.size(); ++j)
  42200. section2->atoms.add (getAtom (j));
  42201. for (j = atoms.size(); --j > i;)
  42202. atoms.remove (j);
  42203. break;
  42204. }
  42205. index = nextIndex;
  42206. }
  42207. return section2;
  42208. }
  42209. void appendAllText (String::Concatenator& concatenator) const
  42210. {
  42211. for (int i = 0; i < atoms.size(); ++i)
  42212. concatenator.append (getAtom(i)->atomText);
  42213. }
  42214. void appendSubstring (String::Concatenator& concatenator,
  42215. const Range<int>& range) const
  42216. {
  42217. int index = 0;
  42218. for (int i = 0; i < atoms.size(); ++i)
  42219. {
  42220. const TextAtom* const atom = getAtom (i);
  42221. const int nextIndex = index + atom->numChars;
  42222. if (range.getStart() < nextIndex)
  42223. {
  42224. if (range.getEnd() <= index)
  42225. break;
  42226. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42227. if (! r.isEmpty())
  42228. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42229. }
  42230. index = nextIndex;
  42231. }
  42232. }
  42233. int getTotalLength() const
  42234. {
  42235. int total = 0;
  42236. for (int i = atoms.size(); --i >= 0;)
  42237. total += getAtom(i)->numChars;
  42238. return total;
  42239. }
  42240. void setFont (const Font& newFont,
  42241. const juce_wchar passwordCharacter)
  42242. {
  42243. if (font != newFont)
  42244. {
  42245. font = newFont;
  42246. for (int i = atoms.size(); --i >= 0;)
  42247. {
  42248. TextAtom* const atom = atoms.getUnchecked(i);
  42249. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42250. }
  42251. }
  42252. }
  42253. Font font;
  42254. Colour colour;
  42255. private:
  42256. Array <TextAtom*> atoms;
  42257. void initialiseAtoms (const String& textToParse,
  42258. const juce_wchar passwordCharacter)
  42259. {
  42260. int i = 0;
  42261. const int len = textToParse.length();
  42262. const juce_wchar* const text = textToParse;
  42263. while (i < len)
  42264. {
  42265. int start = i;
  42266. // create a whitespace atom unless it starts with non-ws
  42267. if (CharacterFunctions::isWhitespace (text[i])
  42268. && text[i] != '\r'
  42269. && text[i] != '\n')
  42270. {
  42271. while (i < len
  42272. && CharacterFunctions::isWhitespace (text[i])
  42273. && text[i] != '\r'
  42274. && text[i] != '\n')
  42275. {
  42276. ++i;
  42277. }
  42278. }
  42279. else
  42280. {
  42281. if (text[i] == '\r')
  42282. {
  42283. ++i;
  42284. if ((i < len) && (text[i] == '\n'))
  42285. {
  42286. ++start;
  42287. ++i;
  42288. }
  42289. }
  42290. else if (text[i] == '\n')
  42291. {
  42292. ++i;
  42293. }
  42294. else
  42295. {
  42296. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42297. ++i;
  42298. }
  42299. }
  42300. TextAtom* const atom = new TextAtom();
  42301. atom->atomText = String (text + start, i - start);
  42302. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42303. atom->numChars = (uint16) (i - start);
  42304. atoms.add (atom);
  42305. }
  42306. }
  42307. UniformTextSection& operator= (const UniformTextSection& other);
  42308. JUCE_LEAK_DETECTOR (UniformTextSection);
  42309. };
  42310. class TextEditor::Iterator
  42311. {
  42312. public:
  42313. Iterator (const Array <UniformTextSection*>& sections_,
  42314. const float wordWrapWidth_,
  42315. const juce_wchar passwordCharacter_)
  42316. : indexInText (0),
  42317. lineY (0),
  42318. lineHeight (0),
  42319. maxDescent (0),
  42320. atomX (0),
  42321. atomRight (0),
  42322. atom (0),
  42323. currentSection (0),
  42324. sections (sections_),
  42325. sectionIndex (0),
  42326. atomIndex (0),
  42327. wordWrapWidth (wordWrapWidth_),
  42328. passwordCharacter (passwordCharacter_)
  42329. {
  42330. jassert (wordWrapWidth_ > 0);
  42331. if (sections.size() > 0)
  42332. {
  42333. currentSection = sections.getUnchecked (sectionIndex);
  42334. if (currentSection != 0)
  42335. beginNewLine();
  42336. }
  42337. }
  42338. Iterator (const Iterator& other)
  42339. : indexInText (other.indexInText),
  42340. lineY (other.lineY),
  42341. lineHeight (other.lineHeight),
  42342. maxDescent (other.maxDescent),
  42343. atomX (other.atomX),
  42344. atomRight (other.atomRight),
  42345. atom (other.atom),
  42346. currentSection (other.currentSection),
  42347. sections (other.sections),
  42348. sectionIndex (other.sectionIndex),
  42349. atomIndex (other.atomIndex),
  42350. wordWrapWidth (other.wordWrapWidth),
  42351. passwordCharacter (other.passwordCharacter),
  42352. tempAtom (other.tempAtom)
  42353. {
  42354. }
  42355. ~Iterator()
  42356. {
  42357. }
  42358. bool next()
  42359. {
  42360. if (atom == &tempAtom)
  42361. {
  42362. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42363. if (numRemaining > 0)
  42364. {
  42365. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42366. atomX = 0;
  42367. if (tempAtom.numChars > 0)
  42368. lineY += lineHeight;
  42369. indexInText += tempAtom.numChars;
  42370. GlyphArrangement g;
  42371. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42372. int split;
  42373. for (split = 0; split < g.getNumGlyphs(); ++split)
  42374. if (shouldWrap (g.getGlyph (split).getRight()))
  42375. break;
  42376. if (split > 0 && split <= numRemaining)
  42377. {
  42378. tempAtom.numChars = (uint16) split;
  42379. tempAtom.width = g.getGlyph (split - 1).getRight();
  42380. atomRight = atomX + tempAtom.width;
  42381. return true;
  42382. }
  42383. }
  42384. }
  42385. bool forceNewLine = false;
  42386. if (sectionIndex >= sections.size())
  42387. {
  42388. moveToEndOfLastAtom();
  42389. return false;
  42390. }
  42391. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42392. {
  42393. if (atomIndex >= currentSection->getNumAtoms())
  42394. {
  42395. if (++sectionIndex >= sections.size())
  42396. {
  42397. moveToEndOfLastAtom();
  42398. return false;
  42399. }
  42400. atomIndex = 0;
  42401. currentSection = sections.getUnchecked (sectionIndex);
  42402. }
  42403. else
  42404. {
  42405. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42406. if (! lastAtom->isWhitespace())
  42407. {
  42408. // handle the case where the last atom in a section is actually part of the same
  42409. // word as the first atom of the next section...
  42410. float right = atomRight + lastAtom->width;
  42411. float lineHeight2 = lineHeight;
  42412. float maxDescent2 = maxDescent;
  42413. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42414. {
  42415. const UniformTextSection* const s = sections.getUnchecked (section);
  42416. if (s->getNumAtoms() == 0)
  42417. break;
  42418. const TextAtom* const nextAtom = s->getAtom (0);
  42419. if (nextAtom->isWhitespace())
  42420. break;
  42421. right += nextAtom->width;
  42422. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42423. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42424. if (shouldWrap (right))
  42425. {
  42426. lineHeight = lineHeight2;
  42427. maxDescent = maxDescent2;
  42428. forceNewLine = true;
  42429. break;
  42430. }
  42431. if (s->getNumAtoms() > 1)
  42432. break;
  42433. }
  42434. }
  42435. }
  42436. }
  42437. if (atom != 0)
  42438. {
  42439. atomX = atomRight;
  42440. indexInText += atom->numChars;
  42441. if (atom->isNewLine())
  42442. beginNewLine();
  42443. }
  42444. atom = currentSection->getAtom (atomIndex);
  42445. atomRight = atomX + atom->width;
  42446. ++atomIndex;
  42447. if (shouldWrap (atomRight) || forceNewLine)
  42448. {
  42449. if (atom->isWhitespace())
  42450. {
  42451. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42452. atomRight = jmin (atomRight, wordWrapWidth);
  42453. }
  42454. else
  42455. {
  42456. atomRight = atom->width;
  42457. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42458. {
  42459. tempAtom = *atom;
  42460. tempAtom.width = 0;
  42461. tempAtom.numChars = 0;
  42462. atom = &tempAtom;
  42463. if (atomX > 0)
  42464. beginNewLine();
  42465. return next();
  42466. }
  42467. beginNewLine();
  42468. return true;
  42469. }
  42470. }
  42471. return true;
  42472. }
  42473. void beginNewLine()
  42474. {
  42475. atomX = 0;
  42476. lineY += lineHeight;
  42477. int tempSectionIndex = sectionIndex;
  42478. int tempAtomIndex = atomIndex;
  42479. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42480. lineHeight = section->font.getHeight();
  42481. maxDescent = section->font.getDescent();
  42482. float x = (atom != 0) ? atom->width : 0;
  42483. while (! shouldWrap (x))
  42484. {
  42485. if (tempSectionIndex >= sections.size())
  42486. break;
  42487. bool checkSize = false;
  42488. if (tempAtomIndex >= section->getNumAtoms())
  42489. {
  42490. if (++tempSectionIndex >= sections.size())
  42491. break;
  42492. tempAtomIndex = 0;
  42493. section = sections.getUnchecked (tempSectionIndex);
  42494. checkSize = true;
  42495. }
  42496. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42497. if (nextAtom == 0)
  42498. break;
  42499. x += nextAtom->width;
  42500. if (shouldWrap (x) || nextAtom->isNewLine())
  42501. break;
  42502. if (checkSize)
  42503. {
  42504. lineHeight = jmax (lineHeight, section->font.getHeight());
  42505. maxDescent = jmax (maxDescent, section->font.getDescent());
  42506. }
  42507. ++tempAtomIndex;
  42508. }
  42509. }
  42510. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42511. {
  42512. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42513. {
  42514. if (lastSection != currentSection)
  42515. {
  42516. lastSection = currentSection;
  42517. g.setColour (currentSection->colour);
  42518. g.setFont (currentSection->font);
  42519. }
  42520. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42521. GlyphArrangement ga;
  42522. ga.addLineOfText (currentSection->font,
  42523. atom->getTrimmedText (passwordCharacter),
  42524. atomX,
  42525. (float) roundToInt (lineY + lineHeight - maxDescent));
  42526. ga.draw (g);
  42527. }
  42528. }
  42529. void drawSelection (Graphics& g,
  42530. const Range<int>& selection) const
  42531. {
  42532. const int startX = roundToInt (indexToX (selection.getStart()));
  42533. const int endX = roundToInt (indexToX (selection.getEnd()));
  42534. const int y = roundToInt (lineY);
  42535. const int nextY = roundToInt (lineY + lineHeight);
  42536. g.fillRect (startX, y, endX - startX, nextY - y);
  42537. }
  42538. void drawSelectedText (Graphics& g,
  42539. const Range<int>& selection,
  42540. const Colour& selectedTextColour) const
  42541. {
  42542. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42543. {
  42544. GlyphArrangement ga;
  42545. ga.addLineOfText (currentSection->font,
  42546. atom->getTrimmedText (passwordCharacter),
  42547. atomX,
  42548. (float) roundToInt (lineY + lineHeight - maxDescent));
  42549. if (selection.getEnd() < indexInText + atom->numChars)
  42550. {
  42551. GlyphArrangement ga2 (ga);
  42552. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42553. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42554. g.setColour (currentSection->colour);
  42555. ga2.draw (g);
  42556. }
  42557. if (selection.getStart() > indexInText)
  42558. {
  42559. GlyphArrangement ga2 (ga);
  42560. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42561. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42562. g.setColour (currentSection->colour);
  42563. ga2.draw (g);
  42564. }
  42565. g.setColour (selectedTextColour);
  42566. ga.draw (g);
  42567. }
  42568. }
  42569. float indexToX (const int indexToFind) const
  42570. {
  42571. if (indexToFind <= indexInText)
  42572. return atomX;
  42573. if (indexToFind >= indexInText + atom->numChars)
  42574. return atomRight;
  42575. GlyphArrangement g;
  42576. g.addLineOfText (currentSection->font,
  42577. atom->getText (passwordCharacter),
  42578. atomX, 0.0f);
  42579. if (indexToFind - indexInText >= g.getNumGlyphs())
  42580. return atomRight;
  42581. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42582. }
  42583. int xToIndex (const float xToFind) const
  42584. {
  42585. if (xToFind <= atomX || atom->isNewLine())
  42586. return indexInText;
  42587. if (xToFind >= atomRight)
  42588. return indexInText + atom->numChars;
  42589. GlyphArrangement g;
  42590. g.addLineOfText (currentSection->font,
  42591. atom->getText (passwordCharacter),
  42592. atomX, 0.0f);
  42593. int j;
  42594. for (j = 0; j < g.getNumGlyphs(); ++j)
  42595. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42596. break;
  42597. return indexInText + j;
  42598. }
  42599. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42600. {
  42601. while (next())
  42602. {
  42603. if (indexInText + atom->numChars > index)
  42604. {
  42605. cx = indexToX (index);
  42606. cy = lineY;
  42607. lineHeight_ = lineHeight;
  42608. return true;
  42609. }
  42610. }
  42611. cx = atomX;
  42612. cy = lineY;
  42613. lineHeight_ = lineHeight;
  42614. return false;
  42615. }
  42616. int indexInText;
  42617. float lineY, lineHeight, maxDescent;
  42618. float atomX, atomRight;
  42619. const TextAtom* atom;
  42620. const UniformTextSection* currentSection;
  42621. private:
  42622. const Array <UniformTextSection*>& sections;
  42623. int sectionIndex, atomIndex;
  42624. const float wordWrapWidth;
  42625. const juce_wchar passwordCharacter;
  42626. TextAtom tempAtom;
  42627. Iterator& operator= (const Iterator&);
  42628. void moveToEndOfLastAtom()
  42629. {
  42630. if (atom != 0)
  42631. {
  42632. atomX = atomRight;
  42633. if (atom->isNewLine())
  42634. {
  42635. atomX = 0.0f;
  42636. lineY += lineHeight;
  42637. }
  42638. }
  42639. }
  42640. bool shouldWrap (const float x) const
  42641. {
  42642. return (x - 0.0001f) >= wordWrapWidth;
  42643. }
  42644. JUCE_LEAK_DETECTOR (Iterator);
  42645. };
  42646. class TextEditor::InsertAction : public UndoableAction
  42647. {
  42648. public:
  42649. InsertAction (TextEditor& owner_,
  42650. const String& text_,
  42651. const int insertIndex_,
  42652. const Font& font_,
  42653. const Colour& colour_,
  42654. const int oldCaretPos_,
  42655. const int newCaretPos_)
  42656. : owner (owner_),
  42657. text (text_),
  42658. insertIndex (insertIndex_),
  42659. oldCaretPos (oldCaretPos_),
  42660. newCaretPos (newCaretPos_),
  42661. font (font_),
  42662. colour (colour_)
  42663. {
  42664. }
  42665. bool perform()
  42666. {
  42667. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42668. return true;
  42669. }
  42670. bool undo()
  42671. {
  42672. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42673. return true;
  42674. }
  42675. int getSizeInUnits()
  42676. {
  42677. return text.length() + 16;
  42678. }
  42679. private:
  42680. TextEditor& owner;
  42681. const String text;
  42682. const int insertIndex, oldCaretPos, newCaretPos;
  42683. const Font font;
  42684. const Colour colour;
  42685. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42686. };
  42687. class TextEditor::RemoveAction : public UndoableAction
  42688. {
  42689. public:
  42690. RemoveAction (TextEditor& owner_,
  42691. const Range<int> range_,
  42692. const int oldCaretPos_,
  42693. const int newCaretPos_,
  42694. const Array <UniformTextSection*>& removedSections_)
  42695. : owner (owner_),
  42696. range (range_),
  42697. oldCaretPos (oldCaretPos_),
  42698. newCaretPos (newCaretPos_),
  42699. removedSections (removedSections_)
  42700. {
  42701. }
  42702. ~RemoveAction()
  42703. {
  42704. for (int i = removedSections.size(); --i >= 0;)
  42705. {
  42706. UniformTextSection* const section = removedSections.getUnchecked (i);
  42707. section->clear();
  42708. delete section;
  42709. }
  42710. }
  42711. bool perform()
  42712. {
  42713. owner.remove (range, 0, newCaretPos);
  42714. return true;
  42715. }
  42716. bool undo()
  42717. {
  42718. owner.reinsert (range.getStart(), removedSections);
  42719. owner.moveCursorTo (oldCaretPos, false);
  42720. return true;
  42721. }
  42722. int getSizeInUnits()
  42723. {
  42724. int n = 0;
  42725. for (int i = removedSections.size(); --i >= 0;)
  42726. n += removedSections.getUnchecked (i)->getTotalLength();
  42727. return n + 16;
  42728. }
  42729. private:
  42730. TextEditor& owner;
  42731. const Range<int> range;
  42732. const int oldCaretPos, newCaretPos;
  42733. Array <UniformTextSection*> removedSections;
  42734. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42735. };
  42736. class TextEditor::TextHolderComponent : public Component,
  42737. public Timer,
  42738. public ValueListener
  42739. {
  42740. public:
  42741. TextHolderComponent (TextEditor& owner_)
  42742. : owner (owner_)
  42743. {
  42744. setWantsKeyboardFocus (false);
  42745. setInterceptsMouseClicks (false, true);
  42746. owner.getTextValue().addListener (this);
  42747. }
  42748. ~TextHolderComponent()
  42749. {
  42750. owner.getTextValue().removeListener (this);
  42751. }
  42752. void paint (Graphics& g)
  42753. {
  42754. owner.drawContent (g);
  42755. }
  42756. void timerCallback()
  42757. {
  42758. owner.timerCallbackInt();
  42759. }
  42760. const MouseCursor getMouseCursor()
  42761. {
  42762. return owner.getMouseCursor();
  42763. }
  42764. void valueChanged (Value&)
  42765. {
  42766. owner.textWasChangedByValue();
  42767. }
  42768. private:
  42769. TextEditor& owner;
  42770. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42771. };
  42772. class TextEditorViewport : public Viewport
  42773. {
  42774. public:
  42775. TextEditorViewport (TextEditor* const owner_)
  42776. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42777. {
  42778. }
  42779. ~TextEditorViewport()
  42780. {
  42781. }
  42782. void visibleAreaChanged (int, int, int, int)
  42783. {
  42784. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42785. // appear and disappear, causing the wrap width to change.
  42786. {
  42787. const float wordWrapWidth = owner->getWordWrapWidth();
  42788. if (wordWrapWidth != lastWordWrapWidth)
  42789. {
  42790. lastWordWrapWidth = wordWrapWidth;
  42791. rentrant = true;
  42792. owner->updateTextHolderSize();
  42793. rentrant = false;
  42794. }
  42795. }
  42796. }
  42797. private:
  42798. TextEditor* const owner;
  42799. float lastWordWrapWidth;
  42800. bool rentrant;
  42801. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42802. };
  42803. namespace TextEditorDefs
  42804. {
  42805. const int flashSpeedIntervalMs = 380;
  42806. const int textChangeMessageId = 0x10003001;
  42807. const int returnKeyMessageId = 0x10003002;
  42808. const int escapeKeyMessageId = 0x10003003;
  42809. const int focusLossMessageId = 0x10003004;
  42810. const int maxActionsPerTransaction = 100;
  42811. int getCharacterCategory (const juce_wchar character)
  42812. {
  42813. return CharacterFunctions::isLetterOrDigit (character)
  42814. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42815. }
  42816. }
  42817. TextEditor::TextEditor (const String& name,
  42818. const juce_wchar passwordCharacter_)
  42819. : Component (name),
  42820. borderSize (1, 1, 1, 3),
  42821. readOnly (false),
  42822. multiline (false),
  42823. wordWrap (false),
  42824. returnKeyStartsNewLine (false),
  42825. caretVisible (true),
  42826. popupMenuEnabled (true),
  42827. selectAllTextWhenFocused (false),
  42828. scrollbarVisible (true),
  42829. wasFocused (false),
  42830. caretFlashState (true),
  42831. keepCursorOnScreen (true),
  42832. tabKeyUsed (false),
  42833. menuActive (false),
  42834. valueTextNeedsUpdating (false),
  42835. cursorX (0),
  42836. cursorY (0),
  42837. cursorHeight (0),
  42838. maxTextLength (0),
  42839. leftIndent (4),
  42840. topIndent (4),
  42841. lastTransactionTime (0),
  42842. currentFont (14.0f),
  42843. totalNumChars (0),
  42844. caretPosition (0),
  42845. passwordCharacter (passwordCharacter_),
  42846. dragType (notDragging)
  42847. {
  42848. setOpaque (true);
  42849. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42850. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42851. viewport->setWantsKeyboardFocus (false);
  42852. viewport->setScrollBarsShown (false, false);
  42853. setMouseCursor (MouseCursor::IBeamCursor);
  42854. setWantsKeyboardFocus (true);
  42855. }
  42856. TextEditor::~TextEditor()
  42857. {
  42858. textValue.referTo (Value());
  42859. clearInternal (0);
  42860. viewport = 0;
  42861. textHolder = 0;
  42862. }
  42863. void TextEditor::newTransaction()
  42864. {
  42865. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42866. undoManager.beginNewTransaction();
  42867. }
  42868. void TextEditor::doUndoRedo (const bool isRedo)
  42869. {
  42870. if (! isReadOnly())
  42871. {
  42872. if (isRedo ? undoManager.redo()
  42873. : undoManager.undo())
  42874. {
  42875. scrollToMakeSureCursorIsVisible();
  42876. repaint();
  42877. textChanged();
  42878. }
  42879. }
  42880. }
  42881. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42882. const bool shouldWordWrap)
  42883. {
  42884. if (multiline != shouldBeMultiLine
  42885. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42886. {
  42887. multiline = shouldBeMultiLine;
  42888. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42889. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42890. scrollbarVisible && multiline);
  42891. viewport->setViewPosition (0, 0);
  42892. resized();
  42893. scrollToMakeSureCursorIsVisible();
  42894. }
  42895. }
  42896. bool TextEditor::isMultiLine() const
  42897. {
  42898. return multiline;
  42899. }
  42900. void TextEditor::setScrollbarsShown (bool shown)
  42901. {
  42902. if (scrollbarVisible != shown)
  42903. {
  42904. scrollbarVisible = shown;
  42905. shown = shown && isMultiLine();
  42906. viewport->setScrollBarsShown (shown, shown);
  42907. }
  42908. }
  42909. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42910. {
  42911. if (readOnly != shouldBeReadOnly)
  42912. {
  42913. readOnly = shouldBeReadOnly;
  42914. enablementChanged();
  42915. }
  42916. }
  42917. bool TextEditor::isReadOnly() const
  42918. {
  42919. return readOnly || ! isEnabled();
  42920. }
  42921. bool TextEditor::isTextInputActive() const
  42922. {
  42923. return ! isReadOnly();
  42924. }
  42925. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42926. {
  42927. returnKeyStartsNewLine = shouldStartNewLine;
  42928. }
  42929. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42930. {
  42931. tabKeyUsed = shouldTabKeyBeUsed;
  42932. }
  42933. void TextEditor::setPopupMenuEnabled (const bool b)
  42934. {
  42935. popupMenuEnabled = b;
  42936. }
  42937. void TextEditor::setSelectAllWhenFocused (const bool b)
  42938. {
  42939. selectAllTextWhenFocused = b;
  42940. }
  42941. const Font TextEditor::getFont() const
  42942. {
  42943. return currentFont;
  42944. }
  42945. void TextEditor::setFont (const Font& newFont)
  42946. {
  42947. currentFont = newFont;
  42948. scrollToMakeSureCursorIsVisible();
  42949. }
  42950. void TextEditor::applyFontToAllText (const Font& newFont)
  42951. {
  42952. currentFont = newFont;
  42953. const Colour overallColour (findColour (textColourId));
  42954. for (int i = sections.size(); --i >= 0;)
  42955. {
  42956. UniformTextSection* const uts = sections.getUnchecked (i);
  42957. uts->setFont (newFont, passwordCharacter);
  42958. uts->colour = overallColour;
  42959. }
  42960. coalesceSimilarSections();
  42961. updateTextHolderSize();
  42962. scrollToMakeSureCursorIsVisible();
  42963. repaint();
  42964. }
  42965. void TextEditor::colourChanged()
  42966. {
  42967. setOpaque (findColour (backgroundColourId).isOpaque());
  42968. repaint();
  42969. }
  42970. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42971. {
  42972. caretVisible = shouldCaretBeVisible;
  42973. if (shouldCaretBeVisible)
  42974. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42975. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42976. : MouseCursor::NormalCursor);
  42977. }
  42978. void TextEditor::setInputRestrictions (const int maxLen,
  42979. const String& chars)
  42980. {
  42981. maxTextLength = jmax (0, maxLen);
  42982. allowedCharacters = chars;
  42983. }
  42984. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42985. {
  42986. textToShowWhenEmpty = text;
  42987. colourForTextWhenEmpty = colourToUse;
  42988. }
  42989. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42990. {
  42991. if (passwordCharacter != newPasswordCharacter)
  42992. {
  42993. passwordCharacter = newPasswordCharacter;
  42994. resized();
  42995. repaint();
  42996. }
  42997. }
  42998. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42999. {
  43000. viewport->setScrollBarThickness (newThicknessPixels);
  43001. }
  43002. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43003. {
  43004. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43005. }
  43006. void TextEditor::clear()
  43007. {
  43008. clearInternal (0);
  43009. updateTextHolderSize();
  43010. undoManager.clearUndoHistory();
  43011. }
  43012. void TextEditor::setText (const String& newText,
  43013. const bool sendTextChangeMessage)
  43014. {
  43015. const int newLength = newText.length();
  43016. if (newLength != getTotalNumChars() || getText() != newText)
  43017. {
  43018. const int oldCursorPos = caretPosition;
  43019. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43020. clearInternal (0);
  43021. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43022. // if you're adding text with line-feeds to a single-line text editor, it
  43023. // ain't gonna look right!
  43024. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43025. if (cursorWasAtEnd && ! isMultiLine())
  43026. moveCursorTo (getTotalNumChars(), false);
  43027. else
  43028. moveCursorTo (oldCursorPos, false);
  43029. if (sendTextChangeMessage)
  43030. textChanged();
  43031. updateTextHolderSize();
  43032. scrollToMakeSureCursorIsVisible();
  43033. undoManager.clearUndoHistory();
  43034. repaint();
  43035. }
  43036. }
  43037. Value& TextEditor::getTextValue()
  43038. {
  43039. if (valueTextNeedsUpdating)
  43040. {
  43041. valueTextNeedsUpdating = false;
  43042. textValue = getText();
  43043. }
  43044. return textValue;
  43045. }
  43046. void TextEditor::textWasChangedByValue()
  43047. {
  43048. if (textValue.getValueSource().getReferenceCount() > 1)
  43049. setText (textValue.getValue());
  43050. }
  43051. void TextEditor::textChanged()
  43052. {
  43053. updateTextHolderSize();
  43054. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43055. if (textValue.getValueSource().getReferenceCount() > 1)
  43056. {
  43057. valueTextNeedsUpdating = false;
  43058. textValue = getText();
  43059. }
  43060. }
  43061. void TextEditor::returnPressed()
  43062. {
  43063. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43064. }
  43065. void TextEditor::escapePressed()
  43066. {
  43067. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43068. }
  43069. void TextEditor::addListener (TextEditorListener* const newListener)
  43070. {
  43071. listeners.add (newListener);
  43072. }
  43073. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  43074. {
  43075. listeners.remove (listenerToRemove);
  43076. }
  43077. void TextEditor::timerCallbackInt()
  43078. {
  43079. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43080. if (caretFlashState != newState)
  43081. {
  43082. caretFlashState = newState;
  43083. if (caretFlashState)
  43084. wasFocused = true;
  43085. if (caretVisible
  43086. && hasKeyboardFocus (false)
  43087. && ! isReadOnly())
  43088. {
  43089. repaintCaret();
  43090. }
  43091. }
  43092. const unsigned int now = Time::getApproximateMillisecondCounter();
  43093. if (now > lastTransactionTime + 200)
  43094. newTransaction();
  43095. }
  43096. void TextEditor::repaintCaret()
  43097. {
  43098. if (! findColour (caretColourId).isTransparent())
  43099. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43100. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43101. 4,
  43102. roundToInt (cursorHeight) + 2);
  43103. }
  43104. void TextEditor::repaintText (const Range<int>& range)
  43105. {
  43106. if (! range.isEmpty())
  43107. {
  43108. float x = 0, y = 0, lh = currentFont.getHeight();
  43109. const float wordWrapWidth = getWordWrapWidth();
  43110. if (wordWrapWidth > 0)
  43111. {
  43112. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43113. i.getCharPosition (range.getStart(), x, y, lh);
  43114. const int y1 = (int) y;
  43115. int y2;
  43116. if (range.getEnd() >= getTotalNumChars())
  43117. {
  43118. y2 = textHolder->getHeight();
  43119. }
  43120. else
  43121. {
  43122. i.getCharPosition (range.getEnd(), x, y, lh);
  43123. y2 = (int) (y + lh * 2.0f);
  43124. }
  43125. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43126. }
  43127. }
  43128. }
  43129. void TextEditor::moveCaret (int newCaretPos)
  43130. {
  43131. if (newCaretPos < 0)
  43132. newCaretPos = 0;
  43133. else if (newCaretPos > getTotalNumChars())
  43134. newCaretPos = getTotalNumChars();
  43135. if (newCaretPos != getCaretPosition())
  43136. {
  43137. repaintCaret();
  43138. caretFlashState = true;
  43139. caretPosition = newCaretPos;
  43140. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43141. scrollToMakeSureCursorIsVisible();
  43142. repaintCaret();
  43143. }
  43144. }
  43145. void TextEditor::setCaretPosition (const int newIndex)
  43146. {
  43147. moveCursorTo (newIndex, false);
  43148. }
  43149. int TextEditor::getCaretPosition() const
  43150. {
  43151. return caretPosition;
  43152. }
  43153. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43154. const int desiredCaretY)
  43155. {
  43156. updateCaretPosition();
  43157. int vx = roundToInt (cursorX) - desiredCaretX;
  43158. int vy = roundToInt (cursorY) - desiredCaretY;
  43159. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43160. {
  43161. vx += desiredCaretX - proportionOfWidth (0.2f);
  43162. }
  43163. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43164. {
  43165. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43166. }
  43167. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43168. if (! isMultiLine())
  43169. {
  43170. vy = viewport->getViewPositionY();
  43171. }
  43172. else
  43173. {
  43174. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43175. const int curH = roundToInt (cursorHeight);
  43176. if (desiredCaretY < 0)
  43177. {
  43178. vy = jmax (0, desiredCaretY + vy);
  43179. }
  43180. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43181. {
  43182. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43183. }
  43184. }
  43185. viewport->setViewPosition (vx, vy);
  43186. }
  43187. const Rectangle<int> TextEditor::getCaretRectangle()
  43188. {
  43189. updateCaretPosition();
  43190. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43191. roundToInt (cursorY) - viewport->getY(),
  43192. 1, roundToInt (cursorHeight));
  43193. }
  43194. float TextEditor::getWordWrapWidth() const
  43195. {
  43196. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43197. : 1.0e10f;
  43198. }
  43199. void TextEditor::updateTextHolderSize()
  43200. {
  43201. const float wordWrapWidth = getWordWrapWidth();
  43202. if (wordWrapWidth > 0)
  43203. {
  43204. float maxWidth = 0.0f;
  43205. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43206. while (i.next())
  43207. maxWidth = jmax (maxWidth, i.atomRight);
  43208. const int w = leftIndent + roundToInt (maxWidth);
  43209. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43210. currentFont.getHeight()));
  43211. textHolder->setSize (w + 1, h + 1);
  43212. }
  43213. }
  43214. int TextEditor::getTextWidth() const
  43215. {
  43216. return textHolder->getWidth();
  43217. }
  43218. int TextEditor::getTextHeight() const
  43219. {
  43220. return textHolder->getHeight();
  43221. }
  43222. void TextEditor::setIndents (const int newLeftIndent,
  43223. const int newTopIndent)
  43224. {
  43225. leftIndent = newLeftIndent;
  43226. topIndent = newTopIndent;
  43227. }
  43228. void TextEditor::setBorder (const BorderSize& border)
  43229. {
  43230. borderSize = border;
  43231. resized();
  43232. }
  43233. const BorderSize TextEditor::getBorder() const
  43234. {
  43235. return borderSize;
  43236. }
  43237. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43238. {
  43239. keepCursorOnScreen = shouldScrollToShowCursor;
  43240. }
  43241. void TextEditor::updateCaretPosition()
  43242. {
  43243. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43244. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43245. }
  43246. void TextEditor::scrollToMakeSureCursorIsVisible()
  43247. {
  43248. updateCaretPosition();
  43249. if (keepCursorOnScreen)
  43250. {
  43251. int x = viewport->getViewPositionX();
  43252. int y = viewport->getViewPositionY();
  43253. const int relativeCursorX = roundToInt (cursorX) - x;
  43254. const int relativeCursorY = roundToInt (cursorY) - y;
  43255. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43256. {
  43257. x += relativeCursorX - proportionOfWidth (0.2f);
  43258. }
  43259. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43260. {
  43261. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43262. }
  43263. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43264. if (! isMultiLine())
  43265. {
  43266. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43267. }
  43268. else
  43269. {
  43270. const int curH = roundToInt (cursorHeight);
  43271. if (relativeCursorY < 0)
  43272. {
  43273. y = jmax (0, relativeCursorY + y);
  43274. }
  43275. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43276. {
  43277. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43278. }
  43279. }
  43280. viewport->setViewPosition (x, y);
  43281. }
  43282. }
  43283. void TextEditor::moveCursorTo (const int newPosition,
  43284. const bool isSelecting)
  43285. {
  43286. if (isSelecting)
  43287. {
  43288. moveCaret (newPosition);
  43289. const Range<int> oldSelection (selection);
  43290. if (dragType == notDragging)
  43291. {
  43292. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43293. dragType = draggingSelectionStart;
  43294. else
  43295. dragType = draggingSelectionEnd;
  43296. }
  43297. if (dragType == draggingSelectionStart)
  43298. {
  43299. if (getCaretPosition() >= selection.getEnd())
  43300. dragType = draggingSelectionEnd;
  43301. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43302. }
  43303. else
  43304. {
  43305. if (getCaretPosition() < selection.getStart())
  43306. dragType = draggingSelectionStart;
  43307. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43308. }
  43309. repaintText (selection.getUnionWith (oldSelection));
  43310. }
  43311. else
  43312. {
  43313. dragType = notDragging;
  43314. repaintText (selection);
  43315. moveCaret (newPosition);
  43316. selection = Range<int>::emptyRange (getCaretPosition());
  43317. }
  43318. }
  43319. int TextEditor::getTextIndexAt (const int x,
  43320. const int y)
  43321. {
  43322. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43323. (float) (y + viewport->getViewPositionY() - topIndent));
  43324. }
  43325. void TextEditor::insertTextAtCaret (const String& newText_)
  43326. {
  43327. String newText (newText_);
  43328. if (allowedCharacters.isNotEmpty())
  43329. newText = newText.retainCharacters (allowedCharacters);
  43330. if (! isMultiLine())
  43331. newText = newText.replaceCharacters ("\r\n", " ");
  43332. else
  43333. newText = newText.replace ("\r\n", "\n");
  43334. const int newCaretPos = selection.getStart() + newText.length();
  43335. const int insertIndex = selection.getStart();
  43336. remove (selection, getUndoManager(),
  43337. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43338. if (maxTextLength > 0)
  43339. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43340. if (newText.isNotEmpty())
  43341. insert (newText,
  43342. insertIndex,
  43343. currentFont,
  43344. findColour (textColourId),
  43345. getUndoManager(),
  43346. newCaretPos);
  43347. textChanged();
  43348. }
  43349. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43350. {
  43351. moveCursorTo (newSelection.getStart(), false);
  43352. moveCursorTo (newSelection.getEnd(), true);
  43353. }
  43354. void TextEditor::copy()
  43355. {
  43356. if (passwordCharacter == 0)
  43357. {
  43358. const String selectedText (getHighlightedText());
  43359. if (selectedText.isNotEmpty())
  43360. SystemClipboard::copyTextToClipboard (selectedText);
  43361. }
  43362. }
  43363. void TextEditor::paste()
  43364. {
  43365. if (! isReadOnly())
  43366. {
  43367. const String clip (SystemClipboard::getTextFromClipboard());
  43368. if (clip.isNotEmpty())
  43369. insertTextAtCaret (clip);
  43370. }
  43371. }
  43372. void TextEditor::cut()
  43373. {
  43374. if (! isReadOnly())
  43375. {
  43376. moveCaret (selection.getEnd());
  43377. insertTextAtCaret (String::empty);
  43378. }
  43379. }
  43380. void TextEditor::drawContent (Graphics& g)
  43381. {
  43382. const float wordWrapWidth = getWordWrapWidth();
  43383. if (wordWrapWidth > 0)
  43384. {
  43385. g.setOrigin (leftIndent, topIndent);
  43386. const Rectangle<int> clip (g.getClipBounds());
  43387. Colour selectedTextColour;
  43388. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43389. while (i.lineY + 200.0 < clip.getY() && i.next())
  43390. {}
  43391. if (! selection.isEmpty())
  43392. {
  43393. g.setColour (findColour (highlightColourId)
  43394. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43395. selectedTextColour = findColour (highlightedTextColourId);
  43396. Iterator i2 (i);
  43397. while (i2.next() && i2.lineY < clip.getBottom())
  43398. {
  43399. if (i2.lineY + i2.lineHeight >= clip.getY()
  43400. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43401. {
  43402. i2.drawSelection (g, selection);
  43403. }
  43404. }
  43405. }
  43406. const UniformTextSection* lastSection = 0;
  43407. while (i.next() && i.lineY < clip.getBottom())
  43408. {
  43409. if (i.lineY + i.lineHeight >= clip.getY())
  43410. {
  43411. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43412. {
  43413. i.drawSelectedText (g, selection, selectedTextColour);
  43414. lastSection = 0;
  43415. }
  43416. else
  43417. {
  43418. i.draw (g, lastSection);
  43419. }
  43420. }
  43421. }
  43422. }
  43423. }
  43424. void TextEditor::paint (Graphics& g)
  43425. {
  43426. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43427. }
  43428. void TextEditor::paintOverChildren (Graphics& g)
  43429. {
  43430. if (caretFlashState
  43431. && hasKeyboardFocus (false)
  43432. && caretVisible
  43433. && ! isReadOnly())
  43434. {
  43435. g.setColour (findColour (caretColourId));
  43436. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43437. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43438. 2.0f, cursorHeight);
  43439. }
  43440. if (textToShowWhenEmpty.isNotEmpty()
  43441. && (! hasKeyboardFocus (false))
  43442. && getTotalNumChars() == 0)
  43443. {
  43444. g.setColour (colourForTextWhenEmpty);
  43445. g.setFont (getFont());
  43446. if (isMultiLine())
  43447. {
  43448. g.drawText (textToShowWhenEmpty,
  43449. 0, 0, getWidth(), getHeight(),
  43450. Justification::centred, true);
  43451. }
  43452. else
  43453. {
  43454. g.drawText (textToShowWhenEmpty,
  43455. leftIndent, topIndent,
  43456. viewport->getWidth() - leftIndent,
  43457. viewport->getHeight() - topIndent,
  43458. Justification::centredLeft, true);
  43459. }
  43460. }
  43461. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43462. }
  43463. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43464. {
  43465. public:
  43466. TextEditorMenuPerformer (TextEditor* const editor_)
  43467. : editor (editor_)
  43468. {
  43469. }
  43470. void modalStateFinished (int returnValue)
  43471. {
  43472. if (editor != 0 && returnValue != 0)
  43473. editor->performPopupMenuAction (returnValue);
  43474. }
  43475. private:
  43476. Component::SafePointer<TextEditor> editor;
  43477. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43478. };
  43479. void TextEditor::mouseDown (const MouseEvent& e)
  43480. {
  43481. beginDragAutoRepeat (100);
  43482. newTransaction();
  43483. if (wasFocused || ! selectAllTextWhenFocused)
  43484. {
  43485. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43486. {
  43487. moveCursorTo (getTextIndexAt (e.x, e.y),
  43488. e.mods.isShiftDown());
  43489. }
  43490. else
  43491. {
  43492. PopupMenu m;
  43493. m.setLookAndFeel (&getLookAndFeel());
  43494. addPopupMenuItems (m, &e);
  43495. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43496. }
  43497. }
  43498. }
  43499. void TextEditor::mouseDrag (const MouseEvent& e)
  43500. {
  43501. if (wasFocused || ! selectAllTextWhenFocused)
  43502. {
  43503. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43504. {
  43505. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43506. }
  43507. }
  43508. }
  43509. void TextEditor::mouseUp (const MouseEvent& e)
  43510. {
  43511. newTransaction();
  43512. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43513. if (wasFocused || ! selectAllTextWhenFocused)
  43514. {
  43515. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43516. {
  43517. moveCaret (getTextIndexAt (e.x, e.y));
  43518. }
  43519. }
  43520. wasFocused = true;
  43521. }
  43522. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43523. {
  43524. int tokenEnd = getTextIndexAt (e.x, e.y);
  43525. int tokenStart = tokenEnd;
  43526. if (e.getNumberOfClicks() > 3)
  43527. {
  43528. tokenStart = 0;
  43529. tokenEnd = getTotalNumChars();
  43530. }
  43531. else
  43532. {
  43533. const String t (getText());
  43534. const int totalLength = getTotalNumChars();
  43535. while (tokenEnd < totalLength)
  43536. {
  43537. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43538. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43539. ++tokenEnd;
  43540. else
  43541. break;
  43542. }
  43543. tokenStart = tokenEnd;
  43544. while (tokenStart > 0)
  43545. {
  43546. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43547. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43548. --tokenStart;
  43549. else
  43550. break;
  43551. }
  43552. if (e.getNumberOfClicks() > 2)
  43553. {
  43554. while (tokenEnd < totalLength)
  43555. {
  43556. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43557. ++tokenEnd;
  43558. else
  43559. break;
  43560. }
  43561. while (tokenStart > 0)
  43562. {
  43563. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43564. --tokenStart;
  43565. else
  43566. break;
  43567. }
  43568. }
  43569. }
  43570. moveCursorTo (tokenEnd, false);
  43571. moveCursorTo (tokenStart, true);
  43572. }
  43573. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43574. {
  43575. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43576. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43577. }
  43578. bool TextEditor::keyPressed (const KeyPress& key)
  43579. {
  43580. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43581. return false;
  43582. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43583. if (key.isKeyCode (KeyPress::leftKey)
  43584. || key.isKeyCode (KeyPress::upKey))
  43585. {
  43586. newTransaction();
  43587. int newPos;
  43588. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43589. newPos = indexAtPosition (cursorX, cursorY - 1);
  43590. else if (moveInWholeWordSteps)
  43591. newPos = findWordBreakBefore (getCaretPosition());
  43592. else
  43593. newPos = getCaretPosition() - 1;
  43594. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43595. }
  43596. else if (key.isKeyCode (KeyPress::rightKey)
  43597. || key.isKeyCode (KeyPress::downKey))
  43598. {
  43599. newTransaction();
  43600. int newPos;
  43601. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43602. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43603. else if (moveInWholeWordSteps)
  43604. newPos = findWordBreakAfter (getCaretPosition());
  43605. else
  43606. newPos = getCaretPosition() + 1;
  43607. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43608. }
  43609. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43610. {
  43611. newTransaction();
  43612. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43613. key.getModifiers().isShiftDown());
  43614. }
  43615. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43616. {
  43617. newTransaction();
  43618. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43619. key.getModifiers().isShiftDown());
  43620. }
  43621. else if (key.isKeyCode (KeyPress::homeKey))
  43622. {
  43623. newTransaction();
  43624. if (isMultiLine() && ! moveInWholeWordSteps)
  43625. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43626. key.getModifiers().isShiftDown());
  43627. else
  43628. moveCursorTo (0, key.getModifiers().isShiftDown());
  43629. }
  43630. else if (key.isKeyCode (KeyPress::endKey))
  43631. {
  43632. newTransaction();
  43633. if (isMultiLine() && ! moveInWholeWordSteps)
  43634. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43635. key.getModifiers().isShiftDown());
  43636. else
  43637. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43638. }
  43639. else if (key.isKeyCode (KeyPress::backspaceKey))
  43640. {
  43641. if (moveInWholeWordSteps)
  43642. {
  43643. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43644. }
  43645. else
  43646. {
  43647. if (selection.isEmpty() && selection.getStart() > 0)
  43648. selection.setStart (selection.getEnd() - 1);
  43649. }
  43650. cut();
  43651. }
  43652. else if (key.isKeyCode (KeyPress::deleteKey))
  43653. {
  43654. if (key.getModifiers().isShiftDown())
  43655. copy();
  43656. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43657. selection.setEnd (selection.getStart() + 1);
  43658. cut();
  43659. }
  43660. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43661. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43662. {
  43663. newTransaction();
  43664. copy();
  43665. }
  43666. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43667. {
  43668. newTransaction();
  43669. copy();
  43670. cut();
  43671. }
  43672. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43673. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43674. {
  43675. newTransaction();
  43676. paste();
  43677. }
  43678. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43679. {
  43680. newTransaction();
  43681. doUndoRedo (false);
  43682. }
  43683. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43684. {
  43685. newTransaction();
  43686. doUndoRedo (true);
  43687. }
  43688. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43689. {
  43690. newTransaction();
  43691. moveCursorTo (getTotalNumChars(), false);
  43692. moveCursorTo (0, true);
  43693. }
  43694. else if (key == KeyPress::returnKey)
  43695. {
  43696. newTransaction();
  43697. if (returnKeyStartsNewLine)
  43698. insertTextAtCaret ("\n");
  43699. else
  43700. returnPressed();
  43701. }
  43702. else if (key.isKeyCode (KeyPress::escapeKey))
  43703. {
  43704. newTransaction();
  43705. moveCursorTo (getCaretPosition(), false);
  43706. escapePressed();
  43707. }
  43708. else if (key.getTextCharacter() >= ' '
  43709. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43710. {
  43711. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43712. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43713. }
  43714. else
  43715. {
  43716. return false;
  43717. }
  43718. return true;
  43719. }
  43720. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43721. {
  43722. if (! isKeyDown)
  43723. return false;
  43724. #if JUCE_WINDOWS
  43725. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43726. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43727. #endif
  43728. // (overridden to avoid forwarding key events to the parent)
  43729. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43730. }
  43731. const int baseMenuItemID = 0x7fff0000;
  43732. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43733. {
  43734. const bool writable = ! isReadOnly();
  43735. if (passwordCharacter == 0)
  43736. {
  43737. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43738. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43739. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43740. }
  43741. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43742. m.addSeparator();
  43743. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43744. m.addSeparator();
  43745. if (getUndoManager() != 0)
  43746. {
  43747. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43748. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43749. }
  43750. }
  43751. void TextEditor::performPopupMenuAction (const int menuItemID)
  43752. {
  43753. switch (menuItemID)
  43754. {
  43755. case baseMenuItemID + 1:
  43756. copy();
  43757. cut();
  43758. break;
  43759. case baseMenuItemID + 2:
  43760. copy();
  43761. break;
  43762. case baseMenuItemID + 3:
  43763. paste();
  43764. break;
  43765. case baseMenuItemID + 4:
  43766. cut();
  43767. break;
  43768. case baseMenuItemID + 5:
  43769. moveCursorTo (getTotalNumChars(), false);
  43770. moveCursorTo (0, true);
  43771. break;
  43772. case baseMenuItemID + 6:
  43773. doUndoRedo (false);
  43774. break;
  43775. case baseMenuItemID + 7:
  43776. doUndoRedo (true);
  43777. break;
  43778. default:
  43779. break;
  43780. }
  43781. }
  43782. void TextEditor::focusGained (FocusChangeType)
  43783. {
  43784. newTransaction();
  43785. caretFlashState = true;
  43786. if (selectAllTextWhenFocused)
  43787. {
  43788. moveCursorTo (0, false);
  43789. moveCursorTo (getTotalNumChars(), true);
  43790. }
  43791. repaint();
  43792. if (caretVisible)
  43793. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43794. ComponentPeer* const peer = getPeer();
  43795. if (peer != 0 && ! isReadOnly())
  43796. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43797. }
  43798. void TextEditor::focusLost (FocusChangeType)
  43799. {
  43800. newTransaction();
  43801. wasFocused = false;
  43802. textHolder->stopTimer();
  43803. caretFlashState = false;
  43804. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43805. repaint();
  43806. }
  43807. void TextEditor::resized()
  43808. {
  43809. viewport->setBoundsInset (borderSize);
  43810. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43811. updateTextHolderSize();
  43812. if (! isMultiLine())
  43813. {
  43814. scrollToMakeSureCursorIsVisible();
  43815. }
  43816. else
  43817. {
  43818. updateCaretPosition();
  43819. }
  43820. }
  43821. void TextEditor::handleCommandMessage (const int commandId)
  43822. {
  43823. Component::BailOutChecker checker (this);
  43824. switch (commandId)
  43825. {
  43826. case TextEditorDefs::textChangeMessageId:
  43827. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43828. break;
  43829. case TextEditorDefs::returnKeyMessageId:
  43830. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43831. break;
  43832. case TextEditorDefs::escapeKeyMessageId:
  43833. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43834. break;
  43835. case TextEditorDefs::focusLossMessageId:
  43836. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43837. break;
  43838. default:
  43839. jassertfalse;
  43840. break;
  43841. }
  43842. }
  43843. void TextEditor::enablementChanged()
  43844. {
  43845. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43846. : MouseCursor::IBeamCursor);
  43847. repaint();
  43848. }
  43849. UndoManager* TextEditor::getUndoManager() throw()
  43850. {
  43851. return isReadOnly() ? 0 : &undoManager;
  43852. }
  43853. void TextEditor::clearInternal (UndoManager* const um)
  43854. {
  43855. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43856. }
  43857. void TextEditor::insert (const String& text,
  43858. const int insertIndex,
  43859. const Font& font,
  43860. const Colour& colour,
  43861. UndoManager* const um,
  43862. const int caretPositionToMoveTo)
  43863. {
  43864. if (text.isNotEmpty())
  43865. {
  43866. if (um != 0)
  43867. {
  43868. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43869. newTransaction();
  43870. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43871. caretPosition, caretPositionToMoveTo));
  43872. }
  43873. else
  43874. {
  43875. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43876. // a line gets moved due to word wrap
  43877. int index = 0;
  43878. int nextIndex = 0;
  43879. for (int i = 0; i < sections.size(); ++i)
  43880. {
  43881. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43882. if (insertIndex == index)
  43883. {
  43884. sections.insert (i, new UniformTextSection (text,
  43885. font, colour,
  43886. passwordCharacter));
  43887. break;
  43888. }
  43889. else if (insertIndex > index && insertIndex < nextIndex)
  43890. {
  43891. splitSection (i, insertIndex - index);
  43892. sections.insert (i + 1, new UniformTextSection (text,
  43893. font, colour,
  43894. passwordCharacter));
  43895. break;
  43896. }
  43897. index = nextIndex;
  43898. }
  43899. if (nextIndex == insertIndex)
  43900. sections.add (new UniformTextSection (text,
  43901. font, colour,
  43902. passwordCharacter));
  43903. coalesceSimilarSections();
  43904. totalNumChars = -1;
  43905. valueTextNeedsUpdating = true;
  43906. moveCursorTo (caretPositionToMoveTo, false);
  43907. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43908. }
  43909. }
  43910. }
  43911. void TextEditor::reinsert (const int insertIndex,
  43912. const Array <UniformTextSection*>& sectionsToInsert)
  43913. {
  43914. int index = 0;
  43915. int nextIndex = 0;
  43916. for (int i = 0; i < sections.size(); ++i)
  43917. {
  43918. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43919. if (insertIndex == index)
  43920. {
  43921. for (int j = sectionsToInsert.size(); --j >= 0;)
  43922. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43923. break;
  43924. }
  43925. else if (insertIndex > index && insertIndex < nextIndex)
  43926. {
  43927. splitSection (i, insertIndex - index);
  43928. for (int j = sectionsToInsert.size(); --j >= 0;)
  43929. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43930. break;
  43931. }
  43932. index = nextIndex;
  43933. }
  43934. if (nextIndex == insertIndex)
  43935. {
  43936. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43937. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43938. }
  43939. coalesceSimilarSections();
  43940. totalNumChars = -1;
  43941. valueTextNeedsUpdating = true;
  43942. }
  43943. void TextEditor::remove (const Range<int>& range,
  43944. UndoManager* const um,
  43945. const int caretPositionToMoveTo)
  43946. {
  43947. if (! range.isEmpty())
  43948. {
  43949. int index = 0;
  43950. for (int i = 0; i < sections.size(); ++i)
  43951. {
  43952. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43953. if (range.getStart() > index && range.getStart() < nextIndex)
  43954. {
  43955. splitSection (i, range.getStart() - index);
  43956. --i;
  43957. }
  43958. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43959. {
  43960. splitSection (i, range.getEnd() - index);
  43961. --i;
  43962. }
  43963. else
  43964. {
  43965. index = nextIndex;
  43966. if (index > range.getEnd())
  43967. break;
  43968. }
  43969. }
  43970. index = 0;
  43971. if (um != 0)
  43972. {
  43973. Array <UniformTextSection*> removedSections;
  43974. for (int i = 0; i < sections.size(); ++i)
  43975. {
  43976. if (range.getEnd() <= range.getStart())
  43977. break;
  43978. UniformTextSection* const section = sections.getUnchecked (i);
  43979. const int nextIndex = index + section->getTotalLength();
  43980. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43981. removedSections.add (new UniformTextSection (*section));
  43982. index = nextIndex;
  43983. }
  43984. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43985. newTransaction();
  43986. um->perform (new RemoveAction (*this, range, caretPosition,
  43987. caretPositionToMoveTo, removedSections));
  43988. }
  43989. else
  43990. {
  43991. Range<int> remainingRange (range);
  43992. for (int i = 0; i < sections.size(); ++i)
  43993. {
  43994. UniformTextSection* const section = sections.getUnchecked (i);
  43995. const int nextIndex = index + section->getTotalLength();
  43996. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43997. {
  43998. sections.remove(i);
  43999. section->clear();
  44000. delete section;
  44001. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44002. if (remainingRange.isEmpty())
  44003. break;
  44004. --i;
  44005. }
  44006. else
  44007. {
  44008. index = nextIndex;
  44009. }
  44010. }
  44011. coalesceSimilarSections();
  44012. totalNumChars = -1;
  44013. valueTextNeedsUpdating = true;
  44014. moveCursorTo (caretPositionToMoveTo, false);
  44015. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44016. }
  44017. }
  44018. }
  44019. const String TextEditor::getText() const
  44020. {
  44021. String t;
  44022. t.preallocateStorage (getTotalNumChars());
  44023. String::Concatenator concatenator (t);
  44024. for (int i = 0; i < sections.size(); ++i)
  44025. sections.getUnchecked (i)->appendAllText (concatenator);
  44026. return t;
  44027. }
  44028. const String TextEditor::getTextInRange (const Range<int>& range) const
  44029. {
  44030. String t;
  44031. if (! range.isEmpty())
  44032. {
  44033. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44034. String::Concatenator concatenator (t);
  44035. int index = 0;
  44036. for (int i = 0; i < sections.size(); ++i)
  44037. {
  44038. const UniformTextSection* const s = sections.getUnchecked (i);
  44039. const int nextIndex = index + s->getTotalLength();
  44040. if (range.getStart() < nextIndex)
  44041. {
  44042. if (range.getEnd() <= index)
  44043. break;
  44044. s->appendSubstring (concatenator, range - index);
  44045. }
  44046. index = nextIndex;
  44047. }
  44048. }
  44049. return t;
  44050. }
  44051. const String TextEditor::getHighlightedText() const
  44052. {
  44053. return getTextInRange (selection);
  44054. }
  44055. int TextEditor::getTotalNumChars() const
  44056. {
  44057. if (totalNumChars < 0)
  44058. {
  44059. totalNumChars = 0;
  44060. for (int i = sections.size(); --i >= 0;)
  44061. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44062. }
  44063. return totalNumChars;
  44064. }
  44065. bool TextEditor::isEmpty() const
  44066. {
  44067. return getTotalNumChars() == 0;
  44068. }
  44069. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44070. {
  44071. const float wordWrapWidth = getWordWrapWidth();
  44072. if (wordWrapWidth > 0 && sections.size() > 0)
  44073. {
  44074. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44075. i.getCharPosition (index, cx, cy, lineHeight);
  44076. }
  44077. else
  44078. {
  44079. cx = cy = 0;
  44080. lineHeight = currentFont.getHeight();
  44081. }
  44082. }
  44083. int TextEditor::indexAtPosition (const float x, const float y)
  44084. {
  44085. const float wordWrapWidth = getWordWrapWidth();
  44086. if (wordWrapWidth > 0)
  44087. {
  44088. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44089. while (i.next())
  44090. {
  44091. if (i.lineY + i.lineHeight > y)
  44092. {
  44093. if (i.lineY > y)
  44094. return jmax (0, i.indexInText - 1);
  44095. if (i.atomX >= x)
  44096. return i.indexInText;
  44097. if (x < i.atomRight)
  44098. return i.xToIndex (x);
  44099. }
  44100. }
  44101. }
  44102. return getTotalNumChars();
  44103. }
  44104. int TextEditor::findWordBreakAfter (const int position) const
  44105. {
  44106. const String t (getTextInRange (Range<int> (position, position + 512)));
  44107. const int totalLength = t.length();
  44108. int i = 0;
  44109. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44110. ++i;
  44111. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44112. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44113. ++i;
  44114. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44115. ++i;
  44116. return position + i;
  44117. }
  44118. int TextEditor::findWordBreakBefore (const int position) const
  44119. {
  44120. if (position <= 0)
  44121. return 0;
  44122. const int startOfBuffer = jmax (0, position - 512);
  44123. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44124. int i = position - startOfBuffer;
  44125. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44126. --i;
  44127. if (i > 0)
  44128. {
  44129. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44130. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44131. --i;
  44132. }
  44133. jassert (startOfBuffer + i >= 0);
  44134. return startOfBuffer + i;
  44135. }
  44136. void TextEditor::splitSection (const int sectionIndex,
  44137. const int charToSplitAt)
  44138. {
  44139. jassert (sections[sectionIndex] != 0);
  44140. sections.insert (sectionIndex + 1,
  44141. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44142. }
  44143. void TextEditor::coalesceSimilarSections()
  44144. {
  44145. for (int i = 0; i < sections.size() - 1; ++i)
  44146. {
  44147. UniformTextSection* const s1 = sections.getUnchecked (i);
  44148. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44149. if (s1->font == s2->font
  44150. && s1->colour == s2->colour)
  44151. {
  44152. s1->append (*s2, passwordCharacter);
  44153. sections.remove (i + 1);
  44154. delete s2;
  44155. --i;
  44156. }
  44157. }
  44158. }
  44159. END_JUCE_NAMESPACE
  44160. /*** End of inlined file: juce_TextEditor.cpp ***/
  44161. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44162. BEGIN_JUCE_NAMESPACE
  44163. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44164. class ToolbarSpacerComp : public ToolbarItemComponent
  44165. {
  44166. public:
  44167. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44168. : ToolbarItemComponent (itemId_, String::empty, false),
  44169. fixedSize (fixedSize_),
  44170. drawBar (drawBar_)
  44171. {
  44172. }
  44173. ~ToolbarSpacerComp()
  44174. {
  44175. }
  44176. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44177. int& preferredSize, int& minSize, int& maxSize)
  44178. {
  44179. if (fixedSize <= 0)
  44180. {
  44181. preferredSize = toolbarThickness * 2;
  44182. minSize = 4;
  44183. maxSize = 32768;
  44184. }
  44185. else
  44186. {
  44187. maxSize = roundToInt (toolbarThickness * fixedSize);
  44188. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44189. preferredSize = maxSize;
  44190. if (getEditingMode() == editableOnPalette)
  44191. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44192. }
  44193. return true;
  44194. }
  44195. void paintButtonArea (Graphics&, int, int, bool, bool)
  44196. {
  44197. }
  44198. void contentAreaChanged (const Rectangle<int>&)
  44199. {
  44200. }
  44201. int getResizeOrder() const throw()
  44202. {
  44203. return fixedSize <= 0 ? 0 : 1;
  44204. }
  44205. void paint (Graphics& g)
  44206. {
  44207. const int w = getWidth();
  44208. const int h = getHeight();
  44209. if (drawBar)
  44210. {
  44211. g.setColour (findColour (Toolbar::separatorColourId, true));
  44212. const float thickness = 0.2f;
  44213. if (isToolbarVertical())
  44214. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44215. else
  44216. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44217. }
  44218. if (getEditingMode() != normalMode && ! drawBar)
  44219. {
  44220. g.setColour (findColour (Toolbar::separatorColourId, true));
  44221. const int indentX = jmin (2, (w - 3) / 2);
  44222. const int indentY = jmin (2, (h - 3) / 2);
  44223. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44224. if (fixedSize <= 0)
  44225. {
  44226. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44227. if (isToolbarVertical())
  44228. {
  44229. x1 = w * 0.5f;
  44230. y1 = h * 0.4f;
  44231. x2 = x1;
  44232. y2 = indentX * 2.0f;
  44233. x3 = x1;
  44234. y3 = h * 0.6f;
  44235. x4 = x1;
  44236. y4 = h - y2;
  44237. hw = w * 0.15f;
  44238. hl = w * 0.2f;
  44239. }
  44240. else
  44241. {
  44242. x1 = w * 0.4f;
  44243. y1 = h * 0.5f;
  44244. x2 = indentX * 2.0f;
  44245. y2 = y1;
  44246. x3 = w * 0.6f;
  44247. y3 = y1;
  44248. x4 = w - x2;
  44249. y4 = y1;
  44250. hw = h * 0.15f;
  44251. hl = h * 0.2f;
  44252. }
  44253. Path p;
  44254. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44255. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44256. g.fillPath (p);
  44257. }
  44258. }
  44259. }
  44260. private:
  44261. const float fixedSize;
  44262. const bool drawBar;
  44263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44264. };
  44265. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44266. {
  44267. public:
  44268. MissingItemsComponent (Toolbar& owner_, const int height_)
  44269. : PopupMenuCustomComponent (true),
  44270. owner (&owner_),
  44271. height (height_)
  44272. {
  44273. for (int i = owner_.items.size(); --i >= 0;)
  44274. {
  44275. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44276. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44277. {
  44278. oldIndexes.insert (0, i);
  44279. addAndMakeVisible (tc, 0);
  44280. }
  44281. }
  44282. layout (400);
  44283. }
  44284. ~MissingItemsComponent()
  44285. {
  44286. if (owner != 0)
  44287. {
  44288. for (int i = 0; i < getNumChildComponents(); ++i)
  44289. {
  44290. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44291. if (tc != 0)
  44292. {
  44293. tc->setVisible (false);
  44294. const int index = oldIndexes.remove (i);
  44295. owner->addChildComponent (tc, index);
  44296. --i;
  44297. }
  44298. }
  44299. owner->resized();
  44300. }
  44301. }
  44302. void layout (const int preferredWidth)
  44303. {
  44304. const int indent = 8;
  44305. int x = indent;
  44306. int y = indent;
  44307. int maxX = 0;
  44308. for (int i = 0; i < getNumChildComponents(); ++i)
  44309. {
  44310. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44311. if (tc != 0)
  44312. {
  44313. int preferredSize = 1, minSize = 1, maxSize = 1;
  44314. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44315. {
  44316. if (x + preferredSize > preferredWidth && x > indent)
  44317. {
  44318. x = indent;
  44319. y += height;
  44320. }
  44321. tc->setBounds (x, y, preferredSize, height);
  44322. x += preferredSize;
  44323. maxX = jmax (maxX, x);
  44324. }
  44325. }
  44326. }
  44327. setSize (maxX + 8, y + height + 8);
  44328. }
  44329. void getIdealSize (int& idealWidth, int& idealHeight)
  44330. {
  44331. idealWidth = getWidth();
  44332. idealHeight = getHeight();
  44333. }
  44334. private:
  44335. Component::SafePointer<Toolbar> owner;
  44336. const int height;
  44337. Array <int> oldIndexes;
  44338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44339. };
  44340. Toolbar::Toolbar()
  44341. : vertical (false),
  44342. isEditingActive (false),
  44343. toolbarStyle (Toolbar::iconsOnly)
  44344. {
  44345. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44346. missingItemsButton->setAlwaysOnTop (true);
  44347. missingItemsButton->addButtonListener (this);
  44348. }
  44349. Toolbar::~Toolbar()
  44350. {
  44351. items.clear();
  44352. }
  44353. void Toolbar::setVertical (const bool shouldBeVertical)
  44354. {
  44355. if (vertical != shouldBeVertical)
  44356. {
  44357. vertical = shouldBeVertical;
  44358. resized();
  44359. }
  44360. }
  44361. void Toolbar::clear()
  44362. {
  44363. items.clear();
  44364. resized();
  44365. }
  44366. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44367. {
  44368. if (itemId == ToolbarItemFactory::separatorBarId)
  44369. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44370. else if (itemId == ToolbarItemFactory::spacerId)
  44371. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44372. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44373. return new ToolbarSpacerComp (itemId, 0, false);
  44374. return factory.createItem (itemId);
  44375. }
  44376. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44377. const int itemId,
  44378. const int insertIndex)
  44379. {
  44380. // An ID can't be zero - this might indicate a mistake somewhere?
  44381. jassert (itemId != 0);
  44382. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44383. if (tc != 0)
  44384. {
  44385. #if JUCE_DEBUG
  44386. Array <int> allowedIds;
  44387. factory.getAllToolbarItemIds (allowedIds);
  44388. // If your factory can create an item for a given ID, it must also return
  44389. // that ID from its getAllToolbarItemIds() method!
  44390. jassert (allowedIds.contains (itemId));
  44391. #endif
  44392. items.insert (insertIndex, tc);
  44393. addAndMakeVisible (tc, insertIndex);
  44394. }
  44395. }
  44396. void Toolbar::addItem (ToolbarItemFactory& factory,
  44397. const int itemId,
  44398. const int insertIndex)
  44399. {
  44400. addItemInternal (factory, itemId, insertIndex);
  44401. resized();
  44402. }
  44403. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44404. {
  44405. Array <int> ids;
  44406. factoryToUse.getDefaultItemSet (ids);
  44407. clear();
  44408. for (int i = 0; i < ids.size(); ++i)
  44409. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44410. resized();
  44411. }
  44412. void Toolbar::removeToolbarItem (const int itemIndex)
  44413. {
  44414. items.remove (itemIndex);
  44415. resized();
  44416. }
  44417. int Toolbar::getNumItems() const throw()
  44418. {
  44419. return items.size();
  44420. }
  44421. int Toolbar::getItemId (const int itemIndex) const throw()
  44422. {
  44423. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44424. return tc != 0 ? tc->getItemId() : 0;
  44425. }
  44426. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44427. {
  44428. return items [itemIndex];
  44429. }
  44430. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44431. {
  44432. for (;;)
  44433. {
  44434. index += delta;
  44435. ToolbarItemComponent* const tc = getItemComponent (index);
  44436. if (tc == 0)
  44437. break;
  44438. if (tc->isActive)
  44439. return tc;
  44440. }
  44441. return 0;
  44442. }
  44443. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44444. {
  44445. if (toolbarStyle != newStyle)
  44446. {
  44447. toolbarStyle = newStyle;
  44448. updateAllItemPositions (false);
  44449. }
  44450. }
  44451. const String Toolbar::toString() const
  44452. {
  44453. String s ("TB:");
  44454. for (int i = 0; i < getNumItems(); ++i)
  44455. s << getItemId(i) << ' ';
  44456. return s.trimEnd();
  44457. }
  44458. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44459. const String& savedVersion)
  44460. {
  44461. if (! savedVersion.startsWith ("TB:"))
  44462. return false;
  44463. StringArray tokens;
  44464. tokens.addTokens (savedVersion.substring (3), false);
  44465. clear();
  44466. for (int i = 0; i < tokens.size(); ++i)
  44467. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44468. resized();
  44469. return true;
  44470. }
  44471. void Toolbar::paint (Graphics& g)
  44472. {
  44473. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44474. }
  44475. int Toolbar::getThickness() const throw()
  44476. {
  44477. return vertical ? getWidth() : getHeight();
  44478. }
  44479. int Toolbar::getLength() const throw()
  44480. {
  44481. return vertical ? getHeight() : getWidth();
  44482. }
  44483. void Toolbar::setEditingActive (const bool active)
  44484. {
  44485. if (isEditingActive != active)
  44486. {
  44487. isEditingActive = active;
  44488. updateAllItemPositions (false);
  44489. }
  44490. }
  44491. void Toolbar::resized()
  44492. {
  44493. updateAllItemPositions (false);
  44494. }
  44495. void Toolbar::updateAllItemPositions (const bool animate)
  44496. {
  44497. if (getWidth() > 0 && getHeight() > 0)
  44498. {
  44499. StretchableObjectResizer resizer;
  44500. int i;
  44501. for (i = 0; i < items.size(); ++i)
  44502. {
  44503. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44504. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44505. : ToolbarItemComponent::normalMode);
  44506. tc->setStyle (toolbarStyle);
  44507. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44508. int preferredSize = 1, minSize = 1, maxSize = 1;
  44509. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44510. preferredSize, minSize, maxSize))
  44511. {
  44512. tc->isActive = true;
  44513. resizer.addItem (preferredSize, minSize, maxSize,
  44514. spacer != 0 ? spacer->getResizeOrder() : 2);
  44515. }
  44516. else
  44517. {
  44518. tc->isActive = false;
  44519. tc->setVisible (false);
  44520. }
  44521. }
  44522. resizer.resizeToFit (getLength());
  44523. int totalLength = 0;
  44524. for (i = 0; i < resizer.getNumItems(); ++i)
  44525. totalLength += (int) resizer.getItemSize (i);
  44526. const bool itemsOffTheEnd = totalLength > getLength();
  44527. const int extrasButtonSize = getThickness() / 2;
  44528. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44529. missingItemsButton->setVisible (itemsOffTheEnd);
  44530. missingItemsButton->setEnabled (! isEditingActive);
  44531. if (vertical)
  44532. missingItemsButton->setCentrePosition (getWidth() / 2,
  44533. getHeight() - 4 - extrasButtonSize / 2);
  44534. else
  44535. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44536. getHeight() / 2);
  44537. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44538. : missingItemsButton->getX()) - 4
  44539. : getLength();
  44540. int pos = 0, activeIndex = 0;
  44541. for (i = 0; i < items.size(); ++i)
  44542. {
  44543. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44544. if (tc->isActive)
  44545. {
  44546. const int size = (int) resizer.getItemSize (activeIndex++);
  44547. Rectangle<int> newBounds;
  44548. if (vertical)
  44549. newBounds.setBounds (0, pos, getWidth(), size);
  44550. else
  44551. newBounds.setBounds (pos, 0, size, getHeight());
  44552. if (animate)
  44553. {
  44554. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44555. }
  44556. else
  44557. {
  44558. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44559. tc->setBounds (newBounds);
  44560. }
  44561. pos += size;
  44562. tc->setVisible (pos <= maxLength
  44563. && ((! tc->isBeingDragged)
  44564. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44565. }
  44566. }
  44567. }
  44568. }
  44569. void Toolbar::buttonClicked (Button*)
  44570. {
  44571. jassert (missingItemsButton->isShowing());
  44572. if (missingItemsButton->isShowing())
  44573. {
  44574. PopupMenu m;
  44575. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44576. m.showAt (missingItemsButton);
  44577. }
  44578. }
  44579. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44580. Component* /*sourceComponent*/)
  44581. {
  44582. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44583. }
  44584. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44585. {
  44586. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44587. if (tc != 0)
  44588. {
  44589. if (! items.contains (tc))
  44590. {
  44591. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44592. {
  44593. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44594. if (palette != 0)
  44595. palette->replaceComponent (tc);
  44596. }
  44597. else
  44598. {
  44599. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44600. }
  44601. items.add (tc);
  44602. addChildComponent (tc);
  44603. updateAllItemPositions (true);
  44604. }
  44605. for (int i = getNumItems(); --i >= 0;)
  44606. {
  44607. const int currentIndex = items.indexOf (tc);
  44608. int newIndex = currentIndex;
  44609. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44610. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44611. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44612. .getComponentDestination (getChildComponent (newIndex)));
  44613. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44614. if (prev != 0)
  44615. {
  44616. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44617. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44618. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44619. {
  44620. newIndex = getIndexOfChildComponent (prev);
  44621. }
  44622. }
  44623. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44624. if (next != 0)
  44625. {
  44626. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44627. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44628. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44629. {
  44630. newIndex = getIndexOfChildComponent (next) + 1;
  44631. }
  44632. }
  44633. if (newIndex == currentIndex)
  44634. break;
  44635. items.removeObject (tc, false);
  44636. removeChildComponent (tc);
  44637. addChildComponent (tc, newIndex);
  44638. items.insert (newIndex, tc);
  44639. updateAllItemPositions (true);
  44640. }
  44641. }
  44642. }
  44643. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44644. {
  44645. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44646. if (tc != 0 && isParentOf (tc))
  44647. {
  44648. items.removeObject (tc, false);
  44649. removeChildComponent (tc);
  44650. updateAllItemPositions (true);
  44651. }
  44652. }
  44653. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44654. {
  44655. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44656. if (tc != 0)
  44657. tc->setState (Button::buttonNormal);
  44658. }
  44659. void Toolbar::mouseDown (const MouseEvent&)
  44660. {
  44661. }
  44662. class ToolbarCustomisationDialog : public DialogWindow
  44663. {
  44664. public:
  44665. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44666. Toolbar* const toolbar_,
  44667. const int optionFlags)
  44668. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44669. toolbar (toolbar_)
  44670. {
  44671. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44672. setResizable (true, true);
  44673. setResizeLimits (400, 300, 1500, 1000);
  44674. positionNearBar();
  44675. }
  44676. ~ToolbarCustomisationDialog()
  44677. {
  44678. setContentComponent (0, true);
  44679. }
  44680. void closeButtonPressed()
  44681. {
  44682. setVisible (false);
  44683. }
  44684. bool canModalEventBeSentToComponent (const Component* comp)
  44685. {
  44686. return toolbar->isParentOf (comp);
  44687. }
  44688. void positionNearBar()
  44689. {
  44690. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44691. const int tbx = toolbar->getScreenX();
  44692. const int tby = toolbar->getScreenY();
  44693. const int gap = 8;
  44694. int x, y;
  44695. if (toolbar->isVertical())
  44696. {
  44697. y = tby;
  44698. if (tbx > screenSize.getCentreX())
  44699. x = tbx - getWidth() - gap;
  44700. else
  44701. x = tbx + toolbar->getWidth() + gap;
  44702. }
  44703. else
  44704. {
  44705. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44706. if (tby > screenSize.getCentreY())
  44707. y = tby - getHeight() - gap;
  44708. else
  44709. y = tby + toolbar->getHeight() + gap;
  44710. }
  44711. setTopLeftPosition (x, y);
  44712. }
  44713. private:
  44714. Toolbar* const toolbar;
  44715. class CustomiserPanel : public Component,
  44716. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44717. private ButtonListener
  44718. {
  44719. public:
  44720. CustomiserPanel (ToolbarItemFactory& factory_,
  44721. Toolbar* const toolbar_,
  44722. const int optionFlags)
  44723. : factory (factory_),
  44724. toolbar (toolbar_),
  44725. palette (factory_, toolbar_),
  44726. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44727. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44728. defaultButton (TRANS ("Restore to default set of items"))
  44729. {
  44730. addAndMakeVisible (&palette);
  44731. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44732. | Toolbar::allowIconsWithTextChoice
  44733. | Toolbar::allowTextOnlyChoice)) != 0)
  44734. {
  44735. addAndMakeVisible (&styleBox);
  44736. styleBox.setEditableText (false);
  44737. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44738. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44739. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44740. int selectedStyle = 0;
  44741. switch (toolbar_->getStyle())
  44742. {
  44743. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44744. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44745. case Toolbar::textOnly: selectedStyle = 3; break;
  44746. }
  44747. styleBox.setSelectedId (selectedStyle);
  44748. styleBox.addListener (this);
  44749. }
  44750. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44751. {
  44752. addAndMakeVisible (&defaultButton);
  44753. defaultButton.addButtonListener (this);
  44754. }
  44755. addAndMakeVisible (&instructions);
  44756. instructions.setFont (Font (13.0f));
  44757. setSize (500, 300);
  44758. }
  44759. void comboBoxChanged (ComboBox*)
  44760. {
  44761. switch (styleBox.getSelectedId())
  44762. {
  44763. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44764. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44765. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44766. }
  44767. palette.resized(); // to make it update the styles
  44768. }
  44769. void buttonClicked (Button*)
  44770. {
  44771. toolbar->addDefaultItems (factory);
  44772. }
  44773. void paint (Graphics& g)
  44774. {
  44775. Colour background;
  44776. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44777. if (dw != 0)
  44778. background = dw->getBackgroundColour();
  44779. g.setColour (background.contrasting().withAlpha (0.3f));
  44780. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44781. }
  44782. void resized()
  44783. {
  44784. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44785. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44786. defaultButton.changeWidthToFitText (22);
  44787. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44788. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44789. }
  44790. private:
  44791. ToolbarItemFactory& factory;
  44792. Toolbar* const toolbar;
  44793. ToolbarItemPalette palette;
  44794. Label instructions;
  44795. ComboBox styleBox;
  44796. TextButton defaultButton;
  44797. };
  44798. };
  44799. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44800. {
  44801. setEditingActive (true);
  44802. #if JUCE_DEBUG
  44803. Component::SafePointer<Component> checker (this);
  44804. #endif
  44805. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44806. dw.runModalLoop();
  44807. #if JUCE_DEBUG
  44808. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44809. #endif
  44810. setEditingActive (false);
  44811. }
  44812. END_JUCE_NAMESPACE
  44813. /*** End of inlined file: juce_Toolbar.cpp ***/
  44814. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44815. BEGIN_JUCE_NAMESPACE
  44816. ToolbarItemFactory::ToolbarItemFactory()
  44817. {
  44818. }
  44819. ToolbarItemFactory::~ToolbarItemFactory()
  44820. {
  44821. }
  44822. class ItemDragAndDropOverlayComponent : public Component
  44823. {
  44824. public:
  44825. ItemDragAndDropOverlayComponent()
  44826. : isDragging (false)
  44827. {
  44828. setAlwaysOnTop (true);
  44829. setRepaintsOnMouseActivity (true);
  44830. setMouseCursor (MouseCursor::DraggingHandCursor);
  44831. }
  44832. void paint (Graphics& g)
  44833. {
  44834. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44835. if (isMouseOverOrDragging()
  44836. && tc != 0
  44837. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44838. {
  44839. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44840. g.drawRect (0, 0, getWidth(), getHeight(),
  44841. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44842. }
  44843. }
  44844. void mouseDown (const MouseEvent& e)
  44845. {
  44846. isDragging = false;
  44847. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44848. if (tc != 0)
  44849. {
  44850. tc->dragOffsetX = e.x;
  44851. tc->dragOffsetY = e.y;
  44852. }
  44853. }
  44854. void mouseDrag (const MouseEvent& e)
  44855. {
  44856. if (! (isDragging || e.mouseWasClicked()))
  44857. {
  44858. isDragging = true;
  44859. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44860. if (dnd != 0)
  44861. {
  44862. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44863. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44864. if (tc != 0)
  44865. {
  44866. tc->isBeingDragged = true;
  44867. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44868. tc->setVisible (false);
  44869. }
  44870. }
  44871. }
  44872. }
  44873. void mouseUp (const MouseEvent&)
  44874. {
  44875. isDragging = false;
  44876. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44877. if (tc != 0)
  44878. {
  44879. tc->isBeingDragged = false;
  44880. Toolbar* const tb = tc->getToolbar();
  44881. if (tb != 0)
  44882. tb->updateAllItemPositions (true);
  44883. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44884. delete tc;
  44885. }
  44886. }
  44887. void parentSizeChanged()
  44888. {
  44889. setBounds (0, 0, getParentWidth(), getParentHeight());
  44890. }
  44891. private:
  44892. bool isDragging;
  44893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44894. };
  44895. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44896. const String& labelText,
  44897. const bool isBeingUsedAsAButton_)
  44898. : Button (labelText),
  44899. itemId (itemId_),
  44900. mode (normalMode),
  44901. toolbarStyle (Toolbar::iconsOnly),
  44902. dragOffsetX (0),
  44903. dragOffsetY (0),
  44904. isActive (true),
  44905. isBeingDragged (false),
  44906. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44907. {
  44908. // Your item ID can't be 0!
  44909. jassert (itemId_ != 0);
  44910. }
  44911. ToolbarItemComponent::~ToolbarItemComponent()
  44912. {
  44913. overlayComp = 0;
  44914. }
  44915. Toolbar* ToolbarItemComponent::getToolbar() const
  44916. {
  44917. return dynamic_cast <Toolbar*> (getParentComponent());
  44918. }
  44919. bool ToolbarItemComponent::isToolbarVertical() const
  44920. {
  44921. const Toolbar* const t = getToolbar();
  44922. return t != 0 && t->isVertical();
  44923. }
  44924. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44925. {
  44926. if (toolbarStyle != newStyle)
  44927. {
  44928. toolbarStyle = newStyle;
  44929. repaint();
  44930. resized();
  44931. }
  44932. }
  44933. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44934. {
  44935. if (isBeingUsedAsAButton)
  44936. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44937. over, down, *this);
  44938. if (toolbarStyle != Toolbar::iconsOnly)
  44939. {
  44940. const int indent = contentArea.getX();
  44941. int y = indent;
  44942. int h = getHeight() - indent * 2;
  44943. if (toolbarStyle == Toolbar::iconsWithText)
  44944. {
  44945. y = contentArea.getBottom() + indent / 2;
  44946. h -= contentArea.getHeight();
  44947. }
  44948. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44949. getButtonText(), *this);
  44950. }
  44951. if (! contentArea.isEmpty())
  44952. {
  44953. Graphics::ScopedSaveState ss (g);
  44954. g.reduceClipRegion (contentArea);
  44955. g.setOrigin (contentArea.getX(), contentArea.getY());
  44956. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44957. }
  44958. }
  44959. void ToolbarItemComponent::resized()
  44960. {
  44961. if (toolbarStyle != Toolbar::textOnly)
  44962. {
  44963. const int indent = jmin (proportionOfWidth (0.08f),
  44964. proportionOfHeight (0.08f));
  44965. contentArea = Rectangle<int> (indent, indent,
  44966. getWidth() - indent * 2,
  44967. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44968. : (getHeight() - indent * 2));
  44969. }
  44970. else
  44971. {
  44972. contentArea = Rectangle<int>();
  44973. }
  44974. contentAreaChanged (contentArea);
  44975. }
  44976. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44977. {
  44978. if (mode != newMode)
  44979. {
  44980. mode = newMode;
  44981. repaint();
  44982. if (mode == normalMode)
  44983. {
  44984. overlayComp = 0;
  44985. }
  44986. else if (overlayComp == 0)
  44987. {
  44988. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44989. overlayComp->parentSizeChanged();
  44990. }
  44991. resized();
  44992. }
  44993. }
  44994. END_JUCE_NAMESPACE
  44995. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44996. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44997. BEGIN_JUCE_NAMESPACE
  44998. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44999. Toolbar* const toolbar_)
  45000. : factory (factory_),
  45001. toolbar (toolbar_)
  45002. {
  45003. Component* const itemHolder = new Component();
  45004. viewport.setViewedComponent (itemHolder);
  45005. Array <int> allIds;
  45006. factory.getAllToolbarItemIds (allIds);
  45007. for (int i = 0; i < allIds.size(); ++i)
  45008. addComponent (allIds.getUnchecked (i), -1);
  45009. addAndMakeVisible (&viewport);
  45010. }
  45011. ToolbarItemPalette::~ToolbarItemPalette()
  45012. {
  45013. }
  45014. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  45015. {
  45016. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  45017. jassert (tc != 0);
  45018. if (tc != 0)
  45019. {
  45020. items.insert (index, tc);
  45021. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  45022. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45023. }
  45024. }
  45025. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45026. {
  45027. const int index = items.indexOf (comp);
  45028. jassert (index >= 0);
  45029. items.removeObject (comp, false);
  45030. addComponent (comp->getItemId(), index);
  45031. resized();
  45032. }
  45033. void ToolbarItemPalette::resized()
  45034. {
  45035. viewport.setBoundsInset (BorderSize (1));
  45036. Component* const itemHolder = viewport.getViewedComponent();
  45037. const int indent = 8;
  45038. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  45039. const int height = toolbar->getThickness();
  45040. int x = indent;
  45041. int y = indent;
  45042. int maxX = 0;
  45043. for (int i = 0; i < items.size(); ++i)
  45044. {
  45045. ToolbarItemComponent* const tc = items.getUnchecked(i);
  45046. tc->setStyle (toolbar->getStyle());
  45047. int preferredSize = 1, minSize = 1, maxSize = 1;
  45048. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45049. {
  45050. if (x + preferredSize > preferredWidth && x > indent)
  45051. {
  45052. x = indent;
  45053. y += height;
  45054. }
  45055. tc->setBounds (x, y, preferredSize, height);
  45056. x += preferredSize + 8;
  45057. maxX = jmax (maxX, x);
  45058. }
  45059. }
  45060. itemHolder->setSize (maxX, y + height + 8);
  45061. }
  45062. END_JUCE_NAMESPACE
  45063. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45064. /*** Start of inlined file: juce_TreeView.cpp ***/
  45065. BEGIN_JUCE_NAMESPACE
  45066. class TreeViewContentComponent : public Component,
  45067. public TooltipClient
  45068. {
  45069. public:
  45070. TreeViewContentComponent (TreeView& owner_)
  45071. : owner (owner_),
  45072. buttonUnderMouse (0),
  45073. isDragging (false)
  45074. {
  45075. }
  45076. ~TreeViewContentComponent()
  45077. {
  45078. }
  45079. void mouseDown (const MouseEvent& e)
  45080. {
  45081. updateButtonUnderMouse (e);
  45082. isDragging = false;
  45083. needSelectionOnMouseUp = false;
  45084. Rectangle<int> pos;
  45085. TreeViewItem* const item = findItemAt (e.y, pos);
  45086. if (item == 0)
  45087. return;
  45088. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45089. // as selection clicks)
  45090. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45091. {
  45092. if (e.x >= pos.getX() - owner.getIndentSize())
  45093. item->setOpen (! item->isOpen());
  45094. // (clicks to the left of an open/close button are ignored)
  45095. }
  45096. else
  45097. {
  45098. // mouse-down inside the body of the item..
  45099. if (! owner.isMultiSelectEnabled())
  45100. item->setSelected (true, true);
  45101. else if (item->isSelected())
  45102. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45103. else
  45104. selectBasedOnModifiers (item, e.mods);
  45105. if (e.x >= pos.getX())
  45106. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45107. }
  45108. }
  45109. void mouseUp (const MouseEvent& e)
  45110. {
  45111. updateButtonUnderMouse (e);
  45112. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45113. {
  45114. Rectangle<int> pos;
  45115. TreeViewItem* const item = findItemAt (e.y, pos);
  45116. if (item != 0)
  45117. selectBasedOnModifiers (item, e.mods);
  45118. }
  45119. }
  45120. void mouseDoubleClick (const MouseEvent& e)
  45121. {
  45122. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45123. {
  45124. Rectangle<int> pos;
  45125. TreeViewItem* const item = findItemAt (e.y, pos);
  45126. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45127. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45128. }
  45129. }
  45130. void mouseDrag (const MouseEvent& e)
  45131. {
  45132. if (isEnabled()
  45133. && ! (isDragging || e.mouseWasClicked()
  45134. || e.getDistanceFromDragStart() < 5
  45135. || e.mods.isPopupMenu()))
  45136. {
  45137. isDragging = true;
  45138. Rectangle<int> pos;
  45139. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45140. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45141. {
  45142. const String dragDescription (item->getDragSourceDescription());
  45143. if (dragDescription.isNotEmpty())
  45144. {
  45145. DragAndDropContainer* const dragContainer
  45146. = DragAndDropContainer::findParentDragContainerFor (this);
  45147. if (dragContainer != 0)
  45148. {
  45149. pos.setSize (pos.getWidth(), item->itemHeight);
  45150. Image dragImage (Component::createComponentSnapshot (pos, true));
  45151. dragImage.multiplyAllAlphas (0.6f);
  45152. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45153. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45154. }
  45155. else
  45156. {
  45157. // to be able to do a drag-and-drop operation, the treeview needs to
  45158. // be inside a component which is also a DragAndDropContainer.
  45159. jassertfalse;
  45160. }
  45161. }
  45162. }
  45163. }
  45164. }
  45165. void mouseMove (const MouseEvent& e)
  45166. {
  45167. updateButtonUnderMouse (e);
  45168. }
  45169. void mouseExit (const MouseEvent& e)
  45170. {
  45171. updateButtonUnderMouse (e);
  45172. }
  45173. void paint (Graphics& g)
  45174. {
  45175. if (owner.rootItem != 0)
  45176. {
  45177. owner.handleAsyncUpdate();
  45178. if (! owner.rootItemVisible)
  45179. g.setOrigin (0, -owner.rootItem->itemHeight);
  45180. owner.rootItem->paintRecursively (g, getWidth());
  45181. }
  45182. }
  45183. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45184. {
  45185. if (owner.rootItem != 0)
  45186. {
  45187. owner.handleAsyncUpdate();
  45188. if (! owner.rootItemVisible)
  45189. y += owner.rootItem->itemHeight;
  45190. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45191. if (ti != 0)
  45192. itemPosition = ti->getItemPosition (false);
  45193. return ti;
  45194. }
  45195. return 0;
  45196. }
  45197. void updateComponents()
  45198. {
  45199. const int visibleTop = -getY();
  45200. const int visibleBottom = visibleTop + getParentHeight();
  45201. {
  45202. for (int i = items.size(); --i >= 0;)
  45203. items.getUnchecked(i)->shouldKeep = false;
  45204. }
  45205. {
  45206. TreeViewItem* item = owner.rootItem;
  45207. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45208. while (item != 0 && y < visibleBottom)
  45209. {
  45210. y += item->itemHeight;
  45211. if (y >= visibleTop)
  45212. {
  45213. RowItem* const ri = findItem (item->uid);
  45214. if (ri != 0)
  45215. {
  45216. ri->shouldKeep = true;
  45217. }
  45218. else
  45219. {
  45220. Component* const comp = item->createItemComponent();
  45221. if (comp != 0)
  45222. {
  45223. items.add (new RowItem (item, comp, item->uid));
  45224. addAndMakeVisible (comp);
  45225. }
  45226. }
  45227. }
  45228. item = item->getNextVisibleItem (true);
  45229. }
  45230. }
  45231. for (int i = items.size(); --i >= 0;)
  45232. {
  45233. RowItem* const ri = items.getUnchecked(i);
  45234. bool keep = false;
  45235. if (isParentOf (ri->component))
  45236. {
  45237. if (ri->shouldKeep)
  45238. {
  45239. Rectangle<int> pos (ri->item->getItemPosition (false));
  45240. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45241. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45242. {
  45243. keep = true;
  45244. ri->component->setBounds (pos);
  45245. }
  45246. }
  45247. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45248. {
  45249. keep = true;
  45250. ri->component->setSize (0, 0);
  45251. }
  45252. }
  45253. if (! keep)
  45254. items.remove (i);
  45255. }
  45256. }
  45257. void updateButtonUnderMouse (const MouseEvent& e)
  45258. {
  45259. TreeViewItem* newItem = 0;
  45260. if (owner.openCloseButtonsVisible)
  45261. {
  45262. Rectangle<int> pos;
  45263. TreeViewItem* item = findItemAt (e.y, pos);
  45264. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45265. {
  45266. newItem = item;
  45267. if (! newItem->mightContainSubItems())
  45268. newItem = 0;
  45269. }
  45270. }
  45271. if (buttonUnderMouse != newItem)
  45272. {
  45273. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45274. {
  45275. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45276. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45277. }
  45278. buttonUnderMouse = newItem;
  45279. if (buttonUnderMouse != 0)
  45280. {
  45281. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45282. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45283. }
  45284. }
  45285. }
  45286. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45287. {
  45288. return item == buttonUnderMouse;
  45289. }
  45290. void resized()
  45291. {
  45292. owner.itemsChanged();
  45293. }
  45294. const String getTooltip()
  45295. {
  45296. Rectangle<int> pos;
  45297. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45298. if (item != 0)
  45299. return item->getTooltip();
  45300. return owner.getTooltip();
  45301. }
  45302. private:
  45303. TreeView& owner;
  45304. struct RowItem
  45305. {
  45306. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45307. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45308. {
  45309. }
  45310. ~RowItem()
  45311. {
  45312. component.deleteAndZero();
  45313. }
  45314. Component::SafePointer<Component> component;
  45315. TreeViewItem* item;
  45316. int uid;
  45317. bool shouldKeep;
  45318. };
  45319. OwnedArray <RowItem> items;
  45320. TreeViewItem* buttonUnderMouse;
  45321. bool isDragging, needSelectionOnMouseUp;
  45322. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45323. {
  45324. TreeViewItem* firstSelected = 0;
  45325. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45326. {
  45327. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45328. jassert (lastSelected != 0);
  45329. int rowStart = firstSelected->getRowNumberInTree();
  45330. int rowEnd = lastSelected->getRowNumberInTree();
  45331. if (rowStart > rowEnd)
  45332. swapVariables (rowStart, rowEnd);
  45333. int ourRow = item->getRowNumberInTree();
  45334. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45335. if (ourRow > otherEnd)
  45336. swapVariables (ourRow, otherEnd);
  45337. for (int i = ourRow; i <= otherEnd; ++i)
  45338. owner.getItemOnRow (i)->setSelected (true, false);
  45339. }
  45340. else
  45341. {
  45342. const bool cmd = modifiers.isCommandDown();
  45343. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45344. }
  45345. }
  45346. bool containsItem (TreeViewItem* const item) const throw()
  45347. {
  45348. for (int i = items.size(); --i >= 0;)
  45349. if (items.getUnchecked(i)->item == item)
  45350. return true;
  45351. return false;
  45352. }
  45353. RowItem* findItem (const int uid) const throw()
  45354. {
  45355. for (int i = items.size(); --i >= 0;)
  45356. {
  45357. RowItem* const ri = items.getUnchecked(i);
  45358. if (ri->uid == uid)
  45359. return ri;
  45360. }
  45361. return 0;
  45362. }
  45363. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45364. {
  45365. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45366. {
  45367. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45368. if (source->isDragging())
  45369. {
  45370. Component* const underMouse = source->getComponentUnderMouse();
  45371. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45372. return true;
  45373. }
  45374. }
  45375. return false;
  45376. }
  45377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45378. };
  45379. class TreeView::TreeViewport : public Viewport
  45380. {
  45381. public:
  45382. TreeViewport() throw() : lastX (-1) {}
  45383. ~TreeViewport() throw() {}
  45384. void updateComponents (const bool triggerResize = false)
  45385. {
  45386. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45387. if (tvc != 0)
  45388. {
  45389. if (triggerResize)
  45390. tvc->resized();
  45391. else
  45392. tvc->updateComponents();
  45393. }
  45394. repaint();
  45395. }
  45396. void visibleAreaChanged (int x, int, int, int)
  45397. {
  45398. const bool hasScrolledSideways = (x != lastX);
  45399. lastX = x;
  45400. updateComponents (hasScrolledSideways);
  45401. }
  45402. private:
  45403. int lastX;
  45404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45405. };
  45406. TreeView::TreeView (const String& componentName)
  45407. : Component (componentName),
  45408. rootItem (0),
  45409. indentSize (24),
  45410. defaultOpenness (false),
  45411. needsRecalculating (true),
  45412. rootItemVisible (true),
  45413. multiSelectEnabled (false),
  45414. openCloseButtonsVisible (true)
  45415. {
  45416. addAndMakeVisible (viewport = new TreeViewport());
  45417. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45418. viewport->setWantsKeyboardFocus (false);
  45419. setWantsKeyboardFocus (true);
  45420. }
  45421. TreeView::~TreeView()
  45422. {
  45423. if (rootItem != 0)
  45424. rootItem->setOwnerView (0);
  45425. }
  45426. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45427. {
  45428. if (rootItem != newRootItem)
  45429. {
  45430. if (newRootItem != 0)
  45431. {
  45432. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45433. if (newRootItem->ownerView != 0)
  45434. newRootItem->ownerView->setRootItem (0);
  45435. }
  45436. if (rootItem != 0)
  45437. rootItem->setOwnerView (0);
  45438. rootItem = newRootItem;
  45439. if (newRootItem != 0)
  45440. newRootItem->setOwnerView (this);
  45441. needsRecalculating = true;
  45442. handleAsyncUpdate();
  45443. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45444. {
  45445. rootItem->setOpen (false); // force a re-open
  45446. rootItem->setOpen (true);
  45447. }
  45448. }
  45449. }
  45450. void TreeView::deleteRootItem()
  45451. {
  45452. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45453. setRootItem (0);
  45454. }
  45455. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45456. {
  45457. rootItemVisible = shouldBeVisible;
  45458. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45459. {
  45460. rootItem->setOpen (false); // force a re-open
  45461. rootItem->setOpen (true);
  45462. }
  45463. itemsChanged();
  45464. }
  45465. void TreeView::colourChanged()
  45466. {
  45467. setOpaque (findColour (backgroundColourId).isOpaque());
  45468. repaint();
  45469. }
  45470. void TreeView::setIndentSize (const int newIndentSize)
  45471. {
  45472. if (indentSize != newIndentSize)
  45473. {
  45474. indentSize = newIndentSize;
  45475. resized();
  45476. }
  45477. }
  45478. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45479. {
  45480. if (defaultOpenness != isOpenByDefault)
  45481. {
  45482. defaultOpenness = isOpenByDefault;
  45483. itemsChanged();
  45484. }
  45485. }
  45486. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45487. {
  45488. multiSelectEnabled = canMultiSelect;
  45489. }
  45490. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45491. {
  45492. if (openCloseButtonsVisible != shouldBeVisible)
  45493. {
  45494. openCloseButtonsVisible = shouldBeVisible;
  45495. itemsChanged();
  45496. }
  45497. }
  45498. Viewport* TreeView::getViewport() const throw()
  45499. {
  45500. return viewport;
  45501. }
  45502. void TreeView::clearSelectedItems()
  45503. {
  45504. if (rootItem != 0)
  45505. rootItem->deselectAllRecursively();
  45506. }
  45507. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45508. {
  45509. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45510. }
  45511. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45512. {
  45513. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45514. }
  45515. int TreeView::getNumRowsInTree() const
  45516. {
  45517. if (rootItem != 0)
  45518. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45519. return 0;
  45520. }
  45521. TreeViewItem* TreeView::getItemOnRow (int index) const
  45522. {
  45523. if (! rootItemVisible)
  45524. ++index;
  45525. if (rootItem != 0 && index >= 0)
  45526. return rootItem->getItemOnRow (index);
  45527. return 0;
  45528. }
  45529. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45530. {
  45531. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45532. Rectangle<int> pos;
  45533. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45534. }
  45535. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45536. {
  45537. if (rootItem == 0)
  45538. return 0;
  45539. return rootItem->findItemFromIdentifierString (identifierString);
  45540. }
  45541. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45542. {
  45543. XmlElement* e = 0;
  45544. if (rootItem != 0)
  45545. {
  45546. e = rootItem->getOpennessState();
  45547. if (e != 0 && alsoIncludeScrollPosition)
  45548. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45549. }
  45550. return e;
  45551. }
  45552. void TreeView::restoreOpennessState (const XmlElement& newState)
  45553. {
  45554. if (rootItem != 0)
  45555. {
  45556. rootItem->restoreOpennessState (newState);
  45557. if (newState.hasAttribute ("scrollPos"))
  45558. viewport->setViewPosition (viewport->getViewPositionX(),
  45559. newState.getIntAttribute ("scrollPos"));
  45560. }
  45561. }
  45562. void TreeView::paint (Graphics& g)
  45563. {
  45564. g.fillAll (findColour (backgroundColourId));
  45565. }
  45566. void TreeView::resized()
  45567. {
  45568. viewport->setBounds (getLocalBounds());
  45569. itemsChanged();
  45570. handleAsyncUpdate();
  45571. }
  45572. void TreeView::enablementChanged()
  45573. {
  45574. repaint();
  45575. }
  45576. void TreeView::moveSelectedRow (int delta)
  45577. {
  45578. if (delta == 0)
  45579. return;
  45580. int rowSelected = 0;
  45581. TreeViewItem* const firstSelected = getSelectedItem (0);
  45582. if (firstSelected != 0)
  45583. rowSelected = firstSelected->getRowNumberInTree();
  45584. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45585. for (;;)
  45586. {
  45587. TreeViewItem* item = getItemOnRow (rowSelected);
  45588. if (item != 0)
  45589. {
  45590. if (! item->canBeSelected())
  45591. {
  45592. // if the row we want to highlight doesn't allow it, try skipping
  45593. // to the next item..
  45594. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45595. rowSelected + (delta < 0 ? -1 : 1));
  45596. if (rowSelected != nextRowToTry)
  45597. {
  45598. rowSelected = nextRowToTry;
  45599. continue;
  45600. }
  45601. else
  45602. {
  45603. break;
  45604. }
  45605. }
  45606. item->setSelected (true, true);
  45607. scrollToKeepItemVisible (item);
  45608. }
  45609. break;
  45610. }
  45611. }
  45612. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45613. {
  45614. if (item != 0 && item->ownerView == this)
  45615. {
  45616. handleAsyncUpdate();
  45617. item = item->getDeepestOpenParentItem();
  45618. int y = item->y;
  45619. int viewTop = viewport->getViewPositionY();
  45620. if (y < viewTop)
  45621. {
  45622. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45623. }
  45624. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45625. {
  45626. viewport->setViewPosition (viewport->getViewPositionX(),
  45627. (y + item->itemHeight) - viewport->getViewHeight());
  45628. }
  45629. }
  45630. }
  45631. bool TreeView::keyPressed (const KeyPress& key)
  45632. {
  45633. if (key.isKeyCode (KeyPress::upKey))
  45634. {
  45635. moveSelectedRow (-1);
  45636. }
  45637. else if (key.isKeyCode (KeyPress::downKey))
  45638. {
  45639. moveSelectedRow (1);
  45640. }
  45641. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45642. {
  45643. if (rootItem != 0)
  45644. {
  45645. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45646. if (key.isKeyCode (KeyPress::pageUpKey))
  45647. rowsOnScreen = -rowsOnScreen;
  45648. moveSelectedRow (rowsOnScreen);
  45649. }
  45650. }
  45651. else if (key.isKeyCode (KeyPress::homeKey))
  45652. {
  45653. moveSelectedRow (-0x3fffffff);
  45654. }
  45655. else if (key.isKeyCode (KeyPress::endKey))
  45656. {
  45657. moveSelectedRow (0x3fffffff);
  45658. }
  45659. else if (key.isKeyCode (KeyPress::returnKey))
  45660. {
  45661. TreeViewItem* const firstSelected = getSelectedItem (0);
  45662. if (firstSelected != 0)
  45663. firstSelected->setOpen (! firstSelected->isOpen());
  45664. }
  45665. else if (key.isKeyCode (KeyPress::leftKey))
  45666. {
  45667. TreeViewItem* const firstSelected = getSelectedItem (0);
  45668. if (firstSelected != 0)
  45669. {
  45670. if (firstSelected->isOpen())
  45671. {
  45672. firstSelected->setOpen (false);
  45673. }
  45674. else
  45675. {
  45676. TreeViewItem* parent = firstSelected->parentItem;
  45677. if ((! rootItemVisible) && parent == rootItem)
  45678. parent = 0;
  45679. if (parent != 0)
  45680. {
  45681. parent->setSelected (true, true);
  45682. scrollToKeepItemVisible (parent);
  45683. }
  45684. }
  45685. }
  45686. }
  45687. else if (key.isKeyCode (KeyPress::rightKey))
  45688. {
  45689. TreeViewItem* const firstSelected = getSelectedItem (0);
  45690. if (firstSelected != 0)
  45691. {
  45692. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45693. moveSelectedRow (1);
  45694. else
  45695. firstSelected->setOpen (true);
  45696. }
  45697. }
  45698. else
  45699. {
  45700. return false;
  45701. }
  45702. return true;
  45703. }
  45704. void TreeView::itemsChanged() throw()
  45705. {
  45706. needsRecalculating = true;
  45707. repaint();
  45708. triggerAsyncUpdate();
  45709. }
  45710. void TreeView::handleAsyncUpdate()
  45711. {
  45712. if (needsRecalculating)
  45713. {
  45714. needsRecalculating = false;
  45715. const ScopedLock sl (nodeAlterationLock);
  45716. if (rootItem != 0)
  45717. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45718. viewport->updateComponents();
  45719. if (rootItem != 0)
  45720. {
  45721. viewport->getViewedComponent()
  45722. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45723. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45724. }
  45725. else
  45726. {
  45727. viewport->getViewedComponent()->setSize (0, 0);
  45728. }
  45729. }
  45730. }
  45731. class TreeView::InsertPointHighlight : public Component
  45732. {
  45733. public:
  45734. InsertPointHighlight()
  45735. : lastItem (0)
  45736. {
  45737. setSize (100, 12);
  45738. setAlwaysOnTop (true);
  45739. setInterceptsMouseClicks (false, false);
  45740. }
  45741. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45742. {
  45743. lastItem = item;
  45744. lastIndex = insertIndex;
  45745. const int offset = getHeight() / 2;
  45746. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45747. }
  45748. void paint (Graphics& g)
  45749. {
  45750. Path p;
  45751. const float h = (float) getHeight();
  45752. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45753. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45754. p.lineTo ((float) getWidth(), h / 2.0f);
  45755. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45756. g.strokePath (p, PathStrokeType (2.0f));
  45757. }
  45758. TreeViewItem* lastItem;
  45759. int lastIndex;
  45760. private:
  45761. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45762. };
  45763. class TreeView::TargetGroupHighlight : public Component
  45764. {
  45765. public:
  45766. TargetGroupHighlight()
  45767. {
  45768. setAlwaysOnTop (true);
  45769. setInterceptsMouseClicks (false, false);
  45770. }
  45771. void setTargetPosition (TreeViewItem* const item) throw()
  45772. {
  45773. Rectangle<int> r (item->getItemPosition (true));
  45774. r.setHeight (item->getItemHeight());
  45775. setBounds (r);
  45776. }
  45777. void paint (Graphics& g)
  45778. {
  45779. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45780. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45781. }
  45782. private:
  45783. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45784. };
  45785. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45786. {
  45787. beginDragAutoRepeat (100);
  45788. if (dragInsertPointHighlight == 0)
  45789. {
  45790. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45791. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45792. }
  45793. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45794. dragTargetGroupHighlight->setTargetPosition (item);
  45795. }
  45796. void TreeView::hideDragHighlight() throw()
  45797. {
  45798. dragInsertPointHighlight = 0;
  45799. dragTargetGroupHighlight = 0;
  45800. }
  45801. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45802. const StringArray& files, const String& sourceDescription,
  45803. Component* sourceComponent) const throw()
  45804. {
  45805. insertIndex = 0;
  45806. TreeViewItem* item = getItemAt (y);
  45807. if (item == 0)
  45808. return 0;
  45809. Rectangle<int> itemPos (item->getItemPosition (true));
  45810. insertIndex = item->getIndexInParent();
  45811. const int oldY = y;
  45812. y = itemPos.getY();
  45813. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45814. {
  45815. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45816. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45817. {
  45818. // Check if we're trying to drag into an empty group item..
  45819. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45820. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45821. {
  45822. insertIndex = 0;
  45823. x = itemPos.getX() + getIndentSize();
  45824. y = itemPos.getBottom();
  45825. return item;
  45826. }
  45827. }
  45828. }
  45829. if (oldY > itemPos.getCentreY())
  45830. {
  45831. y += item->getItemHeight();
  45832. while (item->isLastOfSiblings() && item->parentItem != 0
  45833. && item->parentItem->parentItem != 0)
  45834. {
  45835. if (x > itemPos.getX())
  45836. break;
  45837. item = item->parentItem;
  45838. itemPos = item->getItemPosition (true);
  45839. insertIndex = item->getIndexInParent();
  45840. }
  45841. ++insertIndex;
  45842. }
  45843. x = itemPos.getX();
  45844. return item->parentItem;
  45845. }
  45846. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45847. {
  45848. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45849. int insertIndex;
  45850. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45851. if (item != 0)
  45852. {
  45853. if (scrolled || dragInsertPointHighlight == 0
  45854. || dragInsertPointHighlight->lastItem != item
  45855. || dragInsertPointHighlight->lastIndex != insertIndex)
  45856. {
  45857. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45858. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45859. showDragHighlight (item, insertIndex, x, y);
  45860. else
  45861. hideDragHighlight();
  45862. }
  45863. }
  45864. else
  45865. {
  45866. hideDragHighlight();
  45867. }
  45868. }
  45869. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45870. {
  45871. hideDragHighlight();
  45872. int insertIndex;
  45873. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45874. if (item != 0)
  45875. {
  45876. if (files.size() > 0)
  45877. {
  45878. if (item->isInterestedInFileDrag (files))
  45879. item->filesDropped (files, insertIndex);
  45880. }
  45881. else
  45882. {
  45883. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45884. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45885. }
  45886. }
  45887. }
  45888. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45889. {
  45890. return true;
  45891. }
  45892. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45893. {
  45894. fileDragMove (files, x, y);
  45895. }
  45896. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45897. {
  45898. handleDrag (files, String::empty, 0, x, y);
  45899. }
  45900. void TreeView::fileDragExit (const StringArray&)
  45901. {
  45902. hideDragHighlight();
  45903. }
  45904. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45905. {
  45906. handleDrop (files, String::empty, 0, x, y);
  45907. }
  45908. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45909. {
  45910. return true;
  45911. }
  45912. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45913. {
  45914. itemDragMove (sourceDescription, sourceComponent, x, y);
  45915. }
  45916. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45917. {
  45918. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45919. }
  45920. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45921. {
  45922. hideDragHighlight();
  45923. }
  45924. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45925. {
  45926. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45927. }
  45928. enum TreeViewOpenness
  45929. {
  45930. opennessDefault = 0,
  45931. opennessClosed = 1,
  45932. opennessOpen = 2
  45933. };
  45934. TreeViewItem::TreeViewItem()
  45935. : ownerView (0),
  45936. parentItem (0),
  45937. y (0),
  45938. itemHeight (0),
  45939. totalHeight (0),
  45940. selected (false),
  45941. redrawNeeded (true),
  45942. drawLinesInside (true),
  45943. drawsInLeftMargin (false),
  45944. openness (opennessDefault)
  45945. {
  45946. static int nextUID = 0;
  45947. uid = nextUID++;
  45948. }
  45949. TreeViewItem::~TreeViewItem()
  45950. {
  45951. }
  45952. const String TreeViewItem::getUniqueName() const
  45953. {
  45954. return String::empty;
  45955. }
  45956. void TreeViewItem::itemOpennessChanged (bool)
  45957. {
  45958. }
  45959. int TreeViewItem::getNumSubItems() const throw()
  45960. {
  45961. return subItems.size();
  45962. }
  45963. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45964. {
  45965. return subItems [index];
  45966. }
  45967. void TreeViewItem::clearSubItems()
  45968. {
  45969. if (subItems.size() > 0)
  45970. {
  45971. if (ownerView != 0)
  45972. {
  45973. const ScopedLock sl (ownerView->nodeAlterationLock);
  45974. subItems.clear();
  45975. treeHasChanged();
  45976. }
  45977. else
  45978. {
  45979. subItems.clear();
  45980. }
  45981. }
  45982. }
  45983. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45984. {
  45985. if (newItem != 0)
  45986. {
  45987. newItem->parentItem = this;
  45988. newItem->setOwnerView (ownerView);
  45989. newItem->y = 0;
  45990. newItem->itemHeight = newItem->getItemHeight();
  45991. newItem->totalHeight = 0;
  45992. newItem->itemWidth = newItem->getItemWidth();
  45993. newItem->totalWidth = 0;
  45994. if (ownerView != 0)
  45995. {
  45996. const ScopedLock sl (ownerView->nodeAlterationLock);
  45997. subItems.insert (insertPosition, newItem);
  45998. treeHasChanged();
  45999. if (newItem->isOpen())
  46000. newItem->itemOpennessChanged (true);
  46001. }
  46002. else
  46003. {
  46004. subItems.insert (insertPosition, newItem);
  46005. if (newItem->isOpen())
  46006. newItem->itemOpennessChanged (true);
  46007. }
  46008. }
  46009. }
  46010. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46011. {
  46012. if (ownerView != 0)
  46013. {
  46014. const ScopedLock sl (ownerView->nodeAlterationLock);
  46015. if (isPositiveAndBelow (index, subItems.size()))
  46016. {
  46017. subItems.remove (index, deleteItem);
  46018. treeHasChanged();
  46019. }
  46020. }
  46021. else
  46022. {
  46023. subItems.remove (index, deleteItem);
  46024. }
  46025. }
  46026. bool TreeViewItem::isOpen() const throw()
  46027. {
  46028. if (openness == opennessDefault)
  46029. return ownerView != 0 && ownerView->defaultOpenness;
  46030. else
  46031. return openness == opennessOpen;
  46032. }
  46033. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46034. {
  46035. if (isOpen() != shouldBeOpen)
  46036. {
  46037. openness = shouldBeOpen ? opennessOpen
  46038. : opennessClosed;
  46039. treeHasChanged();
  46040. itemOpennessChanged (isOpen());
  46041. }
  46042. }
  46043. bool TreeViewItem::isSelected() const throw()
  46044. {
  46045. return selected;
  46046. }
  46047. void TreeViewItem::deselectAllRecursively()
  46048. {
  46049. setSelected (false, false);
  46050. for (int i = 0; i < subItems.size(); ++i)
  46051. subItems.getUnchecked(i)->deselectAllRecursively();
  46052. }
  46053. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46054. const bool deselectOtherItemsFirst)
  46055. {
  46056. if (shouldBeSelected && ! canBeSelected())
  46057. return;
  46058. if (deselectOtherItemsFirst)
  46059. getTopLevelItem()->deselectAllRecursively();
  46060. if (shouldBeSelected != selected)
  46061. {
  46062. selected = shouldBeSelected;
  46063. if (ownerView != 0)
  46064. ownerView->repaint();
  46065. itemSelectionChanged (shouldBeSelected);
  46066. }
  46067. }
  46068. void TreeViewItem::paintItem (Graphics&, int, int)
  46069. {
  46070. }
  46071. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46072. {
  46073. ownerView->getLookAndFeel()
  46074. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46075. }
  46076. void TreeViewItem::itemClicked (const MouseEvent&)
  46077. {
  46078. }
  46079. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46080. {
  46081. if (mightContainSubItems())
  46082. setOpen (! isOpen());
  46083. }
  46084. void TreeViewItem::itemSelectionChanged (bool)
  46085. {
  46086. }
  46087. const String TreeViewItem::getTooltip()
  46088. {
  46089. return String::empty;
  46090. }
  46091. const String TreeViewItem::getDragSourceDescription()
  46092. {
  46093. return String::empty;
  46094. }
  46095. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46096. {
  46097. return false;
  46098. }
  46099. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46100. {
  46101. }
  46102. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46103. {
  46104. return false;
  46105. }
  46106. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46107. {
  46108. }
  46109. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46110. {
  46111. const int indentX = getIndentX();
  46112. int width = itemWidth;
  46113. if (ownerView != 0 && width < 0)
  46114. width = ownerView->viewport->getViewWidth() - indentX;
  46115. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46116. if (relativeToTreeViewTopLeft)
  46117. r -= ownerView->viewport->getViewPosition();
  46118. return r;
  46119. }
  46120. void TreeViewItem::treeHasChanged() const throw()
  46121. {
  46122. if (ownerView != 0)
  46123. ownerView->itemsChanged();
  46124. }
  46125. void TreeViewItem::repaintItem() const
  46126. {
  46127. if (ownerView != 0 && areAllParentsOpen())
  46128. {
  46129. Rectangle<int> r (getItemPosition (true));
  46130. r.setLeft (0);
  46131. ownerView->viewport->repaint (r);
  46132. }
  46133. }
  46134. bool TreeViewItem::areAllParentsOpen() const throw()
  46135. {
  46136. return parentItem == 0
  46137. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46138. }
  46139. void TreeViewItem::updatePositions (int newY)
  46140. {
  46141. y = newY;
  46142. itemHeight = getItemHeight();
  46143. totalHeight = itemHeight;
  46144. itemWidth = getItemWidth();
  46145. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46146. if (isOpen())
  46147. {
  46148. newY += totalHeight;
  46149. for (int i = 0; i < subItems.size(); ++i)
  46150. {
  46151. TreeViewItem* const ti = subItems.getUnchecked(i);
  46152. ti->updatePositions (newY);
  46153. newY += ti->totalHeight;
  46154. totalHeight += ti->totalHeight;
  46155. totalWidth = jmax (totalWidth, ti->totalWidth);
  46156. }
  46157. }
  46158. }
  46159. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46160. {
  46161. TreeViewItem* result = this;
  46162. TreeViewItem* item = this;
  46163. while (item->parentItem != 0)
  46164. {
  46165. item = item->parentItem;
  46166. if (! item->isOpen())
  46167. result = item;
  46168. }
  46169. return result;
  46170. }
  46171. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46172. {
  46173. ownerView = newOwner;
  46174. for (int i = subItems.size(); --i >= 0;)
  46175. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46176. }
  46177. int TreeViewItem::getIndentX() const throw()
  46178. {
  46179. const int indentWidth = ownerView->getIndentSize();
  46180. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46181. if (! ownerView->openCloseButtonsVisible)
  46182. x -= indentWidth;
  46183. TreeViewItem* p = parentItem;
  46184. while (p != 0)
  46185. {
  46186. x += indentWidth;
  46187. p = p->parentItem;
  46188. }
  46189. return x;
  46190. }
  46191. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46192. {
  46193. drawsInLeftMargin = canDrawInLeftMargin;
  46194. }
  46195. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46196. {
  46197. jassert (ownerView != 0);
  46198. if (ownerView == 0)
  46199. return;
  46200. const int indent = getIndentX();
  46201. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46202. {
  46203. Graphics::ScopedSaveState ss (g);
  46204. g.setOrigin (indent, 0);
  46205. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46206. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46207. paintItem (g, itemW, itemHeight);
  46208. }
  46209. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46210. const float halfH = itemHeight * 0.5f;
  46211. int depth = 0;
  46212. TreeViewItem* p = parentItem;
  46213. while (p != 0)
  46214. {
  46215. ++depth;
  46216. p = p->parentItem;
  46217. }
  46218. if (! ownerView->rootItemVisible)
  46219. --depth;
  46220. const int indentWidth = ownerView->getIndentSize();
  46221. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46222. {
  46223. float x = (depth + 0.5f) * indentWidth;
  46224. if (depth >= 0)
  46225. {
  46226. if (parentItem != 0 && parentItem->drawLinesInside)
  46227. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46228. if ((parentItem != 0 && parentItem->drawLinesInside)
  46229. || (parentItem == 0 && drawLinesInside))
  46230. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46231. }
  46232. p = parentItem;
  46233. int d = depth;
  46234. while (p != 0 && --d >= 0)
  46235. {
  46236. x -= (float) indentWidth;
  46237. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46238. && ! p->isLastOfSiblings())
  46239. {
  46240. g.drawLine (x, 0, x, (float) itemHeight);
  46241. }
  46242. p = p->parentItem;
  46243. }
  46244. if (mightContainSubItems())
  46245. {
  46246. Graphics::ScopedSaveState ss (g);
  46247. g.setOrigin (depth * indentWidth, 0);
  46248. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46249. paintOpenCloseButton (g, indentWidth, itemHeight,
  46250. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46251. ->isMouseOverButton (this));
  46252. }
  46253. }
  46254. if (isOpen())
  46255. {
  46256. const Rectangle<int> clip (g.getClipBounds());
  46257. for (int i = 0; i < subItems.size(); ++i)
  46258. {
  46259. TreeViewItem* const ti = subItems.getUnchecked(i);
  46260. const int relY = ti->y - y;
  46261. if (relY >= clip.getBottom())
  46262. break;
  46263. if (relY + ti->totalHeight >= clip.getY())
  46264. {
  46265. Graphics::ScopedSaveState ss (g);
  46266. g.setOrigin (0, relY);
  46267. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46268. ti->paintRecursively (g, width);
  46269. }
  46270. }
  46271. }
  46272. }
  46273. bool TreeViewItem::isLastOfSiblings() const throw()
  46274. {
  46275. return parentItem == 0
  46276. || parentItem->subItems.getLast() == this;
  46277. }
  46278. int TreeViewItem::getIndexInParent() const throw()
  46279. {
  46280. return parentItem == 0 ? 0
  46281. : parentItem->subItems.indexOf (this);
  46282. }
  46283. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46284. {
  46285. return parentItem == 0 ? this
  46286. : parentItem->getTopLevelItem();
  46287. }
  46288. int TreeViewItem::getNumRows() const throw()
  46289. {
  46290. int num = 1;
  46291. if (isOpen())
  46292. {
  46293. for (int i = subItems.size(); --i >= 0;)
  46294. num += subItems.getUnchecked(i)->getNumRows();
  46295. }
  46296. return num;
  46297. }
  46298. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46299. {
  46300. if (index == 0)
  46301. return this;
  46302. if (index > 0 && isOpen())
  46303. {
  46304. --index;
  46305. for (int i = 0; i < subItems.size(); ++i)
  46306. {
  46307. TreeViewItem* const item = subItems.getUnchecked(i);
  46308. if (index == 0)
  46309. return item;
  46310. const int numRows = item->getNumRows();
  46311. if (numRows > index)
  46312. return item->getItemOnRow (index);
  46313. index -= numRows;
  46314. }
  46315. }
  46316. return 0;
  46317. }
  46318. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46319. {
  46320. if (isPositiveAndBelow (targetY, totalHeight))
  46321. {
  46322. const int h = itemHeight;
  46323. if (targetY < h)
  46324. return this;
  46325. if (isOpen())
  46326. {
  46327. targetY -= h;
  46328. for (int i = 0; i < subItems.size(); ++i)
  46329. {
  46330. TreeViewItem* const ti = subItems.getUnchecked(i);
  46331. if (targetY < ti->totalHeight)
  46332. return ti->findItemRecursively (targetY);
  46333. targetY -= ti->totalHeight;
  46334. }
  46335. }
  46336. }
  46337. return 0;
  46338. }
  46339. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46340. {
  46341. int total = isSelected() ? 1 : 0;
  46342. if (depth != 0)
  46343. for (int i = subItems.size(); --i >= 0;)
  46344. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46345. return total;
  46346. }
  46347. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46348. {
  46349. if (isSelected())
  46350. {
  46351. if (index == 0)
  46352. return this;
  46353. --index;
  46354. }
  46355. if (index >= 0)
  46356. {
  46357. for (int i = 0; i < subItems.size(); ++i)
  46358. {
  46359. TreeViewItem* const item = subItems.getUnchecked(i);
  46360. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46361. if (found != 0)
  46362. return found;
  46363. index -= item->countSelectedItemsRecursively (-1);
  46364. }
  46365. }
  46366. return 0;
  46367. }
  46368. int TreeViewItem::getRowNumberInTree() const throw()
  46369. {
  46370. if (parentItem != 0 && ownerView != 0)
  46371. {
  46372. int n = 1 + parentItem->getRowNumberInTree();
  46373. int ourIndex = parentItem->subItems.indexOf (this);
  46374. jassert (ourIndex >= 0);
  46375. while (--ourIndex >= 0)
  46376. n += parentItem->subItems [ourIndex]->getNumRows();
  46377. if (parentItem->parentItem == 0
  46378. && ! ownerView->rootItemVisible)
  46379. --n;
  46380. return n;
  46381. }
  46382. else
  46383. {
  46384. return 0;
  46385. }
  46386. }
  46387. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46388. {
  46389. drawLinesInside = drawLines;
  46390. }
  46391. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46392. {
  46393. if (recurse && isOpen() && subItems.size() > 0)
  46394. return subItems [0];
  46395. if (parentItem != 0)
  46396. {
  46397. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46398. if (nextIndex >= parentItem->subItems.size())
  46399. return parentItem->getNextVisibleItem (false);
  46400. return parentItem->subItems [nextIndex];
  46401. }
  46402. return 0;
  46403. }
  46404. const String TreeViewItem::getItemIdentifierString() const
  46405. {
  46406. String s;
  46407. if (parentItem != 0)
  46408. s = parentItem->getItemIdentifierString();
  46409. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46410. }
  46411. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46412. {
  46413. const String thisId (getUniqueName());
  46414. if (thisId == identifierString)
  46415. return this;
  46416. if (identifierString.startsWith (thisId + "/"))
  46417. {
  46418. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46419. bool wasOpen = isOpen();
  46420. setOpen (true);
  46421. for (int i = subItems.size(); --i >= 0;)
  46422. {
  46423. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46424. if (item != 0)
  46425. return item;
  46426. }
  46427. setOpen (wasOpen);
  46428. }
  46429. return 0;
  46430. }
  46431. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46432. {
  46433. if (e.hasTagName ("CLOSED"))
  46434. {
  46435. setOpen (false);
  46436. }
  46437. else if (e.hasTagName ("OPEN"))
  46438. {
  46439. setOpen (true);
  46440. forEachXmlChildElement (e, n)
  46441. {
  46442. const String id (n->getStringAttribute ("id"));
  46443. for (int i = 0; i < subItems.size(); ++i)
  46444. {
  46445. TreeViewItem* const ti = subItems.getUnchecked(i);
  46446. if (ti->getUniqueName() == id)
  46447. {
  46448. ti->restoreOpennessState (*n);
  46449. break;
  46450. }
  46451. }
  46452. }
  46453. }
  46454. }
  46455. XmlElement* TreeViewItem::getOpennessState() const throw()
  46456. {
  46457. const String name (getUniqueName());
  46458. if (name.isNotEmpty())
  46459. {
  46460. XmlElement* e;
  46461. if (isOpen())
  46462. {
  46463. e = new XmlElement ("OPEN");
  46464. for (int i = 0; i < subItems.size(); ++i)
  46465. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46466. }
  46467. else
  46468. {
  46469. e = new XmlElement ("CLOSED");
  46470. }
  46471. e->setAttribute ("id", name);
  46472. return e;
  46473. }
  46474. else
  46475. {
  46476. // trying to save the openness for an element that has no name - this won't
  46477. // work because it needs the names to identify what to open.
  46478. jassertfalse;
  46479. }
  46480. return 0;
  46481. }
  46482. END_JUCE_NAMESPACE
  46483. /*** End of inlined file: juce_TreeView.cpp ***/
  46484. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46485. BEGIN_JUCE_NAMESPACE
  46486. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46487. : fileList (listToShow)
  46488. {
  46489. }
  46490. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46491. {
  46492. }
  46493. FileBrowserListener::~FileBrowserListener()
  46494. {
  46495. }
  46496. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46497. {
  46498. listeners.add (listener);
  46499. }
  46500. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46501. {
  46502. listeners.remove (listener);
  46503. }
  46504. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46505. {
  46506. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46507. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46508. }
  46509. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46510. {
  46511. if (fileList.getDirectory().exists())
  46512. {
  46513. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46514. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46515. }
  46516. }
  46517. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46518. {
  46519. if (fileList.getDirectory().exists())
  46520. {
  46521. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46522. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46523. }
  46524. }
  46525. END_JUCE_NAMESPACE
  46526. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46527. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46528. BEGIN_JUCE_NAMESPACE
  46529. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46530. TimeSliceThread& thread_)
  46531. : fileFilter (fileFilter_),
  46532. thread (thread_),
  46533. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46534. fileFindHandle (0),
  46535. shouldStop (true)
  46536. {
  46537. }
  46538. DirectoryContentsList::~DirectoryContentsList()
  46539. {
  46540. clear();
  46541. }
  46542. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46543. {
  46544. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46545. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46546. }
  46547. bool DirectoryContentsList::ignoresHiddenFiles() const
  46548. {
  46549. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46550. }
  46551. const File& DirectoryContentsList::getDirectory() const
  46552. {
  46553. return root;
  46554. }
  46555. void DirectoryContentsList::setDirectory (const File& directory,
  46556. const bool includeDirectories,
  46557. const bool includeFiles)
  46558. {
  46559. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46560. if (directory != root)
  46561. {
  46562. clear();
  46563. root = directory;
  46564. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46565. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46566. }
  46567. int newFlags = fileTypeFlags;
  46568. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46569. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46570. setTypeFlags (newFlags);
  46571. }
  46572. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46573. {
  46574. if (fileTypeFlags != newFlags)
  46575. {
  46576. fileTypeFlags = newFlags;
  46577. refresh();
  46578. }
  46579. }
  46580. void DirectoryContentsList::clear()
  46581. {
  46582. shouldStop = true;
  46583. thread.removeTimeSliceClient (this);
  46584. fileFindHandle = 0;
  46585. if (files.size() > 0)
  46586. {
  46587. files.clear();
  46588. changed();
  46589. }
  46590. }
  46591. void DirectoryContentsList::refresh()
  46592. {
  46593. clear();
  46594. if (root.isDirectory())
  46595. {
  46596. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46597. shouldStop = false;
  46598. thread.addTimeSliceClient (this);
  46599. }
  46600. }
  46601. int DirectoryContentsList::getNumFiles() const
  46602. {
  46603. return files.size();
  46604. }
  46605. bool DirectoryContentsList::getFileInfo (const int index,
  46606. FileInfo& result) const
  46607. {
  46608. const ScopedLock sl (fileListLock);
  46609. const FileInfo* const info = files [index];
  46610. if (info != 0)
  46611. {
  46612. result = *info;
  46613. return true;
  46614. }
  46615. return false;
  46616. }
  46617. const File DirectoryContentsList::getFile (const int index) const
  46618. {
  46619. const ScopedLock sl (fileListLock);
  46620. const FileInfo* const info = files [index];
  46621. if (info != 0)
  46622. return root.getChildFile (info->filename);
  46623. return File::nonexistent;
  46624. }
  46625. bool DirectoryContentsList::isStillLoading() const
  46626. {
  46627. return fileFindHandle != 0;
  46628. }
  46629. void DirectoryContentsList::changed()
  46630. {
  46631. sendChangeMessage();
  46632. }
  46633. bool DirectoryContentsList::useTimeSlice()
  46634. {
  46635. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46636. bool hasChanged = false;
  46637. for (int i = 100; --i >= 0;)
  46638. {
  46639. if (! checkNextFile (hasChanged))
  46640. {
  46641. if (hasChanged)
  46642. changed();
  46643. return false;
  46644. }
  46645. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46646. break;
  46647. }
  46648. if (hasChanged)
  46649. changed();
  46650. return true;
  46651. }
  46652. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46653. {
  46654. if (fileFindHandle != 0)
  46655. {
  46656. bool fileFoundIsDir, isHidden, isReadOnly;
  46657. int64 fileSize;
  46658. Time modTime, creationTime;
  46659. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46660. &modTime, &creationTime, &isReadOnly))
  46661. {
  46662. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46663. fileSize, modTime, creationTime, isReadOnly))
  46664. {
  46665. hasChanged = true;
  46666. }
  46667. return true;
  46668. }
  46669. else
  46670. {
  46671. fileFindHandle = 0;
  46672. }
  46673. }
  46674. return false;
  46675. }
  46676. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46677. const DirectoryContentsList::FileInfo* const second)
  46678. {
  46679. #if JUCE_WINDOWS
  46680. if (first->isDirectory != second->isDirectory)
  46681. return first->isDirectory ? -1 : 1;
  46682. #endif
  46683. return first->filename.compareIgnoreCase (second->filename);
  46684. }
  46685. bool DirectoryContentsList::addFile (const File& file,
  46686. const bool isDir,
  46687. const int64 fileSize,
  46688. const Time& modTime,
  46689. const Time& creationTime,
  46690. const bool isReadOnly)
  46691. {
  46692. if (fileFilter == 0
  46693. || ((! isDir) && fileFilter->isFileSuitable (file))
  46694. || (isDir && fileFilter->isDirectorySuitable (file)))
  46695. {
  46696. ScopedPointer <FileInfo> info (new FileInfo());
  46697. info->filename = file.getFileName();
  46698. info->fileSize = fileSize;
  46699. info->modificationTime = modTime;
  46700. info->creationTime = creationTime;
  46701. info->isDirectory = isDir;
  46702. info->isReadOnly = isReadOnly;
  46703. const ScopedLock sl (fileListLock);
  46704. for (int i = files.size(); --i >= 0;)
  46705. if (files.getUnchecked(i)->filename == info->filename)
  46706. return false;
  46707. files.addSorted (*this, info.release());
  46708. return true;
  46709. }
  46710. return false;
  46711. }
  46712. END_JUCE_NAMESPACE
  46713. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46714. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46715. BEGIN_JUCE_NAMESPACE
  46716. FileBrowserComponent::FileBrowserComponent (int flags_,
  46717. const File& initialFileOrDirectory,
  46718. const FileFilter* fileFilter_,
  46719. FilePreviewComponent* previewComp_)
  46720. : FileFilter (String::empty),
  46721. fileFilter (fileFilter_),
  46722. flags (flags_),
  46723. previewComp (previewComp_),
  46724. currentPathBox ("path"),
  46725. fileLabel ("f", TRANS ("file:")),
  46726. thread ("Juce FileBrowser")
  46727. {
  46728. // You need to specify one or other of the open/save flags..
  46729. jassert ((flags & (saveMode | openMode)) != 0);
  46730. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46731. // You need to specify at least one of these flags..
  46732. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46733. String filename;
  46734. if (initialFileOrDirectory == File::nonexistent)
  46735. {
  46736. currentRoot = File::getCurrentWorkingDirectory();
  46737. }
  46738. else if (initialFileOrDirectory.isDirectory())
  46739. {
  46740. currentRoot = initialFileOrDirectory;
  46741. }
  46742. else
  46743. {
  46744. chosenFiles.add (initialFileOrDirectory);
  46745. currentRoot = initialFileOrDirectory.getParentDirectory();
  46746. filename = initialFileOrDirectory.getFileName();
  46747. }
  46748. fileList = new DirectoryContentsList (this, thread);
  46749. if ((flags & useTreeView) != 0)
  46750. {
  46751. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46752. fileListComponent = tree;
  46753. if ((flags & canSelectMultipleItems) != 0)
  46754. tree->setMultiSelectEnabled (true);
  46755. addAndMakeVisible (tree);
  46756. }
  46757. else
  46758. {
  46759. FileListComponent* const list = new FileListComponent (*fileList);
  46760. fileListComponent = list;
  46761. list->setOutlineThickness (1);
  46762. if ((flags & canSelectMultipleItems) != 0)
  46763. list->setMultipleSelectionEnabled (true);
  46764. addAndMakeVisible (list);
  46765. }
  46766. fileListComponent->addListener (this);
  46767. addAndMakeVisible (&currentPathBox);
  46768. currentPathBox.setEditableText (true);
  46769. StringArray rootNames, rootPaths;
  46770. const BigInteger separators (getRoots (rootNames, rootPaths));
  46771. for (int i = 0; i < rootNames.size(); ++i)
  46772. {
  46773. if (separators [i])
  46774. currentPathBox.addSeparator();
  46775. currentPathBox.addItem (rootNames[i], i + 1);
  46776. }
  46777. currentPathBox.addSeparator();
  46778. currentPathBox.addListener (this);
  46779. addAndMakeVisible (&filenameBox);
  46780. filenameBox.setMultiLine (false);
  46781. filenameBox.setSelectAllWhenFocused (true);
  46782. filenameBox.setText (filename, false);
  46783. filenameBox.addListener (this);
  46784. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46785. addAndMakeVisible (&fileLabel);
  46786. fileLabel.attachToComponent (&filenameBox, true);
  46787. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46788. goUpButton->addButtonListener (this);
  46789. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46790. if (previewComp != 0)
  46791. addAndMakeVisible (previewComp);
  46792. setRoot (currentRoot);
  46793. thread.startThread (4);
  46794. }
  46795. FileBrowserComponent::~FileBrowserComponent()
  46796. {
  46797. fileListComponent = 0;
  46798. fileList = 0;
  46799. thread.stopThread (10000);
  46800. }
  46801. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46802. {
  46803. listeners.add (newListener);
  46804. }
  46805. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46806. {
  46807. listeners.remove (listener);
  46808. }
  46809. bool FileBrowserComponent::isSaveMode() const throw()
  46810. {
  46811. return (flags & saveMode) != 0;
  46812. }
  46813. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46814. {
  46815. if (chosenFiles.size() == 0 && currentFileIsValid())
  46816. return 1;
  46817. return chosenFiles.size();
  46818. }
  46819. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46820. {
  46821. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46822. return currentRoot;
  46823. if (! filenameBox.isReadOnly())
  46824. return currentRoot.getChildFile (filenameBox.getText());
  46825. return chosenFiles[index];
  46826. }
  46827. bool FileBrowserComponent::currentFileIsValid() const
  46828. {
  46829. if (isSaveMode())
  46830. return ! getSelectedFile (0).isDirectory();
  46831. else
  46832. return getSelectedFile (0).exists();
  46833. }
  46834. const File FileBrowserComponent::getHighlightedFile() const throw()
  46835. {
  46836. return fileListComponent->getSelectedFile (0);
  46837. }
  46838. void FileBrowserComponent::deselectAllFiles()
  46839. {
  46840. fileListComponent->deselectAllFiles();
  46841. }
  46842. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46843. {
  46844. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46845. }
  46846. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46847. {
  46848. return true;
  46849. }
  46850. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46851. {
  46852. if (f.isDirectory())
  46853. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46854. return (flags & canSelectFiles) != 0 && f.exists()
  46855. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46856. }
  46857. const File FileBrowserComponent::getRoot() const
  46858. {
  46859. return currentRoot;
  46860. }
  46861. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46862. {
  46863. if (currentRoot != newRootDirectory)
  46864. {
  46865. fileListComponent->scrollToTop();
  46866. String path (newRootDirectory.getFullPathName());
  46867. if (path.isEmpty())
  46868. path = File::separatorString;
  46869. StringArray rootNames, rootPaths;
  46870. getRoots (rootNames, rootPaths);
  46871. if (! rootPaths.contains (path, true))
  46872. {
  46873. bool alreadyListed = false;
  46874. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46875. {
  46876. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46877. {
  46878. alreadyListed = true;
  46879. break;
  46880. }
  46881. }
  46882. if (! alreadyListed)
  46883. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46884. }
  46885. }
  46886. currentRoot = newRootDirectory;
  46887. fileList->setDirectory (currentRoot, true, true);
  46888. String currentRootName (currentRoot.getFullPathName());
  46889. if (currentRootName.isEmpty())
  46890. currentRootName = File::separatorString;
  46891. currentPathBox.setText (currentRootName, true);
  46892. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46893. && currentRoot.getParentDirectory() != currentRoot);
  46894. }
  46895. void FileBrowserComponent::goUp()
  46896. {
  46897. setRoot (getRoot().getParentDirectory());
  46898. }
  46899. void FileBrowserComponent::refresh()
  46900. {
  46901. fileList->refresh();
  46902. }
  46903. const String FileBrowserComponent::getActionVerb() const
  46904. {
  46905. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46906. }
  46907. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46908. {
  46909. return previewComp;
  46910. }
  46911. void FileBrowserComponent::resized()
  46912. {
  46913. getLookAndFeel()
  46914. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46915. &currentPathBox, &filenameBox, goUpButton);
  46916. }
  46917. void FileBrowserComponent::sendListenerChangeMessage()
  46918. {
  46919. Component::BailOutChecker checker (this);
  46920. if (previewComp != 0)
  46921. previewComp->selectedFileChanged (getSelectedFile (0));
  46922. // You shouldn't delete the browser when the file gets changed!
  46923. jassert (! checker.shouldBailOut());
  46924. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46925. }
  46926. void FileBrowserComponent::selectionChanged()
  46927. {
  46928. StringArray newFilenames;
  46929. bool resetChosenFiles = true;
  46930. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46931. {
  46932. const File f (fileListComponent->getSelectedFile (i));
  46933. if (isFileOrDirSuitable (f))
  46934. {
  46935. if (resetChosenFiles)
  46936. {
  46937. chosenFiles.clear();
  46938. resetChosenFiles = false;
  46939. }
  46940. chosenFiles.add (f);
  46941. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46942. }
  46943. }
  46944. if (newFilenames.size() > 0)
  46945. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46946. sendListenerChangeMessage();
  46947. }
  46948. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46949. {
  46950. Component::BailOutChecker checker (this);
  46951. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46952. }
  46953. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46954. {
  46955. if (f.isDirectory())
  46956. {
  46957. setRoot (f);
  46958. if ((flags & canSelectDirectories) != 0)
  46959. filenameBox.setText (String::empty);
  46960. }
  46961. else
  46962. {
  46963. Component::BailOutChecker checker (this);
  46964. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46965. }
  46966. }
  46967. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46968. {
  46969. (void) key;
  46970. #if JUCE_LINUX || JUCE_WINDOWS
  46971. if (key.getModifiers().isCommandDown()
  46972. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46973. {
  46974. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46975. fileList->refresh();
  46976. return true;
  46977. }
  46978. #endif
  46979. return false;
  46980. }
  46981. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46982. {
  46983. sendListenerChangeMessage();
  46984. }
  46985. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46986. {
  46987. if (filenameBox.getText().containsChar (File::separator))
  46988. {
  46989. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46990. if (f.isDirectory())
  46991. {
  46992. setRoot (f);
  46993. chosenFiles.clear();
  46994. filenameBox.setText (String::empty);
  46995. }
  46996. else
  46997. {
  46998. setRoot (f.getParentDirectory());
  46999. chosenFiles.clear();
  47000. chosenFiles.add (f);
  47001. filenameBox.setText (f.getFileName());
  47002. }
  47003. }
  47004. else
  47005. {
  47006. fileDoubleClicked (getSelectedFile (0));
  47007. }
  47008. }
  47009. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47010. {
  47011. }
  47012. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47013. {
  47014. if (! isSaveMode())
  47015. selectionChanged();
  47016. }
  47017. void FileBrowserComponent::buttonClicked (Button*)
  47018. {
  47019. goUp();
  47020. }
  47021. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47022. {
  47023. const String newText (currentPathBox.getText().trim().unquoted());
  47024. if (newText.isNotEmpty())
  47025. {
  47026. const int index = currentPathBox.getSelectedId() - 1;
  47027. StringArray rootNames, rootPaths;
  47028. getRoots (rootNames, rootPaths);
  47029. if (rootPaths [index].isNotEmpty())
  47030. {
  47031. setRoot (File (rootPaths [index]));
  47032. }
  47033. else
  47034. {
  47035. File f (newText);
  47036. for (;;)
  47037. {
  47038. if (f.isDirectory())
  47039. {
  47040. setRoot (f);
  47041. break;
  47042. }
  47043. if (f.getParentDirectory() == f)
  47044. break;
  47045. f = f.getParentDirectory();
  47046. }
  47047. }
  47048. }
  47049. }
  47050. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47051. {
  47052. BigInteger separators;
  47053. #if JUCE_WINDOWS
  47054. Array<File> roots;
  47055. File::findFileSystemRoots (roots);
  47056. rootPaths.clear();
  47057. for (int i = 0; i < roots.size(); ++i)
  47058. {
  47059. const File& drive = roots.getReference(i);
  47060. String name (drive.getFullPathName());
  47061. rootPaths.add (name);
  47062. if (drive.isOnHardDisk())
  47063. {
  47064. String volume (drive.getVolumeLabel());
  47065. if (volume.isEmpty())
  47066. volume = TRANS("Hard Drive");
  47067. name << " [" << volume << ']';
  47068. }
  47069. else if (drive.isOnCDRomDrive())
  47070. {
  47071. name << TRANS(" [CD/DVD drive]");
  47072. }
  47073. rootNames.add (name);
  47074. }
  47075. separators.setBit (rootPaths.size());
  47076. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47077. rootNames.add ("Documents");
  47078. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47079. rootNames.add ("Desktop");
  47080. #endif
  47081. #if JUCE_MAC
  47082. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47083. rootNames.add ("Home folder");
  47084. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47085. rootNames.add ("Documents");
  47086. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47087. rootNames.add ("Desktop");
  47088. separators.setBit (rootPaths.size());
  47089. Array <File> volumes;
  47090. File vol ("/Volumes");
  47091. vol.findChildFiles (volumes, File::findDirectories, false);
  47092. for (int i = 0; i < volumes.size(); ++i)
  47093. {
  47094. const File& volume = volumes.getReference(i);
  47095. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47096. {
  47097. rootPaths.add (volume.getFullPathName());
  47098. rootNames.add (volume.getFileName());
  47099. }
  47100. }
  47101. #endif
  47102. #if JUCE_LINUX
  47103. rootPaths.add ("/");
  47104. rootNames.add ("/");
  47105. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47106. rootNames.add ("Home folder");
  47107. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47108. rootNames.add ("Desktop");
  47109. #endif
  47110. return separators;
  47111. }
  47112. END_JUCE_NAMESPACE
  47113. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47114. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47115. BEGIN_JUCE_NAMESPACE
  47116. FileChooser::FileChooser (const String& chooserBoxTitle,
  47117. const File& currentFileOrDirectory,
  47118. const String& fileFilters,
  47119. const bool useNativeDialogBox_)
  47120. : title (chooserBoxTitle),
  47121. filters (fileFilters),
  47122. startingFile (currentFileOrDirectory),
  47123. useNativeDialogBox (useNativeDialogBox_)
  47124. {
  47125. #if JUCE_LINUX
  47126. useNativeDialogBox = false;
  47127. #endif
  47128. if (! fileFilters.containsNonWhitespaceChars())
  47129. filters = "*";
  47130. }
  47131. FileChooser::~FileChooser()
  47132. {
  47133. }
  47134. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47135. {
  47136. return showDialog (false, true, false, false, false, previewComponent);
  47137. }
  47138. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47139. {
  47140. return showDialog (false, true, false, false, true, previewComponent);
  47141. }
  47142. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47143. {
  47144. return showDialog (true, true, false, false, true, previewComponent);
  47145. }
  47146. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47147. {
  47148. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47149. }
  47150. bool FileChooser::browseForDirectory()
  47151. {
  47152. return showDialog (true, false, false, false, false, 0);
  47153. }
  47154. const File FileChooser::getResult() const
  47155. {
  47156. // if you've used a multiple-file select, you should use the getResults() method
  47157. // to retrieve all the files that were chosen.
  47158. jassert (results.size() <= 1);
  47159. return results.getFirst();
  47160. }
  47161. const Array<File>& FileChooser::getResults() const
  47162. {
  47163. return results;
  47164. }
  47165. bool FileChooser::showDialog (const bool selectsDirectories,
  47166. const bool selectsFiles,
  47167. const bool isSave,
  47168. const bool warnAboutOverwritingExistingFiles,
  47169. const bool selectMultipleFiles,
  47170. FilePreviewComponent* const previewComponent)
  47171. {
  47172. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47173. results.clear();
  47174. // the preview component needs to be the right size before you pass it in here..
  47175. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47176. && previewComponent->getHeight() > 10));
  47177. #if JUCE_WINDOWS
  47178. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47179. #elif JUCE_MAC
  47180. if (useNativeDialogBox && (previewComponent == 0))
  47181. #else
  47182. if (false)
  47183. #endif
  47184. {
  47185. showPlatformDialog (results, title, startingFile, filters,
  47186. selectsDirectories, selectsFiles, isSave,
  47187. warnAboutOverwritingExistingFiles,
  47188. selectMultipleFiles,
  47189. previewComponent);
  47190. }
  47191. else
  47192. {
  47193. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47194. selectsDirectories ? "*" : String::empty,
  47195. String::empty);
  47196. int flags = isSave ? FileBrowserComponent::saveMode
  47197. : FileBrowserComponent::openMode;
  47198. if (selectsFiles)
  47199. flags |= FileBrowserComponent::canSelectFiles;
  47200. if (selectsDirectories)
  47201. {
  47202. flags |= FileBrowserComponent::canSelectDirectories;
  47203. if (! isSave)
  47204. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47205. }
  47206. if (selectMultipleFiles)
  47207. flags |= FileBrowserComponent::canSelectMultipleItems;
  47208. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47209. FileChooserDialogBox box (title, String::empty,
  47210. browserComponent,
  47211. warnAboutOverwritingExistingFiles,
  47212. browserComponent.findColour (AlertWindow::backgroundColourId));
  47213. if (box.show())
  47214. {
  47215. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47216. results.add (browserComponent.getSelectedFile (i));
  47217. }
  47218. }
  47219. if (previouslyFocused != 0)
  47220. previouslyFocused->grabKeyboardFocus();
  47221. return results.size() > 0;
  47222. }
  47223. FilePreviewComponent::FilePreviewComponent()
  47224. {
  47225. }
  47226. FilePreviewComponent::~FilePreviewComponent()
  47227. {
  47228. }
  47229. END_JUCE_NAMESPACE
  47230. /*** End of inlined file: juce_FileChooser.cpp ***/
  47231. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47232. BEGIN_JUCE_NAMESPACE
  47233. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47234. const String& instructions,
  47235. FileBrowserComponent& chooserComponent,
  47236. const bool warnAboutOverwritingExistingFiles_,
  47237. const Colour& backgroundColour)
  47238. : ResizableWindow (name, backgroundColour, true),
  47239. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47240. {
  47241. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47242. setResizable (true, true);
  47243. setResizeLimits (300, 300, 1200, 1000);
  47244. content->okButton.addButtonListener (this);
  47245. content->cancelButton.addButtonListener (this);
  47246. content->newFolderButton.addButtonListener (this);
  47247. content->chooserComponent.addListener (this);
  47248. selectionChanged();
  47249. }
  47250. FileChooserDialogBox::~FileChooserDialogBox()
  47251. {
  47252. content->chooserComponent.removeListener (this);
  47253. }
  47254. bool FileChooserDialogBox::show (int w, int h)
  47255. {
  47256. return showAt (-1, -1, w, h);
  47257. }
  47258. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47259. {
  47260. if (w <= 0)
  47261. {
  47262. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47263. if (previewComp != 0)
  47264. w = 400 + previewComp->getWidth();
  47265. else
  47266. w = 600;
  47267. }
  47268. if (h <= 0)
  47269. h = 500;
  47270. if (x < 0 || y < 0)
  47271. centreWithSize (w, h);
  47272. else
  47273. setBounds (x, y, w, h);
  47274. const bool ok = (runModalLoop() != 0);
  47275. setVisible (false);
  47276. return ok;
  47277. }
  47278. void FileChooserDialogBox::buttonClicked (Button* button)
  47279. {
  47280. if (button == &(content->okButton))
  47281. {
  47282. okButtonPressed();
  47283. }
  47284. else if (button == &(content->cancelButton))
  47285. {
  47286. closeButtonPressed();
  47287. }
  47288. else if (button == &(content->newFolderButton))
  47289. {
  47290. createNewFolder();
  47291. }
  47292. }
  47293. void FileChooserDialogBox::closeButtonPressed()
  47294. {
  47295. setVisible (false);
  47296. }
  47297. void FileChooserDialogBox::selectionChanged()
  47298. {
  47299. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47300. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47301. && content->chooserComponent.getRoot().isDirectory());
  47302. }
  47303. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47304. {
  47305. }
  47306. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47307. {
  47308. selectionChanged();
  47309. content->okButton.triggerClick();
  47310. }
  47311. void FileChooserDialogBox::okButtonPressed()
  47312. {
  47313. if ((! (warnAboutOverwritingExistingFiles
  47314. && content->chooserComponent.isSaveMode()
  47315. && content->chooserComponent.getSelectedFile(0).exists()))
  47316. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47317. TRANS("File already exists"),
  47318. TRANS("There's already a file called:")
  47319. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47320. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47321. TRANS("overwrite"),
  47322. TRANS("cancel")))
  47323. {
  47324. exitModalState (1);
  47325. }
  47326. }
  47327. void FileChooserDialogBox::createNewFolder()
  47328. {
  47329. File parent (content->chooserComponent.getRoot());
  47330. if (parent.isDirectory())
  47331. {
  47332. AlertWindow aw (TRANS("New Folder"),
  47333. TRANS("Please enter the name for the folder"),
  47334. AlertWindow::NoIcon, this);
  47335. aw.addTextEditor ("name", String::empty, String::empty, false);
  47336. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47337. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47338. if (aw.runModalLoop() != 0)
  47339. {
  47340. aw.setVisible (false);
  47341. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47342. if (! name.isEmpty())
  47343. {
  47344. if (! parent.getChildFile (name).createDirectory())
  47345. {
  47346. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47347. TRANS ("New Folder"),
  47348. TRANS ("Couldn't create the folder!"));
  47349. }
  47350. content->chooserComponent.refresh();
  47351. }
  47352. }
  47353. }
  47354. }
  47355. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47356. : Component (name), instructions (instructions_),
  47357. chooserComponent (chooserComponent_),
  47358. okButton (chooserComponent_.getActionVerb()),
  47359. cancelButton (TRANS ("Cancel")),
  47360. newFolderButton (TRANS ("New Folder"))
  47361. {
  47362. addAndMakeVisible (&chooserComponent);
  47363. addAndMakeVisible (&okButton);
  47364. okButton.addShortcut (KeyPress::returnKey);
  47365. addAndMakeVisible (&cancelButton);
  47366. cancelButton.addShortcut (KeyPress::escapeKey);
  47367. addChildComponent (&newFolderButton);
  47368. setInterceptsMouseClicks (false, true);
  47369. }
  47370. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47371. {
  47372. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47373. text.draw (g);
  47374. }
  47375. void FileChooserDialogBox::ContentComponent::resized()
  47376. {
  47377. const int buttonHeight = 26;
  47378. Rectangle<int> area (getLocalBounds());
  47379. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47380. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47381. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47382. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47383. Rectangle<int> buttonArea (area.reduced (16, 10));
  47384. okButton.changeWidthToFitText (buttonHeight);
  47385. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47386. buttonArea.removeFromRight (16);
  47387. cancelButton.changeWidthToFitText (buttonHeight);
  47388. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47389. newFolderButton.changeWidthToFitText (buttonHeight);
  47390. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47391. }
  47392. END_JUCE_NAMESPACE
  47393. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47394. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47395. BEGIN_JUCE_NAMESPACE
  47396. FileFilter::FileFilter (const String& filterDescription)
  47397. : description (filterDescription)
  47398. {
  47399. }
  47400. FileFilter::~FileFilter()
  47401. {
  47402. }
  47403. const String& FileFilter::getDescription() const throw()
  47404. {
  47405. return description;
  47406. }
  47407. END_JUCE_NAMESPACE
  47408. /*** End of inlined file: juce_FileFilter.cpp ***/
  47409. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47410. BEGIN_JUCE_NAMESPACE
  47411. const Image juce_createIconForFile (const File& file);
  47412. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47413. : ListBox (String::empty, 0),
  47414. DirectoryContentsDisplayComponent (listToShow)
  47415. {
  47416. setModel (this);
  47417. fileList.addChangeListener (this);
  47418. }
  47419. FileListComponent::~FileListComponent()
  47420. {
  47421. fileList.removeChangeListener (this);
  47422. }
  47423. int FileListComponent::getNumSelectedFiles() const
  47424. {
  47425. return getNumSelectedRows();
  47426. }
  47427. const File FileListComponent::getSelectedFile (int index) const
  47428. {
  47429. return fileList.getFile (getSelectedRow (index));
  47430. }
  47431. void FileListComponent::deselectAllFiles()
  47432. {
  47433. deselectAllRows();
  47434. }
  47435. void FileListComponent::scrollToTop()
  47436. {
  47437. getVerticalScrollBar()->setCurrentRangeStart (0);
  47438. }
  47439. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47440. {
  47441. updateContent();
  47442. if (lastDirectory != fileList.getDirectory())
  47443. {
  47444. lastDirectory = fileList.getDirectory();
  47445. deselectAllRows();
  47446. }
  47447. }
  47448. class FileListItemComponent : public Component,
  47449. public TimeSliceClient,
  47450. public AsyncUpdater
  47451. {
  47452. public:
  47453. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47454. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47455. {
  47456. }
  47457. ~FileListItemComponent()
  47458. {
  47459. thread.removeTimeSliceClient (this);
  47460. }
  47461. void paint (Graphics& g)
  47462. {
  47463. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47464. file.getFileName(),
  47465. &icon, fileSize, modTime,
  47466. isDirectory, highlighted,
  47467. index, owner);
  47468. }
  47469. void mouseDown (const MouseEvent& e)
  47470. {
  47471. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47472. owner.sendMouseClickMessage (file, e);
  47473. }
  47474. void mouseDoubleClick (const MouseEvent&)
  47475. {
  47476. owner.sendDoubleClickMessage (file);
  47477. }
  47478. void update (const File& root,
  47479. const DirectoryContentsList::FileInfo* const fileInfo,
  47480. const int index_,
  47481. const bool highlighted_)
  47482. {
  47483. thread.removeTimeSliceClient (this);
  47484. if (highlighted_ != highlighted || index_ != index)
  47485. {
  47486. index = index_;
  47487. highlighted = highlighted_;
  47488. repaint();
  47489. }
  47490. File newFile;
  47491. String newFileSize, newModTime;
  47492. if (fileInfo != 0)
  47493. {
  47494. newFile = root.getChildFile (fileInfo->filename);
  47495. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47496. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47497. }
  47498. if (newFile != file
  47499. || fileSize != newFileSize
  47500. || modTime != newModTime)
  47501. {
  47502. file = newFile;
  47503. fileSize = newFileSize;
  47504. modTime = newModTime;
  47505. icon = Image::null;
  47506. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47507. repaint();
  47508. }
  47509. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47510. {
  47511. updateIcon (true);
  47512. if (! icon.isValid())
  47513. thread.addTimeSliceClient (this);
  47514. }
  47515. }
  47516. bool useTimeSlice()
  47517. {
  47518. updateIcon (false);
  47519. return false;
  47520. }
  47521. void handleAsyncUpdate()
  47522. {
  47523. repaint();
  47524. }
  47525. private:
  47526. FileListComponent& owner;
  47527. TimeSliceThread& thread;
  47528. File file;
  47529. String fileSize, modTime;
  47530. Image icon;
  47531. int index;
  47532. bool highlighted, isDirectory;
  47533. void updateIcon (const bool onlyUpdateIfCached)
  47534. {
  47535. if (icon.isNull())
  47536. {
  47537. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47538. Image im (ImageCache::getFromHashCode (hashCode));
  47539. if (im.isNull() && ! onlyUpdateIfCached)
  47540. {
  47541. im = juce_createIconForFile (file);
  47542. if (im.isValid())
  47543. ImageCache::addImageToCache (im, hashCode);
  47544. }
  47545. if (im.isValid())
  47546. {
  47547. icon = im;
  47548. triggerAsyncUpdate();
  47549. }
  47550. }
  47551. }
  47552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47553. };
  47554. int FileListComponent::getNumRows()
  47555. {
  47556. return fileList.getNumFiles();
  47557. }
  47558. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47559. {
  47560. }
  47561. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47562. {
  47563. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47564. if (comp == 0)
  47565. {
  47566. delete existingComponentToUpdate;
  47567. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47568. }
  47569. DirectoryContentsList::FileInfo fileInfo;
  47570. if (fileList.getFileInfo (row, fileInfo))
  47571. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47572. else
  47573. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47574. return comp;
  47575. }
  47576. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47577. {
  47578. sendSelectionChangeMessage();
  47579. }
  47580. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47581. {
  47582. }
  47583. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47584. {
  47585. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47586. }
  47587. END_JUCE_NAMESPACE
  47588. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47589. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47590. BEGIN_JUCE_NAMESPACE
  47591. FilenameComponent::FilenameComponent (const String& name,
  47592. const File& currentFile,
  47593. const bool canEditFilename,
  47594. const bool isDirectory,
  47595. const bool isForSaving,
  47596. const String& fileBrowserWildcard,
  47597. const String& enforcedSuffix_,
  47598. const String& textWhenNothingSelected)
  47599. : Component (name),
  47600. maxRecentFiles (30),
  47601. isDir (isDirectory),
  47602. isSaving (isForSaving),
  47603. isFileDragOver (false),
  47604. wildcard (fileBrowserWildcard),
  47605. enforcedSuffix (enforcedSuffix_)
  47606. {
  47607. addAndMakeVisible (&filenameBox);
  47608. filenameBox.setEditableText (canEditFilename);
  47609. filenameBox.addListener (this);
  47610. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47611. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47612. setBrowseButtonText ("...");
  47613. setCurrentFile (currentFile, true);
  47614. }
  47615. FilenameComponent::~FilenameComponent()
  47616. {
  47617. }
  47618. void FilenameComponent::paintOverChildren (Graphics& g)
  47619. {
  47620. if (isFileDragOver)
  47621. {
  47622. g.setColour (Colours::red.withAlpha (0.2f));
  47623. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47624. }
  47625. }
  47626. void FilenameComponent::resized()
  47627. {
  47628. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47629. }
  47630. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47631. {
  47632. browseButtonText = newBrowseButtonText;
  47633. lookAndFeelChanged();
  47634. }
  47635. void FilenameComponent::lookAndFeelChanged()
  47636. {
  47637. browseButton = 0;
  47638. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47639. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47640. resized();
  47641. browseButton->addButtonListener (this);
  47642. }
  47643. void FilenameComponent::setTooltip (const String& newTooltip)
  47644. {
  47645. SettableTooltipClient::setTooltip (newTooltip);
  47646. filenameBox.setTooltip (newTooltip);
  47647. }
  47648. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47649. {
  47650. defaultBrowseFile = newDefaultDirectory;
  47651. }
  47652. void FilenameComponent::buttonClicked (Button*)
  47653. {
  47654. FileChooser fc (TRANS("Choose a new file"),
  47655. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47656. : getCurrentFile(),
  47657. wildcard);
  47658. if (isDir ? fc.browseForDirectory()
  47659. : (isSaving ? fc.browseForFileToSave (false)
  47660. : fc.browseForFileToOpen()))
  47661. {
  47662. setCurrentFile (fc.getResult(), true);
  47663. }
  47664. }
  47665. void FilenameComponent::comboBoxChanged (ComboBox*)
  47666. {
  47667. setCurrentFile (getCurrentFile(), true);
  47668. }
  47669. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47670. {
  47671. return true;
  47672. }
  47673. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47674. {
  47675. isFileDragOver = false;
  47676. repaint();
  47677. const File f (filenames[0]);
  47678. if (f.exists() && (f.isDirectory() == isDir))
  47679. setCurrentFile (f, true);
  47680. }
  47681. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47682. {
  47683. isFileDragOver = true;
  47684. repaint();
  47685. }
  47686. void FilenameComponent::fileDragExit (const StringArray&)
  47687. {
  47688. isFileDragOver = false;
  47689. repaint();
  47690. }
  47691. const File FilenameComponent::getCurrentFile() const
  47692. {
  47693. File f (filenameBox.getText());
  47694. if (enforcedSuffix.isNotEmpty())
  47695. f = f.withFileExtension (enforcedSuffix);
  47696. return f;
  47697. }
  47698. void FilenameComponent::setCurrentFile (File newFile,
  47699. const bool addToRecentlyUsedList,
  47700. const bool sendChangeNotification)
  47701. {
  47702. if (enforcedSuffix.isNotEmpty())
  47703. newFile = newFile.withFileExtension (enforcedSuffix);
  47704. if (newFile.getFullPathName() != lastFilename)
  47705. {
  47706. lastFilename = newFile.getFullPathName();
  47707. if (addToRecentlyUsedList)
  47708. addRecentlyUsedFile (newFile);
  47709. filenameBox.setText (lastFilename, true);
  47710. if (sendChangeNotification)
  47711. triggerAsyncUpdate();
  47712. }
  47713. }
  47714. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47715. {
  47716. filenameBox.setEditableText (shouldBeEditable);
  47717. }
  47718. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47719. {
  47720. StringArray names;
  47721. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47722. names.add (filenameBox.getItemText (i));
  47723. return names;
  47724. }
  47725. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47726. {
  47727. if (filenames != getRecentlyUsedFilenames())
  47728. {
  47729. filenameBox.clear();
  47730. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47731. filenameBox.addItem (filenames[i], i + 1);
  47732. }
  47733. }
  47734. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47735. {
  47736. maxRecentFiles = jmax (1, newMaximum);
  47737. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47738. }
  47739. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47740. {
  47741. StringArray files (getRecentlyUsedFilenames());
  47742. if (file.getFullPathName().isNotEmpty())
  47743. {
  47744. files.removeString (file.getFullPathName(), true);
  47745. files.insert (0, file.getFullPathName());
  47746. setRecentlyUsedFilenames (files);
  47747. }
  47748. }
  47749. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47750. {
  47751. listeners.add (listener);
  47752. }
  47753. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47754. {
  47755. listeners.remove (listener);
  47756. }
  47757. void FilenameComponent::handleAsyncUpdate()
  47758. {
  47759. Component::BailOutChecker checker (this);
  47760. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47761. }
  47762. END_JUCE_NAMESPACE
  47763. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47764. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47765. BEGIN_JUCE_NAMESPACE
  47766. FileSearchPathListComponent::FileSearchPathListComponent()
  47767. : addButton ("+"),
  47768. removeButton ("-"),
  47769. changeButton (TRANS ("change...")),
  47770. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47771. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47772. {
  47773. listBox.setModel (this);
  47774. addAndMakeVisible (&listBox);
  47775. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47776. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47777. listBox.setOutlineThickness (1);
  47778. addAndMakeVisible (&addButton);
  47779. addButton.addButtonListener (this);
  47780. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47781. addAndMakeVisible (&removeButton);
  47782. removeButton.addButtonListener (this);
  47783. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47784. addAndMakeVisible (&changeButton);
  47785. changeButton.addButtonListener (this);
  47786. addAndMakeVisible (&upButton);
  47787. upButton.addButtonListener (this);
  47788. {
  47789. Path arrowPath;
  47790. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47791. DrawablePath arrowImage;
  47792. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47793. arrowImage.setPath (arrowPath);
  47794. upButton.setImages (&arrowImage);
  47795. }
  47796. addAndMakeVisible (&downButton);
  47797. downButton.addButtonListener (this);
  47798. {
  47799. Path arrowPath;
  47800. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47801. DrawablePath arrowImage;
  47802. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47803. arrowImage.setPath (arrowPath);
  47804. downButton.setImages (&arrowImage);
  47805. }
  47806. updateButtons();
  47807. }
  47808. FileSearchPathListComponent::~FileSearchPathListComponent()
  47809. {
  47810. }
  47811. void FileSearchPathListComponent::updateButtons()
  47812. {
  47813. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47814. removeButton.setEnabled (anythingSelected);
  47815. changeButton.setEnabled (anythingSelected);
  47816. upButton.setEnabled (anythingSelected);
  47817. downButton.setEnabled (anythingSelected);
  47818. }
  47819. void FileSearchPathListComponent::changed()
  47820. {
  47821. listBox.updateContent();
  47822. listBox.repaint();
  47823. updateButtons();
  47824. }
  47825. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47826. {
  47827. if (newPath.toString() != path.toString())
  47828. {
  47829. path = newPath;
  47830. changed();
  47831. }
  47832. }
  47833. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47834. {
  47835. defaultBrowseTarget = newDefaultDirectory;
  47836. }
  47837. int FileSearchPathListComponent::getNumRows()
  47838. {
  47839. return path.getNumPaths();
  47840. }
  47841. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47842. {
  47843. if (rowIsSelected)
  47844. g.fillAll (findColour (TextEditor::highlightColourId));
  47845. g.setColour (findColour (ListBox::textColourId));
  47846. Font f (height * 0.7f);
  47847. f.setHorizontalScale (0.9f);
  47848. g.setFont (f);
  47849. g.drawText (path [rowNumber].getFullPathName(),
  47850. 4, 0, width - 6, height,
  47851. Justification::centredLeft, true);
  47852. }
  47853. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47854. {
  47855. if (isPositiveAndBelow (row, path.getNumPaths()))
  47856. {
  47857. path.remove (row);
  47858. changed();
  47859. }
  47860. }
  47861. void FileSearchPathListComponent::returnKeyPressed (int row)
  47862. {
  47863. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47864. if (chooser.browseForDirectory())
  47865. {
  47866. path.remove (row);
  47867. path.add (chooser.getResult(), row);
  47868. changed();
  47869. }
  47870. }
  47871. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47872. {
  47873. returnKeyPressed (row);
  47874. }
  47875. void FileSearchPathListComponent::selectedRowsChanged (int)
  47876. {
  47877. updateButtons();
  47878. }
  47879. void FileSearchPathListComponent::paint (Graphics& g)
  47880. {
  47881. g.fillAll (findColour (backgroundColourId));
  47882. }
  47883. void FileSearchPathListComponent::resized()
  47884. {
  47885. const int buttonH = 22;
  47886. const int buttonY = getHeight() - buttonH - 4;
  47887. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47888. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47889. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47890. changeButton.changeWidthToFitText (buttonH);
  47891. downButton.setSize (buttonH * 2, buttonH);
  47892. upButton.setSize (buttonH * 2, buttonH);
  47893. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47894. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47895. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47896. }
  47897. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47898. {
  47899. return true;
  47900. }
  47901. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47902. {
  47903. for (int i = filenames.size(); --i >= 0;)
  47904. {
  47905. const File f (filenames[i]);
  47906. if (f.isDirectory())
  47907. {
  47908. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47909. path.add (f, row);
  47910. changed();
  47911. }
  47912. }
  47913. }
  47914. void FileSearchPathListComponent::buttonClicked (Button* button)
  47915. {
  47916. const int currentRow = listBox.getSelectedRow();
  47917. if (button == &removeButton)
  47918. {
  47919. deleteKeyPressed (currentRow);
  47920. }
  47921. else if (button == &addButton)
  47922. {
  47923. File start (defaultBrowseTarget);
  47924. if (start == File::nonexistent)
  47925. start = path [0];
  47926. if (start == File::nonexistent)
  47927. start = File::getCurrentWorkingDirectory();
  47928. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47929. if (chooser.browseForDirectory())
  47930. {
  47931. path.add (chooser.getResult(), currentRow);
  47932. }
  47933. }
  47934. else if (button == &changeButton)
  47935. {
  47936. returnKeyPressed (currentRow);
  47937. }
  47938. else if (button == &upButton)
  47939. {
  47940. if (currentRow > 0 && currentRow < path.getNumPaths())
  47941. {
  47942. const File f (path[currentRow]);
  47943. path.remove (currentRow);
  47944. path.add (f, currentRow - 1);
  47945. listBox.selectRow (currentRow - 1);
  47946. }
  47947. }
  47948. else if (button == &downButton)
  47949. {
  47950. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47951. {
  47952. const File f (path[currentRow]);
  47953. path.remove (currentRow);
  47954. path.add (f, currentRow + 1);
  47955. listBox.selectRow (currentRow + 1);
  47956. }
  47957. }
  47958. changed();
  47959. }
  47960. END_JUCE_NAMESPACE
  47961. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47962. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47963. BEGIN_JUCE_NAMESPACE
  47964. const Image juce_createIconForFile (const File& file);
  47965. class FileListTreeItem : public TreeViewItem,
  47966. public TimeSliceClient,
  47967. public AsyncUpdater,
  47968. public ChangeListener
  47969. {
  47970. public:
  47971. FileListTreeItem (FileTreeComponent& owner_,
  47972. DirectoryContentsList* const parentContentsList_,
  47973. const int indexInContentsList_,
  47974. const File& file_,
  47975. TimeSliceThread& thread_)
  47976. : file (file_),
  47977. owner (owner_),
  47978. parentContentsList (parentContentsList_),
  47979. indexInContentsList (indexInContentsList_),
  47980. subContentsList (0),
  47981. canDeleteSubContentsList (false),
  47982. thread (thread_),
  47983. icon (0)
  47984. {
  47985. DirectoryContentsList::FileInfo fileInfo;
  47986. if (parentContentsList_ != 0
  47987. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47988. {
  47989. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47990. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47991. isDirectory = fileInfo.isDirectory;
  47992. }
  47993. else
  47994. {
  47995. isDirectory = true;
  47996. }
  47997. }
  47998. ~FileListTreeItem()
  47999. {
  48000. thread.removeTimeSliceClient (this);
  48001. clearSubItems();
  48002. if (canDeleteSubContentsList)
  48003. delete subContentsList;
  48004. }
  48005. bool mightContainSubItems() { return isDirectory; }
  48006. const String getUniqueName() const { return file.getFullPathName(); }
  48007. int getItemHeight() const { return 22; }
  48008. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48009. void itemOpennessChanged (bool isNowOpen)
  48010. {
  48011. if (isNowOpen)
  48012. {
  48013. clearSubItems();
  48014. isDirectory = file.isDirectory();
  48015. if (isDirectory)
  48016. {
  48017. if (subContentsList == 0)
  48018. {
  48019. jassert (parentContentsList != 0);
  48020. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48021. l->setDirectory (file, true, true);
  48022. setSubContentsList (l);
  48023. canDeleteSubContentsList = true;
  48024. }
  48025. changeListenerCallback (0);
  48026. }
  48027. }
  48028. }
  48029. void setSubContentsList (DirectoryContentsList* newList)
  48030. {
  48031. jassert (subContentsList == 0);
  48032. subContentsList = newList;
  48033. newList->addChangeListener (this);
  48034. }
  48035. void changeListenerCallback (ChangeBroadcaster*)
  48036. {
  48037. clearSubItems();
  48038. if (isOpen() && subContentsList != 0)
  48039. {
  48040. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48041. {
  48042. FileListTreeItem* const item
  48043. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48044. addSubItem (item);
  48045. }
  48046. }
  48047. }
  48048. void paintItem (Graphics& g, int width, int height)
  48049. {
  48050. if (file != File::nonexistent)
  48051. {
  48052. updateIcon (true);
  48053. if (icon.isNull())
  48054. thread.addTimeSliceClient (this);
  48055. }
  48056. owner.getLookAndFeel()
  48057. .drawFileBrowserRow (g, width, height,
  48058. file.getFileName(),
  48059. &icon, fileSize, modTime,
  48060. isDirectory, isSelected(),
  48061. indexInContentsList, owner);
  48062. }
  48063. void itemClicked (const MouseEvent& e)
  48064. {
  48065. owner.sendMouseClickMessage (file, e);
  48066. }
  48067. void itemDoubleClicked (const MouseEvent& e)
  48068. {
  48069. TreeViewItem::itemDoubleClicked (e);
  48070. owner.sendDoubleClickMessage (file);
  48071. }
  48072. void itemSelectionChanged (bool)
  48073. {
  48074. owner.sendSelectionChangeMessage();
  48075. }
  48076. bool useTimeSlice()
  48077. {
  48078. updateIcon (false);
  48079. thread.removeTimeSliceClient (this);
  48080. return false;
  48081. }
  48082. void handleAsyncUpdate()
  48083. {
  48084. owner.repaint();
  48085. }
  48086. const File file;
  48087. private:
  48088. FileTreeComponent& owner;
  48089. DirectoryContentsList* parentContentsList;
  48090. int indexInContentsList;
  48091. DirectoryContentsList* subContentsList;
  48092. bool isDirectory, canDeleteSubContentsList;
  48093. TimeSliceThread& thread;
  48094. Image icon;
  48095. String fileSize;
  48096. String modTime;
  48097. void updateIcon (const bool onlyUpdateIfCached)
  48098. {
  48099. if (icon.isNull())
  48100. {
  48101. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48102. Image im (ImageCache::getFromHashCode (hashCode));
  48103. if (im.isNull() && ! onlyUpdateIfCached)
  48104. {
  48105. im = juce_createIconForFile (file);
  48106. if (im.isValid())
  48107. ImageCache::addImageToCache (im, hashCode);
  48108. }
  48109. if (im.isValid())
  48110. {
  48111. icon = im;
  48112. triggerAsyncUpdate();
  48113. }
  48114. }
  48115. }
  48116. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  48117. };
  48118. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48119. : DirectoryContentsDisplayComponent (listToShow)
  48120. {
  48121. FileListTreeItem* const root
  48122. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48123. listToShow.getTimeSliceThread());
  48124. root->setSubContentsList (&listToShow);
  48125. setRootItemVisible (false);
  48126. setRootItem (root);
  48127. }
  48128. FileTreeComponent::~FileTreeComponent()
  48129. {
  48130. deleteRootItem();
  48131. }
  48132. const File FileTreeComponent::getSelectedFile (const int index) const
  48133. {
  48134. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48135. return item != 0 ? item->file
  48136. : File::nonexistent;
  48137. }
  48138. void FileTreeComponent::deselectAllFiles()
  48139. {
  48140. clearSelectedItems();
  48141. }
  48142. void FileTreeComponent::scrollToTop()
  48143. {
  48144. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48145. }
  48146. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48147. {
  48148. dragAndDropDescription = description;
  48149. }
  48150. END_JUCE_NAMESPACE
  48151. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48152. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48153. BEGIN_JUCE_NAMESPACE
  48154. ImagePreviewComponent::ImagePreviewComponent()
  48155. {
  48156. }
  48157. ImagePreviewComponent::~ImagePreviewComponent()
  48158. {
  48159. }
  48160. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48161. {
  48162. const int availableW = proportionOfWidth (0.97f);
  48163. const int availableH = getHeight() - 13 * 4;
  48164. const double scale = jmin (1.0,
  48165. availableW / (double) w,
  48166. availableH / (double) h);
  48167. w = roundToInt (scale * w);
  48168. h = roundToInt (scale * h);
  48169. }
  48170. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48171. {
  48172. if (fileToLoad != file)
  48173. {
  48174. fileToLoad = file;
  48175. startTimer (100);
  48176. }
  48177. }
  48178. void ImagePreviewComponent::timerCallback()
  48179. {
  48180. stopTimer();
  48181. currentThumbnail = Image::null;
  48182. currentDetails = String::empty;
  48183. repaint();
  48184. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48185. if (in != 0)
  48186. {
  48187. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48188. if (format != 0)
  48189. {
  48190. currentThumbnail = format->decodeImage (*in);
  48191. if (currentThumbnail.isValid())
  48192. {
  48193. int w = currentThumbnail.getWidth();
  48194. int h = currentThumbnail.getHeight();
  48195. currentDetails
  48196. << fileToLoad.getFileName() << "\n"
  48197. << format->getFormatName() << "\n"
  48198. << w << " x " << h << " pixels\n"
  48199. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48200. getThumbSize (w, h);
  48201. currentThumbnail = currentThumbnail.rescaled (w, h);
  48202. }
  48203. }
  48204. }
  48205. }
  48206. void ImagePreviewComponent::paint (Graphics& g)
  48207. {
  48208. if (currentThumbnail.isValid())
  48209. {
  48210. g.setFont (13.0f);
  48211. int w = currentThumbnail.getWidth();
  48212. int h = currentThumbnail.getHeight();
  48213. getThumbSize (w, h);
  48214. const int numLines = 4;
  48215. const int totalH = 13 * numLines + h + 4;
  48216. const int y = (getHeight() - totalH) / 2;
  48217. g.drawImageWithin (currentThumbnail,
  48218. (getWidth() - w) / 2, y, w, h,
  48219. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48220. false);
  48221. g.drawFittedText (currentDetails,
  48222. 0, y + h + 4, getWidth(), 100,
  48223. Justification::centredTop, numLines);
  48224. }
  48225. }
  48226. END_JUCE_NAMESPACE
  48227. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48228. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48229. BEGIN_JUCE_NAMESPACE
  48230. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48231. const String& directoryWildcardPatterns,
  48232. const String& description_)
  48233. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48234. : (description_ + " (" + fileWildcardPatterns + ")"))
  48235. {
  48236. parse (fileWildcardPatterns, fileWildcards);
  48237. parse (directoryWildcardPatterns, directoryWildcards);
  48238. }
  48239. WildcardFileFilter::~WildcardFileFilter()
  48240. {
  48241. }
  48242. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48243. {
  48244. return match (file, fileWildcards);
  48245. }
  48246. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48247. {
  48248. return match (file, directoryWildcards);
  48249. }
  48250. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48251. {
  48252. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48253. result.trim();
  48254. result.removeEmptyStrings();
  48255. // special case for *.*, because people use it to mean "any file", but it
  48256. // would actually ignore files with no extension.
  48257. for (int i = result.size(); --i >= 0;)
  48258. if (result[i] == "*.*")
  48259. result.set (i, "*");
  48260. }
  48261. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48262. {
  48263. const String filename (file.getFileName());
  48264. for (int i = wildcards.size(); --i >= 0;)
  48265. if (filename.matchesWildcard (wildcards[i], true))
  48266. return true;
  48267. return false;
  48268. }
  48269. END_JUCE_NAMESPACE
  48270. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48271. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48272. BEGIN_JUCE_NAMESPACE
  48273. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48274. {
  48275. }
  48276. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48277. {
  48278. }
  48279. namespace KeyboardFocusHelpers
  48280. {
  48281. // This will sort a set of components, so that they are ordered in terms of
  48282. // left-to-right and then top-to-bottom.
  48283. class ScreenPositionComparator
  48284. {
  48285. public:
  48286. ScreenPositionComparator() {}
  48287. static int compareElements (const Component* const first, const Component* const second)
  48288. {
  48289. int explicitOrder1 = first->getExplicitFocusOrder();
  48290. if (explicitOrder1 <= 0)
  48291. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48292. int explicitOrder2 = second->getExplicitFocusOrder();
  48293. if (explicitOrder2 <= 0)
  48294. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48295. if (explicitOrder1 != explicitOrder2)
  48296. return explicitOrder1 - explicitOrder2;
  48297. const int diff = first->getY() - second->getY();
  48298. return (diff == 0) ? first->getX() - second->getX()
  48299. : diff;
  48300. }
  48301. };
  48302. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48303. {
  48304. if (parent->getNumChildComponents() > 0)
  48305. {
  48306. Array <Component*> localComps;
  48307. ScreenPositionComparator comparator;
  48308. int i;
  48309. for (i = parent->getNumChildComponents(); --i >= 0;)
  48310. {
  48311. Component* const c = parent->getChildComponent (i);
  48312. if (c->isVisible() && c->isEnabled())
  48313. localComps.addSorted (comparator, c);
  48314. }
  48315. for (i = 0; i < localComps.size(); ++i)
  48316. {
  48317. Component* const c = localComps.getUnchecked (i);
  48318. if (c->getWantsKeyboardFocus())
  48319. comps.add (c);
  48320. if (! c->isFocusContainer())
  48321. findAllFocusableComponents (c, comps);
  48322. }
  48323. }
  48324. }
  48325. }
  48326. namespace KeyboardFocusHelpers
  48327. {
  48328. Component* getIncrementedComponent (Component* const current, const int delta)
  48329. {
  48330. Component* focusContainer = current->getParentComponent();
  48331. if (focusContainer != 0)
  48332. {
  48333. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48334. focusContainer = focusContainer->getParentComponent();
  48335. if (focusContainer != 0)
  48336. {
  48337. Array <Component*> comps;
  48338. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48339. if (comps.size() > 0)
  48340. {
  48341. const int index = comps.indexOf (current);
  48342. return comps [(index + comps.size() + delta) % comps.size()];
  48343. }
  48344. }
  48345. }
  48346. return 0;
  48347. }
  48348. }
  48349. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48350. {
  48351. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48352. }
  48353. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48354. {
  48355. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48356. }
  48357. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48358. {
  48359. Array <Component*> comps;
  48360. if (parentComponent != 0)
  48361. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48362. return comps.getFirst();
  48363. }
  48364. END_JUCE_NAMESPACE
  48365. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48366. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48367. BEGIN_JUCE_NAMESPACE
  48368. bool KeyListener::keyStateChanged (const bool, Component*)
  48369. {
  48370. return false;
  48371. }
  48372. END_JUCE_NAMESPACE
  48373. /*** End of inlined file: juce_KeyListener.cpp ***/
  48374. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48375. BEGIN_JUCE_NAMESPACE
  48376. // N.B. these two includes are put here deliberately to avoid problems with
  48377. // old GCCs failing on long include paths
  48378. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48379. {
  48380. public:
  48381. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48382. const CommandID commandID_,
  48383. const String& keyName,
  48384. const int keyNum_)
  48385. : Button (keyName),
  48386. owner (owner_),
  48387. commandID (commandID_),
  48388. keyNum (keyNum_)
  48389. {
  48390. setWantsKeyboardFocus (false);
  48391. setTriggeredOnMouseDown (keyNum >= 0);
  48392. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48393. : TRANS("click to change this key-mapping"));
  48394. }
  48395. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48396. {
  48397. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48398. keyNum >= 0 ? getName() : String::empty);
  48399. }
  48400. void clicked()
  48401. {
  48402. if (keyNum >= 0)
  48403. {
  48404. // existing key clicked..
  48405. PopupMenu m;
  48406. m.addItem (1, TRANS("change this key-mapping"));
  48407. m.addSeparator();
  48408. m.addItem (2, TRANS("remove this key-mapping"));
  48409. switch (m.show())
  48410. {
  48411. case 1: assignNewKey(); break;
  48412. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48413. default: break;
  48414. }
  48415. }
  48416. else
  48417. {
  48418. assignNewKey(); // + button pressed..
  48419. }
  48420. }
  48421. void fitToContent (const int h) throw()
  48422. {
  48423. if (keyNum < 0)
  48424. {
  48425. setSize (h, h);
  48426. }
  48427. else
  48428. {
  48429. Font f (h * 0.6f);
  48430. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48431. }
  48432. }
  48433. class KeyEntryWindow : public AlertWindow
  48434. {
  48435. public:
  48436. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48437. : AlertWindow (TRANS("New key-mapping"),
  48438. TRANS("Please press a key combination now..."),
  48439. AlertWindow::NoIcon),
  48440. owner (owner_)
  48441. {
  48442. addButton (TRANS("Ok"), 1);
  48443. addButton (TRANS("Cancel"), 0);
  48444. // (avoid return + escape keys getting processed by the buttons..)
  48445. for (int i = getNumChildComponents(); --i >= 0;)
  48446. getChildComponent (i)->setWantsKeyboardFocus (false);
  48447. setWantsKeyboardFocus (true);
  48448. grabKeyboardFocus();
  48449. }
  48450. bool keyPressed (const KeyPress& key)
  48451. {
  48452. lastPress = key;
  48453. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48454. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48455. if (previousCommand != 0)
  48456. message << "\n\n" << TRANS("(Currently assigned to \"")
  48457. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48458. setMessage (message);
  48459. return true;
  48460. }
  48461. bool keyStateChanged (bool)
  48462. {
  48463. return true;
  48464. }
  48465. KeyPress lastPress;
  48466. private:
  48467. KeyMappingEditorComponent& owner;
  48468. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48469. };
  48470. void assignNewKey()
  48471. {
  48472. KeyEntryWindow entryWindow (owner);
  48473. if (entryWindow.runModalLoop() != 0)
  48474. {
  48475. entryWindow.setVisible (false);
  48476. if (entryWindow.lastPress.isValid())
  48477. {
  48478. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48479. if (previousCommand == 0
  48480. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48481. TRANS("Change key-mapping"),
  48482. TRANS("This key is already assigned to the command \"")
  48483. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48484. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48485. TRANS("Re-assign"),
  48486. TRANS("Cancel")))
  48487. {
  48488. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48489. if (keyNum >= 0)
  48490. owner.getMappings().removeKeyPress (commandID, keyNum);
  48491. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48492. }
  48493. }
  48494. }
  48495. }
  48496. private:
  48497. KeyMappingEditorComponent& owner;
  48498. const CommandID commandID;
  48499. const int keyNum;
  48500. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48501. };
  48502. class KeyMappingEditorComponent::ItemComponent : public Component
  48503. {
  48504. public:
  48505. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48506. : owner (owner_), commandID (commandID_)
  48507. {
  48508. setInterceptsMouseClicks (false, true);
  48509. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48510. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48511. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48512. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48513. addKeyPressButton (String::empty, -1, isReadOnly);
  48514. }
  48515. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48516. {
  48517. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48518. keyChangeButtons.add (b);
  48519. b->setEnabled (! isReadOnly);
  48520. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48521. addChildComponent (b);
  48522. }
  48523. void paint (Graphics& g)
  48524. {
  48525. g.setFont (getHeight() * 0.7f);
  48526. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48527. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48528. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48529. Justification::centredLeft, true);
  48530. }
  48531. void resized()
  48532. {
  48533. int x = getWidth() - 4;
  48534. for (int i = keyChangeButtons.size(); --i >= 0;)
  48535. {
  48536. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48537. b->fitToContent (getHeight() - 2);
  48538. b->setTopRightPosition (x, 1);
  48539. x = b->getX() - 5;
  48540. }
  48541. }
  48542. private:
  48543. KeyMappingEditorComponent& owner;
  48544. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48545. const CommandID commandID;
  48546. enum { maxNumAssignments = 3 };
  48547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48548. };
  48549. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48550. {
  48551. public:
  48552. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48553. : owner (owner_), commandID (commandID_)
  48554. {
  48555. }
  48556. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48557. bool mightContainSubItems() { return false; }
  48558. int getItemHeight() const { return 20; }
  48559. Component* createItemComponent()
  48560. {
  48561. return new ItemComponent (owner, commandID);
  48562. }
  48563. private:
  48564. KeyMappingEditorComponent& owner;
  48565. const CommandID commandID;
  48566. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48567. };
  48568. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48569. {
  48570. public:
  48571. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48572. : owner (owner_), categoryName (name)
  48573. {
  48574. }
  48575. const String getUniqueName() const { return categoryName + "_cat"; }
  48576. bool mightContainSubItems() { return true; }
  48577. int getItemHeight() const { return 28; }
  48578. void paintItem (Graphics& g, int width, int height)
  48579. {
  48580. g.setFont (height * 0.6f, Font::bold);
  48581. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48582. g.drawText (categoryName,
  48583. 2, 0, width - 2, height,
  48584. Justification::centredLeft, true);
  48585. }
  48586. void itemOpennessChanged (bool isNowOpen)
  48587. {
  48588. if (isNowOpen)
  48589. {
  48590. if (getNumSubItems() == 0)
  48591. {
  48592. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48593. for (int i = 0; i < commands.size(); ++i)
  48594. {
  48595. if (owner.shouldCommandBeIncluded (commands[i]))
  48596. addSubItem (new MappingItem (owner, commands[i]));
  48597. }
  48598. }
  48599. }
  48600. else
  48601. {
  48602. clearSubItems();
  48603. }
  48604. }
  48605. private:
  48606. KeyMappingEditorComponent& owner;
  48607. String categoryName;
  48608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48609. };
  48610. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48611. public ChangeListener,
  48612. public ButtonListener
  48613. {
  48614. public:
  48615. TopLevelItem (KeyMappingEditorComponent& owner_)
  48616. : owner (owner_)
  48617. {
  48618. setLinesDrawnForSubItems (false);
  48619. owner.getMappings().addChangeListener (this);
  48620. }
  48621. ~TopLevelItem()
  48622. {
  48623. owner.getMappings().removeChangeListener (this);
  48624. }
  48625. bool mightContainSubItems() { return true; }
  48626. const String getUniqueName() const { return "keys"; }
  48627. void changeListenerCallback (ChangeBroadcaster*)
  48628. {
  48629. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48630. clearSubItems();
  48631. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48632. for (int i = 0; i < categories.size(); ++i)
  48633. {
  48634. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48635. int count = 0;
  48636. for (int j = 0; j < commands.size(); ++j)
  48637. if (owner.shouldCommandBeIncluded (commands[j]))
  48638. ++count;
  48639. if (count > 0)
  48640. addSubItem (new CategoryItem (owner, categories[i]));
  48641. }
  48642. if (oldOpenness != 0)
  48643. owner.tree.restoreOpennessState (*oldOpenness);
  48644. }
  48645. void buttonClicked (Button*)
  48646. {
  48647. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48648. TRANS("Reset to defaults"),
  48649. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48650. TRANS("Reset")))
  48651. {
  48652. owner.getMappings().resetToDefaultMappings();
  48653. }
  48654. }
  48655. private:
  48656. KeyMappingEditorComponent& owner;
  48657. };
  48658. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48659. const bool showResetToDefaultButton)
  48660. : mappings (mappingManager),
  48661. resetButton (TRANS ("reset to defaults"))
  48662. {
  48663. treeItem = new TopLevelItem (*this);
  48664. if (showResetToDefaultButton)
  48665. {
  48666. addAndMakeVisible (&resetButton);
  48667. resetButton.addButtonListener (treeItem);
  48668. }
  48669. addAndMakeVisible (&tree);
  48670. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48671. tree.setRootItemVisible (false);
  48672. tree.setDefaultOpenness (true);
  48673. tree.setRootItem (treeItem);
  48674. }
  48675. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48676. {
  48677. tree.setRootItem (0);
  48678. }
  48679. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48680. const Colour& textColour)
  48681. {
  48682. setColour (backgroundColourId, mainBackground);
  48683. setColour (textColourId, textColour);
  48684. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48685. }
  48686. void KeyMappingEditorComponent::parentHierarchyChanged()
  48687. {
  48688. treeItem->changeListenerCallback (0);
  48689. }
  48690. void KeyMappingEditorComponent::resized()
  48691. {
  48692. int h = getHeight();
  48693. if (resetButton.isVisible())
  48694. {
  48695. const int buttonHeight = 20;
  48696. h -= buttonHeight + 8;
  48697. int x = getWidth() - 8;
  48698. resetButton.changeWidthToFitText (buttonHeight);
  48699. resetButton.setTopRightPosition (x, h + 6);
  48700. }
  48701. tree.setBounds (0, 0, getWidth(), h);
  48702. }
  48703. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48704. {
  48705. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48706. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48707. }
  48708. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48709. {
  48710. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48711. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48712. }
  48713. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48714. {
  48715. return key.getTextDescription();
  48716. }
  48717. END_JUCE_NAMESPACE
  48718. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48719. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48720. BEGIN_JUCE_NAMESPACE
  48721. KeyPress::KeyPress() throw()
  48722. : keyCode (0),
  48723. mods (0),
  48724. textCharacter (0)
  48725. {
  48726. }
  48727. KeyPress::KeyPress (const int keyCode_,
  48728. const ModifierKeys& mods_,
  48729. const juce_wchar textCharacter_) throw()
  48730. : keyCode (keyCode_),
  48731. mods (mods_),
  48732. textCharacter (textCharacter_)
  48733. {
  48734. }
  48735. KeyPress::KeyPress (const int keyCode_) throw()
  48736. : keyCode (keyCode_),
  48737. textCharacter (0)
  48738. {
  48739. }
  48740. KeyPress::KeyPress (const KeyPress& other) throw()
  48741. : keyCode (other.keyCode),
  48742. mods (other.mods),
  48743. textCharacter (other.textCharacter)
  48744. {
  48745. }
  48746. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48747. {
  48748. keyCode = other.keyCode;
  48749. mods = other.mods;
  48750. textCharacter = other.textCharacter;
  48751. return *this;
  48752. }
  48753. bool KeyPress::operator== (const KeyPress& other) const throw()
  48754. {
  48755. return mods.getRawFlags() == other.mods.getRawFlags()
  48756. && (textCharacter == other.textCharacter
  48757. || textCharacter == 0
  48758. || other.textCharacter == 0)
  48759. && (keyCode == other.keyCode
  48760. || (keyCode < 256
  48761. && other.keyCode < 256
  48762. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48763. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48764. }
  48765. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48766. {
  48767. return ! operator== (other);
  48768. }
  48769. bool KeyPress::isCurrentlyDown() const
  48770. {
  48771. return isKeyCurrentlyDown (keyCode)
  48772. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48773. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48774. }
  48775. namespace KeyPressHelpers
  48776. {
  48777. struct KeyNameAndCode
  48778. {
  48779. const char* name;
  48780. int code;
  48781. };
  48782. const KeyNameAndCode translations[] =
  48783. {
  48784. { "spacebar", KeyPress::spaceKey },
  48785. { "return", KeyPress::returnKey },
  48786. { "escape", KeyPress::escapeKey },
  48787. { "backspace", KeyPress::backspaceKey },
  48788. { "cursor left", KeyPress::leftKey },
  48789. { "cursor right", KeyPress::rightKey },
  48790. { "cursor up", KeyPress::upKey },
  48791. { "cursor down", KeyPress::downKey },
  48792. { "page up", KeyPress::pageUpKey },
  48793. { "page down", KeyPress::pageDownKey },
  48794. { "home", KeyPress::homeKey },
  48795. { "end", KeyPress::endKey },
  48796. { "delete", KeyPress::deleteKey },
  48797. { "insert", KeyPress::insertKey },
  48798. { "tab", KeyPress::tabKey },
  48799. { "play", KeyPress::playKey },
  48800. { "stop", KeyPress::stopKey },
  48801. { "fast forward", KeyPress::fastForwardKey },
  48802. { "rewind", KeyPress::rewindKey }
  48803. };
  48804. const String numberPadPrefix() { return "numpad "; }
  48805. }
  48806. const KeyPress KeyPress::createFromDescription (const String& desc)
  48807. {
  48808. int modifiers = 0;
  48809. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48810. || desc.containsWholeWordIgnoreCase ("control")
  48811. || desc.containsWholeWordIgnoreCase ("ctl"))
  48812. modifiers |= ModifierKeys::ctrlModifier;
  48813. if (desc.containsWholeWordIgnoreCase ("shift")
  48814. || desc.containsWholeWordIgnoreCase ("shft"))
  48815. modifiers |= ModifierKeys::shiftModifier;
  48816. if (desc.containsWholeWordIgnoreCase ("alt")
  48817. || desc.containsWholeWordIgnoreCase ("option"))
  48818. modifiers |= ModifierKeys::altModifier;
  48819. if (desc.containsWholeWordIgnoreCase ("command")
  48820. || desc.containsWholeWordIgnoreCase ("cmd"))
  48821. modifiers |= ModifierKeys::commandModifier;
  48822. int key = 0;
  48823. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48824. {
  48825. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48826. {
  48827. key = KeyPressHelpers::translations[i].code;
  48828. break;
  48829. }
  48830. }
  48831. if (key == 0)
  48832. {
  48833. // see if it's a numpad key..
  48834. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48835. {
  48836. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48837. if (lastChar >= '0' && lastChar <= '9')
  48838. key = numberPad0 + lastChar - '0';
  48839. else if (lastChar == '+')
  48840. key = numberPadAdd;
  48841. else if (lastChar == '-')
  48842. key = numberPadSubtract;
  48843. else if (lastChar == '*')
  48844. key = numberPadMultiply;
  48845. else if (lastChar == '/')
  48846. key = numberPadDivide;
  48847. else if (lastChar == '.')
  48848. key = numberPadDecimalPoint;
  48849. else if (lastChar == '=')
  48850. key = numberPadEquals;
  48851. else if (desc.endsWith ("separator"))
  48852. key = numberPadSeparator;
  48853. else if (desc.endsWith ("delete"))
  48854. key = numberPadDelete;
  48855. }
  48856. if (key == 0)
  48857. {
  48858. // see if it's a function key..
  48859. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48860. for (int i = 1; i <= 12; ++i)
  48861. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48862. key = F1Key + i - 1;
  48863. if (key == 0)
  48864. {
  48865. // give up and use the hex code..
  48866. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48867. .toLowerCase()
  48868. .retainCharacters ("0123456789abcdef")
  48869. .getHexValue32();
  48870. if (hexCode > 0)
  48871. key = hexCode;
  48872. else
  48873. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48874. }
  48875. }
  48876. }
  48877. return KeyPress (key, ModifierKeys (modifiers), 0);
  48878. }
  48879. const String KeyPress::getTextDescription() const
  48880. {
  48881. String desc;
  48882. if (keyCode > 0)
  48883. {
  48884. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48885. // want to store it as being a slash, not shift+whatever.
  48886. if (textCharacter == '/')
  48887. return "/";
  48888. if (mods.isCtrlDown())
  48889. desc << "ctrl + ";
  48890. if (mods.isShiftDown())
  48891. desc << "shift + ";
  48892. #if JUCE_MAC
  48893. // only do this on the mac, because on Windows ctrl and command are the same,
  48894. // and this would get confusing
  48895. if (mods.isCommandDown())
  48896. desc << "command + ";
  48897. if (mods.isAltDown())
  48898. desc << "option + ";
  48899. #else
  48900. if (mods.isAltDown())
  48901. desc << "alt + ";
  48902. #endif
  48903. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48904. if (keyCode == KeyPressHelpers::translations[i].code)
  48905. return desc + KeyPressHelpers::translations[i].name;
  48906. if (keyCode >= F1Key && keyCode <= F16Key)
  48907. desc << 'F' << (1 + keyCode - F1Key);
  48908. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48909. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48910. else if (keyCode >= 33 && keyCode < 176)
  48911. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48912. else if (keyCode == numberPadAdd)
  48913. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48914. else if (keyCode == numberPadSubtract)
  48915. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48916. else if (keyCode == numberPadMultiply)
  48917. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48918. else if (keyCode == numberPadDivide)
  48919. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48920. else if (keyCode == numberPadSeparator)
  48921. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48922. else if (keyCode == numberPadDecimalPoint)
  48923. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48924. else if (keyCode == numberPadDelete)
  48925. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48926. else
  48927. desc << '#' << String::toHexString (keyCode);
  48928. }
  48929. return desc;
  48930. }
  48931. END_JUCE_NAMESPACE
  48932. /*** End of inlined file: juce_KeyPress.cpp ***/
  48933. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48934. BEGIN_JUCE_NAMESPACE
  48935. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48936. : commandManager (commandManager_)
  48937. {
  48938. // A manager is needed to get the descriptions of commands, and will be called when
  48939. // a command is invoked. So you can't leave this null..
  48940. jassert (commandManager_ != 0);
  48941. Desktop::getInstance().addFocusChangeListener (this);
  48942. }
  48943. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48944. : commandManager (other.commandManager)
  48945. {
  48946. Desktop::getInstance().addFocusChangeListener (this);
  48947. }
  48948. KeyPressMappingSet::~KeyPressMappingSet()
  48949. {
  48950. Desktop::getInstance().removeFocusChangeListener (this);
  48951. }
  48952. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48953. {
  48954. for (int i = 0; i < mappings.size(); ++i)
  48955. if (mappings.getUnchecked(i)->commandID == commandID)
  48956. return mappings.getUnchecked (i)->keypresses;
  48957. return Array <KeyPress> ();
  48958. }
  48959. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48960. const KeyPress& newKeyPress,
  48961. int insertIndex)
  48962. {
  48963. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48964. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48965. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48966. && ! newKeyPress.getModifiers().isShiftDown()));
  48967. if (findCommandForKeyPress (newKeyPress) != commandID)
  48968. {
  48969. removeKeyPress (newKeyPress);
  48970. if (newKeyPress.isValid())
  48971. {
  48972. for (int i = mappings.size(); --i >= 0;)
  48973. {
  48974. if (mappings.getUnchecked(i)->commandID == commandID)
  48975. {
  48976. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48977. sendChangeMessage();
  48978. return;
  48979. }
  48980. }
  48981. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48982. if (ci != 0)
  48983. {
  48984. CommandMapping* const cm = new CommandMapping();
  48985. cm->commandID = commandID;
  48986. cm->keypresses.add (newKeyPress);
  48987. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48988. mappings.add (cm);
  48989. sendChangeMessage();
  48990. }
  48991. }
  48992. }
  48993. }
  48994. void KeyPressMappingSet::resetToDefaultMappings()
  48995. {
  48996. mappings.clear();
  48997. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48998. {
  48999. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49000. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49001. {
  49002. addKeyPress (ci->commandID,
  49003. ci->defaultKeypresses.getReference (j));
  49004. }
  49005. }
  49006. sendChangeMessage();
  49007. }
  49008. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49009. {
  49010. clearAllKeyPresses (commandID);
  49011. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49012. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49013. {
  49014. addKeyPress (ci->commandID,
  49015. ci->defaultKeypresses.getReference (j));
  49016. }
  49017. }
  49018. void KeyPressMappingSet::clearAllKeyPresses()
  49019. {
  49020. if (mappings.size() > 0)
  49021. {
  49022. sendChangeMessage();
  49023. mappings.clear();
  49024. }
  49025. }
  49026. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49027. {
  49028. for (int i = mappings.size(); --i >= 0;)
  49029. {
  49030. if (mappings.getUnchecked(i)->commandID == commandID)
  49031. {
  49032. mappings.remove (i);
  49033. sendChangeMessage();
  49034. }
  49035. }
  49036. }
  49037. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49038. {
  49039. if (keypress.isValid())
  49040. {
  49041. for (int i = mappings.size(); --i >= 0;)
  49042. {
  49043. CommandMapping* const cm = mappings.getUnchecked(i);
  49044. for (int j = cm->keypresses.size(); --j >= 0;)
  49045. {
  49046. if (keypress == cm->keypresses [j])
  49047. {
  49048. cm->keypresses.remove (j);
  49049. sendChangeMessage();
  49050. }
  49051. }
  49052. }
  49053. }
  49054. }
  49055. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49056. {
  49057. for (int i = mappings.size(); --i >= 0;)
  49058. {
  49059. if (mappings.getUnchecked(i)->commandID == commandID)
  49060. {
  49061. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49062. sendChangeMessage();
  49063. break;
  49064. }
  49065. }
  49066. }
  49067. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49068. {
  49069. for (int i = 0; i < mappings.size(); ++i)
  49070. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49071. return mappings.getUnchecked(i)->commandID;
  49072. return 0;
  49073. }
  49074. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49075. {
  49076. for (int i = mappings.size(); --i >= 0;)
  49077. if (mappings.getUnchecked(i)->commandID == commandID)
  49078. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49079. return false;
  49080. }
  49081. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49082. const KeyPress& key,
  49083. const bool isKeyDown,
  49084. const int millisecsSinceKeyPressed,
  49085. Component* const originatingComponent) const
  49086. {
  49087. ApplicationCommandTarget::InvocationInfo info (commandID);
  49088. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49089. info.isKeyDown = isKeyDown;
  49090. info.keyPress = key;
  49091. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49092. info.originatingComponent = originatingComponent;
  49093. commandManager->invoke (info, false);
  49094. }
  49095. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49096. {
  49097. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49098. {
  49099. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49100. {
  49101. // if the XML was created as a set of differences from the default mappings,
  49102. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49103. resetToDefaultMappings();
  49104. }
  49105. else
  49106. {
  49107. // if the XML was created calling createXml (false), then we need to clear all
  49108. // the keys and treat the xml as describing the entire set of mappings.
  49109. clearAllKeyPresses();
  49110. }
  49111. forEachXmlChildElement (xmlVersion, map)
  49112. {
  49113. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49114. if (commandId != 0)
  49115. {
  49116. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49117. if (map->hasTagName ("MAPPING"))
  49118. {
  49119. addKeyPress (commandId, key);
  49120. }
  49121. else if (map->hasTagName ("UNMAPPING"))
  49122. {
  49123. if (containsMapping (commandId, key))
  49124. removeKeyPress (key);
  49125. }
  49126. }
  49127. }
  49128. return true;
  49129. }
  49130. return false;
  49131. }
  49132. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49133. {
  49134. ScopedPointer <KeyPressMappingSet> defaultSet;
  49135. if (saveDifferencesFromDefaultSet)
  49136. {
  49137. defaultSet = new KeyPressMappingSet (commandManager);
  49138. defaultSet->resetToDefaultMappings();
  49139. }
  49140. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49141. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49142. int i;
  49143. for (i = 0; i < mappings.size(); ++i)
  49144. {
  49145. const CommandMapping* const cm = mappings.getUnchecked(i);
  49146. for (int j = 0; j < cm->keypresses.size(); ++j)
  49147. {
  49148. if (defaultSet == 0
  49149. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49150. {
  49151. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49152. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49153. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49154. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49155. }
  49156. }
  49157. }
  49158. if (defaultSet != 0)
  49159. {
  49160. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49161. {
  49162. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49163. for (int j = 0; j < cm->keypresses.size(); ++j)
  49164. {
  49165. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49166. {
  49167. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49168. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49169. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49170. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49171. }
  49172. }
  49173. }
  49174. }
  49175. return doc;
  49176. }
  49177. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49178. Component* originatingComponent)
  49179. {
  49180. bool used = false;
  49181. const CommandID commandID = findCommandForKeyPress (key);
  49182. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49183. if (ci != 0
  49184. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49185. {
  49186. ApplicationCommandInfo info (0);
  49187. if (commandManager->getTargetForCommand (commandID, info) != 0
  49188. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49189. {
  49190. invokeCommand (commandID, key, true, 0, originatingComponent);
  49191. used = true;
  49192. }
  49193. else
  49194. {
  49195. if (originatingComponent != 0)
  49196. originatingComponent->getLookAndFeel().playAlertSound();
  49197. }
  49198. }
  49199. return used;
  49200. }
  49201. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49202. {
  49203. bool used = false;
  49204. const uint32 now = Time::getMillisecondCounter();
  49205. for (int i = mappings.size(); --i >= 0;)
  49206. {
  49207. CommandMapping* const cm = mappings.getUnchecked(i);
  49208. if (cm->wantsKeyUpDownCallbacks)
  49209. {
  49210. for (int j = cm->keypresses.size(); --j >= 0;)
  49211. {
  49212. const KeyPress key (cm->keypresses.getReference (j));
  49213. const bool isDown = key.isCurrentlyDown();
  49214. int keyPressEntryIndex = 0;
  49215. bool wasDown = false;
  49216. for (int k = keysDown.size(); --k >= 0;)
  49217. {
  49218. if (key == keysDown.getUnchecked(k)->key)
  49219. {
  49220. keyPressEntryIndex = k;
  49221. wasDown = true;
  49222. used = true;
  49223. break;
  49224. }
  49225. }
  49226. if (isDown != wasDown)
  49227. {
  49228. int millisecs = 0;
  49229. if (isDown)
  49230. {
  49231. KeyPressTime* const k = new KeyPressTime();
  49232. k->key = key;
  49233. k->timeWhenPressed = now;
  49234. keysDown.add (k);
  49235. }
  49236. else
  49237. {
  49238. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49239. if (now > pressTime)
  49240. millisecs = now - pressTime;
  49241. keysDown.remove (keyPressEntryIndex);
  49242. }
  49243. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49244. used = true;
  49245. }
  49246. }
  49247. }
  49248. }
  49249. return used;
  49250. }
  49251. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49252. {
  49253. if (focusedComponent != 0)
  49254. focusedComponent->keyStateChanged (false);
  49255. }
  49256. END_JUCE_NAMESPACE
  49257. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49258. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49259. BEGIN_JUCE_NAMESPACE
  49260. ModifierKeys::ModifierKeys (const int flags_) throw()
  49261. : flags (flags_)
  49262. {
  49263. }
  49264. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49265. : flags (other.flags)
  49266. {
  49267. }
  49268. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49269. {
  49270. flags = other.flags;
  49271. return *this;
  49272. }
  49273. ModifierKeys ModifierKeys::currentModifiers;
  49274. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49275. {
  49276. return currentModifiers;
  49277. }
  49278. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49279. {
  49280. int num = 0;
  49281. if (isLeftButtonDown()) ++num;
  49282. if (isRightButtonDown()) ++num;
  49283. if (isMiddleButtonDown()) ++num;
  49284. return num;
  49285. }
  49286. END_JUCE_NAMESPACE
  49287. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49288. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49289. BEGIN_JUCE_NAMESPACE
  49290. class ComponentAnimator::AnimationTask
  49291. {
  49292. public:
  49293. AnimationTask (Component* const comp)
  49294. : component (comp)
  49295. {
  49296. }
  49297. void reset (const Rectangle<int>& finalBounds,
  49298. float finalAlpha,
  49299. int millisecondsToSpendMoving,
  49300. bool useProxyComponent,
  49301. double startSpeed_, double endSpeed_)
  49302. {
  49303. msElapsed = 0;
  49304. msTotal = jmax (1, millisecondsToSpendMoving);
  49305. lastProgress = 0;
  49306. destination = finalBounds;
  49307. destAlpha = finalAlpha;
  49308. isMoving = (finalBounds != component->getBounds());
  49309. isChangingAlpha = (finalAlpha != component->getAlpha());
  49310. left = component->getX();
  49311. top = component->getY();
  49312. right = component->getRight();
  49313. bottom = component->getBottom();
  49314. alpha = component->getAlpha();
  49315. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49316. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49317. midSpeed = invTotalDistance;
  49318. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49319. if (useProxyComponent)
  49320. proxy = new ProxyComponent (*component);
  49321. else
  49322. proxy = 0;
  49323. component->setVisible (! useProxyComponent);
  49324. }
  49325. bool useTimeslice (const int elapsed)
  49326. {
  49327. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49328. : static_cast <Component*> (component);
  49329. if (c != 0)
  49330. {
  49331. msElapsed += elapsed;
  49332. double newProgress = msElapsed / (double) msTotal;
  49333. if (newProgress >= 0 && newProgress < 1.0)
  49334. {
  49335. newProgress = timeToDistance (newProgress);
  49336. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49337. jassert (newProgress >= lastProgress);
  49338. lastProgress = newProgress;
  49339. if (delta < 1.0)
  49340. {
  49341. bool stillBusy = false;
  49342. if (isMoving)
  49343. {
  49344. left += (destination.getX() - left) * delta;
  49345. top += (destination.getY() - top) * delta;
  49346. right += (destination.getRight() - right) * delta;
  49347. bottom += (destination.getBottom() - bottom) * delta;
  49348. const Rectangle<int> newBounds (roundToInt (left),
  49349. roundToInt (top),
  49350. roundToInt (right - left),
  49351. roundToInt (bottom - top));
  49352. if (newBounds != destination)
  49353. {
  49354. c->setBounds (newBounds);
  49355. stillBusy = true;
  49356. }
  49357. }
  49358. if (isChangingAlpha)
  49359. {
  49360. alpha += (destAlpha - alpha) * delta;
  49361. c->setAlpha ((float) alpha);
  49362. stillBusy = true;
  49363. }
  49364. if (stillBusy)
  49365. return true;
  49366. }
  49367. }
  49368. }
  49369. moveToFinalDestination();
  49370. return false;
  49371. }
  49372. void moveToFinalDestination()
  49373. {
  49374. if (component != 0)
  49375. {
  49376. component->setAlpha ((float) destAlpha);
  49377. component->setBounds (destination);
  49378. }
  49379. }
  49380. class ProxyComponent : public Component
  49381. {
  49382. public:
  49383. ProxyComponent (Component& component)
  49384. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49385. {
  49386. setBounds (component.getBounds());
  49387. setAlpha (component.getAlpha());
  49388. setInterceptsMouseClicks (false, false);
  49389. Component* const parent = component.getParentComponent();
  49390. if (parent != 0)
  49391. parent->addAndMakeVisible (this);
  49392. else if (component.isOnDesktop() && component.getPeer() != 0)
  49393. addToDesktop (component.getPeer()->getStyleFlags());
  49394. else
  49395. jassertfalse; // seem to be trying to animate a component that's not visible..
  49396. setVisible (true);
  49397. toBehind (&component);
  49398. }
  49399. void paint (Graphics& g)
  49400. {
  49401. g.setOpacity (1.0f);
  49402. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49403. 0, 0, image.getWidth(), image.getHeight());
  49404. }
  49405. private:
  49406. Image image;
  49407. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49408. };
  49409. Component::SafePointer<Component> component;
  49410. ScopedPointer<Component> proxy;
  49411. Rectangle<int> destination;
  49412. double destAlpha;
  49413. int msElapsed, msTotal;
  49414. double startSpeed, midSpeed, endSpeed, lastProgress;
  49415. double left, top, right, bottom, alpha;
  49416. bool isMoving, isChangingAlpha;
  49417. private:
  49418. double timeToDistance (const double time) const throw()
  49419. {
  49420. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49421. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49422. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49423. }
  49424. };
  49425. ComponentAnimator::ComponentAnimator()
  49426. : lastTime (0)
  49427. {
  49428. }
  49429. ComponentAnimator::~ComponentAnimator()
  49430. {
  49431. }
  49432. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49433. {
  49434. for (int i = tasks.size(); --i >= 0;)
  49435. if (component == tasks.getUnchecked(i)->component.getComponent())
  49436. return tasks.getUnchecked(i);
  49437. return 0;
  49438. }
  49439. void ComponentAnimator::animateComponent (Component* const component,
  49440. const Rectangle<int>& finalBounds,
  49441. const float finalAlpha,
  49442. const int millisecondsToSpendMoving,
  49443. const bool useProxyComponent,
  49444. const double startSpeed,
  49445. const double endSpeed)
  49446. {
  49447. // the speeds must be 0 or greater!
  49448. jassert (startSpeed >= 0 && endSpeed >= 0)
  49449. if (component != 0)
  49450. {
  49451. AnimationTask* at = findTaskFor (component);
  49452. if (at == 0)
  49453. {
  49454. at = new AnimationTask (component);
  49455. tasks.add (at);
  49456. sendChangeMessage();
  49457. }
  49458. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49459. useProxyComponent, startSpeed, endSpeed);
  49460. if (! isTimerRunning())
  49461. {
  49462. lastTime = Time::getMillisecondCounter();
  49463. startTimer (1000 / 50);
  49464. }
  49465. }
  49466. }
  49467. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49468. {
  49469. if (component != 0)
  49470. {
  49471. if (component->isShowing() && millisecondsToTake > 0)
  49472. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49473. component->setVisible (false);
  49474. }
  49475. }
  49476. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49477. {
  49478. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49479. {
  49480. component->setAlpha (0.0f);
  49481. component->setVisible (true);
  49482. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49483. }
  49484. }
  49485. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49486. {
  49487. if (tasks.size() > 0)
  49488. {
  49489. if (moveComponentsToTheirFinalPositions)
  49490. for (int i = tasks.size(); --i >= 0;)
  49491. tasks.getUnchecked(i)->moveToFinalDestination();
  49492. tasks.clear();
  49493. sendChangeMessage();
  49494. }
  49495. }
  49496. void ComponentAnimator::cancelAnimation (Component* const component,
  49497. const bool moveComponentToItsFinalPosition)
  49498. {
  49499. AnimationTask* const at = findTaskFor (component);
  49500. if (at != 0)
  49501. {
  49502. if (moveComponentToItsFinalPosition)
  49503. at->moveToFinalDestination();
  49504. tasks.removeObject (at);
  49505. sendChangeMessage();
  49506. }
  49507. }
  49508. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49509. {
  49510. jassert (component != 0);
  49511. AnimationTask* const at = findTaskFor (component);
  49512. if (at != 0)
  49513. return at->destination;
  49514. return component->getBounds();
  49515. }
  49516. bool ComponentAnimator::isAnimating (Component* component) const
  49517. {
  49518. return findTaskFor (component) != 0;
  49519. }
  49520. void ComponentAnimator::timerCallback()
  49521. {
  49522. const uint32 timeNow = Time::getMillisecondCounter();
  49523. if (lastTime == 0 || lastTime == timeNow)
  49524. lastTime = timeNow;
  49525. const int elapsed = timeNow - lastTime;
  49526. for (int i = tasks.size(); --i >= 0;)
  49527. {
  49528. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49529. {
  49530. tasks.remove (i);
  49531. sendChangeMessage();
  49532. }
  49533. }
  49534. lastTime = timeNow;
  49535. if (tasks.size() == 0)
  49536. stopTimer();
  49537. }
  49538. END_JUCE_NAMESPACE
  49539. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49540. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49541. BEGIN_JUCE_NAMESPACE
  49542. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49543. : minW (0),
  49544. maxW (0x3fffffff),
  49545. minH (0),
  49546. maxH (0x3fffffff),
  49547. minOffTop (0),
  49548. minOffLeft (0),
  49549. minOffBottom (0),
  49550. minOffRight (0),
  49551. aspectRatio (0.0)
  49552. {
  49553. }
  49554. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49555. {
  49556. }
  49557. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49558. {
  49559. minW = minimumWidth;
  49560. }
  49561. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49562. {
  49563. maxW = maximumWidth;
  49564. }
  49565. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49566. {
  49567. minH = minimumHeight;
  49568. }
  49569. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49570. {
  49571. maxH = maximumHeight;
  49572. }
  49573. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49574. {
  49575. jassert (maxW >= minimumWidth);
  49576. jassert (maxH >= minimumHeight);
  49577. jassert (minimumWidth > 0 && minimumHeight > 0);
  49578. minW = minimumWidth;
  49579. minH = minimumHeight;
  49580. if (minW > maxW)
  49581. maxW = minW;
  49582. if (minH > maxH)
  49583. maxH = minH;
  49584. }
  49585. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49586. {
  49587. jassert (maximumWidth >= minW);
  49588. jassert (maximumHeight >= minH);
  49589. jassert (maximumWidth > 0 && maximumHeight > 0);
  49590. maxW = jmax (minW, maximumWidth);
  49591. maxH = jmax (minH, maximumHeight);
  49592. }
  49593. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49594. const int minimumHeight,
  49595. const int maximumWidth,
  49596. const int maximumHeight) throw()
  49597. {
  49598. jassert (maximumWidth >= minimumWidth);
  49599. jassert (maximumHeight >= minimumHeight);
  49600. jassert (maximumWidth > 0 && maximumHeight > 0);
  49601. jassert (minimumWidth > 0 && minimumHeight > 0);
  49602. minW = jmax (0, minimumWidth);
  49603. minH = jmax (0, minimumHeight);
  49604. maxW = jmax (minW, maximumWidth);
  49605. maxH = jmax (minH, maximumHeight);
  49606. }
  49607. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49608. const int minimumWhenOffTheLeft,
  49609. const int minimumWhenOffTheBottom,
  49610. const int minimumWhenOffTheRight) throw()
  49611. {
  49612. minOffTop = minimumWhenOffTheTop;
  49613. minOffLeft = minimumWhenOffTheLeft;
  49614. minOffBottom = minimumWhenOffTheBottom;
  49615. minOffRight = minimumWhenOffTheRight;
  49616. }
  49617. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49618. {
  49619. aspectRatio = jmax (0.0, widthOverHeight);
  49620. }
  49621. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49622. {
  49623. return aspectRatio;
  49624. }
  49625. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49626. const Rectangle<int>& targetBounds,
  49627. const bool isStretchingTop,
  49628. const bool isStretchingLeft,
  49629. const bool isStretchingBottom,
  49630. const bool isStretchingRight)
  49631. {
  49632. jassert (component != 0);
  49633. Rectangle<int> limits, bounds (targetBounds);
  49634. BorderSize border;
  49635. Component* const parent = component->getParentComponent();
  49636. if (parent == 0)
  49637. {
  49638. ComponentPeer* peer = component->getPeer();
  49639. if (peer != 0)
  49640. border = peer->getFrameSize();
  49641. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49642. }
  49643. else
  49644. {
  49645. limits.setSize (parent->getWidth(), parent->getHeight());
  49646. }
  49647. border.addTo (bounds);
  49648. checkBounds (bounds,
  49649. border.addedTo (component->getBounds()), limits,
  49650. isStretchingTop, isStretchingLeft,
  49651. isStretchingBottom, isStretchingRight);
  49652. border.subtractFrom (bounds);
  49653. applyBoundsToComponent (component, bounds);
  49654. }
  49655. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49656. {
  49657. setBoundsForComponent (component, component->getBounds(),
  49658. false, false, false, false);
  49659. }
  49660. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49661. const Rectangle<int>& bounds)
  49662. {
  49663. component->setBounds (bounds);
  49664. }
  49665. void ComponentBoundsConstrainer::resizeStart()
  49666. {
  49667. }
  49668. void ComponentBoundsConstrainer::resizeEnd()
  49669. {
  49670. }
  49671. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49672. const Rectangle<int>& old,
  49673. const Rectangle<int>& limits,
  49674. const bool isStretchingTop,
  49675. const bool isStretchingLeft,
  49676. const bool isStretchingBottom,
  49677. const bool isStretchingRight)
  49678. {
  49679. // constrain the size if it's being stretched..
  49680. if (isStretchingLeft)
  49681. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49682. if (isStretchingRight)
  49683. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49684. if (isStretchingTop)
  49685. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49686. if (isStretchingBottom)
  49687. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49688. if (bounds.isEmpty())
  49689. return;
  49690. if (minOffTop > 0)
  49691. {
  49692. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49693. if (bounds.getY() < limit)
  49694. {
  49695. if (isStretchingTop)
  49696. bounds.setTop (limits.getY());
  49697. else
  49698. bounds.setY (limit);
  49699. }
  49700. }
  49701. if (minOffLeft > 0)
  49702. {
  49703. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49704. if (bounds.getX() < limit)
  49705. {
  49706. if (isStretchingLeft)
  49707. bounds.setLeft (limits.getX());
  49708. else
  49709. bounds.setX (limit);
  49710. }
  49711. }
  49712. if (minOffBottom > 0)
  49713. {
  49714. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49715. if (bounds.getY() > limit)
  49716. {
  49717. if (isStretchingBottom)
  49718. bounds.setBottom (limits.getBottom());
  49719. else
  49720. bounds.setY (limit);
  49721. }
  49722. }
  49723. if (minOffRight > 0)
  49724. {
  49725. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49726. if (bounds.getX() > limit)
  49727. {
  49728. if (isStretchingRight)
  49729. bounds.setRight (limits.getRight());
  49730. else
  49731. bounds.setX (limit);
  49732. }
  49733. }
  49734. // constrain the aspect ratio if one has been specified..
  49735. if (aspectRatio > 0.0)
  49736. {
  49737. bool adjustWidth;
  49738. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49739. {
  49740. adjustWidth = true;
  49741. }
  49742. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49743. {
  49744. adjustWidth = false;
  49745. }
  49746. else
  49747. {
  49748. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49749. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49750. adjustWidth = (oldRatio > newRatio);
  49751. }
  49752. if (adjustWidth)
  49753. {
  49754. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49755. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49756. {
  49757. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49758. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49759. }
  49760. }
  49761. else
  49762. {
  49763. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49764. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49765. {
  49766. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49767. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49768. }
  49769. }
  49770. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49771. {
  49772. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49773. }
  49774. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49775. {
  49776. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49777. }
  49778. else
  49779. {
  49780. if (isStretchingLeft)
  49781. bounds.setX (old.getRight() - bounds.getWidth());
  49782. if (isStretchingTop)
  49783. bounds.setY (old.getBottom() - bounds.getHeight());
  49784. }
  49785. }
  49786. jassert (! bounds.isEmpty());
  49787. }
  49788. END_JUCE_NAMESPACE
  49789. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49790. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49791. BEGIN_JUCE_NAMESPACE
  49792. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49793. : component (component_),
  49794. lastPeer (0),
  49795. reentrant (false)
  49796. {
  49797. jassert (component != 0); // can't use this with a null pointer..
  49798. component->addComponentListener (this);
  49799. registerWithParentComps();
  49800. }
  49801. ComponentMovementWatcher::~ComponentMovementWatcher()
  49802. {
  49803. component->removeComponentListener (this);
  49804. unregister();
  49805. }
  49806. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49807. {
  49808. // agh! don't delete the target component without deleting this object first!
  49809. jassert (component != 0);
  49810. if (! reentrant)
  49811. {
  49812. reentrant = true;
  49813. ComponentPeer* const peer = component->getPeer();
  49814. if (peer != lastPeer)
  49815. {
  49816. componentPeerChanged();
  49817. if (component == 0)
  49818. return;
  49819. lastPeer = peer;
  49820. }
  49821. unregister();
  49822. registerWithParentComps();
  49823. reentrant = false;
  49824. componentMovedOrResized (*component, true, true);
  49825. }
  49826. }
  49827. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49828. {
  49829. // agh! don't delete the target component without deleting this object first!
  49830. jassert (component != 0);
  49831. if (wasMoved)
  49832. {
  49833. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49834. wasMoved = lastBounds.getPosition() != pos;
  49835. lastBounds.setPosition (pos);
  49836. }
  49837. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49838. lastBounds.setSize (component->getWidth(), component->getHeight());
  49839. if (wasMoved || wasResized)
  49840. componentMovedOrResized (wasMoved, wasResized);
  49841. }
  49842. void ComponentMovementWatcher::registerWithParentComps()
  49843. {
  49844. Component* p = component->getParentComponent();
  49845. while (p != 0)
  49846. {
  49847. p->addComponentListener (this);
  49848. registeredParentComps.add (p);
  49849. p = p->getParentComponent();
  49850. }
  49851. }
  49852. void ComponentMovementWatcher::unregister()
  49853. {
  49854. for (int i = registeredParentComps.size(); --i >= 0;)
  49855. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49856. registeredParentComps.clear();
  49857. }
  49858. END_JUCE_NAMESPACE
  49859. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49860. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49861. BEGIN_JUCE_NAMESPACE
  49862. GroupComponent::GroupComponent (const String& componentName,
  49863. const String& labelText)
  49864. : Component (componentName),
  49865. text (labelText),
  49866. justification (Justification::left)
  49867. {
  49868. setInterceptsMouseClicks (false, true);
  49869. }
  49870. GroupComponent::~GroupComponent()
  49871. {
  49872. }
  49873. void GroupComponent::setText (const String& newText)
  49874. {
  49875. if (text != newText)
  49876. {
  49877. text = newText;
  49878. repaint();
  49879. }
  49880. }
  49881. const String GroupComponent::getText() const
  49882. {
  49883. return text;
  49884. }
  49885. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49886. {
  49887. if (justification != newJustification)
  49888. {
  49889. justification = newJustification;
  49890. repaint();
  49891. }
  49892. }
  49893. void GroupComponent::paint (Graphics& g)
  49894. {
  49895. getLookAndFeel()
  49896. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49897. text, justification,
  49898. *this);
  49899. }
  49900. void GroupComponent::enablementChanged()
  49901. {
  49902. repaint();
  49903. }
  49904. void GroupComponent::colourChanged()
  49905. {
  49906. repaint();
  49907. }
  49908. END_JUCE_NAMESPACE
  49909. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49910. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49911. BEGIN_JUCE_NAMESPACE
  49912. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49913. : DocumentWindow (String::empty, backgroundColour,
  49914. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49915. {
  49916. }
  49917. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49918. {
  49919. }
  49920. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49921. {
  49922. MultiDocumentPanel* const owner = getOwner();
  49923. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49924. if (owner != 0)
  49925. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49926. }
  49927. void MultiDocumentPanelWindow::closeButtonPressed()
  49928. {
  49929. MultiDocumentPanel* const owner = getOwner();
  49930. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49931. if (owner != 0)
  49932. owner->closeDocument (getContentComponent(), true);
  49933. }
  49934. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49935. {
  49936. DocumentWindow::activeWindowStatusChanged();
  49937. updateOrder();
  49938. }
  49939. void MultiDocumentPanelWindow::broughtToFront()
  49940. {
  49941. DocumentWindow::broughtToFront();
  49942. updateOrder();
  49943. }
  49944. void MultiDocumentPanelWindow::updateOrder()
  49945. {
  49946. MultiDocumentPanel* const owner = getOwner();
  49947. if (owner != 0)
  49948. owner->updateOrder();
  49949. }
  49950. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49951. {
  49952. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49953. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49954. }
  49955. class MDITabbedComponentInternal : public TabbedComponent
  49956. {
  49957. public:
  49958. MDITabbedComponentInternal()
  49959. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49960. {
  49961. }
  49962. ~MDITabbedComponentInternal()
  49963. {
  49964. }
  49965. void currentTabChanged (int, const String&)
  49966. {
  49967. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49968. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49969. if (owner != 0)
  49970. owner->updateOrder();
  49971. }
  49972. };
  49973. MultiDocumentPanel::MultiDocumentPanel()
  49974. : mode (MaximisedWindowsWithTabs),
  49975. backgroundColour (Colours::lightblue),
  49976. maximumNumDocuments (0),
  49977. numDocsBeforeTabsUsed (0)
  49978. {
  49979. setOpaque (true);
  49980. }
  49981. MultiDocumentPanel::~MultiDocumentPanel()
  49982. {
  49983. closeAllDocuments (false);
  49984. }
  49985. namespace MultiDocHelpers
  49986. {
  49987. bool shouldDeleteComp (Component* const c)
  49988. {
  49989. return c->getProperties() ["mdiDocumentDelete_"];
  49990. }
  49991. }
  49992. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49993. {
  49994. while (components.size() > 0)
  49995. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49996. return false;
  49997. return true;
  49998. }
  49999. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50000. {
  50001. return new MultiDocumentPanelWindow (backgroundColour);
  50002. }
  50003. void MultiDocumentPanel::addWindow (Component* component)
  50004. {
  50005. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50006. dw->setResizable (true, false);
  50007. dw->setContentComponent (component, false, true);
  50008. dw->setName (component->getName());
  50009. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50010. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50011. int x = 4;
  50012. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50013. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50014. x += 16;
  50015. dw->setTopLeftPosition (x, x);
  50016. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50017. if (pos.toString().isNotEmpty())
  50018. dw->restoreWindowStateFromString (pos.toString());
  50019. addAndMakeVisible (dw);
  50020. dw->toFront (true);
  50021. }
  50022. bool MultiDocumentPanel::addDocument (Component* const component,
  50023. const Colour& docColour,
  50024. const bool deleteWhenRemoved)
  50025. {
  50026. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50027. // with a frame-within-a-frame! Just pass in the bare content component.
  50028. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50029. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50030. return false;
  50031. components.add (component);
  50032. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50033. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50034. component->addComponentListener (this);
  50035. if (mode == FloatingWindows)
  50036. {
  50037. if (isFullscreenWhenOneDocument())
  50038. {
  50039. if (components.size() == 1)
  50040. {
  50041. addAndMakeVisible (component);
  50042. }
  50043. else
  50044. {
  50045. if (components.size() == 2)
  50046. addWindow (components.getFirst());
  50047. addWindow (component);
  50048. }
  50049. }
  50050. else
  50051. {
  50052. addWindow (component);
  50053. }
  50054. }
  50055. else
  50056. {
  50057. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50058. {
  50059. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50060. Array <Component*> temp (components);
  50061. for (int i = 0; i < temp.size(); ++i)
  50062. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50063. resized();
  50064. }
  50065. else
  50066. {
  50067. if (tabComponent != 0)
  50068. tabComponent->addTab (component->getName(), docColour, component, false);
  50069. else
  50070. addAndMakeVisible (component);
  50071. }
  50072. setActiveDocument (component);
  50073. }
  50074. resized();
  50075. activeDocumentChanged();
  50076. return true;
  50077. }
  50078. bool MultiDocumentPanel::closeDocument (Component* component,
  50079. const bool checkItsOkToCloseFirst)
  50080. {
  50081. if (components.contains (component))
  50082. {
  50083. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50084. return false;
  50085. component->removeComponentListener (this);
  50086. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50087. component->getProperties().remove ("mdiDocumentDelete_");
  50088. component->getProperties().remove ("mdiDocumentBkg_");
  50089. if (mode == FloatingWindows)
  50090. {
  50091. for (int i = getNumChildComponents(); --i >= 0;)
  50092. {
  50093. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50094. if (dw != 0 && dw->getContentComponent() == component)
  50095. {
  50096. dw->setContentComponent (0, false);
  50097. delete dw;
  50098. break;
  50099. }
  50100. }
  50101. if (shouldDelete)
  50102. delete component;
  50103. components.removeValue (component);
  50104. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50105. {
  50106. for (int i = getNumChildComponents(); --i >= 0;)
  50107. {
  50108. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50109. if (dw != 0)
  50110. {
  50111. dw->setContentComponent (0, false);
  50112. delete dw;
  50113. }
  50114. }
  50115. addAndMakeVisible (components.getFirst());
  50116. }
  50117. }
  50118. else
  50119. {
  50120. jassert (components.indexOf (component) >= 0);
  50121. if (tabComponent != 0)
  50122. {
  50123. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50124. if (tabComponent->getTabContentComponent (i) == component)
  50125. tabComponent->removeTab (i);
  50126. }
  50127. else
  50128. {
  50129. removeChildComponent (component);
  50130. }
  50131. if (shouldDelete)
  50132. delete component;
  50133. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50134. tabComponent = 0;
  50135. components.removeValue (component);
  50136. if (components.size() > 0 && tabComponent == 0)
  50137. addAndMakeVisible (components.getFirst());
  50138. }
  50139. resized();
  50140. activeDocumentChanged();
  50141. }
  50142. else
  50143. {
  50144. jassertfalse;
  50145. }
  50146. return true;
  50147. }
  50148. int MultiDocumentPanel::getNumDocuments() const throw()
  50149. {
  50150. return components.size();
  50151. }
  50152. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50153. {
  50154. return components [index];
  50155. }
  50156. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50157. {
  50158. if (mode == FloatingWindows)
  50159. {
  50160. for (int i = getNumChildComponents(); --i >= 0;)
  50161. {
  50162. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50163. if (dw != 0 && dw->isActiveWindow())
  50164. return dw->getContentComponent();
  50165. }
  50166. }
  50167. return components.getLast();
  50168. }
  50169. void MultiDocumentPanel::setActiveDocument (Component* component)
  50170. {
  50171. if (mode == FloatingWindows)
  50172. {
  50173. component = getContainerComp (component);
  50174. if (component != 0)
  50175. component->toFront (true);
  50176. }
  50177. else if (tabComponent != 0)
  50178. {
  50179. jassert (components.indexOf (component) >= 0);
  50180. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50181. {
  50182. if (tabComponent->getTabContentComponent (i) == component)
  50183. {
  50184. tabComponent->setCurrentTabIndex (i);
  50185. break;
  50186. }
  50187. }
  50188. }
  50189. else
  50190. {
  50191. component->grabKeyboardFocus();
  50192. }
  50193. }
  50194. void MultiDocumentPanel::activeDocumentChanged()
  50195. {
  50196. }
  50197. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50198. {
  50199. maximumNumDocuments = newNumber;
  50200. }
  50201. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50202. {
  50203. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50204. }
  50205. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50206. {
  50207. return numDocsBeforeTabsUsed != 0;
  50208. }
  50209. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50210. {
  50211. if (mode != newLayoutMode)
  50212. {
  50213. mode = newLayoutMode;
  50214. if (mode == FloatingWindows)
  50215. {
  50216. tabComponent = 0;
  50217. }
  50218. else
  50219. {
  50220. for (int i = getNumChildComponents(); --i >= 0;)
  50221. {
  50222. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50223. if (dw != 0)
  50224. {
  50225. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50226. dw->setContentComponent (0, false);
  50227. delete dw;
  50228. }
  50229. }
  50230. }
  50231. resized();
  50232. const Array <Component*> tempComps (components);
  50233. components.clear();
  50234. for (int i = 0; i < tempComps.size(); ++i)
  50235. {
  50236. Component* const c = tempComps.getUnchecked(i);
  50237. addDocument (c,
  50238. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50239. MultiDocHelpers::shouldDeleteComp (c));
  50240. }
  50241. }
  50242. }
  50243. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50244. {
  50245. if (backgroundColour != newBackgroundColour)
  50246. {
  50247. backgroundColour = newBackgroundColour;
  50248. setOpaque (newBackgroundColour.isOpaque());
  50249. repaint();
  50250. }
  50251. }
  50252. void MultiDocumentPanel::paint (Graphics& g)
  50253. {
  50254. g.fillAll (backgroundColour);
  50255. }
  50256. void MultiDocumentPanel::resized()
  50257. {
  50258. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50259. {
  50260. for (int i = getNumChildComponents(); --i >= 0;)
  50261. getChildComponent (i)->setBounds (getLocalBounds());
  50262. }
  50263. setWantsKeyboardFocus (components.size() == 0);
  50264. }
  50265. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50266. {
  50267. if (mode == FloatingWindows)
  50268. {
  50269. for (int i = 0; i < getNumChildComponents(); ++i)
  50270. {
  50271. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50272. if (dw != 0 && dw->getContentComponent() == c)
  50273. {
  50274. c = dw;
  50275. break;
  50276. }
  50277. }
  50278. }
  50279. return c;
  50280. }
  50281. void MultiDocumentPanel::componentNameChanged (Component&)
  50282. {
  50283. if (mode == FloatingWindows)
  50284. {
  50285. for (int i = 0; i < getNumChildComponents(); ++i)
  50286. {
  50287. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50288. if (dw != 0)
  50289. dw->setName (dw->getContentComponent()->getName());
  50290. }
  50291. }
  50292. else if (tabComponent != 0)
  50293. {
  50294. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50295. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50296. }
  50297. }
  50298. void MultiDocumentPanel::updateOrder()
  50299. {
  50300. const Array <Component*> oldList (components);
  50301. if (mode == FloatingWindows)
  50302. {
  50303. components.clear();
  50304. for (int i = 0; i < getNumChildComponents(); ++i)
  50305. {
  50306. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50307. if (dw != 0)
  50308. components.add (dw->getContentComponent());
  50309. }
  50310. }
  50311. else
  50312. {
  50313. if (tabComponent != 0)
  50314. {
  50315. Component* const current = tabComponent->getCurrentContentComponent();
  50316. if (current != 0)
  50317. {
  50318. components.removeValue (current);
  50319. components.add (current);
  50320. }
  50321. }
  50322. }
  50323. if (components != oldList)
  50324. activeDocumentChanged();
  50325. }
  50326. END_JUCE_NAMESPACE
  50327. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50328. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50329. BEGIN_JUCE_NAMESPACE
  50330. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50331. : zone (zoneFlags)
  50332. {}
  50333. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50334. : zone (other.zone)
  50335. {}
  50336. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50337. {
  50338. zone = other.zone;
  50339. return *this;
  50340. }
  50341. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50342. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50343. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50344. const BorderSize& border,
  50345. const Point<int>& position)
  50346. {
  50347. int z = 0;
  50348. if (totalSize.contains (position)
  50349. && ! border.subtractedFrom (totalSize).contains (position))
  50350. {
  50351. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50352. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50353. z |= left;
  50354. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50355. z |= right;
  50356. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50357. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50358. z |= top;
  50359. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50360. z |= bottom;
  50361. }
  50362. return Zone (z);
  50363. }
  50364. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50365. {
  50366. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50367. switch (zone)
  50368. {
  50369. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50370. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50371. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50372. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50373. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50374. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50375. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50376. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50377. default: break;
  50378. }
  50379. return mc;
  50380. }
  50381. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50382. ComponentBoundsConstrainer* const constrainer_)
  50383. : component (componentToResize),
  50384. constrainer (constrainer_),
  50385. borderSize (5),
  50386. mouseZone (0)
  50387. {
  50388. }
  50389. ResizableBorderComponent::~ResizableBorderComponent()
  50390. {
  50391. }
  50392. void ResizableBorderComponent::paint (Graphics& g)
  50393. {
  50394. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50395. }
  50396. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50397. {
  50398. updateMouseZone (e);
  50399. }
  50400. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50401. {
  50402. updateMouseZone (e);
  50403. }
  50404. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50405. {
  50406. if (component == 0)
  50407. {
  50408. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50409. return;
  50410. }
  50411. updateMouseZone (e);
  50412. originalBounds = component->getBounds();
  50413. if (constrainer != 0)
  50414. constrainer->resizeStart();
  50415. }
  50416. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50417. {
  50418. if (component == 0)
  50419. {
  50420. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50421. return;
  50422. }
  50423. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50424. if (constrainer != 0)
  50425. constrainer->setBoundsForComponent (component, bounds,
  50426. mouseZone.isDraggingTopEdge(),
  50427. mouseZone.isDraggingLeftEdge(),
  50428. mouseZone.isDraggingBottomEdge(),
  50429. mouseZone.isDraggingRightEdge());
  50430. else
  50431. component->setBounds (bounds);
  50432. }
  50433. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50434. {
  50435. if (constrainer != 0)
  50436. constrainer->resizeEnd();
  50437. }
  50438. bool ResizableBorderComponent::hitTest (int x, int y)
  50439. {
  50440. return x < borderSize.getLeft()
  50441. || x >= getWidth() - borderSize.getRight()
  50442. || y < borderSize.getTop()
  50443. || y >= getHeight() - borderSize.getBottom();
  50444. }
  50445. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50446. {
  50447. if (borderSize != newBorderSize)
  50448. {
  50449. borderSize = newBorderSize;
  50450. repaint();
  50451. }
  50452. }
  50453. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50454. {
  50455. return borderSize;
  50456. }
  50457. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50458. {
  50459. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50460. if (mouseZone != newZone)
  50461. {
  50462. mouseZone = newZone;
  50463. setMouseCursor (newZone.getMouseCursor());
  50464. }
  50465. }
  50466. END_JUCE_NAMESPACE
  50467. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50468. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50469. BEGIN_JUCE_NAMESPACE
  50470. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50471. ComponentBoundsConstrainer* const constrainer_)
  50472. : component (componentToResize),
  50473. constrainer (constrainer_)
  50474. {
  50475. setRepaintsOnMouseActivity (true);
  50476. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50477. }
  50478. ResizableCornerComponent::~ResizableCornerComponent()
  50479. {
  50480. }
  50481. void ResizableCornerComponent::paint (Graphics& g)
  50482. {
  50483. getLookAndFeel()
  50484. .drawCornerResizer (g, getWidth(), getHeight(),
  50485. isMouseOverOrDragging(),
  50486. isMouseButtonDown());
  50487. }
  50488. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50489. {
  50490. if (component == 0)
  50491. {
  50492. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50493. return;
  50494. }
  50495. originalBounds = component->getBounds();
  50496. if (constrainer != 0)
  50497. constrainer->resizeStart();
  50498. }
  50499. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50500. {
  50501. if (component == 0)
  50502. {
  50503. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50504. return;
  50505. }
  50506. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50507. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50508. if (constrainer != 0)
  50509. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50510. else
  50511. component->setBounds (r);
  50512. }
  50513. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50514. {
  50515. if (constrainer != 0)
  50516. constrainer->resizeStart();
  50517. }
  50518. bool ResizableCornerComponent::hitTest (int x, int y)
  50519. {
  50520. if (getWidth() <= 0)
  50521. return false;
  50522. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50523. return y >= yAtX - getHeight() / 4;
  50524. }
  50525. END_JUCE_NAMESPACE
  50526. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50527. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50528. BEGIN_JUCE_NAMESPACE
  50529. class ScrollBar::ScrollbarButton : public Button
  50530. {
  50531. public:
  50532. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50533. : Button (String::empty),
  50534. direction (direction_),
  50535. owner (owner_)
  50536. {
  50537. setWantsKeyboardFocus (false);
  50538. }
  50539. void paintButton (Graphics& g, bool over, bool down)
  50540. {
  50541. getLookAndFeel()
  50542. .drawScrollbarButton (g, owner,
  50543. getWidth(), getHeight(),
  50544. direction,
  50545. owner.isVertical(),
  50546. over, down);
  50547. }
  50548. void clicked()
  50549. {
  50550. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50551. }
  50552. int direction;
  50553. private:
  50554. ScrollBar& owner;
  50555. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50556. };
  50557. ScrollBar::ScrollBar (const bool vertical_,
  50558. const bool buttonsAreVisible)
  50559. : totalRange (0.0, 1.0),
  50560. visibleRange (0.0, 0.1),
  50561. singleStepSize (0.1),
  50562. thumbAreaStart (0),
  50563. thumbAreaSize (0),
  50564. thumbStart (0),
  50565. thumbSize (0),
  50566. initialDelayInMillisecs (100),
  50567. repeatDelayInMillisecs (50),
  50568. minimumDelayInMillisecs (10),
  50569. vertical (vertical_),
  50570. isDraggingThumb (false),
  50571. autohides (true)
  50572. {
  50573. setButtonVisibility (buttonsAreVisible);
  50574. setRepaintsOnMouseActivity (true);
  50575. setFocusContainer (true);
  50576. }
  50577. ScrollBar::~ScrollBar()
  50578. {
  50579. upButton = 0;
  50580. downButton = 0;
  50581. }
  50582. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50583. {
  50584. if (totalRange != newRangeLimit)
  50585. {
  50586. totalRange = newRangeLimit;
  50587. setCurrentRange (visibleRange);
  50588. updateThumbPosition();
  50589. }
  50590. }
  50591. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50592. {
  50593. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50594. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50595. }
  50596. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50597. {
  50598. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50599. if (visibleRange != constrainedRange)
  50600. {
  50601. visibleRange = constrainedRange;
  50602. updateThumbPosition();
  50603. triggerAsyncUpdate();
  50604. }
  50605. }
  50606. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50607. {
  50608. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50609. }
  50610. void ScrollBar::setCurrentRangeStart (const double newStart)
  50611. {
  50612. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50613. }
  50614. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50615. {
  50616. singleStepSize = newSingleStepSize;
  50617. }
  50618. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50619. {
  50620. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50621. }
  50622. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50623. {
  50624. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50625. }
  50626. void ScrollBar::scrollToTop()
  50627. {
  50628. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50629. }
  50630. void ScrollBar::scrollToBottom()
  50631. {
  50632. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50633. }
  50634. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50635. const int repeatDelayInMillisecs_,
  50636. const int minimumDelayInMillisecs_)
  50637. {
  50638. initialDelayInMillisecs = initialDelayInMillisecs_;
  50639. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50640. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50641. if (upButton != 0)
  50642. {
  50643. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50644. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50645. }
  50646. }
  50647. void ScrollBar::addListener (Listener* const listener)
  50648. {
  50649. listeners.add (listener);
  50650. }
  50651. void ScrollBar::removeListener (Listener* const listener)
  50652. {
  50653. listeners.remove (listener);
  50654. }
  50655. void ScrollBar::handleAsyncUpdate()
  50656. {
  50657. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50658. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50659. }
  50660. void ScrollBar::updateThumbPosition()
  50661. {
  50662. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50663. : thumbAreaSize);
  50664. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50665. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50666. if (newThumbSize > thumbAreaSize)
  50667. newThumbSize = thumbAreaSize;
  50668. int newThumbStart = thumbAreaStart;
  50669. if (totalRange.getLength() > visibleRange.getLength())
  50670. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50671. / (totalRange.getLength() - visibleRange.getLength()));
  50672. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50673. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50674. {
  50675. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50676. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50677. if (vertical)
  50678. repaint (0, repaintStart, getWidth(), repaintSize);
  50679. else
  50680. repaint (repaintStart, 0, repaintSize, getHeight());
  50681. thumbStart = newThumbStart;
  50682. thumbSize = newThumbSize;
  50683. }
  50684. }
  50685. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50686. {
  50687. if (vertical != shouldBeVertical)
  50688. {
  50689. vertical = shouldBeVertical;
  50690. if (upButton != 0)
  50691. {
  50692. upButton->direction = vertical ? 0 : 3;
  50693. downButton->direction = vertical ? 2 : 1;
  50694. }
  50695. updateThumbPosition();
  50696. }
  50697. }
  50698. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50699. {
  50700. upButton = 0;
  50701. downButton = 0;
  50702. if (buttonsAreVisible)
  50703. {
  50704. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50705. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50706. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50707. }
  50708. updateThumbPosition();
  50709. }
  50710. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50711. {
  50712. autohides = shouldHideWhenFullRange;
  50713. updateThumbPosition();
  50714. }
  50715. bool ScrollBar::autoHides() const throw()
  50716. {
  50717. return autohides;
  50718. }
  50719. void ScrollBar::paint (Graphics& g)
  50720. {
  50721. if (thumbAreaSize > 0)
  50722. {
  50723. LookAndFeel& lf = getLookAndFeel();
  50724. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50725. ? thumbSize : 0;
  50726. if (vertical)
  50727. {
  50728. lf.drawScrollbar (g, *this,
  50729. 0, thumbAreaStart,
  50730. getWidth(), thumbAreaSize,
  50731. vertical,
  50732. thumbStart, thumb,
  50733. isMouseOver(), isMouseButtonDown());
  50734. }
  50735. else
  50736. {
  50737. lf.drawScrollbar (g, *this,
  50738. thumbAreaStart, 0,
  50739. thumbAreaSize, getHeight(),
  50740. vertical,
  50741. thumbStart, thumb,
  50742. isMouseOver(), isMouseButtonDown());
  50743. }
  50744. }
  50745. }
  50746. void ScrollBar::lookAndFeelChanged()
  50747. {
  50748. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50749. }
  50750. void ScrollBar::resized()
  50751. {
  50752. const int length = ((vertical) ? getHeight() : getWidth());
  50753. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50754. : 0;
  50755. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50756. {
  50757. thumbAreaStart = length >> 1;
  50758. thumbAreaSize = 0;
  50759. }
  50760. else
  50761. {
  50762. thumbAreaStart = buttonSize;
  50763. thumbAreaSize = length - (buttonSize << 1);
  50764. }
  50765. if (upButton != 0)
  50766. {
  50767. if (vertical)
  50768. {
  50769. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50770. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50771. }
  50772. else
  50773. {
  50774. upButton->setBounds (0, 0, buttonSize, getHeight());
  50775. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50776. }
  50777. }
  50778. updateThumbPosition();
  50779. }
  50780. void ScrollBar::mouseDown (const MouseEvent& e)
  50781. {
  50782. isDraggingThumb = false;
  50783. lastMousePos = vertical ? e.y : e.x;
  50784. dragStartMousePos = lastMousePos;
  50785. dragStartRange = visibleRange.getStart();
  50786. if (dragStartMousePos < thumbStart)
  50787. {
  50788. moveScrollbarInPages (-1);
  50789. startTimer (400);
  50790. }
  50791. else if (dragStartMousePos >= thumbStart + thumbSize)
  50792. {
  50793. moveScrollbarInPages (1);
  50794. startTimer (400);
  50795. }
  50796. else
  50797. {
  50798. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50799. && (thumbAreaSize > thumbSize);
  50800. }
  50801. }
  50802. void ScrollBar::mouseDrag (const MouseEvent& e)
  50803. {
  50804. const int mousePos = vertical ? e.y : e.x;
  50805. if (isDraggingThumb && lastMousePos != mousePos)
  50806. {
  50807. const int deltaPixels = mousePos - dragStartMousePos;
  50808. setCurrentRangeStart (dragStartRange
  50809. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50810. / (thumbAreaSize - thumbSize));
  50811. }
  50812. lastMousePos = mousePos;
  50813. }
  50814. void ScrollBar::mouseUp (const MouseEvent&)
  50815. {
  50816. isDraggingThumb = false;
  50817. stopTimer();
  50818. repaint();
  50819. }
  50820. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50821. float wheelIncrementX,
  50822. float wheelIncrementY)
  50823. {
  50824. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50825. if (increment < 0)
  50826. increment = jmin (increment * 10.0f, -1.0f);
  50827. else if (increment > 0)
  50828. increment = jmax (increment * 10.0f, 1.0f);
  50829. setCurrentRange (visibleRange - singleStepSize * increment);
  50830. }
  50831. void ScrollBar::timerCallback()
  50832. {
  50833. if (isMouseButtonDown())
  50834. {
  50835. startTimer (40);
  50836. if (lastMousePos < thumbStart)
  50837. setCurrentRange (visibleRange - visibleRange.getLength());
  50838. else if (lastMousePos > thumbStart + thumbSize)
  50839. setCurrentRangeStart (visibleRange.getEnd());
  50840. }
  50841. else
  50842. {
  50843. stopTimer();
  50844. }
  50845. }
  50846. bool ScrollBar::keyPressed (const KeyPress& key)
  50847. {
  50848. if (! isVisible())
  50849. return false;
  50850. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50851. moveScrollbarInSteps (-1);
  50852. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50853. moveScrollbarInSteps (1);
  50854. else if (key.isKeyCode (KeyPress::pageUpKey))
  50855. moveScrollbarInPages (-1);
  50856. else if (key.isKeyCode (KeyPress::pageDownKey))
  50857. moveScrollbarInPages (1);
  50858. else if (key.isKeyCode (KeyPress::homeKey))
  50859. scrollToTop();
  50860. else if (key.isKeyCode (KeyPress::endKey))
  50861. scrollToBottom();
  50862. else
  50863. return false;
  50864. return true;
  50865. }
  50866. END_JUCE_NAMESPACE
  50867. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50868. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50869. BEGIN_JUCE_NAMESPACE
  50870. StretchableLayoutManager::StretchableLayoutManager()
  50871. : totalSize (0)
  50872. {
  50873. }
  50874. StretchableLayoutManager::~StretchableLayoutManager()
  50875. {
  50876. }
  50877. void StretchableLayoutManager::clearAllItems()
  50878. {
  50879. items.clear();
  50880. totalSize = 0;
  50881. }
  50882. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50883. const double minimumSize,
  50884. const double maximumSize,
  50885. const double preferredSize)
  50886. {
  50887. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50888. if (layout == 0)
  50889. {
  50890. layout = new ItemLayoutProperties();
  50891. layout->itemIndex = itemIndex;
  50892. int i;
  50893. for (i = 0; i < items.size(); ++i)
  50894. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50895. break;
  50896. items.insert (i, layout);
  50897. }
  50898. layout->minSize = minimumSize;
  50899. layout->maxSize = maximumSize;
  50900. layout->preferredSize = preferredSize;
  50901. layout->currentSize = 0;
  50902. }
  50903. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50904. double& minimumSize,
  50905. double& maximumSize,
  50906. double& preferredSize) const
  50907. {
  50908. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50909. if (layout != 0)
  50910. {
  50911. minimumSize = layout->minSize;
  50912. maximumSize = layout->maxSize;
  50913. preferredSize = layout->preferredSize;
  50914. return true;
  50915. }
  50916. return false;
  50917. }
  50918. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50919. {
  50920. totalSize = newTotalSize;
  50921. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50922. }
  50923. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50924. {
  50925. int pos = 0;
  50926. for (int i = 0; i < itemIndex; ++i)
  50927. {
  50928. const ItemLayoutProperties* const layout = getInfoFor (i);
  50929. if (layout != 0)
  50930. pos += layout->currentSize;
  50931. }
  50932. return pos;
  50933. }
  50934. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50935. {
  50936. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50937. if (layout != 0)
  50938. return layout->currentSize;
  50939. return 0;
  50940. }
  50941. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50942. {
  50943. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50944. if (layout != 0)
  50945. return -layout->currentSize / (double) totalSize;
  50946. return 0;
  50947. }
  50948. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50949. int newPosition)
  50950. {
  50951. for (int i = items.size(); --i >= 0;)
  50952. {
  50953. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50954. if (layout->itemIndex == itemIndex)
  50955. {
  50956. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50957. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50958. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50959. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50960. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50961. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50962. endPos += layout->currentSize;
  50963. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50964. updatePrefSizesToMatchCurrentPositions();
  50965. break;
  50966. }
  50967. }
  50968. }
  50969. void StretchableLayoutManager::layOutComponents (Component** const components,
  50970. int numComponents,
  50971. int x, int y, int w, int h,
  50972. const bool vertically,
  50973. const bool resizeOtherDimension)
  50974. {
  50975. setTotalSize (vertically ? h : w);
  50976. int pos = vertically ? y : x;
  50977. for (int i = 0; i < numComponents; ++i)
  50978. {
  50979. const ItemLayoutProperties* const layout = getInfoFor (i);
  50980. if (layout != 0)
  50981. {
  50982. Component* const c = components[i];
  50983. if (c != 0)
  50984. {
  50985. if (i == numComponents - 1)
  50986. {
  50987. // if it's the last item, crop it to exactly fit the available space..
  50988. if (resizeOtherDimension)
  50989. {
  50990. if (vertically)
  50991. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50992. else
  50993. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50994. }
  50995. else
  50996. {
  50997. if (vertically)
  50998. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50999. else
  51000. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51001. }
  51002. }
  51003. else
  51004. {
  51005. if (resizeOtherDimension)
  51006. {
  51007. if (vertically)
  51008. c->setBounds (x, pos, w, layout->currentSize);
  51009. else
  51010. c->setBounds (pos, y, layout->currentSize, h);
  51011. }
  51012. else
  51013. {
  51014. if (vertically)
  51015. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51016. else
  51017. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51018. }
  51019. }
  51020. }
  51021. pos += layout->currentSize;
  51022. }
  51023. }
  51024. }
  51025. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51026. {
  51027. for (int i = items.size(); --i >= 0;)
  51028. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51029. return items.getUnchecked(i);
  51030. return 0;
  51031. }
  51032. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51033. const int endIndex,
  51034. const int availableSpace,
  51035. int startPos)
  51036. {
  51037. // calculate the total sizes
  51038. int i;
  51039. double totalIdealSize = 0.0;
  51040. int totalMinimums = 0;
  51041. for (i = startIndex; i < endIndex; ++i)
  51042. {
  51043. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51044. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51045. totalMinimums += layout->currentSize;
  51046. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51047. }
  51048. if (totalIdealSize <= 0)
  51049. totalIdealSize = 1.0;
  51050. // now calc the best sizes..
  51051. int extraSpace = availableSpace - totalMinimums;
  51052. while (extraSpace > 0)
  51053. {
  51054. int numWantingMoreSpace = 0;
  51055. int numHavingTakenExtraSpace = 0;
  51056. // first figure out how many comps want a slice of the extra space..
  51057. for (i = startIndex; i < endIndex; ++i)
  51058. {
  51059. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51060. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51061. const int bestSize = jlimit (layout->currentSize,
  51062. jmax (layout->currentSize,
  51063. sizeToRealSize (layout->maxSize, totalSize)),
  51064. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51065. if (bestSize > layout->currentSize)
  51066. ++numWantingMoreSpace;
  51067. }
  51068. // ..share out the extra space..
  51069. for (i = startIndex; i < endIndex; ++i)
  51070. {
  51071. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51072. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51073. int bestSize = jlimit (layout->currentSize,
  51074. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51075. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51076. const int extraWanted = bestSize - layout->currentSize;
  51077. if (extraWanted > 0)
  51078. {
  51079. const int extraAllowed = jmin (extraWanted,
  51080. extraSpace / jmax (1, numWantingMoreSpace));
  51081. if (extraAllowed > 0)
  51082. {
  51083. ++numHavingTakenExtraSpace;
  51084. --numWantingMoreSpace;
  51085. layout->currentSize += extraAllowed;
  51086. extraSpace -= extraAllowed;
  51087. }
  51088. }
  51089. }
  51090. if (numHavingTakenExtraSpace <= 0)
  51091. break;
  51092. }
  51093. // ..and calculate the end position
  51094. for (i = startIndex; i < endIndex; ++i)
  51095. {
  51096. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51097. startPos += layout->currentSize;
  51098. }
  51099. return startPos;
  51100. }
  51101. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51102. const int endIndex) const
  51103. {
  51104. int totalMinimums = 0;
  51105. for (int i = startIndex; i < endIndex; ++i)
  51106. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51107. return totalMinimums;
  51108. }
  51109. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51110. {
  51111. int totalMaximums = 0;
  51112. for (int i = startIndex; i < endIndex; ++i)
  51113. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51114. return totalMaximums;
  51115. }
  51116. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51117. {
  51118. for (int i = 0; i < items.size(); ++i)
  51119. {
  51120. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51121. layout->preferredSize
  51122. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51123. : getItemCurrentAbsoluteSize (i);
  51124. }
  51125. }
  51126. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51127. {
  51128. if (size < 0)
  51129. size *= -totalSpace;
  51130. return roundToInt (size);
  51131. }
  51132. END_JUCE_NAMESPACE
  51133. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51134. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51135. BEGIN_JUCE_NAMESPACE
  51136. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51137. const int itemIndex_,
  51138. const bool isVertical_)
  51139. : layout (layout_),
  51140. itemIndex (itemIndex_),
  51141. isVertical (isVertical_)
  51142. {
  51143. setRepaintsOnMouseActivity (true);
  51144. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51145. : MouseCursor::UpDownResizeCursor));
  51146. }
  51147. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51148. {
  51149. }
  51150. void StretchableLayoutResizerBar::paint (Graphics& g)
  51151. {
  51152. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51153. getWidth(), getHeight(),
  51154. isVertical,
  51155. isMouseOver(),
  51156. isMouseButtonDown());
  51157. }
  51158. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51159. {
  51160. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51161. }
  51162. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51163. {
  51164. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51165. : e.getDistanceFromDragStartY());
  51166. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51167. {
  51168. layout->setItemPosition (itemIndex, desiredPos);
  51169. hasBeenMoved();
  51170. }
  51171. }
  51172. void StretchableLayoutResizerBar::hasBeenMoved()
  51173. {
  51174. if (getParentComponent() != 0)
  51175. getParentComponent()->resized();
  51176. }
  51177. END_JUCE_NAMESPACE
  51178. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51179. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51180. BEGIN_JUCE_NAMESPACE
  51181. StretchableObjectResizer::StretchableObjectResizer()
  51182. {
  51183. }
  51184. StretchableObjectResizer::~StretchableObjectResizer()
  51185. {
  51186. }
  51187. void StretchableObjectResizer::addItem (const double size,
  51188. const double minSize, const double maxSize,
  51189. const int order)
  51190. {
  51191. // the order must be >= 0 but less than the maximum integer value.
  51192. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51193. Item* const item = new Item();
  51194. item->size = size;
  51195. item->minSize = minSize;
  51196. item->maxSize = maxSize;
  51197. item->order = order;
  51198. items.add (item);
  51199. }
  51200. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51201. {
  51202. const Item* const it = items [index];
  51203. return it != 0 ? it->size : 0;
  51204. }
  51205. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51206. {
  51207. int order = 0;
  51208. for (;;)
  51209. {
  51210. double currentSize = 0;
  51211. double minSize = 0;
  51212. double maxSize = 0;
  51213. int nextHighestOrder = std::numeric_limits<int>::max();
  51214. for (int i = 0; i < items.size(); ++i)
  51215. {
  51216. const Item* const it = items.getUnchecked(i);
  51217. currentSize += it->size;
  51218. if (it->order <= order)
  51219. {
  51220. minSize += it->minSize;
  51221. maxSize += it->maxSize;
  51222. }
  51223. else
  51224. {
  51225. minSize += it->size;
  51226. maxSize += it->size;
  51227. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51228. }
  51229. }
  51230. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51231. if (thisIterationTarget >= currentSize)
  51232. {
  51233. const double availableExtraSpace = maxSize - currentSize;
  51234. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51235. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51236. for (int i = 0; i < items.size(); ++i)
  51237. {
  51238. Item* const it = items.getUnchecked(i);
  51239. if (it->order <= order)
  51240. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51241. }
  51242. }
  51243. else
  51244. {
  51245. const double amountOfSlack = currentSize - minSize;
  51246. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51247. const double scale = targetAmountOfSlack / amountOfSlack;
  51248. for (int i = 0; i < items.size(); ++i)
  51249. {
  51250. Item* const it = items.getUnchecked(i);
  51251. if (it->order <= order)
  51252. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51253. }
  51254. }
  51255. if (nextHighestOrder < std::numeric_limits<int>::max())
  51256. order = nextHighestOrder;
  51257. else
  51258. break;
  51259. }
  51260. }
  51261. END_JUCE_NAMESPACE
  51262. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51263. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51264. BEGIN_JUCE_NAMESPACE
  51265. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51266. : Button (name),
  51267. owner (owner_),
  51268. overlapPixels (0)
  51269. {
  51270. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51271. setComponentEffect (&shadow);
  51272. setWantsKeyboardFocus (false);
  51273. }
  51274. TabBarButton::~TabBarButton()
  51275. {
  51276. }
  51277. int TabBarButton::getIndex() const
  51278. {
  51279. return owner.indexOfTabButton (this);
  51280. }
  51281. void TabBarButton::paintButton (Graphics& g,
  51282. bool isMouseOverButton,
  51283. bool isButtonDown)
  51284. {
  51285. const Rectangle<int> area (getActiveArea());
  51286. g.setOrigin (area.getX(), area.getY());
  51287. getLookAndFeel()
  51288. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51289. owner.getTabBackgroundColour (getIndex()),
  51290. getIndex(), getButtonText(), *this,
  51291. owner.getOrientation(),
  51292. isMouseOverButton, isButtonDown,
  51293. getToggleState());
  51294. }
  51295. void TabBarButton::clicked (const ModifierKeys& mods)
  51296. {
  51297. if (mods.isPopupMenu())
  51298. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51299. else
  51300. owner.setCurrentTabIndex (getIndex());
  51301. }
  51302. bool TabBarButton::hitTest (int mx, int my)
  51303. {
  51304. const Rectangle<int> area (getActiveArea());
  51305. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51306. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51307. {
  51308. if (isPositiveAndBelow (mx, getWidth())
  51309. && my >= area.getY() + overlapPixels
  51310. && my < area.getBottom() - overlapPixels)
  51311. return true;
  51312. }
  51313. else
  51314. {
  51315. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51316. && isPositiveAndBelow (my, getHeight()))
  51317. return true;
  51318. }
  51319. Path p;
  51320. getLookAndFeel()
  51321. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51322. owner.getOrientation(), false, false, getToggleState());
  51323. return p.contains ((float) (mx - area.getX()),
  51324. (float) (my - area.getY()));
  51325. }
  51326. int TabBarButton::getBestTabLength (const int depth)
  51327. {
  51328. return jlimit (depth * 2,
  51329. depth * 7,
  51330. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51331. }
  51332. const Rectangle<int> TabBarButton::getActiveArea()
  51333. {
  51334. Rectangle<int> r (getLocalBounds());
  51335. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51336. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51337. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51338. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51339. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51340. return r;
  51341. }
  51342. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51343. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51344. {
  51345. public:
  51346. BehindFrontTabComp (TabbedButtonBar& owner_)
  51347. : owner (owner_)
  51348. {
  51349. setInterceptsMouseClicks (false, false);
  51350. }
  51351. void paint (Graphics& g)
  51352. {
  51353. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51354. owner, owner.getOrientation());
  51355. }
  51356. void enablementChanged()
  51357. {
  51358. repaint();
  51359. }
  51360. void buttonClicked (Button*)
  51361. {
  51362. owner.showExtraItemsMenu();
  51363. }
  51364. private:
  51365. TabbedButtonBar& owner;
  51366. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51367. };
  51368. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51369. : orientation (orientation_),
  51370. minimumScale (0.7),
  51371. currentTabIndex (-1)
  51372. {
  51373. setInterceptsMouseClicks (false, true);
  51374. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51375. setFocusContainer (true);
  51376. }
  51377. TabbedButtonBar::~TabbedButtonBar()
  51378. {
  51379. tabs.clear();
  51380. extraTabsButton = 0;
  51381. }
  51382. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51383. {
  51384. orientation = newOrientation;
  51385. for (int i = getNumChildComponents(); --i >= 0;)
  51386. getChildComponent (i)->resized();
  51387. resized();
  51388. }
  51389. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51390. {
  51391. return new TabBarButton (name, *this);
  51392. }
  51393. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51394. {
  51395. minimumScale = newMinimumScale;
  51396. resized();
  51397. }
  51398. void TabbedButtonBar::clearTabs()
  51399. {
  51400. tabs.clear();
  51401. extraTabsButton = 0;
  51402. setCurrentTabIndex (-1);
  51403. }
  51404. void TabbedButtonBar::addTab (const String& tabName,
  51405. const Colour& tabBackgroundColour,
  51406. int insertIndex)
  51407. {
  51408. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51409. if (tabName.isNotEmpty())
  51410. {
  51411. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51412. insertIndex = tabs.size();
  51413. TabInfo* newTab = new TabInfo();
  51414. newTab->name = tabName;
  51415. newTab->colour = tabBackgroundColour;
  51416. newTab->component = createTabButton (tabName, insertIndex);
  51417. jassert (newTab->component != 0);
  51418. tabs.insert (insertIndex, newTab);
  51419. addAndMakeVisible (newTab->component, insertIndex);
  51420. resized();
  51421. if (currentTabIndex < 0)
  51422. setCurrentTabIndex (0);
  51423. }
  51424. }
  51425. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51426. {
  51427. TabInfo* const tab = tabs [tabIndex];
  51428. if (tab != 0 && tab->name != newName)
  51429. {
  51430. tab->name = newName;
  51431. tab->component->setButtonText (newName);
  51432. resized();
  51433. }
  51434. }
  51435. void TabbedButtonBar::removeTab (const int tabIndex)
  51436. {
  51437. if (tabs [tabIndex] != 0)
  51438. {
  51439. const int oldTabIndex = currentTabIndex;
  51440. if (currentTabIndex == tabIndex)
  51441. currentTabIndex = -1;
  51442. tabs.remove (tabIndex);
  51443. resized();
  51444. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51445. }
  51446. }
  51447. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51448. {
  51449. tabs.move (currentIndex, newIndex);
  51450. resized();
  51451. }
  51452. int TabbedButtonBar::getNumTabs() const
  51453. {
  51454. return tabs.size();
  51455. }
  51456. const String TabbedButtonBar::getCurrentTabName() const
  51457. {
  51458. TabInfo* tab = tabs [currentTabIndex];
  51459. return tab == 0 ? String::empty : tab->name;
  51460. }
  51461. const StringArray TabbedButtonBar::getTabNames() const
  51462. {
  51463. StringArray names;
  51464. for (int i = 0; i < tabs.size(); ++i)
  51465. names.add (tabs.getUnchecked(i)->name);
  51466. return names;
  51467. }
  51468. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51469. {
  51470. if (currentTabIndex != newIndex)
  51471. {
  51472. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51473. newIndex = -1;
  51474. currentTabIndex = newIndex;
  51475. for (int i = 0; i < tabs.size(); ++i)
  51476. {
  51477. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51478. tb->setToggleState (i == newIndex, false);
  51479. }
  51480. resized();
  51481. if (sendChangeMessage_)
  51482. sendChangeMessage();
  51483. currentTabChanged (newIndex, getCurrentTabName());
  51484. }
  51485. }
  51486. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51487. {
  51488. TabInfo* const tab = tabs[index];
  51489. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51490. }
  51491. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51492. {
  51493. for (int i = tabs.size(); --i >= 0;)
  51494. if (tabs.getUnchecked(i)->component == button)
  51495. return i;
  51496. return -1;
  51497. }
  51498. void TabbedButtonBar::lookAndFeelChanged()
  51499. {
  51500. extraTabsButton = 0;
  51501. resized();
  51502. }
  51503. void TabbedButtonBar::resized()
  51504. {
  51505. int depth = getWidth();
  51506. int length = getHeight();
  51507. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51508. swapVariables (depth, length);
  51509. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51510. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51511. int i, totalLength = overlap;
  51512. int numVisibleButtons = tabs.size();
  51513. for (i = 0; i < tabs.size(); ++i)
  51514. {
  51515. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51516. totalLength += tb->getBestTabLength (depth) - overlap;
  51517. tb->overlapPixels = overlap / 2;
  51518. }
  51519. double scale = 1.0;
  51520. if (totalLength > length)
  51521. scale = jmax (minimumScale, length / (double) totalLength);
  51522. const bool isTooBig = totalLength * scale > length;
  51523. int tabsButtonPos = 0;
  51524. if (isTooBig)
  51525. {
  51526. if (extraTabsButton == 0)
  51527. {
  51528. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51529. extraTabsButton->addButtonListener (behindFrontTab);
  51530. extraTabsButton->setAlwaysOnTop (true);
  51531. extraTabsButton->setTriggeredOnMouseDown (true);
  51532. }
  51533. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51534. extraTabsButton->setSize (buttonSize, buttonSize);
  51535. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51536. {
  51537. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51538. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51539. }
  51540. else
  51541. {
  51542. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51543. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51544. }
  51545. totalLength = 0;
  51546. for (i = 0; i < tabs.size(); ++i)
  51547. {
  51548. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51549. const int newLength = totalLength + tb->getBestTabLength (depth);
  51550. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51551. {
  51552. totalLength += overlap;
  51553. break;
  51554. }
  51555. numVisibleButtons = i + 1;
  51556. totalLength = newLength - overlap;
  51557. }
  51558. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51559. }
  51560. else
  51561. {
  51562. extraTabsButton = 0;
  51563. }
  51564. int pos = 0;
  51565. TabBarButton* frontTab = 0;
  51566. for (i = 0; i < tabs.size(); ++i)
  51567. {
  51568. TabBarButton* const tb = getTabButton (i);
  51569. if (tb != 0)
  51570. {
  51571. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51572. if (i < numVisibleButtons)
  51573. {
  51574. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51575. tb->setBounds (pos, 0, bestLength, getHeight());
  51576. else
  51577. tb->setBounds (0, pos, getWidth(), bestLength);
  51578. tb->toBack();
  51579. if (i == currentTabIndex)
  51580. frontTab = tb;
  51581. tb->setVisible (true);
  51582. }
  51583. else
  51584. {
  51585. tb->setVisible (false);
  51586. }
  51587. pos += bestLength - overlap;
  51588. }
  51589. }
  51590. behindFrontTab->setBounds (getLocalBounds());
  51591. if (frontTab != 0)
  51592. {
  51593. frontTab->toFront (false);
  51594. behindFrontTab->toBehind (frontTab);
  51595. }
  51596. }
  51597. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51598. {
  51599. TabInfo* const tab = tabs [tabIndex];
  51600. return tab == 0 ? Colours::white : tab->colour;
  51601. }
  51602. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51603. {
  51604. TabInfo* const tab = tabs [tabIndex];
  51605. if (tab != 0 && tab->colour != newColour)
  51606. {
  51607. tab->colour = newColour;
  51608. repaint();
  51609. }
  51610. }
  51611. void TabbedButtonBar::showExtraItemsMenu()
  51612. {
  51613. PopupMenu m;
  51614. for (int i = 0; i < tabs.size(); ++i)
  51615. {
  51616. const TabInfo* const tab = tabs.getUnchecked(i);
  51617. if (! tab->component->isVisible())
  51618. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51619. }
  51620. const int res = m.showAt (extraTabsButton);
  51621. if (res != 0)
  51622. setCurrentTabIndex (res - 1);
  51623. }
  51624. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51625. {
  51626. }
  51627. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51628. {
  51629. }
  51630. END_JUCE_NAMESPACE
  51631. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51632. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51633. BEGIN_JUCE_NAMESPACE
  51634. class TabCompButtonBar : public TabbedButtonBar
  51635. {
  51636. public:
  51637. TabCompButtonBar (TabbedComponent& owner_,
  51638. const TabbedButtonBar::Orientation orientation_)
  51639. : TabbedButtonBar (orientation_),
  51640. owner (owner_)
  51641. {
  51642. }
  51643. ~TabCompButtonBar()
  51644. {
  51645. }
  51646. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51647. {
  51648. owner.changeCallback (newCurrentTabIndex, newTabName);
  51649. }
  51650. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51651. {
  51652. owner.popupMenuClickOnTab (tabIndex, tabName);
  51653. }
  51654. const Colour getTabBackgroundColour (const int tabIndex)
  51655. {
  51656. return owner.tabs->getTabBackgroundColour (tabIndex);
  51657. }
  51658. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51659. {
  51660. return owner.createTabButton (tabName, tabIndex);
  51661. }
  51662. private:
  51663. TabbedComponent& owner;
  51664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabCompButtonBar);
  51665. };
  51666. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51667. : tabDepth (30),
  51668. outlineThickness (1),
  51669. edgeIndent (0)
  51670. {
  51671. addAndMakeVisible (tabs = new TabCompButtonBar (*this, orientation));
  51672. }
  51673. TabbedComponent::~TabbedComponent()
  51674. {
  51675. clearTabs();
  51676. tabs = 0;
  51677. }
  51678. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51679. {
  51680. tabs->setOrientation (orientation);
  51681. resized();
  51682. }
  51683. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51684. {
  51685. return tabs->getOrientation();
  51686. }
  51687. void TabbedComponent::setTabBarDepth (const int newDepth)
  51688. {
  51689. if (tabDepth != newDepth)
  51690. {
  51691. tabDepth = newDepth;
  51692. resized();
  51693. }
  51694. }
  51695. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51696. {
  51697. return new TabBarButton (tabName, *tabs);
  51698. }
  51699. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51700. void TabbedComponent::clearTabs()
  51701. {
  51702. if (panelComponent != 0)
  51703. {
  51704. panelComponent->setVisible (false);
  51705. removeChildComponent (panelComponent);
  51706. panelComponent = 0;
  51707. }
  51708. tabs->clearTabs();
  51709. for (int i = contentComponents.size(); --i >= 0;)
  51710. {
  51711. Component::SafePointer<Component>& c = *contentComponents.getUnchecked (i);
  51712. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51713. c.deleteAndZero();
  51714. }
  51715. contentComponents.clear();
  51716. }
  51717. void TabbedComponent::addTab (const String& tabName,
  51718. const Colour& tabBackgroundColour,
  51719. Component* const contentComponent,
  51720. const bool deleteComponentWhenNotNeeded,
  51721. const int insertIndex)
  51722. {
  51723. contentComponents.insert (insertIndex, new Component::SafePointer<Component> (contentComponent));
  51724. if (contentComponent != 0)
  51725. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51726. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51727. }
  51728. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51729. {
  51730. tabs->setTabName (tabIndex, newName);
  51731. }
  51732. void TabbedComponent::removeTab (const int tabIndex)
  51733. {
  51734. Component::SafePointer<Component>* c = contentComponents [tabIndex];
  51735. if (c != 0)
  51736. {
  51737. if ((bool) ((*c)->getProperties() [deleteComponentId]))
  51738. c->deleteAndZero();
  51739. contentComponents.remove (tabIndex);
  51740. tabs->removeTab (tabIndex);
  51741. }
  51742. }
  51743. int TabbedComponent::getNumTabs() const
  51744. {
  51745. return tabs->getNumTabs();
  51746. }
  51747. const StringArray TabbedComponent::getTabNames() const
  51748. {
  51749. return tabs->getTabNames();
  51750. }
  51751. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51752. {
  51753. Component::SafePointer<Component>* const c = contentComponents [tabIndex];
  51754. return c != 0 ? *c : 0;
  51755. }
  51756. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51757. {
  51758. return tabs->getTabBackgroundColour (tabIndex);
  51759. }
  51760. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51761. {
  51762. tabs->setTabBackgroundColour (tabIndex, newColour);
  51763. if (getCurrentTabIndex() == tabIndex)
  51764. repaint();
  51765. }
  51766. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51767. {
  51768. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51769. }
  51770. int TabbedComponent::getCurrentTabIndex() const
  51771. {
  51772. return tabs->getCurrentTabIndex();
  51773. }
  51774. const String TabbedComponent::getCurrentTabName() const
  51775. {
  51776. return tabs->getCurrentTabName();
  51777. }
  51778. void TabbedComponent::setOutline (int thickness)
  51779. {
  51780. outlineThickness = thickness;
  51781. repaint();
  51782. }
  51783. void TabbedComponent::setIndent (const int indentThickness)
  51784. {
  51785. edgeIndent = indentThickness;
  51786. }
  51787. void TabbedComponent::paint (Graphics& g)
  51788. {
  51789. g.fillAll (findColour (backgroundColourId));
  51790. const TabbedButtonBar::Orientation o = getOrientation();
  51791. int x = 0;
  51792. int y = 0;
  51793. int r = getWidth();
  51794. int b = getHeight();
  51795. if (o == TabbedButtonBar::TabsAtTop)
  51796. y += tabDepth;
  51797. else if (o == TabbedButtonBar::TabsAtBottom)
  51798. b -= tabDepth;
  51799. else if (o == TabbedButtonBar::TabsAtLeft)
  51800. x += tabDepth;
  51801. else if (o == TabbedButtonBar::TabsAtRight)
  51802. r -= tabDepth;
  51803. g.reduceClipRegion (x, y, r - x, b - y);
  51804. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51805. if (outlineThickness > 0)
  51806. {
  51807. if (o == TabbedButtonBar::TabsAtTop)
  51808. --y;
  51809. else if (o == TabbedButtonBar::TabsAtBottom)
  51810. ++b;
  51811. else if (o == TabbedButtonBar::TabsAtLeft)
  51812. --x;
  51813. else if (o == TabbedButtonBar::TabsAtRight)
  51814. ++r;
  51815. g.setColour (findColour (outlineColourId));
  51816. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51817. }
  51818. }
  51819. void TabbedComponent::resized()
  51820. {
  51821. const TabbedButtonBar::Orientation o = getOrientation();
  51822. const int indent = edgeIndent + outlineThickness;
  51823. BorderSize indents (indent);
  51824. if (o == TabbedButtonBar::TabsAtTop)
  51825. {
  51826. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51827. indents.setTop (tabDepth + edgeIndent);
  51828. }
  51829. else if (o == TabbedButtonBar::TabsAtBottom)
  51830. {
  51831. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51832. indents.setBottom (tabDepth + edgeIndent);
  51833. }
  51834. else if (o == TabbedButtonBar::TabsAtLeft)
  51835. {
  51836. tabs->setBounds (0, 0, tabDepth, getHeight());
  51837. indents.setLeft (tabDepth + edgeIndent);
  51838. }
  51839. else if (o == TabbedButtonBar::TabsAtRight)
  51840. {
  51841. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51842. indents.setRight (tabDepth + edgeIndent);
  51843. }
  51844. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51845. for (int i = contentComponents.size(); --i >= 0;)
  51846. if (*contentComponents.getUnchecked (i) != 0)
  51847. (*contentComponents.getUnchecked (i))->setBounds (bounds);
  51848. }
  51849. void TabbedComponent::lookAndFeelChanged()
  51850. {
  51851. for (int i = contentComponents.size(); --i >= 0;)
  51852. if (*contentComponents.getUnchecked (i) != 0)
  51853. (*contentComponents.getUnchecked (i))->lookAndFeelChanged();
  51854. }
  51855. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51856. const String& newTabName)
  51857. {
  51858. if (panelComponent != 0)
  51859. {
  51860. panelComponent->setVisible (false);
  51861. removeChildComponent (panelComponent);
  51862. panelComponent = 0;
  51863. }
  51864. if (getCurrentTabIndex() >= 0)
  51865. {
  51866. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51867. if (panelComponent != 0)
  51868. {
  51869. // do these ops as two stages instead of addAndMakeVisible() so that the
  51870. // component has always got a parent when it gets the visibilityChanged() callback
  51871. addChildComponent (panelComponent);
  51872. panelComponent->setVisible (true);
  51873. panelComponent->toFront (true);
  51874. }
  51875. repaint();
  51876. }
  51877. resized();
  51878. currentTabChanged (newCurrentTabIndex, newTabName);
  51879. }
  51880. void TabbedComponent::currentTabChanged (const int, const String&)
  51881. {
  51882. }
  51883. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51884. {
  51885. }
  51886. END_JUCE_NAMESPACE
  51887. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51888. /*** Start of inlined file: juce_Viewport.cpp ***/
  51889. BEGIN_JUCE_NAMESPACE
  51890. Viewport::Viewport (const String& componentName)
  51891. : Component (componentName),
  51892. scrollBarThickness (0),
  51893. singleStepX (16),
  51894. singleStepY (16),
  51895. showHScrollbar (true),
  51896. showVScrollbar (true),
  51897. verticalScrollBar (true),
  51898. horizontalScrollBar (false)
  51899. {
  51900. // content holder is used to clip the contents so they don't overlap the scrollbars
  51901. addAndMakeVisible (&contentHolder);
  51902. contentHolder.setInterceptsMouseClicks (false, true);
  51903. addChildComponent (&verticalScrollBar);
  51904. addChildComponent (&horizontalScrollBar);
  51905. verticalScrollBar.addListener (this);
  51906. horizontalScrollBar.addListener (this);
  51907. setInterceptsMouseClicks (false, true);
  51908. setWantsKeyboardFocus (true);
  51909. }
  51910. Viewport::~Viewport()
  51911. {
  51912. deleteContentComp();
  51913. }
  51914. void Viewport::visibleAreaChanged (int, int, int, int)
  51915. {
  51916. }
  51917. void Viewport::deleteContentComp()
  51918. {
  51919. // This sets the content comp to a null pointer before deleting the old one, in case
  51920. // anything tries to use the old one while it's in mid-deletion..
  51921. ScopedPointer<Component> oldCompDeleter (contentComp);
  51922. contentComp = 0;
  51923. }
  51924. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51925. {
  51926. if (contentComp.getComponent() != newViewedComponent)
  51927. {
  51928. deleteContentComp();
  51929. contentComp = newViewedComponent;
  51930. if (contentComp != 0)
  51931. {
  51932. contentComp->setTopLeftPosition (0, 0);
  51933. contentHolder.addAndMakeVisible (contentComp);
  51934. contentComp->addComponentListener (this);
  51935. }
  51936. updateVisibleArea();
  51937. }
  51938. }
  51939. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51940. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51941. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51942. {
  51943. if (contentComp != 0)
  51944. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51945. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51946. }
  51947. void Viewport::setViewPosition (const Point<int>& newPosition)
  51948. {
  51949. setViewPosition (newPosition.getX(), newPosition.getY());
  51950. }
  51951. void Viewport::setViewPositionProportionately (const double x, const double y)
  51952. {
  51953. if (contentComp != 0)
  51954. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51955. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51956. }
  51957. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51958. {
  51959. if (contentComp != 0)
  51960. {
  51961. int dx = 0, dy = 0;
  51962. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51963. {
  51964. if (mouseX < activeBorderThickness)
  51965. dx = activeBorderThickness - mouseX;
  51966. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51967. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51968. if (dx < 0)
  51969. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51970. else
  51971. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51972. }
  51973. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51974. {
  51975. if (mouseY < activeBorderThickness)
  51976. dy = activeBorderThickness - mouseY;
  51977. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51978. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51979. if (dy < 0)
  51980. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51981. else
  51982. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51983. }
  51984. if (dx != 0 || dy != 0)
  51985. {
  51986. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51987. contentComp->getY() + dy);
  51988. return true;
  51989. }
  51990. }
  51991. return false;
  51992. }
  51993. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51994. {
  51995. updateVisibleArea();
  51996. }
  51997. void Viewport::resized()
  51998. {
  51999. updateVisibleArea();
  52000. }
  52001. void Viewport::updateVisibleArea()
  52002. {
  52003. const int scrollbarWidth = getScrollBarThickness();
  52004. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52005. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52006. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52007. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52008. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52009. Rectangle<int> contentArea (getLocalBounds());
  52010. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52011. {
  52012. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52013. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52014. if (vBarVisible)
  52015. contentArea.setWidth (getWidth() - scrollbarWidth);
  52016. if (hBarVisible)
  52017. contentArea.setHeight (getHeight() - scrollbarWidth);
  52018. if (! contentArea.contains (contentComp->getBounds()))
  52019. {
  52020. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52021. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52022. }
  52023. }
  52024. if (vBarVisible)
  52025. contentArea.setWidth (getWidth() - scrollbarWidth);
  52026. if (hBarVisible)
  52027. contentArea.setHeight (getHeight() - scrollbarWidth);
  52028. contentHolder.setBounds (contentArea);
  52029. Rectangle<int> contentBounds;
  52030. if (contentComp != 0)
  52031. contentBounds = contentComp->getBounds();
  52032. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52033. if (hBarVisible)
  52034. {
  52035. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52036. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52037. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52038. horizontalScrollBar.setSingleStepSize (singleStepX);
  52039. horizontalScrollBar.cancelPendingUpdate();
  52040. }
  52041. if (vBarVisible)
  52042. {
  52043. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52044. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52045. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52046. verticalScrollBar.setSingleStepSize (singleStepY);
  52047. verticalScrollBar.cancelPendingUpdate();
  52048. }
  52049. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52050. horizontalScrollBar.setVisible (hBarVisible);
  52051. verticalScrollBar.setVisible (vBarVisible);
  52052. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52053. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52054. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52055. if (lastVisibleArea != visibleArea)
  52056. {
  52057. lastVisibleArea = visibleArea;
  52058. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52059. }
  52060. horizontalScrollBar.handleUpdateNowIfNeeded();
  52061. verticalScrollBar.handleUpdateNowIfNeeded();
  52062. }
  52063. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52064. {
  52065. if (singleStepX != stepX || singleStepY != stepY)
  52066. {
  52067. singleStepX = stepX;
  52068. singleStepY = stepY;
  52069. updateVisibleArea();
  52070. }
  52071. }
  52072. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52073. const bool showHorizontalScrollbarIfNeeded)
  52074. {
  52075. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52076. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52077. {
  52078. showVScrollbar = showVerticalScrollbarIfNeeded;
  52079. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52080. updateVisibleArea();
  52081. }
  52082. }
  52083. void Viewport::setScrollBarThickness (const int thickness)
  52084. {
  52085. if (scrollBarThickness != thickness)
  52086. {
  52087. scrollBarThickness = thickness;
  52088. updateVisibleArea();
  52089. }
  52090. }
  52091. int Viewport::getScrollBarThickness() const
  52092. {
  52093. return scrollBarThickness > 0 ? scrollBarThickness
  52094. : getLookAndFeel().getDefaultScrollbarWidth();
  52095. }
  52096. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52097. {
  52098. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52099. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52100. }
  52101. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52102. {
  52103. const int newRangeStartInt = roundToInt (newRangeStart);
  52104. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52105. {
  52106. setViewPosition (newRangeStartInt, getViewPositionY());
  52107. }
  52108. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52109. {
  52110. setViewPosition (getViewPositionX(), newRangeStartInt);
  52111. }
  52112. }
  52113. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52114. {
  52115. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52116. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52117. }
  52118. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52119. {
  52120. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52121. {
  52122. const bool hasVertBar = verticalScrollBar.isVisible();
  52123. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52124. if (hasHorzBar || hasVertBar)
  52125. {
  52126. if (wheelIncrementX != 0)
  52127. {
  52128. wheelIncrementX *= 14.0f * singleStepX;
  52129. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52130. : jmax (wheelIncrementX, 1.0f);
  52131. }
  52132. if (wheelIncrementY != 0)
  52133. {
  52134. wheelIncrementY *= 14.0f * singleStepY;
  52135. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52136. : jmax (wheelIncrementY, 1.0f);
  52137. }
  52138. Point<int> pos (getViewPosition());
  52139. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52140. {
  52141. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52142. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52143. }
  52144. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52145. {
  52146. if (wheelIncrementX == 0 && ! hasVertBar)
  52147. wheelIncrementX = wheelIncrementY;
  52148. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52149. }
  52150. else if (hasVertBar && wheelIncrementY != 0)
  52151. {
  52152. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52153. }
  52154. if (pos != getViewPosition())
  52155. {
  52156. setViewPosition (pos);
  52157. return true;
  52158. }
  52159. }
  52160. }
  52161. return false;
  52162. }
  52163. bool Viewport::keyPressed (const KeyPress& key)
  52164. {
  52165. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52166. || key.isKeyCode (KeyPress::downKey)
  52167. || key.isKeyCode (KeyPress::pageUpKey)
  52168. || key.isKeyCode (KeyPress::pageDownKey)
  52169. || key.isKeyCode (KeyPress::homeKey)
  52170. || key.isKeyCode (KeyPress::endKey);
  52171. if (verticalScrollBar.isVisible() && isUpDownKey)
  52172. return verticalScrollBar.keyPressed (key);
  52173. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52174. || key.isKeyCode (KeyPress::rightKey);
  52175. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52176. return horizontalScrollBar.keyPressed (key);
  52177. return false;
  52178. }
  52179. END_JUCE_NAMESPACE
  52180. /*** End of inlined file: juce_Viewport.cpp ***/
  52181. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52182. BEGIN_JUCE_NAMESPACE
  52183. namespace LookAndFeelHelpers
  52184. {
  52185. void createRoundedPath (Path& p,
  52186. const float x, const float y,
  52187. const float w, const float h,
  52188. const float cs,
  52189. const bool curveTopLeft, const bool curveTopRight,
  52190. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52191. {
  52192. const float cs2 = 2.0f * cs;
  52193. if (curveTopLeft)
  52194. {
  52195. p.startNewSubPath (x, y + cs);
  52196. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52197. }
  52198. else
  52199. {
  52200. p.startNewSubPath (x, y);
  52201. }
  52202. if (curveTopRight)
  52203. {
  52204. p.lineTo (x + w - cs, y);
  52205. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52206. }
  52207. else
  52208. {
  52209. p.lineTo (x + w, y);
  52210. }
  52211. if (curveBottomRight)
  52212. {
  52213. p.lineTo (x + w, y + h - cs);
  52214. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52215. }
  52216. else
  52217. {
  52218. p.lineTo (x + w, y + h);
  52219. }
  52220. if (curveBottomLeft)
  52221. {
  52222. p.lineTo (x + cs, y + h);
  52223. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52224. }
  52225. else
  52226. {
  52227. p.lineTo (x, y + h);
  52228. }
  52229. p.closeSubPath();
  52230. }
  52231. const Colour createBaseColour (const Colour& buttonColour,
  52232. const bool hasKeyboardFocus,
  52233. const bool isMouseOverButton,
  52234. const bool isButtonDown) throw()
  52235. {
  52236. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52237. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52238. if (isButtonDown)
  52239. return baseColour.contrasting (0.2f);
  52240. else if (isMouseOverButton)
  52241. return baseColour.contrasting (0.1f);
  52242. return baseColour;
  52243. }
  52244. const TextLayout layoutTooltipText (const String& text) throw()
  52245. {
  52246. const float tooltipFontSize = 12.0f;
  52247. const int maxToolTipWidth = 400;
  52248. const Font f (tooltipFontSize, Font::bold);
  52249. TextLayout tl (text, f);
  52250. tl.layout (maxToolTipWidth, Justification::left, true);
  52251. return tl;
  52252. }
  52253. LookAndFeel* defaultLF = 0;
  52254. LookAndFeel* currentDefaultLF = 0;
  52255. }
  52256. LookAndFeel::LookAndFeel()
  52257. {
  52258. /* if this fails it means you're trying to create a LookAndFeel object before
  52259. the static Colours have been initialised. That ain't gonna work. It probably
  52260. means that you're using a static LookAndFeel object and that your compiler has
  52261. decided to intialise it before the Colours class.
  52262. */
  52263. jassert (Colours::white == Colour (0xffffffff));
  52264. // set up the standard set of colours..
  52265. const int textButtonColour = 0xffbbbbff;
  52266. const int textHighlightColour = 0x401111ee;
  52267. const int standardOutlineColour = 0xb2808080;
  52268. static const int standardColours[] =
  52269. {
  52270. TextButton::buttonColourId, textButtonColour,
  52271. TextButton::buttonOnColourId, 0xff4444ff,
  52272. TextButton::textColourOnId, 0xff000000,
  52273. TextButton::textColourOffId, 0xff000000,
  52274. ComboBox::buttonColourId, 0xffbbbbff,
  52275. ComboBox::outlineColourId, standardOutlineColour,
  52276. ToggleButton::textColourId, 0xff000000,
  52277. TextEditor::backgroundColourId, 0xffffffff,
  52278. TextEditor::textColourId, 0xff000000,
  52279. TextEditor::highlightColourId, textHighlightColour,
  52280. TextEditor::highlightedTextColourId, 0xff000000,
  52281. TextEditor::caretColourId, 0xff000000,
  52282. TextEditor::outlineColourId, 0x00000000,
  52283. TextEditor::focusedOutlineColourId, textButtonColour,
  52284. TextEditor::shadowColourId, 0x38000000,
  52285. Label::backgroundColourId, 0x00000000,
  52286. Label::textColourId, 0xff000000,
  52287. Label::outlineColourId, 0x00000000,
  52288. ScrollBar::backgroundColourId, 0x00000000,
  52289. ScrollBar::thumbColourId, 0xffffffff,
  52290. ScrollBar::trackColourId, 0xffffffff,
  52291. TreeView::linesColourId, 0x4c000000,
  52292. TreeView::backgroundColourId, 0x00000000,
  52293. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52294. PopupMenu::backgroundColourId, 0xffffffff,
  52295. PopupMenu::textColourId, 0xff000000,
  52296. PopupMenu::headerTextColourId, 0xff000000,
  52297. PopupMenu::highlightedTextColourId, 0xffffffff,
  52298. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52299. ComboBox::textColourId, 0xff000000,
  52300. ComboBox::backgroundColourId, 0xffffffff,
  52301. ComboBox::arrowColourId, 0x99000000,
  52302. ListBox::backgroundColourId, 0xffffffff,
  52303. ListBox::outlineColourId, standardOutlineColour,
  52304. ListBox::textColourId, 0xff000000,
  52305. Slider::backgroundColourId, 0x00000000,
  52306. Slider::thumbColourId, textButtonColour,
  52307. Slider::trackColourId, 0x7fffffff,
  52308. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52309. Slider::rotarySliderOutlineColourId, 0x66000000,
  52310. Slider::textBoxTextColourId, 0xff000000,
  52311. Slider::textBoxBackgroundColourId, 0xffffffff,
  52312. Slider::textBoxHighlightColourId, textHighlightColour,
  52313. Slider::textBoxOutlineColourId, standardOutlineColour,
  52314. ResizableWindow::backgroundColourId, 0xff777777,
  52315. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52316. AlertWindow::backgroundColourId, 0xffededed,
  52317. AlertWindow::textColourId, 0xff000000,
  52318. AlertWindow::outlineColourId, 0xff666666,
  52319. ProgressBar::backgroundColourId, 0xffeeeeee,
  52320. ProgressBar::foregroundColourId, 0xffaaaaee,
  52321. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52322. TooltipWindow::textColourId, 0xff000000,
  52323. TooltipWindow::outlineColourId, 0x4c000000,
  52324. TabbedComponent::backgroundColourId, 0x00000000,
  52325. TabbedComponent::outlineColourId, 0xff777777,
  52326. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52327. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52328. Toolbar::backgroundColourId, 0xfff6f8f9,
  52329. Toolbar::separatorColourId, 0x4c000000,
  52330. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52331. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52332. Toolbar::labelTextColourId, 0xff000000,
  52333. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52334. HyperlinkButton::textColourId, 0xcc1111ee,
  52335. GroupComponent::outlineColourId, 0x66000000,
  52336. GroupComponent::textColourId, 0xff000000,
  52337. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52338. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52339. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52340. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52341. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52342. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52343. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52344. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52345. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52346. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52347. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52348. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52349. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52350. CodeEditorComponent::caretColourId, 0xff000000,
  52351. CodeEditorComponent::highlightColourId, textHighlightColour,
  52352. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52353. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52354. ColourSelector::labelTextColourId, 0xff000000,
  52355. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52356. KeyMappingEditorComponent::textColourId, 0xff000000,
  52357. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52358. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52359. DrawableButton::textColourId, 0xff000000,
  52360. };
  52361. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52362. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52363. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52364. if (defaultSansName.isEmpty())
  52365. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52366. defaultSans = defaultSansName;
  52367. defaultSerif = defaultSerifName;
  52368. defaultFixed = defaultFixedName;
  52369. Font::setFallbackFontName (defaultFallback);
  52370. }
  52371. LookAndFeel::~LookAndFeel()
  52372. {
  52373. if (this == LookAndFeelHelpers::currentDefaultLF)
  52374. setDefaultLookAndFeel (0);
  52375. }
  52376. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52377. {
  52378. const int index = colourIds.indexOf (colourId);
  52379. if (index >= 0)
  52380. return colours [index];
  52381. jassertfalse;
  52382. return Colours::black;
  52383. }
  52384. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52385. {
  52386. const int index = colourIds.indexOf (colourId);
  52387. if (index >= 0)
  52388. {
  52389. colours.set (index, colour);
  52390. }
  52391. else
  52392. {
  52393. colourIds.add (colourId);
  52394. colours.add (colour);
  52395. }
  52396. }
  52397. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52398. {
  52399. return colourIds.contains (colourId);
  52400. }
  52401. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52402. {
  52403. // if this happens, your app hasn't initialised itself properly.. if you're
  52404. // trying to hack your own main() function, have a look at
  52405. // JUCEApplication::initialiseForGUI()
  52406. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52407. return *LookAndFeelHelpers::currentDefaultLF;
  52408. }
  52409. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52410. {
  52411. using namespace LookAndFeelHelpers;
  52412. if (newDefaultLookAndFeel == 0)
  52413. {
  52414. if (defaultLF == 0)
  52415. defaultLF = new LookAndFeel();
  52416. newDefaultLookAndFeel = defaultLF;
  52417. }
  52418. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52419. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52420. {
  52421. Component* const c = Desktop::getInstance().getComponent (i);
  52422. if (c != 0)
  52423. c->sendLookAndFeelChange();
  52424. }
  52425. }
  52426. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52427. {
  52428. using namespace LookAndFeelHelpers;
  52429. if (currentDefaultLF == defaultLF)
  52430. currentDefaultLF = 0;
  52431. deleteAndZero (defaultLF);
  52432. }
  52433. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52434. {
  52435. String faceName (font.getTypefaceName());
  52436. if (faceName == Font::getDefaultSansSerifFontName())
  52437. faceName = defaultSans;
  52438. else if (faceName == Font::getDefaultSerifFontName())
  52439. faceName = defaultSerif;
  52440. else if (faceName == Font::getDefaultMonospacedFontName())
  52441. faceName = defaultFixed;
  52442. Font f (font);
  52443. f.setTypefaceName (faceName);
  52444. return Typeface::createSystemTypefaceFor (f);
  52445. }
  52446. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52447. {
  52448. defaultSans = newName;
  52449. }
  52450. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52451. {
  52452. return component.getMouseCursor();
  52453. }
  52454. void LookAndFeel::drawButtonBackground (Graphics& g,
  52455. Button& button,
  52456. const Colour& backgroundColour,
  52457. bool isMouseOverButton,
  52458. bool isButtonDown)
  52459. {
  52460. const int width = button.getWidth();
  52461. const int height = button.getHeight();
  52462. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52463. const float halfThickness = outlineThickness * 0.5f;
  52464. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52465. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52466. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52467. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52468. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52469. button.hasKeyboardFocus (true),
  52470. isMouseOverButton, isButtonDown)
  52471. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52472. drawGlassLozenge (g,
  52473. indentL,
  52474. indentT,
  52475. width - indentL - indentR,
  52476. height - indentT - indentB,
  52477. baseColour, outlineThickness, -1.0f,
  52478. button.isConnectedOnLeft(),
  52479. button.isConnectedOnRight(),
  52480. button.isConnectedOnTop(),
  52481. button.isConnectedOnBottom());
  52482. }
  52483. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52484. {
  52485. return button.getFont();
  52486. }
  52487. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52488. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52489. {
  52490. Font font (getFontForTextButton (button));
  52491. g.setFont (font);
  52492. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52493. : TextButton::textColourOffId)
  52494. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52495. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52496. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52497. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52498. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52499. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52500. g.drawFittedText (button.getButtonText(),
  52501. leftIndent,
  52502. yIndent,
  52503. button.getWidth() - leftIndent - rightIndent,
  52504. button.getHeight() - yIndent * 2,
  52505. Justification::centred, 2);
  52506. }
  52507. void LookAndFeel::drawTickBox (Graphics& g,
  52508. Component& component,
  52509. float x, float y, float w, float h,
  52510. const bool ticked,
  52511. const bool isEnabled,
  52512. const bool isMouseOverButton,
  52513. const bool isButtonDown)
  52514. {
  52515. const float boxSize = w * 0.7f;
  52516. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52517. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52518. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52519. true, isMouseOverButton, isButtonDown),
  52520. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52521. if (ticked)
  52522. {
  52523. Path tick;
  52524. tick.startNewSubPath (1.5f, 3.0f);
  52525. tick.lineTo (3.0f, 6.0f);
  52526. tick.lineTo (6.0f, 0.0f);
  52527. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52528. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52529. .translated (x, y));
  52530. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52531. }
  52532. }
  52533. void LookAndFeel::drawToggleButton (Graphics& g,
  52534. ToggleButton& button,
  52535. bool isMouseOverButton,
  52536. bool isButtonDown)
  52537. {
  52538. if (button.hasKeyboardFocus (true))
  52539. {
  52540. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52541. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52542. }
  52543. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52544. const float tickWidth = fontSize * 1.1f;
  52545. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52546. tickWidth, tickWidth,
  52547. button.getToggleState(),
  52548. button.isEnabled(),
  52549. isMouseOverButton,
  52550. isButtonDown);
  52551. g.setColour (button.findColour (ToggleButton::textColourId));
  52552. g.setFont (fontSize);
  52553. if (! button.isEnabled())
  52554. g.setOpacity (0.5f);
  52555. const int textX = (int) tickWidth + 5;
  52556. g.drawFittedText (button.getButtonText(),
  52557. textX, 0,
  52558. button.getWidth() - textX - 2, button.getHeight(),
  52559. Justification::centredLeft, 10);
  52560. }
  52561. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52562. {
  52563. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52564. const int tickWidth = jmin (24, button.getHeight());
  52565. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52566. button.getHeight());
  52567. }
  52568. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52569. const String& message,
  52570. const String& button1,
  52571. const String& button2,
  52572. const String& button3,
  52573. AlertWindow::AlertIconType iconType,
  52574. int numButtons,
  52575. Component* associatedComponent)
  52576. {
  52577. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52578. if (numButtons == 1)
  52579. {
  52580. aw->addButton (button1, 0,
  52581. KeyPress (KeyPress::escapeKey, 0, 0),
  52582. KeyPress (KeyPress::returnKey, 0, 0));
  52583. }
  52584. else
  52585. {
  52586. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52587. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52588. if (button1ShortCut == button2ShortCut)
  52589. button2ShortCut = KeyPress();
  52590. if (numButtons == 2)
  52591. {
  52592. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52593. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52594. }
  52595. else if (numButtons == 3)
  52596. {
  52597. aw->addButton (button1, 1, button1ShortCut);
  52598. aw->addButton (button2, 2, button2ShortCut);
  52599. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52600. }
  52601. }
  52602. return aw;
  52603. }
  52604. void LookAndFeel::drawAlertBox (Graphics& g,
  52605. AlertWindow& alert,
  52606. const Rectangle<int>& textArea,
  52607. TextLayout& textLayout)
  52608. {
  52609. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52610. int iconSpaceUsed = 0;
  52611. Justification alignment (Justification::horizontallyCentred);
  52612. const int iconWidth = 80;
  52613. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52614. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52615. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52616. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52617. iconSize, iconSize);
  52618. if (alert.getAlertType() != AlertWindow::NoIcon)
  52619. {
  52620. Path icon;
  52621. uint32 colour;
  52622. char character;
  52623. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52624. {
  52625. colour = 0x55ff5555;
  52626. character = '!';
  52627. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52628. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52629. (float) iconRect.getX(), (float) iconRect.getBottom());
  52630. icon = icon.createPathWithRoundedCorners (5.0f);
  52631. }
  52632. else
  52633. {
  52634. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52635. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52636. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52637. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52638. }
  52639. GlyphArrangement ga;
  52640. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52641. String::charToString (character),
  52642. (float) iconRect.getX(), (float) iconRect.getY(),
  52643. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52644. Justification::centred, false);
  52645. ga.createPath (icon);
  52646. icon.setUsingNonZeroWinding (false);
  52647. g.setColour (Colour (colour));
  52648. g.fillPath (icon);
  52649. iconSpaceUsed = iconWidth;
  52650. alignment = Justification::left;
  52651. }
  52652. g.setColour (alert.findColour (AlertWindow::textColourId));
  52653. textLayout.drawWithin (g,
  52654. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52655. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52656. alignment.getFlags() | Justification::top);
  52657. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52658. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52659. }
  52660. int LookAndFeel::getAlertBoxWindowFlags()
  52661. {
  52662. return ComponentPeer::windowAppearsOnTaskbar
  52663. | ComponentPeer::windowHasDropShadow;
  52664. }
  52665. int LookAndFeel::getAlertWindowButtonHeight()
  52666. {
  52667. return 28;
  52668. }
  52669. const Font LookAndFeel::getAlertWindowFont()
  52670. {
  52671. return Font (12.0f);
  52672. }
  52673. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52674. int width, int height,
  52675. double progress, const String& textToShow)
  52676. {
  52677. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52678. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52679. g.fillAll (background);
  52680. if (progress >= 0.0f && progress < 1.0f)
  52681. {
  52682. drawGlassLozenge (g, 1.0f, 1.0f,
  52683. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52684. (float) (height - 2),
  52685. foreground,
  52686. 0.5f, 0.0f,
  52687. true, true, true, true);
  52688. }
  52689. else
  52690. {
  52691. // spinning bar..
  52692. g.setColour (foreground);
  52693. const int stripeWidth = height * 2;
  52694. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52695. Path p;
  52696. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52697. p.addQuadrilateral (x, 0.0f,
  52698. x + stripeWidth * 0.5f, 0.0f,
  52699. x, (float) height,
  52700. x - stripeWidth * 0.5f, (float) height);
  52701. Image im (Image::ARGB, width, height, true);
  52702. {
  52703. Graphics g2 (im);
  52704. drawGlassLozenge (g2, 1.0f, 1.0f,
  52705. (float) (width - 2),
  52706. (float) (height - 2),
  52707. foreground,
  52708. 0.5f, 0.0f,
  52709. true, true, true, true);
  52710. }
  52711. g.setTiledImageFill (im, 0, 0, 0.85f);
  52712. g.fillPath (p);
  52713. }
  52714. if (textToShow.isNotEmpty())
  52715. {
  52716. g.setColour (Colour::contrasting (background, foreground));
  52717. g.setFont (height * 0.6f);
  52718. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52719. }
  52720. }
  52721. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52722. {
  52723. const float radius = jmin (w, h) * 0.4f;
  52724. const float thickness = radius * 0.15f;
  52725. Path p;
  52726. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52727. radius * 0.6f, thickness,
  52728. thickness * 0.5f);
  52729. const float cx = x + w * 0.5f;
  52730. const float cy = y + h * 0.5f;
  52731. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52732. for (int i = 0; i < 12; ++i)
  52733. {
  52734. const int n = (i + 12 - animationIndex) % 12;
  52735. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52736. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52737. .translated (cx, cy));
  52738. }
  52739. }
  52740. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52741. ScrollBar& scrollbar,
  52742. int width, int height,
  52743. int buttonDirection,
  52744. bool /*isScrollbarVertical*/,
  52745. bool /*isMouseOverButton*/,
  52746. bool isButtonDown)
  52747. {
  52748. Path p;
  52749. if (buttonDirection == 0)
  52750. p.addTriangle (width * 0.5f, height * 0.2f,
  52751. width * 0.1f, height * 0.7f,
  52752. width * 0.9f, height * 0.7f);
  52753. else if (buttonDirection == 1)
  52754. p.addTriangle (width * 0.8f, height * 0.5f,
  52755. width * 0.3f, height * 0.1f,
  52756. width * 0.3f, height * 0.9f);
  52757. else if (buttonDirection == 2)
  52758. p.addTriangle (width * 0.5f, height * 0.8f,
  52759. width * 0.1f, height * 0.3f,
  52760. width * 0.9f, height * 0.3f);
  52761. else if (buttonDirection == 3)
  52762. p.addTriangle (width * 0.2f, height * 0.5f,
  52763. width * 0.7f, height * 0.1f,
  52764. width * 0.7f, height * 0.9f);
  52765. if (isButtonDown)
  52766. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52767. else
  52768. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52769. g.fillPath (p);
  52770. g.setColour (Colour (0x80000000));
  52771. g.strokePath (p, PathStrokeType (0.5f));
  52772. }
  52773. void LookAndFeel::drawScrollbar (Graphics& g,
  52774. ScrollBar& scrollbar,
  52775. int x, int y,
  52776. int width, int height,
  52777. bool isScrollbarVertical,
  52778. int thumbStartPosition,
  52779. int thumbSize,
  52780. bool /*isMouseOver*/,
  52781. bool /*isMouseDown*/)
  52782. {
  52783. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52784. Path slotPath, thumbPath;
  52785. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52786. const float slotIndentx2 = slotIndent * 2.0f;
  52787. const float thumbIndent = slotIndent + 1.0f;
  52788. const float thumbIndentx2 = thumbIndent * 2.0f;
  52789. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52790. if (isScrollbarVertical)
  52791. {
  52792. slotPath.addRoundedRectangle (x + slotIndent,
  52793. y + slotIndent,
  52794. width - slotIndentx2,
  52795. height - slotIndentx2,
  52796. (width - slotIndentx2) * 0.5f);
  52797. if (thumbSize > 0)
  52798. thumbPath.addRoundedRectangle (x + thumbIndent,
  52799. thumbStartPosition + thumbIndent,
  52800. width - thumbIndentx2,
  52801. thumbSize - thumbIndentx2,
  52802. (width - thumbIndentx2) * 0.5f);
  52803. gx1 = (float) x;
  52804. gx2 = x + width * 0.7f;
  52805. }
  52806. else
  52807. {
  52808. slotPath.addRoundedRectangle (x + slotIndent,
  52809. y + slotIndent,
  52810. width - slotIndentx2,
  52811. height - slotIndentx2,
  52812. (height - slotIndentx2) * 0.5f);
  52813. if (thumbSize > 0)
  52814. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52815. y + thumbIndent,
  52816. thumbSize - thumbIndentx2,
  52817. height - thumbIndentx2,
  52818. (height - thumbIndentx2) * 0.5f);
  52819. gy1 = (float) y;
  52820. gy2 = y + height * 0.7f;
  52821. }
  52822. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52823. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52824. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52825. g.fillPath (slotPath);
  52826. if (isScrollbarVertical)
  52827. {
  52828. gx1 = x + width * 0.6f;
  52829. gx2 = (float) x + width;
  52830. }
  52831. else
  52832. {
  52833. gy1 = y + height * 0.6f;
  52834. gy2 = (float) y + height;
  52835. }
  52836. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52837. Colour (0x19000000), gx2, gy2, false));
  52838. g.fillPath (slotPath);
  52839. g.setColour (thumbColour);
  52840. g.fillPath (thumbPath);
  52841. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52842. Colours::transparentBlack, gx2, gy2, false));
  52843. g.saveState();
  52844. if (isScrollbarVertical)
  52845. g.reduceClipRegion (x + width / 2, y, width, height);
  52846. else
  52847. g.reduceClipRegion (x, y + height / 2, width, height);
  52848. g.fillPath (thumbPath);
  52849. g.restoreState();
  52850. g.setColour (Colour (0x4c000000));
  52851. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52852. }
  52853. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52854. {
  52855. return 0;
  52856. }
  52857. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52858. {
  52859. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52860. }
  52861. int LookAndFeel::getDefaultScrollbarWidth()
  52862. {
  52863. return 18;
  52864. }
  52865. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52866. {
  52867. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52868. : scrollbar.getHeight());
  52869. }
  52870. const Path LookAndFeel::getTickShape (const float height)
  52871. {
  52872. static const unsigned char tickShapeData[] =
  52873. {
  52874. 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,
  52875. 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,
  52876. 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,
  52877. 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,
  52878. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52879. };
  52880. Path p;
  52881. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52882. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52883. return p;
  52884. }
  52885. const Path LookAndFeel::getCrossShape (const float height)
  52886. {
  52887. static const unsigned char crossShapeData[] =
  52888. {
  52889. 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,
  52890. 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,
  52891. 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,
  52892. 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,
  52893. 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,
  52894. 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,
  52895. 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
  52896. };
  52897. Path p;
  52898. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52899. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52900. return p;
  52901. }
  52902. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52903. {
  52904. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52905. x += (w - boxSize) >> 1;
  52906. y += (h - boxSize) >> 1;
  52907. w = boxSize;
  52908. h = boxSize;
  52909. g.setColour (Colour (0xe5ffffff));
  52910. g.fillRect (x, y, w, h);
  52911. g.setColour (Colour (0x80000000));
  52912. g.drawRect (x, y, w, h);
  52913. const float size = boxSize / 2 + 1.0f;
  52914. const float centre = (float) (boxSize / 2);
  52915. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52916. if (isPlus)
  52917. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52918. }
  52919. void LookAndFeel::drawBubble (Graphics& g,
  52920. float tipX, float tipY,
  52921. float boxX, float boxY,
  52922. float boxW, float boxH)
  52923. {
  52924. int side = 0;
  52925. if (tipX < boxX)
  52926. side = 1;
  52927. else if (tipX > boxX + boxW)
  52928. side = 3;
  52929. else if (tipY > boxY + boxH)
  52930. side = 2;
  52931. const float indent = 2.0f;
  52932. Path p;
  52933. p.addBubble (boxX + indent,
  52934. boxY + indent,
  52935. boxW - indent * 2.0f,
  52936. boxH - indent * 2.0f,
  52937. 5.0f,
  52938. tipX, tipY,
  52939. side,
  52940. 0.5f,
  52941. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52942. //xxx need to take comp as param for colour
  52943. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52944. g.fillPath (p);
  52945. //xxx as above
  52946. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52947. g.strokePath (p, PathStrokeType (1.33f));
  52948. }
  52949. const Font LookAndFeel::getPopupMenuFont()
  52950. {
  52951. return Font (17.0f);
  52952. }
  52953. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52954. const bool isSeparator,
  52955. int standardMenuItemHeight,
  52956. int& idealWidth,
  52957. int& idealHeight)
  52958. {
  52959. if (isSeparator)
  52960. {
  52961. idealWidth = 50;
  52962. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52963. }
  52964. else
  52965. {
  52966. Font font (getPopupMenuFont());
  52967. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52968. font.setHeight (standardMenuItemHeight / 1.3f);
  52969. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52970. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52971. }
  52972. }
  52973. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52974. {
  52975. const Colour background (findColour (PopupMenu::backgroundColourId));
  52976. g.fillAll (background);
  52977. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52978. for (int i = 0; i < height; i += 3)
  52979. g.fillRect (0, i, width, 1);
  52980. #if ! JUCE_MAC
  52981. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52982. g.drawRect (0, 0, width, height);
  52983. #endif
  52984. }
  52985. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52986. int width, int height,
  52987. bool isScrollUpArrow)
  52988. {
  52989. const Colour background (findColour (PopupMenu::backgroundColourId));
  52990. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52991. background.withAlpha (0.0f),
  52992. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52993. false));
  52994. g.fillRect (1, 1, width - 2, height - 2);
  52995. const float hw = width * 0.5f;
  52996. const float arrowW = height * 0.3f;
  52997. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52998. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52999. Path p;
  53000. p.addTriangle (hw - arrowW, y1,
  53001. hw + arrowW, y1,
  53002. hw, y2);
  53003. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53004. g.fillPath (p);
  53005. }
  53006. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53007. int width, int height,
  53008. const bool isSeparator,
  53009. const bool isActive,
  53010. const bool isHighlighted,
  53011. const bool isTicked,
  53012. const bool hasSubMenu,
  53013. const String& text,
  53014. const String& shortcutKeyText,
  53015. Image* image,
  53016. const Colour* const textColourToUse)
  53017. {
  53018. const float halfH = height * 0.5f;
  53019. if (isSeparator)
  53020. {
  53021. const float separatorIndent = 5.5f;
  53022. g.setColour (Colour (0x33000000));
  53023. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53024. g.setColour (Colour (0x66ffffff));
  53025. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53026. }
  53027. else
  53028. {
  53029. Colour textColour (findColour (PopupMenu::textColourId));
  53030. if (textColourToUse != 0)
  53031. textColour = *textColourToUse;
  53032. if (isHighlighted)
  53033. {
  53034. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53035. g.fillRect (1, 1, width - 2, height - 2);
  53036. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53037. }
  53038. else
  53039. {
  53040. g.setColour (textColour);
  53041. }
  53042. if (! isActive)
  53043. g.setOpacity (0.3f);
  53044. Font font (getPopupMenuFont());
  53045. if (font.getHeight() > height / 1.3f)
  53046. font.setHeight (height / 1.3f);
  53047. g.setFont (font);
  53048. const int leftBorder = (height * 5) / 4;
  53049. const int rightBorder = 4;
  53050. if (image != 0)
  53051. {
  53052. g.drawImageWithin (*image,
  53053. 2, 1, leftBorder - 4, height - 2,
  53054. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53055. }
  53056. else if (isTicked)
  53057. {
  53058. const Path tick (getTickShape (1.0f));
  53059. const float th = font.getAscent();
  53060. const float ty = halfH - th * 0.5f;
  53061. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53062. th, true));
  53063. }
  53064. g.drawFittedText (text,
  53065. leftBorder, 0,
  53066. width - (leftBorder + rightBorder), height,
  53067. Justification::centredLeft, 1);
  53068. if (shortcutKeyText.isNotEmpty())
  53069. {
  53070. Font f2 (font);
  53071. f2.setHeight (f2.getHeight() * 0.75f);
  53072. f2.setHorizontalScale (0.95f);
  53073. g.setFont (f2);
  53074. g.drawText (shortcutKeyText,
  53075. leftBorder,
  53076. 0,
  53077. width - (leftBorder + rightBorder + 4),
  53078. height,
  53079. Justification::centredRight,
  53080. true);
  53081. }
  53082. if (hasSubMenu)
  53083. {
  53084. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53085. const float x = width - height * 0.6f;
  53086. Path p;
  53087. p.addTriangle (x, halfH - arrowH * 0.5f,
  53088. x, halfH + arrowH * 0.5f,
  53089. x + arrowH * 0.6f, halfH);
  53090. g.fillPath (p);
  53091. }
  53092. }
  53093. }
  53094. int LookAndFeel::getMenuWindowFlags()
  53095. {
  53096. return ComponentPeer::windowHasDropShadow;
  53097. }
  53098. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53099. bool, MenuBarComponent& menuBar)
  53100. {
  53101. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53102. if (menuBar.isEnabled())
  53103. {
  53104. drawShinyButtonShape (g,
  53105. -4.0f, 0.0f,
  53106. width + 8.0f, (float) height,
  53107. 0.0f,
  53108. baseColour,
  53109. 0.4f,
  53110. true, true, true, true);
  53111. }
  53112. else
  53113. {
  53114. g.fillAll (baseColour);
  53115. }
  53116. }
  53117. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53118. {
  53119. return Font (menuBar.getHeight() * 0.7f);
  53120. }
  53121. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53122. {
  53123. return getMenuBarFont (menuBar, itemIndex, itemText)
  53124. .getStringWidth (itemText) + menuBar.getHeight();
  53125. }
  53126. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53127. int width, int height,
  53128. int itemIndex,
  53129. const String& itemText,
  53130. bool isMouseOverItem,
  53131. bool isMenuOpen,
  53132. bool /*isMouseOverBar*/,
  53133. MenuBarComponent& menuBar)
  53134. {
  53135. if (! menuBar.isEnabled())
  53136. {
  53137. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53138. .withMultipliedAlpha (0.5f));
  53139. }
  53140. else if (isMenuOpen || isMouseOverItem)
  53141. {
  53142. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53143. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53144. }
  53145. else
  53146. {
  53147. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53148. }
  53149. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53150. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53151. }
  53152. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53153. TextEditor& textEditor)
  53154. {
  53155. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53156. }
  53157. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53158. {
  53159. if (textEditor.isEnabled())
  53160. {
  53161. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53162. {
  53163. const int border = 2;
  53164. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53165. g.drawRect (0, 0, width, height, border);
  53166. g.setOpacity (1.0f);
  53167. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53168. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53169. }
  53170. else
  53171. {
  53172. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53173. g.drawRect (0, 0, width, height);
  53174. g.setOpacity (1.0f);
  53175. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53176. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53177. }
  53178. }
  53179. }
  53180. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53181. const bool isButtonDown,
  53182. int buttonX, int buttonY,
  53183. int buttonW, int buttonH,
  53184. ComboBox& box)
  53185. {
  53186. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53187. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53188. {
  53189. g.setColour (box.findColour (TextButton::buttonColourId));
  53190. g.drawRect (0, 0, width, height, 2);
  53191. }
  53192. else
  53193. {
  53194. g.setColour (box.findColour (ComboBox::outlineColourId));
  53195. g.drawRect (0, 0, width, height);
  53196. }
  53197. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53198. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53199. box.hasKeyboardFocus (true),
  53200. false, isButtonDown)
  53201. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53202. drawGlassLozenge (g,
  53203. buttonX + outlineThickness, buttonY + outlineThickness,
  53204. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53205. baseColour, outlineThickness, -1.0f,
  53206. true, true, true, true);
  53207. if (box.isEnabled())
  53208. {
  53209. const float arrowX = 0.3f;
  53210. const float arrowH = 0.2f;
  53211. Path p;
  53212. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53213. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53214. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53215. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53216. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53217. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53218. g.setColour (box.findColour (ComboBox::arrowColourId));
  53219. g.fillPath (p);
  53220. }
  53221. }
  53222. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53223. {
  53224. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53225. }
  53226. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53227. {
  53228. return new Label (String::empty, String::empty);
  53229. }
  53230. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53231. {
  53232. label.setBounds (1, 1,
  53233. box.getWidth() + 3 - box.getHeight(),
  53234. box.getHeight() - 2);
  53235. label.setFont (getComboBoxFont (box));
  53236. }
  53237. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53238. {
  53239. g.fillAll (label.findColour (Label::backgroundColourId));
  53240. if (! label.isBeingEdited())
  53241. {
  53242. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53243. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53244. g.setFont (label.getFont());
  53245. g.drawFittedText (label.getText(),
  53246. label.getHorizontalBorderSize(),
  53247. label.getVerticalBorderSize(),
  53248. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53249. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53250. label.getJustificationType(),
  53251. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53252. label.getMinimumHorizontalScale());
  53253. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53254. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53255. }
  53256. else if (label.isEnabled())
  53257. {
  53258. g.setColour (label.findColour (Label::outlineColourId));
  53259. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53260. }
  53261. }
  53262. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53263. int x, int y,
  53264. int width, int height,
  53265. float /*sliderPos*/,
  53266. float /*minSliderPos*/,
  53267. float /*maxSliderPos*/,
  53268. const Slider::SliderStyle /*style*/,
  53269. Slider& slider)
  53270. {
  53271. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53272. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53273. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53274. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53275. Path indent;
  53276. if (slider.isHorizontal())
  53277. {
  53278. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53279. const float ih = sliderRadius;
  53280. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53281. gradCol2, 0.0f, iy + ih, false));
  53282. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53283. width + sliderRadius, ih,
  53284. 5.0f);
  53285. g.fillPath (indent);
  53286. }
  53287. else
  53288. {
  53289. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53290. const float iw = sliderRadius;
  53291. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53292. gradCol2, ix + iw, 0.0f, false));
  53293. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53294. iw, height + sliderRadius,
  53295. 5.0f);
  53296. g.fillPath (indent);
  53297. }
  53298. g.setColour (Colour (0x4c000000));
  53299. g.strokePath (indent, PathStrokeType (0.5f));
  53300. }
  53301. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53302. int x, int y,
  53303. int width, int height,
  53304. float sliderPos,
  53305. float minSliderPos,
  53306. float maxSliderPos,
  53307. const Slider::SliderStyle style,
  53308. Slider& slider)
  53309. {
  53310. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53311. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53312. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53313. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53314. slider.isMouseButtonDown() && slider.isEnabled()));
  53315. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53316. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53317. {
  53318. float kx, ky;
  53319. if (style == Slider::LinearVertical)
  53320. {
  53321. kx = x + width * 0.5f;
  53322. ky = sliderPos;
  53323. }
  53324. else
  53325. {
  53326. kx = sliderPos;
  53327. ky = y + height * 0.5f;
  53328. }
  53329. drawGlassSphere (g,
  53330. kx - sliderRadius,
  53331. ky - sliderRadius,
  53332. sliderRadius * 2.0f,
  53333. knobColour, outlineThickness);
  53334. }
  53335. else
  53336. {
  53337. if (style == Slider::ThreeValueVertical)
  53338. {
  53339. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53340. sliderPos - sliderRadius,
  53341. sliderRadius * 2.0f,
  53342. knobColour, outlineThickness);
  53343. }
  53344. else if (style == Slider::ThreeValueHorizontal)
  53345. {
  53346. drawGlassSphere (g,sliderPos - sliderRadius,
  53347. y + height * 0.5f - sliderRadius,
  53348. sliderRadius * 2.0f,
  53349. knobColour, outlineThickness);
  53350. }
  53351. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53352. {
  53353. const float sr = jmin (sliderRadius, width * 0.4f);
  53354. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53355. minSliderPos - sliderRadius,
  53356. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53357. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53358. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53359. }
  53360. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53361. {
  53362. const float sr = jmin (sliderRadius, height * 0.4f);
  53363. drawGlassPointer (g, minSliderPos - sr,
  53364. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53365. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53366. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53367. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53368. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53369. }
  53370. }
  53371. }
  53372. void LookAndFeel::drawLinearSlider (Graphics& g,
  53373. int x, int y,
  53374. int width, int height,
  53375. float sliderPos,
  53376. float minSliderPos,
  53377. float maxSliderPos,
  53378. const Slider::SliderStyle style,
  53379. Slider& slider)
  53380. {
  53381. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53382. if (style == Slider::LinearBar)
  53383. {
  53384. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53385. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53386. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53387. false, isMouseOver,
  53388. isMouseOver || slider.isMouseButtonDown()));
  53389. drawShinyButtonShape (g,
  53390. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53391. baseColour,
  53392. slider.isEnabled() ? 0.9f : 0.3f,
  53393. true, true, true, true);
  53394. }
  53395. else
  53396. {
  53397. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53398. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53399. }
  53400. }
  53401. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53402. {
  53403. return jmin (7,
  53404. slider.getHeight() / 2,
  53405. slider.getWidth() / 2) + 2;
  53406. }
  53407. void LookAndFeel::drawRotarySlider (Graphics& g,
  53408. int x, int y,
  53409. int width, int height,
  53410. float sliderPos,
  53411. const float rotaryStartAngle,
  53412. const float rotaryEndAngle,
  53413. Slider& slider)
  53414. {
  53415. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53416. const float centreX = x + width * 0.5f;
  53417. const float centreY = y + height * 0.5f;
  53418. const float rx = centreX - radius;
  53419. const float ry = centreY - radius;
  53420. const float rw = radius * 2.0f;
  53421. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53422. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53423. if (radius > 12.0f)
  53424. {
  53425. if (slider.isEnabled())
  53426. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53427. else
  53428. g.setColour (Colour (0x80808080));
  53429. const float thickness = 0.7f;
  53430. {
  53431. Path filledArc;
  53432. filledArc.addPieSegment (rx, ry, rw, rw,
  53433. rotaryStartAngle,
  53434. angle,
  53435. thickness);
  53436. g.fillPath (filledArc);
  53437. }
  53438. if (thickness > 0)
  53439. {
  53440. const float innerRadius = radius * 0.2f;
  53441. Path p;
  53442. p.addTriangle (-innerRadius, 0.0f,
  53443. 0.0f, -radius * thickness * 1.1f,
  53444. innerRadius, 0.0f);
  53445. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53446. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53447. }
  53448. if (slider.isEnabled())
  53449. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53450. else
  53451. g.setColour (Colour (0x80808080));
  53452. Path outlineArc;
  53453. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53454. outlineArc.closeSubPath();
  53455. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53456. }
  53457. else
  53458. {
  53459. if (slider.isEnabled())
  53460. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53461. else
  53462. g.setColour (Colour (0x80808080));
  53463. Path p;
  53464. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53465. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53466. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53467. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53468. }
  53469. }
  53470. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53471. {
  53472. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53473. }
  53474. class SliderLabelComp : public Label
  53475. {
  53476. public:
  53477. SliderLabelComp() : Label (String::empty, String::empty) {}
  53478. ~SliderLabelComp() {}
  53479. void mouseWheelMove (const MouseEvent&, float, float) {}
  53480. };
  53481. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53482. {
  53483. Label* const l = new SliderLabelComp();
  53484. l->setJustificationType (Justification::centred);
  53485. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53486. l->setColour (Label::backgroundColourId,
  53487. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53488. : slider.findColour (Slider::textBoxBackgroundColourId));
  53489. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53490. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53491. l->setColour (TextEditor::backgroundColourId,
  53492. slider.findColour (Slider::textBoxBackgroundColourId)
  53493. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53494. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53495. return l;
  53496. }
  53497. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53498. {
  53499. return 0;
  53500. }
  53501. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53502. {
  53503. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53504. width = tl.getWidth() + 14;
  53505. height = tl.getHeight() + 6;
  53506. }
  53507. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53508. {
  53509. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53510. const Colour textCol (findColour (TooltipWindow::textColourId));
  53511. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53512. g.setColour (findColour (TooltipWindow::outlineColourId));
  53513. g.drawRect (0, 0, width, height, 1);
  53514. #endif
  53515. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53516. g.setColour (findColour (TooltipWindow::textColourId));
  53517. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53518. }
  53519. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53520. {
  53521. return new TextButton (text, TRANS("click to browse for a different file"));
  53522. }
  53523. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53524. ComboBox* filenameBox,
  53525. Button* browseButton)
  53526. {
  53527. browseButton->setSize (80, filenameComp.getHeight());
  53528. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53529. if (tb != 0)
  53530. tb->changeWidthToFitText();
  53531. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53532. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53533. }
  53534. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53535. int imageX, int imageY, int imageW, int imageH,
  53536. const Colour& overlayColour,
  53537. float imageOpacity,
  53538. ImageButton& button)
  53539. {
  53540. if (! button.isEnabled())
  53541. imageOpacity *= 0.3f;
  53542. if (! overlayColour.isOpaque())
  53543. {
  53544. g.setOpacity (imageOpacity);
  53545. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53546. 0, 0, image->getWidth(), image->getHeight(), false);
  53547. }
  53548. if (! overlayColour.isTransparent())
  53549. {
  53550. g.setColour (overlayColour);
  53551. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53552. 0, 0, image->getWidth(), image->getHeight(), true);
  53553. }
  53554. }
  53555. void LookAndFeel::drawCornerResizer (Graphics& g,
  53556. int w, int h,
  53557. bool /*isMouseOver*/,
  53558. bool /*isMouseDragging*/)
  53559. {
  53560. const float lineThickness = jmin (w, h) * 0.075f;
  53561. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53562. {
  53563. g.setColour (Colours::lightgrey);
  53564. g.drawLine (w * i,
  53565. h + 1.0f,
  53566. w + 1.0f,
  53567. h * i,
  53568. lineThickness);
  53569. g.setColour (Colours::darkgrey);
  53570. g.drawLine (w * i + lineThickness,
  53571. h + 1.0f,
  53572. w + 1.0f,
  53573. h * i + lineThickness,
  53574. lineThickness);
  53575. }
  53576. }
  53577. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53578. {
  53579. if (! border.isEmpty())
  53580. {
  53581. const Rectangle<int> fullSize (0, 0, w, h);
  53582. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53583. g.saveState();
  53584. g.excludeClipRegion (centreArea);
  53585. g.setColour (Colour (0x50000000));
  53586. g.drawRect (fullSize);
  53587. g.setColour (Colour (0x19000000));
  53588. g.drawRect (centreArea.expanded (1, 1));
  53589. g.restoreState();
  53590. }
  53591. }
  53592. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53593. const BorderSize& /*border*/, ResizableWindow& window)
  53594. {
  53595. g.fillAll (window.getBackgroundColour());
  53596. }
  53597. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53598. const BorderSize& /*border*/, ResizableWindow&)
  53599. {
  53600. }
  53601. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53602. Graphics& g, int w, int h,
  53603. int titleSpaceX, int titleSpaceW,
  53604. const Image* icon,
  53605. bool drawTitleTextOnLeft)
  53606. {
  53607. const bool isActive = window.isActiveWindow();
  53608. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53609. 0.0f, 0.0f,
  53610. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53611. 0.0f, (float) h, false));
  53612. g.fillAll();
  53613. Font font (h * 0.65f, Font::bold);
  53614. g.setFont (font);
  53615. int textW = font.getStringWidth (window.getName());
  53616. int iconW = 0;
  53617. int iconH = 0;
  53618. if (icon != 0)
  53619. {
  53620. iconH = (int) font.getHeight();
  53621. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53622. }
  53623. textW = jmin (titleSpaceW, textW + iconW);
  53624. int textX = drawTitleTextOnLeft ? titleSpaceX
  53625. : jmax (titleSpaceX, (w - textW) / 2);
  53626. if (textX + textW > titleSpaceX + titleSpaceW)
  53627. textX = titleSpaceX + titleSpaceW - textW;
  53628. if (icon != 0)
  53629. {
  53630. g.setOpacity (isActive ? 1.0f : 0.6f);
  53631. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53632. RectanglePlacement::centred, false);
  53633. textX += iconW;
  53634. textW -= iconW;
  53635. }
  53636. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53637. g.setColour (findColour (DocumentWindow::textColourId));
  53638. else
  53639. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53640. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53641. }
  53642. class GlassWindowButton : public Button
  53643. {
  53644. public:
  53645. GlassWindowButton (const String& name, const Colour& col,
  53646. const Path& normalShape_,
  53647. const Path& toggledShape_) throw()
  53648. : Button (name),
  53649. colour (col),
  53650. normalShape (normalShape_),
  53651. toggledShape (toggledShape_)
  53652. {
  53653. }
  53654. ~GlassWindowButton()
  53655. {
  53656. }
  53657. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53658. {
  53659. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53660. if (! isEnabled())
  53661. alpha *= 0.5f;
  53662. float x = 0, y = 0, diam;
  53663. if (getWidth() < getHeight())
  53664. {
  53665. diam = (float) getWidth();
  53666. y = (getHeight() - getWidth()) * 0.5f;
  53667. }
  53668. else
  53669. {
  53670. diam = (float) getHeight();
  53671. y = (getWidth() - getHeight()) * 0.5f;
  53672. }
  53673. x += diam * 0.05f;
  53674. y += diam * 0.05f;
  53675. diam *= 0.9f;
  53676. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53677. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53678. g.fillEllipse (x, y, diam, diam);
  53679. x += 2.0f;
  53680. y += 2.0f;
  53681. diam -= 4.0f;
  53682. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53683. Path& p = getToggleState() ? toggledShape : normalShape;
  53684. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53685. diam * 0.4f, diam * 0.4f, true));
  53686. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53687. g.fillPath (p, t);
  53688. }
  53689. private:
  53690. Colour colour;
  53691. Path normalShape, toggledShape;
  53692. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53693. };
  53694. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53695. {
  53696. Path shape;
  53697. const float crossThickness = 0.25f;
  53698. if (buttonType == DocumentWindow::closeButton)
  53699. {
  53700. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53701. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53702. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53703. }
  53704. else if (buttonType == DocumentWindow::minimiseButton)
  53705. {
  53706. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53707. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53708. }
  53709. else if (buttonType == DocumentWindow::maximiseButton)
  53710. {
  53711. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53712. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53713. Path fullscreenShape;
  53714. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53715. fullscreenShape.lineTo (0.0f, 100.0f);
  53716. fullscreenShape.lineTo (0.0f, 0.0f);
  53717. fullscreenShape.lineTo (100.0f, 0.0f);
  53718. fullscreenShape.lineTo (100.0f, 45.0f);
  53719. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53720. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53721. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53722. }
  53723. jassertfalse;
  53724. return 0;
  53725. }
  53726. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53727. int titleBarX,
  53728. int titleBarY,
  53729. int titleBarW,
  53730. int titleBarH,
  53731. Button* minimiseButton,
  53732. Button* maximiseButton,
  53733. Button* closeButton,
  53734. bool positionTitleBarButtonsOnLeft)
  53735. {
  53736. const int buttonW = titleBarH - titleBarH / 8;
  53737. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53738. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53739. if (closeButton != 0)
  53740. {
  53741. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53742. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53743. }
  53744. if (positionTitleBarButtonsOnLeft)
  53745. swapVariables (minimiseButton, maximiseButton);
  53746. if (maximiseButton != 0)
  53747. {
  53748. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53749. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53750. }
  53751. if (minimiseButton != 0)
  53752. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53753. }
  53754. int LookAndFeel::getDefaultMenuBarHeight()
  53755. {
  53756. return 24;
  53757. }
  53758. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53759. {
  53760. return new DropShadower (0.4f, 1, 5, 10);
  53761. }
  53762. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53763. int w, int h,
  53764. bool /*isVerticalBar*/,
  53765. bool isMouseOver,
  53766. bool isMouseDragging)
  53767. {
  53768. float alpha = 0.5f;
  53769. if (isMouseOver || isMouseDragging)
  53770. {
  53771. g.fillAll (Colour (0x190000ff));
  53772. alpha = 1.0f;
  53773. }
  53774. const float cx = w * 0.5f;
  53775. const float cy = h * 0.5f;
  53776. const float cr = jmin (w, h) * 0.4f;
  53777. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53778. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53779. true));
  53780. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53781. }
  53782. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53783. const String& text,
  53784. const Justification& position,
  53785. GroupComponent& group)
  53786. {
  53787. const float textH = 15.0f;
  53788. const float indent = 3.0f;
  53789. const float textEdgeGap = 4.0f;
  53790. float cs = 5.0f;
  53791. Font f (textH);
  53792. Path p;
  53793. float x = indent;
  53794. float y = f.getAscent() - 3.0f;
  53795. float w = jmax (0.0f, width - x * 2.0f);
  53796. float h = jmax (0.0f, height - y - indent);
  53797. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53798. const float cs2 = 2.0f * cs;
  53799. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53800. float textX = cs + textEdgeGap;
  53801. if (position.testFlags (Justification::horizontallyCentred))
  53802. textX = cs + (w - cs2 - textW) * 0.5f;
  53803. else if (position.testFlags (Justification::right))
  53804. textX = w - cs - textW - textEdgeGap;
  53805. p.startNewSubPath (x + textX + textW, y);
  53806. p.lineTo (x + w - cs, y);
  53807. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53808. p.lineTo (x + w, y + h - cs);
  53809. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53810. p.lineTo (x + cs, y + h);
  53811. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53812. p.lineTo (x, y + cs);
  53813. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53814. p.lineTo (x + textX, y);
  53815. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53816. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53817. .withMultipliedAlpha (alpha));
  53818. g.strokePath (p, PathStrokeType (2.0f));
  53819. g.setColour (group.findColour (GroupComponent::textColourId)
  53820. .withMultipliedAlpha (alpha));
  53821. g.setFont (f);
  53822. g.drawText (text,
  53823. roundToInt (x + textX), 0,
  53824. roundToInt (textW),
  53825. roundToInt (textH),
  53826. Justification::centred, true);
  53827. }
  53828. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53829. {
  53830. return 1 + tabDepth / 3;
  53831. }
  53832. int LookAndFeel::getTabButtonSpaceAroundImage()
  53833. {
  53834. return 4;
  53835. }
  53836. void LookAndFeel::createTabButtonShape (Path& p,
  53837. int width, int height,
  53838. int /*tabIndex*/,
  53839. const String& /*text*/,
  53840. Button& /*button*/,
  53841. TabbedButtonBar::Orientation orientation,
  53842. const bool /*isMouseOver*/,
  53843. const bool /*isMouseDown*/,
  53844. const bool /*isFrontTab*/)
  53845. {
  53846. const float w = (float) width;
  53847. const float h = (float) height;
  53848. float length = w;
  53849. float depth = h;
  53850. if (orientation == TabbedButtonBar::TabsAtLeft
  53851. || orientation == TabbedButtonBar::TabsAtRight)
  53852. {
  53853. swapVariables (length, depth);
  53854. }
  53855. const float indent = (float) getTabButtonOverlap ((int) depth);
  53856. const float overhang = 4.0f;
  53857. if (orientation == TabbedButtonBar::TabsAtLeft)
  53858. {
  53859. p.startNewSubPath (w, 0.0f);
  53860. p.lineTo (0.0f, indent);
  53861. p.lineTo (0.0f, h - indent);
  53862. p.lineTo (w, h);
  53863. p.lineTo (w + overhang, h + overhang);
  53864. p.lineTo (w + overhang, -overhang);
  53865. }
  53866. else if (orientation == TabbedButtonBar::TabsAtRight)
  53867. {
  53868. p.startNewSubPath (0.0f, 0.0f);
  53869. p.lineTo (w, indent);
  53870. p.lineTo (w, h - indent);
  53871. p.lineTo (0.0f, h);
  53872. p.lineTo (-overhang, h + overhang);
  53873. p.lineTo (-overhang, -overhang);
  53874. }
  53875. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53876. {
  53877. p.startNewSubPath (0.0f, 0.0f);
  53878. p.lineTo (indent, h);
  53879. p.lineTo (w - indent, h);
  53880. p.lineTo (w, 0.0f);
  53881. p.lineTo (w + overhang, -overhang);
  53882. p.lineTo (-overhang, -overhang);
  53883. }
  53884. else
  53885. {
  53886. p.startNewSubPath (0.0f, h);
  53887. p.lineTo (indent, 0.0f);
  53888. p.lineTo (w - indent, 0.0f);
  53889. p.lineTo (w, h);
  53890. p.lineTo (w + overhang, h + overhang);
  53891. p.lineTo (-overhang, h + overhang);
  53892. }
  53893. p.closeSubPath();
  53894. p = p.createPathWithRoundedCorners (3.0f);
  53895. }
  53896. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53897. const Path& path,
  53898. const Colour& preferredColour,
  53899. int /*tabIndex*/,
  53900. const String& /*text*/,
  53901. Button& button,
  53902. TabbedButtonBar::Orientation /*orientation*/,
  53903. const bool /*isMouseOver*/,
  53904. const bool /*isMouseDown*/,
  53905. const bool isFrontTab)
  53906. {
  53907. g.setColour (isFrontTab ? preferredColour
  53908. : preferredColour.withMultipliedAlpha (0.9f));
  53909. g.fillPath (path);
  53910. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53911. : TabbedButtonBar::tabOutlineColourId, false)
  53912. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53913. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53914. }
  53915. void LookAndFeel::drawTabButtonText (Graphics& g,
  53916. int x, int y, int w, int h,
  53917. const Colour& preferredBackgroundColour,
  53918. int /*tabIndex*/,
  53919. const String& text,
  53920. Button& button,
  53921. TabbedButtonBar::Orientation orientation,
  53922. const bool isMouseOver,
  53923. const bool isMouseDown,
  53924. const bool isFrontTab)
  53925. {
  53926. int length = w;
  53927. int depth = h;
  53928. if (orientation == TabbedButtonBar::TabsAtLeft
  53929. || orientation == TabbedButtonBar::TabsAtRight)
  53930. {
  53931. swapVariables (length, depth);
  53932. }
  53933. Font font (depth * 0.6f);
  53934. font.setUnderline (button.hasKeyboardFocus (false));
  53935. GlyphArrangement textLayout;
  53936. textLayout.addFittedText (font, text.trim(),
  53937. 0.0f, 0.0f, (float) length, (float) depth,
  53938. Justification::centred,
  53939. jmax (1, depth / 12));
  53940. AffineTransform transform;
  53941. if (orientation == TabbedButtonBar::TabsAtLeft)
  53942. {
  53943. transform = transform.rotated (float_Pi * -0.5f)
  53944. .translated ((float) x, (float) (y + h));
  53945. }
  53946. else if (orientation == TabbedButtonBar::TabsAtRight)
  53947. {
  53948. transform = transform.rotated (float_Pi * 0.5f)
  53949. .translated ((float) (x + w), (float) y);
  53950. }
  53951. else
  53952. {
  53953. transform = transform.translated ((float) x, (float) y);
  53954. }
  53955. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53956. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53957. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53958. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53959. else
  53960. g.setColour (preferredBackgroundColour.contrasting());
  53961. if (! (isMouseOver || isMouseDown))
  53962. g.setOpacity (0.8f);
  53963. if (! button.isEnabled())
  53964. g.setOpacity (0.3f);
  53965. textLayout.draw (g, transform);
  53966. }
  53967. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53968. const String& text,
  53969. int tabDepth,
  53970. Button&)
  53971. {
  53972. Font f (tabDepth * 0.6f);
  53973. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53974. }
  53975. void LookAndFeel::drawTabButton (Graphics& g,
  53976. int w, int h,
  53977. const Colour& preferredColour,
  53978. int tabIndex,
  53979. const String& text,
  53980. Button& button,
  53981. TabbedButtonBar::Orientation orientation,
  53982. const bool isMouseOver,
  53983. const bool isMouseDown,
  53984. const bool isFrontTab)
  53985. {
  53986. int length = w;
  53987. int depth = h;
  53988. if (orientation == TabbedButtonBar::TabsAtLeft
  53989. || orientation == TabbedButtonBar::TabsAtRight)
  53990. {
  53991. swapVariables (length, depth);
  53992. }
  53993. Path tabShape;
  53994. createTabButtonShape (tabShape, w, h,
  53995. tabIndex, text, button, orientation,
  53996. isMouseOver, isMouseDown, isFrontTab);
  53997. fillTabButtonShape (g, tabShape, preferredColour,
  53998. tabIndex, text, button, orientation,
  53999. isMouseOver, isMouseDown, isFrontTab);
  54000. const int indent = getTabButtonOverlap (depth);
  54001. int x = 0, y = 0;
  54002. if (orientation == TabbedButtonBar::TabsAtLeft
  54003. || orientation == TabbedButtonBar::TabsAtRight)
  54004. {
  54005. y += indent;
  54006. h -= indent * 2;
  54007. }
  54008. else
  54009. {
  54010. x += indent;
  54011. w -= indent * 2;
  54012. }
  54013. drawTabButtonText (g, x, y, w, h, preferredColour,
  54014. tabIndex, text, button, orientation,
  54015. isMouseOver, isMouseDown, isFrontTab);
  54016. }
  54017. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54018. int w, int h,
  54019. TabbedButtonBar& tabBar,
  54020. TabbedButtonBar::Orientation orientation)
  54021. {
  54022. const float shadowSize = 0.2f;
  54023. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54024. Rectangle<int> shadowRect;
  54025. if (orientation == TabbedButtonBar::TabsAtLeft)
  54026. {
  54027. x1 = (float) w;
  54028. x2 = w * (1.0f - shadowSize);
  54029. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54030. }
  54031. else if (orientation == TabbedButtonBar::TabsAtRight)
  54032. {
  54033. x2 = w * shadowSize;
  54034. shadowRect.setBounds (0, 0, (int) x2, h);
  54035. }
  54036. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54037. {
  54038. y2 = h * shadowSize;
  54039. shadowRect.setBounds (0, 0, w, (int) y2);
  54040. }
  54041. else
  54042. {
  54043. y1 = (float) h;
  54044. y2 = h * (1.0f - shadowSize);
  54045. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54046. }
  54047. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54048. Colours::transparentBlack, x2, y2, false));
  54049. shadowRect.expand (2, 2);
  54050. g.fillRect (shadowRect);
  54051. g.setColour (Colour (0x80000000));
  54052. if (orientation == TabbedButtonBar::TabsAtLeft)
  54053. {
  54054. g.fillRect (w - 1, 0, 1, h);
  54055. }
  54056. else if (orientation == TabbedButtonBar::TabsAtRight)
  54057. {
  54058. g.fillRect (0, 0, 1, h);
  54059. }
  54060. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54061. {
  54062. g.fillRect (0, 0, w, 1);
  54063. }
  54064. else
  54065. {
  54066. g.fillRect (0, h - 1, w, 1);
  54067. }
  54068. }
  54069. Button* LookAndFeel::createTabBarExtrasButton()
  54070. {
  54071. const float thickness = 7.0f;
  54072. const float indent = 22.0f;
  54073. Path p;
  54074. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54075. DrawablePath ellipse;
  54076. ellipse.setPath (p);
  54077. ellipse.setFill (Colour (0x99ffffff));
  54078. p.clear();
  54079. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54080. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54081. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54082. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54083. p.setUsingNonZeroWinding (false);
  54084. DrawablePath dp;
  54085. dp.setPath (p);
  54086. dp.setFill (Colour (0x59000000));
  54087. DrawableComposite normalImage;
  54088. normalImage.insertDrawable (ellipse);
  54089. normalImage.insertDrawable (dp);
  54090. dp.setFill (Colour (0xcc000000));
  54091. DrawableComposite overImage;
  54092. overImage.insertDrawable (ellipse);
  54093. overImage.insertDrawable (dp);
  54094. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54095. db->setImages (&normalImage, &overImage, 0);
  54096. return db;
  54097. }
  54098. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54099. {
  54100. g.fillAll (Colours::white);
  54101. const int w = header.getWidth();
  54102. const int h = header.getHeight();
  54103. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54104. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54105. false));
  54106. g.fillRect (0, h / 2, w, h);
  54107. g.setColour (Colour (0x33000000));
  54108. g.fillRect (0, h - 1, w, 1);
  54109. for (int i = header.getNumColumns (true); --i >= 0;)
  54110. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54111. }
  54112. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54113. int width, int height,
  54114. bool isMouseOver, bool isMouseDown,
  54115. int columnFlags)
  54116. {
  54117. if (isMouseDown)
  54118. g.fillAll (Colour (0x8899aadd));
  54119. else if (isMouseOver)
  54120. g.fillAll (Colour (0x5599aadd));
  54121. int rightOfText = width - 4;
  54122. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54123. {
  54124. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54125. const float bottom = height - top;
  54126. const float w = height * 0.5f;
  54127. const float x = rightOfText - (w * 1.25f);
  54128. rightOfText = (int) x;
  54129. Path sortArrow;
  54130. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54131. g.setColour (Colour (0x99000000));
  54132. g.fillPath (sortArrow);
  54133. }
  54134. g.setColour (Colours::black);
  54135. g.setFont (height * 0.5f, Font::bold);
  54136. const int textX = 4;
  54137. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54138. }
  54139. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54140. {
  54141. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54142. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54143. background.darker (0.1f),
  54144. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54145. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54146. false));
  54147. g.fillAll();
  54148. }
  54149. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54150. {
  54151. return createTabBarExtrasButton();
  54152. }
  54153. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54154. bool isMouseOver, bool isMouseDown,
  54155. ToolbarItemComponent& component)
  54156. {
  54157. if (isMouseDown)
  54158. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54159. else if (isMouseOver)
  54160. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54161. }
  54162. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54163. const String& text, ToolbarItemComponent& component)
  54164. {
  54165. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54166. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54167. const float fontHeight = jmin (14.0f, height * 0.85f);
  54168. g.setFont (fontHeight);
  54169. g.drawFittedText (text,
  54170. x, y, width, height,
  54171. Justification::centred,
  54172. jmax (1, height / (int) fontHeight));
  54173. }
  54174. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54175. bool isOpen, int width, int height)
  54176. {
  54177. const int buttonSize = (height * 3) / 4;
  54178. const int buttonIndent = (height - buttonSize) / 2;
  54179. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54180. const int textX = buttonIndent * 2 + buttonSize + 2;
  54181. g.setColour (Colours::black);
  54182. g.setFont (height * 0.7f, Font::bold);
  54183. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54184. }
  54185. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54186. PropertyComponent&)
  54187. {
  54188. g.setColour (Colour (0x66ffffff));
  54189. g.fillRect (0, 0, width, height - 1);
  54190. }
  54191. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54192. PropertyComponent& component)
  54193. {
  54194. g.setColour (Colours::black);
  54195. if (! component.isEnabled())
  54196. g.setOpacity (0.6f);
  54197. g.setFont (jmin (height, 24) * 0.65f);
  54198. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54199. g.drawFittedText (component.getName(),
  54200. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54201. Justification::centredLeft, 2);
  54202. }
  54203. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54204. {
  54205. return Rectangle<int> (component.getWidth() / 3, 1,
  54206. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54207. }
  54208. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54209. {
  54210. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54211. {
  54212. Graphics g2 (content);
  54213. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54214. g2.fillPath (path);
  54215. g2.setColour (Colours::white.withAlpha (0.8f));
  54216. g2.strokePath (path, PathStrokeType (2.0f));
  54217. }
  54218. DropShadowEffect shadow;
  54219. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54220. shadow.applyEffect (content, g, 1.0f);
  54221. }
  54222. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54223. const String& instructions,
  54224. GlyphArrangement& text,
  54225. int width)
  54226. {
  54227. text.clear();
  54228. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54229. 8.0f, 22.0f, width - 16.0f,
  54230. Justification::centred);
  54231. text.addJustifiedText (Font (14.0f), instructions,
  54232. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54233. Justification::centred);
  54234. }
  54235. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54236. const String& filename, Image* icon,
  54237. const String& fileSizeDescription,
  54238. const String& fileTimeDescription,
  54239. const bool isDirectory,
  54240. const bool isItemSelected,
  54241. const int /*itemIndex*/,
  54242. DirectoryContentsDisplayComponent&)
  54243. {
  54244. if (isItemSelected)
  54245. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54246. const int x = 32;
  54247. g.setColour (Colours::black);
  54248. if (icon != 0 && icon->isValid())
  54249. {
  54250. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54251. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54252. false);
  54253. }
  54254. else
  54255. {
  54256. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54257. : getDefaultDocumentFileImage();
  54258. if (d != 0)
  54259. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54260. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54261. }
  54262. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54263. g.setFont (height * 0.7f);
  54264. if (width > 450 && ! isDirectory)
  54265. {
  54266. const int sizeX = roundToInt (width * 0.7f);
  54267. const int dateX = roundToInt (width * 0.8f);
  54268. g.drawFittedText (filename,
  54269. x, 0, sizeX - x, height,
  54270. Justification::centredLeft, 1);
  54271. g.setFont (height * 0.5f);
  54272. g.setColour (Colours::darkgrey);
  54273. if (! isDirectory)
  54274. {
  54275. g.drawFittedText (fileSizeDescription,
  54276. sizeX, 0, dateX - sizeX - 8, height,
  54277. Justification::centredRight, 1);
  54278. g.drawFittedText (fileTimeDescription,
  54279. dateX, 0, width - 8 - dateX, height,
  54280. Justification::centredRight, 1);
  54281. }
  54282. }
  54283. else
  54284. {
  54285. g.drawFittedText (filename,
  54286. x, 0, width - x, height,
  54287. Justification::centredLeft, 1);
  54288. }
  54289. }
  54290. Button* LookAndFeel::createFileBrowserGoUpButton()
  54291. {
  54292. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54293. Path arrowPath;
  54294. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54295. DrawablePath arrowImage;
  54296. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54297. arrowImage.setPath (arrowPath);
  54298. goUpButton->setImages (&arrowImage);
  54299. return goUpButton;
  54300. }
  54301. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54302. DirectoryContentsDisplayComponent* fileListComponent,
  54303. FilePreviewComponent* previewComp,
  54304. ComboBox* currentPathBox,
  54305. TextEditor* filenameBox,
  54306. Button* goUpButton)
  54307. {
  54308. const int x = 8;
  54309. int w = browserComp.getWidth() - x - x;
  54310. if (previewComp != 0)
  54311. {
  54312. const int previewWidth = w / 3;
  54313. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54314. w -= previewWidth + 4;
  54315. }
  54316. int y = 4;
  54317. const int controlsHeight = 22;
  54318. const int bottomSectionHeight = controlsHeight + 8;
  54319. const int upButtonWidth = 50;
  54320. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54321. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54322. y += controlsHeight + 4;
  54323. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54324. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54325. y = listAsComp->getBottom() + 4;
  54326. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54327. }
  54328. // Pulls a drawable out of compressed valuetree data..
  54329. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54330. {
  54331. MemoryInputStream m (data, numBytes, false);
  54332. GZIPDecompressorInputStream gz (m);
  54333. ValueTree drawable (ValueTree::readFromStream (gz));
  54334. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54335. }
  54336. const Drawable* LookAndFeel::getDefaultFolderImage()
  54337. {
  54338. if (folderImage == 0)
  54339. {
  54340. static const unsigned char drawableData[] =
  54341. { 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,
  54342. 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,
  54343. 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,
  54344. 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,
  54345. 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,
  54346. 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,
  54347. 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,
  54348. 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,
  54349. 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,
  54350. 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,
  54351. 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,
  54352. 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,
  54353. 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,
  54354. 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,
  54355. 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 };
  54356. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54357. }
  54358. return folderImage;
  54359. }
  54360. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54361. {
  54362. if (documentImage == 0)
  54363. {
  54364. static const unsigned char drawableData[] =
  54365. { 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,
  54366. 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,
  54367. 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,
  54368. 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,
  54369. 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,
  54370. 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,
  54371. 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,
  54372. 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,
  54373. 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,
  54374. 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,
  54375. 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,
  54376. 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,
  54377. 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,
  54378. 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,
  54379. 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,
  54380. 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,
  54381. 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,
  54382. 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,
  54383. 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,
  54384. 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,
  54385. 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,
  54386. 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,
  54387. 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 };
  54388. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54389. }
  54390. return documentImage;
  54391. }
  54392. void LookAndFeel::playAlertSound()
  54393. {
  54394. PlatformUtilities::beep();
  54395. }
  54396. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54397. {
  54398. g.setColour (Colours::white.withAlpha (0.7f));
  54399. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54400. g.setColour (Colours::black.withAlpha (0.2f));
  54401. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54402. const int totalBlocks = 7;
  54403. const int numBlocks = roundToInt (totalBlocks * level);
  54404. const float w = (width - 6.0f) / (float) totalBlocks;
  54405. for (int i = 0; i < totalBlocks; ++i)
  54406. {
  54407. if (i >= numBlocks)
  54408. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54409. else
  54410. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54411. : Colours::red);
  54412. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54413. }
  54414. }
  54415. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54416. {
  54417. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54418. if (keyDescription.isNotEmpty())
  54419. {
  54420. if (button.isEnabled())
  54421. {
  54422. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54423. g.fillAll (textColour.withAlpha (alpha));
  54424. g.setOpacity (0.3f);
  54425. g.drawBevel (0, 0, width, height, 2);
  54426. }
  54427. g.setColour (textColour);
  54428. g.setFont (height * 0.6f);
  54429. g.drawFittedText (keyDescription,
  54430. 3, 0, width - 6, height,
  54431. Justification::centred, 1);
  54432. }
  54433. else
  54434. {
  54435. const float thickness = 7.0f;
  54436. const float indent = 22.0f;
  54437. Path p;
  54438. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54439. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54440. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54441. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54442. p.setUsingNonZeroWinding (false);
  54443. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54444. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54445. }
  54446. if (button.hasKeyboardFocus (false))
  54447. {
  54448. g.setColour (textColour.withAlpha (0.4f));
  54449. g.drawRect (0, 0, width, height);
  54450. }
  54451. }
  54452. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54453. float x, float y, float w, float h,
  54454. float maxCornerSize,
  54455. const Colour& baseColour,
  54456. const float strokeWidth,
  54457. const bool flatOnLeft,
  54458. const bool flatOnRight,
  54459. const bool flatOnTop,
  54460. const bool flatOnBottom) throw()
  54461. {
  54462. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54463. return;
  54464. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54465. Path outline;
  54466. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54467. ! (flatOnLeft || flatOnTop),
  54468. ! (flatOnRight || flatOnTop),
  54469. ! (flatOnLeft || flatOnBottom),
  54470. ! (flatOnRight || flatOnBottom));
  54471. ColourGradient cg (baseColour, 0.0f, y,
  54472. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54473. false);
  54474. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54475. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54476. g.setGradientFill (cg);
  54477. g.fillPath (outline);
  54478. g.setColour (Colour (0x80000000));
  54479. g.strokePath (outline, PathStrokeType (strokeWidth));
  54480. }
  54481. void LookAndFeel::drawGlassSphere (Graphics& g,
  54482. const float x, const float y,
  54483. const float diameter,
  54484. const Colour& colour,
  54485. const float outlineThickness) throw()
  54486. {
  54487. if (diameter <= outlineThickness)
  54488. return;
  54489. Path p;
  54490. p.addEllipse (x, y, diameter, diameter);
  54491. {
  54492. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54493. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54494. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54495. g.setGradientFill (cg);
  54496. g.fillPath (p);
  54497. }
  54498. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54499. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54500. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54501. ColourGradient cg (Colours::transparentBlack,
  54502. x + diameter * 0.5f, y + diameter * 0.5f,
  54503. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54504. x, y + diameter * 0.5f, true);
  54505. cg.addColour (0.7, Colours::transparentBlack);
  54506. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54507. g.setGradientFill (cg);
  54508. g.fillPath (p);
  54509. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54510. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54511. }
  54512. void LookAndFeel::drawGlassPointer (Graphics& g,
  54513. const float x, const float y,
  54514. const float diameter,
  54515. const Colour& colour, const float outlineThickness,
  54516. const int direction) throw()
  54517. {
  54518. if (diameter <= outlineThickness)
  54519. return;
  54520. Path p;
  54521. p.startNewSubPath (x + diameter * 0.5f, y);
  54522. p.lineTo (x + diameter, y + diameter * 0.6f);
  54523. p.lineTo (x + diameter, y + diameter);
  54524. p.lineTo (x, y + diameter);
  54525. p.lineTo (x, y + diameter * 0.6f);
  54526. p.closeSubPath();
  54527. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54528. {
  54529. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54530. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54531. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54532. g.setGradientFill (cg);
  54533. g.fillPath (p);
  54534. }
  54535. ColourGradient cg (Colours::transparentBlack,
  54536. x + diameter * 0.5f, y + diameter * 0.5f,
  54537. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54538. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54539. cg.addColour (0.5, Colours::transparentBlack);
  54540. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54541. g.setGradientFill (cg);
  54542. g.fillPath (p);
  54543. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54544. g.strokePath (p, PathStrokeType (outlineThickness));
  54545. }
  54546. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54547. const float x, const float y,
  54548. const float width, const float height,
  54549. const Colour& colour,
  54550. const float outlineThickness,
  54551. const float cornerSize,
  54552. const bool flatOnLeft,
  54553. const bool flatOnRight,
  54554. const bool flatOnTop,
  54555. const bool flatOnBottom) throw()
  54556. {
  54557. if (width <= outlineThickness || height <= outlineThickness)
  54558. return;
  54559. const int intX = (int) x;
  54560. const int intY = (int) y;
  54561. const int intW = (int) width;
  54562. const int intH = (int) height;
  54563. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54564. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54565. const int intEdge = (int) edgeBlurRadius;
  54566. Path outline;
  54567. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54568. ! (flatOnLeft || flatOnTop),
  54569. ! (flatOnRight || flatOnTop),
  54570. ! (flatOnLeft || flatOnBottom),
  54571. ! (flatOnRight || flatOnBottom));
  54572. {
  54573. ColourGradient cg (colour.darker (0.2f), 0, y,
  54574. colour.darker (0.2f), 0, y + height, false);
  54575. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54576. cg.addColour (0.4, colour);
  54577. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54578. g.setGradientFill (cg);
  54579. g.fillPath (outline);
  54580. }
  54581. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54582. colour.darker (0.2f), x, y + height * 0.5f, true);
  54583. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54584. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54585. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54586. {
  54587. g.saveState();
  54588. g.setGradientFill (cg);
  54589. g.reduceClipRegion (intX, intY, intEdge, intH);
  54590. g.fillPath (outline);
  54591. g.restoreState();
  54592. }
  54593. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54594. {
  54595. cg.point1.setX (x + width - edgeBlurRadius);
  54596. cg.point2.setX (x + width);
  54597. g.saveState();
  54598. g.setGradientFill (cg);
  54599. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54600. g.fillPath (outline);
  54601. g.restoreState();
  54602. }
  54603. {
  54604. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54605. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54606. Path highlight;
  54607. LookAndFeelHelpers::createRoundedPath (highlight,
  54608. x + leftIndent,
  54609. y + cs * 0.1f,
  54610. width - (leftIndent + rightIndent),
  54611. height * 0.4f, cs * 0.4f,
  54612. ! (flatOnLeft || flatOnTop),
  54613. ! (flatOnRight || flatOnTop),
  54614. ! (flatOnLeft || flatOnBottom),
  54615. ! (flatOnRight || flatOnBottom));
  54616. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54617. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54618. g.fillPath (highlight);
  54619. }
  54620. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54621. g.strokePath (outline, PathStrokeType (outlineThickness));
  54622. }
  54623. END_JUCE_NAMESPACE
  54624. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54625. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54626. BEGIN_JUCE_NAMESPACE
  54627. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54628. {
  54629. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54630. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54631. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54632. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54633. setColour (Slider::thumbColourId, Colours::white);
  54634. setColour (Slider::trackColourId, Colour (0x7f000000));
  54635. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54636. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54637. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54638. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54639. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54640. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54641. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54642. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54643. }
  54644. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54645. {
  54646. }
  54647. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54648. Button& button,
  54649. const Colour& backgroundColour,
  54650. bool isMouseOverButton,
  54651. bool isButtonDown)
  54652. {
  54653. const int width = button.getWidth();
  54654. const int height = button.getHeight();
  54655. const float indent = 2.0f;
  54656. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54657. roundToInt (height * 0.4f));
  54658. Path p;
  54659. p.addRoundedRectangle (indent, indent,
  54660. width - indent * 2.0f,
  54661. height - indent * 2.0f,
  54662. (float) cornerSize);
  54663. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54664. if (isMouseOverButton)
  54665. {
  54666. if (isButtonDown)
  54667. bc = bc.brighter();
  54668. else if (bc.getBrightness() > 0.5f)
  54669. bc = bc.darker (0.1f);
  54670. else
  54671. bc = bc.brighter (0.1f);
  54672. }
  54673. g.setColour (bc);
  54674. g.fillPath (p);
  54675. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54676. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54677. }
  54678. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54679. Component& /*component*/,
  54680. float x, float y, float w, float h,
  54681. const bool ticked,
  54682. const bool isEnabled,
  54683. const bool /*isMouseOverButton*/,
  54684. const bool isButtonDown)
  54685. {
  54686. Path box;
  54687. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54688. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54689. : Colours::lightgrey.withAlpha (0.1f));
  54690. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54691. g.fillPath (box, trans);
  54692. g.setColour (Colours::black.withAlpha (0.6f));
  54693. g.strokePath (box, PathStrokeType (0.9f), trans);
  54694. if (ticked)
  54695. {
  54696. Path tick;
  54697. tick.startNewSubPath (1.5f, 3.0f);
  54698. tick.lineTo (3.0f, 6.0f);
  54699. tick.lineTo (6.0f, 0.0f);
  54700. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54701. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54702. }
  54703. }
  54704. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54705. ToggleButton& button,
  54706. bool isMouseOverButton,
  54707. bool isButtonDown)
  54708. {
  54709. if (button.hasKeyboardFocus (true))
  54710. {
  54711. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54712. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54713. }
  54714. const int tickWidth = jmin (20, button.getHeight() - 4);
  54715. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54716. (float) tickWidth, (float) tickWidth,
  54717. button.getToggleState(),
  54718. button.isEnabled(),
  54719. isMouseOverButton,
  54720. isButtonDown);
  54721. g.setColour (button.findColour (ToggleButton::textColourId));
  54722. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54723. if (! button.isEnabled())
  54724. g.setOpacity (0.5f);
  54725. const int textX = tickWidth + 5;
  54726. g.drawFittedText (button.getButtonText(),
  54727. textX, 4,
  54728. button.getWidth() - textX - 2, button.getHeight() - 8,
  54729. Justification::centredLeft, 10);
  54730. }
  54731. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54732. int width, int height,
  54733. double progress, const String& textToShow)
  54734. {
  54735. if (progress < 0 || progress >= 1.0)
  54736. {
  54737. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54738. }
  54739. else
  54740. {
  54741. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54742. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54743. g.fillAll (background);
  54744. g.setColour (foreground);
  54745. g.fillRect (1, 1,
  54746. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54747. height - 2);
  54748. if (textToShow.isNotEmpty())
  54749. {
  54750. g.setColour (Colour::contrasting (background, foreground));
  54751. g.setFont (height * 0.6f);
  54752. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54753. }
  54754. }
  54755. }
  54756. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54757. ScrollBar& bar,
  54758. int width, int height,
  54759. int buttonDirection,
  54760. bool isScrollbarVertical,
  54761. bool isMouseOverButton,
  54762. bool isButtonDown)
  54763. {
  54764. if (isScrollbarVertical)
  54765. width -= 2;
  54766. else
  54767. height -= 2;
  54768. Path p;
  54769. if (buttonDirection == 0)
  54770. p.addTriangle (width * 0.5f, height * 0.2f,
  54771. width * 0.1f, height * 0.7f,
  54772. width * 0.9f, height * 0.7f);
  54773. else if (buttonDirection == 1)
  54774. p.addTriangle (width * 0.8f, height * 0.5f,
  54775. width * 0.3f, height * 0.1f,
  54776. width * 0.3f, height * 0.9f);
  54777. else if (buttonDirection == 2)
  54778. p.addTriangle (width * 0.5f, height * 0.8f,
  54779. width * 0.1f, height * 0.3f,
  54780. width * 0.9f, height * 0.3f);
  54781. else if (buttonDirection == 3)
  54782. p.addTriangle (width * 0.2f, height * 0.5f,
  54783. width * 0.7f, height * 0.1f,
  54784. width * 0.7f, height * 0.9f);
  54785. if (isButtonDown)
  54786. g.setColour (Colours::white);
  54787. else if (isMouseOverButton)
  54788. g.setColour (Colours::white.withAlpha (0.7f));
  54789. else
  54790. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54791. g.fillPath (p);
  54792. g.setColour (Colours::black.withAlpha (0.5f));
  54793. g.strokePath (p, PathStrokeType (0.5f));
  54794. }
  54795. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54796. ScrollBar& bar,
  54797. int x, int y,
  54798. int width, int height,
  54799. bool isScrollbarVertical,
  54800. int thumbStartPosition,
  54801. int thumbSize,
  54802. bool isMouseOver,
  54803. bool isMouseDown)
  54804. {
  54805. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54806. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54807. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54808. if (thumbSize > 0.0f)
  54809. {
  54810. Rectangle<int> thumb;
  54811. if (isScrollbarVertical)
  54812. {
  54813. width -= 2;
  54814. g.fillRect (x + roundToInt (width * 0.35f), y,
  54815. roundToInt (width * 0.3f), height);
  54816. thumb.setBounds (x + 1, thumbStartPosition,
  54817. width - 2, thumbSize);
  54818. }
  54819. else
  54820. {
  54821. height -= 2;
  54822. g.fillRect (x, y + roundToInt (height * 0.35f),
  54823. width, roundToInt (height * 0.3f));
  54824. thumb.setBounds (thumbStartPosition, y + 1,
  54825. thumbSize, height - 2);
  54826. }
  54827. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54828. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54829. g.fillRect (thumb);
  54830. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54831. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54832. if (thumbSize > 16)
  54833. {
  54834. for (int i = 3; --i >= 0;)
  54835. {
  54836. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54837. g.setColour (Colours::black.withAlpha (0.15f));
  54838. if (isScrollbarVertical)
  54839. {
  54840. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54841. g.setColour (Colours::white.withAlpha (0.15f));
  54842. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54843. }
  54844. else
  54845. {
  54846. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54847. g.setColour (Colours::white.withAlpha (0.15f));
  54848. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54849. }
  54850. }
  54851. }
  54852. }
  54853. }
  54854. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54855. {
  54856. return &scrollbarShadow;
  54857. }
  54858. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54859. {
  54860. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54861. g.setColour (Colours::black.withAlpha (0.6f));
  54862. g.drawRect (0, 0, width, height);
  54863. }
  54864. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54865. bool, MenuBarComponent& menuBar)
  54866. {
  54867. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54868. }
  54869. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54870. {
  54871. if (textEditor.isEnabled())
  54872. {
  54873. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54874. g.drawRect (0, 0, width, height);
  54875. }
  54876. }
  54877. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54878. const bool isButtonDown,
  54879. int buttonX, int buttonY,
  54880. int buttonW, int buttonH,
  54881. ComboBox& box)
  54882. {
  54883. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54884. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54885. : ComboBox::backgroundColourId));
  54886. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54887. g.setColour (box.findColour (ComboBox::outlineColourId));
  54888. g.drawRect (0, 0, width, height);
  54889. const float arrowX = 0.2f;
  54890. const float arrowH = 0.3f;
  54891. if (box.isEnabled())
  54892. {
  54893. Path p;
  54894. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54895. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54896. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54897. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54898. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54899. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54900. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54901. : ComboBox::buttonColourId));
  54902. g.fillPath (p);
  54903. }
  54904. }
  54905. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54906. {
  54907. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54908. f.setHorizontalScale (0.9f);
  54909. return f;
  54910. }
  54911. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54912. {
  54913. Path p;
  54914. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54915. g.setColour (fill);
  54916. g.fillPath (p);
  54917. g.setColour (outline);
  54918. g.strokePath (p, PathStrokeType (0.3f));
  54919. }
  54920. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54921. int x, int y,
  54922. int w, int h,
  54923. float sliderPos,
  54924. float minSliderPos,
  54925. float maxSliderPos,
  54926. const Slider::SliderStyle style,
  54927. Slider& slider)
  54928. {
  54929. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54930. if (style == Slider::LinearBar)
  54931. {
  54932. g.setColour (slider.findColour (Slider::thumbColourId));
  54933. g.fillRect (x, y, (int) sliderPos - x, h);
  54934. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54935. g.drawRect (x, y, (int) sliderPos - x, h);
  54936. }
  54937. else
  54938. {
  54939. g.setColour (slider.findColour (Slider::trackColourId)
  54940. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54941. if (slider.isHorizontal())
  54942. {
  54943. g.fillRect (x, y + roundToInt (h * 0.6f),
  54944. w, roundToInt (h * 0.2f));
  54945. }
  54946. else
  54947. {
  54948. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54949. jmin (4, roundToInt (w * 0.2f)), h);
  54950. }
  54951. float alpha = 0.35f;
  54952. if (slider.isEnabled())
  54953. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54954. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54955. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54956. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54957. {
  54958. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54959. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54960. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54961. fill, outline);
  54962. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54963. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54964. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54965. fill, outline);
  54966. }
  54967. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54968. {
  54969. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54970. minSliderPos - 7.0f, y + h * 0.9f ,
  54971. minSliderPos, y + h * 0.9f,
  54972. fill, outline);
  54973. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54974. maxSliderPos, y + h * 0.9f,
  54975. maxSliderPos + 7.0f, y + h * 0.9f,
  54976. fill, outline);
  54977. }
  54978. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54979. {
  54980. drawTriangle (g, sliderPos, y + h * 0.9f,
  54981. sliderPos - 7.0f, y + h * 0.2f,
  54982. sliderPos + 7.0f, y + h * 0.2f,
  54983. fill, outline);
  54984. }
  54985. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54986. {
  54987. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54988. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54989. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54990. fill, outline);
  54991. }
  54992. }
  54993. }
  54994. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54995. {
  54996. if (isIncrement)
  54997. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54998. else
  54999. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55000. }
  55001. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55002. {
  55003. return &scrollbarShadow;
  55004. }
  55005. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55006. {
  55007. return 8;
  55008. }
  55009. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55010. int w, int h,
  55011. bool isMouseOver,
  55012. bool isMouseDragging)
  55013. {
  55014. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55015. : Colours::darkgrey);
  55016. const float lineThickness = jmin (w, h) * 0.1f;
  55017. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55018. {
  55019. g.drawLine (w * i,
  55020. h + 1.0f,
  55021. w + 1.0f,
  55022. h * i,
  55023. lineThickness);
  55024. }
  55025. }
  55026. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55027. {
  55028. Path shape;
  55029. if (buttonType == DocumentWindow::closeButton)
  55030. {
  55031. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55032. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55033. ShapeButton* const b = new ShapeButton ("close",
  55034. Colour (0x7fff3333),
  55035. Colour (0xd7ff3333),
  55036. Colour (0xf7ff3333));
  55037. b->setShape (shape, true, true, true);
  55038. return b;
  55039. }
  55040. else if (buttonType == DocumentWindow::minimiseButton)
  55041. {
  55042. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55043. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55044. DrawablePath dp;
  55045. dp.setPath (shape);
  55046. dp.setFill (Colours::black.withAlpha (0.3f));
  55047. b->setImages (&dp);
  55048. return b;
  55049. }
  55050. else if (buttonType == DocumentWindow::maximiseButton)
  55051. {
  55052. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55053. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55054. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55055. DrawablePath dp;
  55056. dp.setPath (shape);
  55057. dp.setFill (Colours::black.withAlpha (0.3f));
  55058. b->setImages (&dp);
  55059. return b;
  55060. }
  55061. jassertfalse;
  55062. return 0;
  55063. }
  55064. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55065. int titleBarX,
  55066. int titleBarY,
  55067. int titleBarW,
  55068. int titleBarH,
  55069. Button* minimiseButton,
  55070. Button* maximiseButton,
  55071. Button* closeButton,
  55072. bool positionTitleBarButtonsOnLeft)
  55073. {
  55074. titleBarY += titleBarH / 8;
  55075. titleBarH -= titleBarH / 4;
  55076. const int buttonW = titleBarH;
  55077. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55078. : titleBarX + titleBarW - buttonW - 4;
  55079. if (closeButton != 0)
  55080. {
  55081. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55082. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55083. : -(buttonW + buttonW / 5);
  55084. }
  55085. if (positionTitleBarButtonsOnLeft)
  55086. swapVariables (minimiseButton, maximiseButton);
  55087. if (maximiseButton != 0)
  55088. {
  55089. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55090. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55091. }
  55092. if (minimiseButton != 0)
  55093. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55094. }
  55095. END_JUCE_NAMESPACE
  55096. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55097. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55098. BEGIN_JUCE_NAMESPACE
  55099. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55100. : model (0),
  55101. itemUnderMouse (-1),
  55102. currentPopupIndex (-1),
  55103. topLevelIndexClicked (0),
  55104. lastMouseX (0),
  55105. lastMouseY (0)
  55106. {
  55107. setRepaintsOnMouseActivity (true);
  55108. setWantsKeyboardFocus (false);
  55109. setMouseClickGrabsKeyboardFocus (false);
  55110. setModel (model_);
  55111. }
  55112. MenuBarComponent::~MenuBarComponent()
  55113. {
  55114. setModel (0);
  55115. Desktop::getInstance().removeGlobalMouseListener (this);
  55116. }
  55117. MenuBarModel* MenuBarComponent::getModel() const throw()
  55118. {
  55119. return model;
  55120. }
  55121. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55122. {
  55123. if (model != newModel)
  55124. {
  55125. if (model != 0)
  55126. model->removeListener (this);
  55127. model = newModel;
  55128. if (model != 0)
  55129. model->addListener (this);
  55130. repaint();
  55131. menuBarItemsChanged (0);
  55132. }
  55133. }
  55134. void MenuBarComponent::paint (Graphics& g)
  55135. {
  55136. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55137. getLookAndFeel().drawMenuBarBackground (g,
  55138. getWidth(),
  55139. getHeight(),
  55140. isMouseOverBar,
  55141. *this);
  55142. if (model != 0)
  55143. {
  55144. for (int i = 0; i < menuNames.size(); ++i)
  55145. {
  55146. Graphics::ScopedSaveState ss (g);
  55147. g.setOrigin (xPositions [i], 0);
  55148. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55149. getLookAndFeel().drawMenuBarItem (g,
  55150. xPositions[i + 1] - xPositions[i],
  55151. getHeight(),
  55152. i,
  55153. menuNames[i],
  55154. i == itemUnderMouse,
  55155. i == currentPopupIndex,
  55156. isMouseOverBar,
  55157. *this);
  55158. }
  55159. }
  55160. }
  55161. void MenuBarComponent::resized()
  55162. {
  55163. xPositions.clear();
  55164. int x = 0;
  55165. xPositions.add (x);
  55166. for (int i = 0; i < menuNames.size(); ++i)
  55167. {
  55168. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55169. xPositions.add (x);
  55170. }
  55171. }
  55172. int MenuBarComponent::getItemAt (const int x, const int y)
  55173. {
  55174. for (int i = 0; i < xPositions.size(); ++i)
  55175. if (x >= xPositions[i] && x < xPositions[i + 1])
  55176. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55177. return -1;
  55178. }
  55179. void MenuBarComponent::repaintMenuItem (int index)
  55180. {
  55181. if (isPositiveAndBelow (index, xPositions.size()))
  55182. {
  55183. const int x1 = xPositions [index];
  55184. const int x2 = xPositions [index + 1];
  55185. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55186. }
  55187. }
  55188. void MenuBarComponent::setItemUnderMouse (const int index)
  55189. {
  55190. if (itemUnderMouse != index)
  55191. {
  55192. repaintMenuItem (itemUnderMouse);
  55193. itemUnderMouse = index;
  55194. repaintMenuItem (itemUnderMouse);
  55195. }
  55196. }
  55197. void MenuBarComponent::setOpenItem (int index)
  55198. {
  55199. if (currentPopupIndex != index)
  55200. {
  55201. repaintMenuItem (currentPopupIndex);
  55202. currentPopupIndex = index;
  55203. repaintMenuItem (currentPopupIndex);
  55204. if (index >= 0)
  55205. Desktop::getInstance().addGlobalMouseListener (this);
  55206. else
  55207. Desktop::getInstance().removeGlobalMouseListener (this);
  55208. }
  55209. }
  55210. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55211. {
  55212. setItemUnderMouse (getItemAt (x, y));
  55213. }
  55214. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55215. {
  55216. public:
  55217. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55218. : bar (bar_), topLevelIndex (topLevelIndex_)
  55219. {
  55220. }
  55221. void modalStateFinished (int returnValue)
  55222. {
  55223. if (bar != 0)
  55224. bar->menuDismissed (topLevelIndex, returnValue);
  55225. }
  55226. private:
  55227. Component::SafePointer<MenuBarComponent> bar;
  55228. const int topLevelIndex;
  55229. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55230. };
  55231. void MenuBarComponent::showMenu (int index)
  55232. {
  55233. if (index != currentPopupIndex)
  55234. {
  55235. PopupMenu::dismissAllActiveMenus();
  55236. menuBarItemsChanged (0);
  55237. setOpenItem (index);
  55238. setItemUnderMouse (index);
  55239. if (index >= 0)
  55240. {
  55241. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55242. menuNames [itemUnderMouse]));
  55243. if (m.lookAndFeel == 0)
  55244. m.setLookAndFeel (&getLookAndFeel());
  55245. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55246. m.showMenu (localAreaToGlobal (itemPos),
  55247. 0, itemPos.getWidth(), 0, 0, this,
  55248. new AsyncCallback (this, index));
  55249. }
  55250. }
  55251. }
  55252. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55253. {
  55254. topLevelIndexClicked = topLevelIndex;
  55255. postCommandMessage (itemId);
  55256. }
  55257. void MenuBarComponent::handleCommandMessage (int commandId)
  55258. {
  55259. const Point<int> mousePos (getMouseXYRelative());
  55260. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55261. if (currentPopupIndex == topLevelIndexClicked)
  55262. setOpenItem (-1);
  55263. if (commandId != 0 && model != 0)
  55264. model->menuItemSelected (commandId, topLevelIndexClicked);
  55265. }
  55266. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55267. {
  55268. if (e.eventComponent == this)
  55269. updateItemUnderMouse (e.x, e.y);
  55270. }
  55271. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55272. {
  55273. if (e.eventComponent == this)
  55274. updateItemUnderMouse (e.x, e.y);
  55275. }
  55276. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55277. {
  55278. if (currentPopupIndex < 0)
  55279. {
  55280. const MouseEvent e2 (e.getEventRelativeTo (this));
  55281. updateItemUnderMouse (e2.x, e2.y);
  55282. currentPopupIndex = -2;
  55283. showMenu (itemUnderMouse);
  55284. }
  55285. }
  55286. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55287. {
  55288. const MouseEvent e2 (e.getEventRelativeTo (this));
  55289. const int item = getItemAt (e2.x, e2.y);
  55290. if (item >= 0)
  55291. showMenu (item);
  55292. }
  55293. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55294. {
  55295. const MouseEvent e2 (e.getEventRelativeTo (this));
  55296. updateItemUnderMouse (e2.x, e2.y);
  55297. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55298. {
  55299. setOpenItem (-1);
  55300. PopupMenu::dismissAllActiveMenus();
  55301. }
  55302. }
  55303. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55304. {
  55305. const MouseEvent e2 (e.getEventRelativeTo (this));
  55306. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55307. {
  55308. if (currentPopupIndex >= 0)
  55309. {
  55310. const int item = getItemAt (e2.x, e2.y);
  55311. if (item >= 0)
  55312. showMenu (item);
  55313. }
  55314. else
  55315. {
  55316. updateItemUnderMouse (e2.x, e2.y);
  55317. }
  55318. lastMouseX = e2.x;
  55319. lastMouseY = e2.y;
  55320. }
  55321. }
  55322. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55323. {
  55324. bool used = false;
  55325. const int numMenus = menuNames.size();
  55326. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55327. if (key.isKeyCode (KeyPress::leftKey))
  55328. {
  55329. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55330. used = true;
  55331. }
  55332. else if (key.isKeyCode (KeyPress::rightKey))
  55333. {
  55334. showMenu ((currentIndex + 1) % numMenus);
  55335. used = true;
  55336. }
  55337. return used;
  55338. }
  55339. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55340. {
  55341. StringArray newNames;
  55342. if (model != 0)
  55343. newNames = model->getMenuBarNames();
  55344. if (newNames != menuNames)
  55345. {
  55346. menuNames = newNames;
  55347. repaint();
  55348. resized();
  55349. }
  55350. }
  55351. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55352. const ApplicationCommandTarget::InvocationInfo& info)
  55353. {
  55354. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55355. return;
  55356. for (int i = 0; i < menuNames.size(); ++i)
  55357. {
  55358. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55359. if (menu.containsCommandItem (info.commandID))
  55360. {
  55361. setItemUnderMouse (i);
  55362. startTimer (200);
  55363. break;
  55364. }
  55365. }
  55366. }
  55367. void MenuBarComponent::timerCallback()
  55368. {
  55369. stopTimer();
  55370. const Point<int> mousePos (getMouseXYRelative());
  55371. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55372. }
  55373. END_JUCE_NAMESPACE
  55374. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55375. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55376. BEGIN_JUCE_NAMESPACE
  55377. MenuBarModel::MenuBarModel() throw()
  55378. : manager (0)
  55379. {
  55380. }
  55381. MenuBarModel::~MenuBarModel()
  55382. {
  55383. setApplicationCommandManagerToWatch (0);
  55384. }
  55385. void MenuBarModel::menuItemsChanged()
  55386. {
  55387. triggerAsyncUpdate();
  55388. }
  55389. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55390. {
  55391. if (manager != newManager)
  55392. {
  55393. if (manager != 0)
  55394. manager->removeListener (this);
  55395. manager = newManager;
  55396. if (manager != 0)
  55397. manager->addListener (this);
  55398. }
  55399. }
  55400. void MenuBarModel::addListener (Listener* const newListener) throw()
  55401. {
  55402. listeners.add (newListener);
  55403. }
  55404. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55405. {
  55406. // Trying to remove a listener that isn't on the list!
  55407. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55408. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55409. jassert (listeners.contains (listenerToRemove));
  55410. listeners.remove (listenerToRemove);
  55411. }
  55412. void MenuBarModel::handleAsyncUpdate()
  55413. {
  55414. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55415. }
  55416. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55417. {
  55418. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55419. }
  55420. void MenuBarModel::applicationCommandListChanged()
  55421. {
  55422. menuItemsChanged();
  55423. }
  55424. END_JUCE_NAMESPACE
  55425. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55426. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55427. BEGIN_JUCE_NAMESPACE
  55428. class PopupMenu::Item
  55429. {
  55430. public:
  55431. Item()
  55432. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55433. usesColour (false), customComp (0), commandManager (0)
  55434. {
  55435. }
  55436. Item (const int itemId_,
  55437. const String& text_,
  55438. const bool active_,
  55439. const bool isTicked_,
  55440. const Image& im,
  55441. const Colour& textColour_,
  55442. const bool usesColour_,
  55443. PopupMenuCustomComponent* const customComp_,
  55444. const PopupMenu* const subMenu_,
  55445. ApplicationCommandManager* const commandManager_)
  55446. : itemId (itemId_), text (text_), textColour (textColour_),
  55447. active (active_), isSeparator (false), isTicked (isTicked_),
  55448. usesColour (usesColour_), image (im), customComp (customComp_),
  55449. commandManager (commandManager_)
  55450. {
  55451. if (subMenu_ != 0)
  55452. subMenu = new PopupMenu (*subMenu_);
  55453. if (commandManager_ != 0 && itemId_ != 0)
  55454. {
  55455. String shortcutKey;
  55456. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55457. ->getKeyPressesAssignedToCommand (itemId_));
  55458. for (int i = 0; i < keyPresses.size(); ++i)
  55459. {
  55460. const String key (keyPresses.getReference(i).getTextDescription());
  55461. if (shortcutKey.isNotEmpty())
  55462. shortcutKey << ", ";
  55463. if (key.length() == 1)
  55464. shortcutKey << "shortcut: '" << key << '\'';
  55465. else
  55466. shortcutKey << key;
  55467. }
  55468. shortcutKey = shortcutKey.trim();
  55469. if (shortcutKey.isNotEmpty())
  55470. text << "<end>" << shortcutKey;
  55471. }
  55472. }
  55473. Item (const Item& other)
  55474. : itemId (other.itemId),
  55475. text (other.text),
  55476. textColour (other.textColour),
  55477. active (other.active),
  55478. isSeparator (other.isSeparator),
  55479. isTicked (other.isTicked),
  55480. usesColour (other.usesColour),
  55481. image (other.image),
  55482. customComp (other.customComp),
  55483. commandManager (other.commandManager)
  55484. {
  55485. if (other.subMenu != 0)
  55486. subMenu = new PopupMenu (*(other.subMenu));
  55487. }
  55488. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55489. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55490. const int itemId;
  55491. String text;
  55492. const Colour textColour;
  55493. const bool active, isSeparator, isTicked, usesColour;
  55494. Image image;
  55495. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55496. ScopedPointer <PopupMenu> subMenu;
  55497. ApplicationCommandManager* const commandManager;
  55498. private:
  55499. Item& operator= (const Item&);
  55500. JUCE_LEAK_DETECTOR (Item);
  55501. };
  55502. class PopupMenu::ItemComponent : public Component
  55503. {
  55504. public:
  55505. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55506. : itemInfo (itemInfo_),
  55507. isHighlighted (false)
  55508. {
  55509. if (itemInfo.customComp != 0)
  55510. addAndMakeVisible (itemInfo.customComp);
  55511. int itemW = 80;
  55512. int itemH = 16;
  55513. getIdealSize (itemW, itemH, standardItemHeight);
  55514. setSize (itemW, jlimit (2, 600, itemH));
  55515. }
  55516. ~ItemComponent()
  55517. {
  55518. if (itemInfo.customComp != 0)
  55519. removeChildComponent (itemInfo.customComp);
  55520. }
  55521. void getIdealSize (int& idealWidth,
  55522. int& idealHeight,
  55523. const int standardItemHeight)
  55524. {
  55525. if (itemInfo.customComp != 0)
  55526. {
  55527. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55528. }
  55529. else
  55530. {
  55531. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55532. itemInfo.isSeparator,
  55533. standardItemHeight,
  55534. idealWidth,
  55535. idealHeight);
  55536. }
  55537. }
  55538. void paint (Graphics& g)
  55539. {
  55540. if (itemInfo.customComp == 0)
  55541. {
  55542. String mainText (itemInfo.text);
  55543. String endText;
  55544. const int endIndex = mainText.indexOf ("<end>");
  55545. if (endIndex >= 0)
  55546. {
  55547. endText = mainText.substring (endIndex + 5).trim();
  55548. mainText = mainText.substring (0, endIndex);
  55549. }
  55550. getLookAndFeel()
  55551. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55552. itemInfo.isSeparator,
  55553. itemInfo.active,
  55554. isHighlighted,
  55555. itemInfo.isTicked,
  55556. itemInfo.subMenu != 0,
  55557. mainText, endText,
  55558. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55559. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55560. }
  55561. }
  55562. void resized()
  55563. {
  55564. if (getNumChildComponents() > 0)
  55565. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55566. }
  55567. void setHighlighted (bool shouldBeHighlighted)
  55568. {
  55569. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55570. if (isHighlighted != shouldBeHighlighted)
  55571. {
  55572. isHighlighted = shouldBeHighlighted;
  55573. if (itemInfo.customComp != 0)
  55574. {
  55575. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55576. itemInfo.customComp->repaint();
  55577. }
  55578. repaint();
  55579. }
  55580. }
  55581. PopupMenu::Item itemInfo;
  55582. private:
  55583. bool isHighlighted;
  55584. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55585. };
  55586. namespace PopupMenuSettings
  55587. {
  55588. const int scrollZone = 24;
  55589. const int borderSize = 2;
  55590. const int timerInterval = 50;
  55591. const int dismissCommandId = 0x6287345f;
  55592. }
  55593. class PopupMenu::Window : public Component,
  55594. private Timer
  55595. {
  55596. public:
  55597. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55598. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55599. const int minimumWidth_, const int maximumNumColumns_,
  55600. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55601. ApplicationCommandManager** const managerOfChosenCommand_,
  55602. Component* const componentAttachedTo_)
  55603. : Component ("menu"),
  55604. owner (owner_),
  55605. activeSubMenu (0),
  55606. managerOfChosenCommand (managerOfChosenCommand_),
  55607. componentAttachedTo (componentAttachedTo_),
  55608. componentAttachedToOriginal (componentAttachedTo_),
  55609. minimumWidth (minimumWidth_),
  55610. maximumNumColumns (maximumNumColumns_),
  55611. standardItemHeight (standardItemHeight_),
  55612. isOver (false),
  55613. hasBeenOver (false),
  55614. isDown (false),
  55615. needsToScroll (false),
  55616. dismissOnMouseUp (dismissOnMouseUp_),
  55617. hideOnExit (false),
  55618. disableMouseMoves (false),
  55619. hasAnyJuceCompHadFocus (false),
  55620. numColumns (0),
  55621. contentHeight (0),
  55622. childYOffset (0),
  55623. menuCreationTime (Time::getMillisecondCounter()),
  55624. lastMouseMoveTime (0),
  55625. timeEnteredCurrentChildComp (0),
  55626. scrollAcceleration (1.0)
  55627. {
  55628. lastFocused = lastScroll = menuCreationTime;
  55629. setWantsKeyboardFocus (false);
  55630. setMouseClickGrabsKeyboardFocus (false);
  55631. setAlwaysOnTop (true);
  55632. setLookAndFeel (menu.lookAndFeel);
  55633. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55634. for (int i = 0; i < menu.items.size(); ++i)
  55635. {
  55636. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55637. items.add (itemComp);
  55638. addAndMakeVisible (itemComp);
  55639. itemComp->addMouseListener (this, false);
  55640. }
  55641. calculateWindowPos (target, alignToRectangle);
  55642. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55643. updateYPositions();
  55644. if (itemIdThatMustBeVisible != 0)
  55645. {
  55646. const int y = target.getY() - windowPos.getY();
  55647. ensureItemIsVisible (itemIdThatMustBeVisible,
  55648. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55649. }
  55650. resizeToBestWindowPos();
  55651. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55652. getActiveWindows().add (this);
  55653. Desktop::getInstance().addGlobalMouseListener (this);
  55654. }
  55655. ~Window()
  55656. {
  55657. getActiveWindows().removeValue (this);
  55658. Desktop::getInstance().removeGlobalMouseListener (this);
  55659. activeSubMenu = 0;
  55660. items.clear();
  55661. }
  55662. static Window* create (const PopupMenu& menu,
  55663. bool dismissOnMouseUp,
  55664. Window* const owner_,
  55665. const Rectangle<int>& target,
  55666. int minimumWidth,
  55667. int maximumNumColumns,
  55668. int standardItemHeight,
  55669. bool alignToRectangle,
  55670. int itemIdThatMustBeVisible,
  55671. ApplicationCommandManager** managerOfChosenCommand,
  55672. Component* componentAttachedTo)
  55673. {
  55674. if (menu.items.size() > 0)
  55675. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55676. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55677. managerOfChosenCommand, componentAttachedTo);
  55678. return 0;
  55679. }
  55680. void paint (Graphics& g)
  55681. {
  55682. if (isOpaque())
  55683. g.fillAll (Colours::white);
  55684. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55685. }
  55686. void paintOverChildren (Graphics& g)
  55687. {
  55688. if (isScrolling())
  55689. {
  55690. LookAndFeel& lf = getLookAndFeel();
  55691. if (isScrollZoneActive (false))
  55692. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55693. if (isScrollZoneActive (true))
  55694. {
  55695. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55696. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55697. }
  55698. }
  55699. }
  55700. bool isScrollZoneActive (bool bottomOne) const
  55701. {
  55702. return isScrolling()
  55703. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55704. : childYOffset > 0);
  55705. }
  55706. // hide this and all sub-comps
  55707. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55708. {
  55709. if (isVisible())
  55710. {
  55711. activeSubMenu = 0;
  55712. currentChild = 0;
  55713. exitModalState (item != 0 ? item->itemId : 0);
  55714. if (makeInvisible)
  55715. setVisible (false);
  55716. if (item != 0
  55717. && item->commandManager != 0
  55718. && item->itemId != 0)
  55719. {
  55720. *managerOfChosenCommand = item->commandManager;
  55721. }
  55722. }
  55723. }
  55724. void dismissMenu (const PopupMenu::Item* const item)
  55725. {
  55726. if (owner != 0)
  55727. {
  55728. owner->dismissMenu (item);
  55729. }
  55730. else
  55731. {
  55732. if (item != 0)
  55733. {
  55734. // need a copy of this on the stack as the one passed in will get deleted during this call
  55735. const PopupMenu::Item mi (*item);
  55736. hide (&mi, false);
  55737. }
  55738. else
  55739. {
  55740. hide (0, false);
  55741. }
  55742. }
  55743. }
  55744. void mouseMove (const MouseEvent&) { timerCallback(); }
  55745. void mouseDown (const MouseEvent&) { timerCallback(); }
  55746. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55747. void mouseUp (const MouseEvent&) { timerCallback(); }
  55748. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55749. {
  55750. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55751. lastMouse = Point<int> (-1, -1);
  55752. }
  55753. bool keyPressed (const KeyPress& key)
  55754. {
  55755. if (key.isKeyCode (KeyPress::downKey))
  55756. {
  55757. selectNextItem (1);
  55758. }
  55759. else if (key.isKeyCode (KeyPress::upKey))
  55760. {
  55761. selectNextItem (-1);
  55762. }
  55763. else if (key.isKeyCode (KeyPress::leftKey))
  55764. {
  55765. if (owner != 0)
  55766. {
  55767. Component::SafePointer<Window> parentWindow (owner);
  55768. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55769. hide (0, true);
  55770. if (parentWindow != 0)
  55771. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55772. disableTimerUntilMouseMoves();
  55773. }
  55774. else if (componentAttachedTo != 0)
  55775. {
  55776. componentAttachedTo->keyPressed (key);
  55777. }
  55778. }
  55779. else if (key.isKeyCode (KeyPress::rightKey))
  55780. {
  55781. disableTimerUntilMouseMoves();
  55782. if (showSubMenuFor (currentChild))
  55783. {
  55784. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55785. activeSubMenu->selectNextItem (1);
  55786. }
  55787. else if (componentAttachedTo != 0)
  55788. {
  55789. componentAttachedTo->keyPressed (key);
  55790. }
  55791. }
  55792. else if (key.isKeyCode (KeyPress::returnKey))
  55793. {
  55794. triggerCurrentlyHighlightedItem();
  55795. }
  55796. else if (key.isKeyCode (KeyPress::escapeKey))
  55797. {
  55798. dismissMenu (0);
  55799. }
  55800. else
  55801. {
  55802. return false;
  55803. }
  55804. return true;
  55805. }
  55806. void inputAttemptWhenModal()
  55807. {
  55808. Component::SafePointer<Component> deletionChecker (this);
  55809. timerCallback();
  55810. if (deletionChecker != 0 && ! isOverAnyMenu())
  55811. {
  55812. if (componentAttachedTo != 0)
  55813. {
  55814. // we want to dismiss the menu, but if we do it synchronously, then
  55815. // the mouse-click will be allowed to pass through. That's good, except
  55816. // when the user clicks on the button that orginally popped the menu up,
  55817. // as they'll expect the menu to go away, and in fact it'll just
  55818. // come back. So only dismiss synchronously if they're not on the original
  55819. // comp that we're attached to.
  55820. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55821. if (componentAttachedTo->reallyContains (mousePos, true))
  55822. {
  55823. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55824. return;
  55825. }
  55826. }
  55827. dismissMenu (0);
  55828. }
  55829. }
  55830. void handleCommandMessage (int commandId)
  55831. {
  55832. Component::handleCommandMessage (commandId);
  55833. if (commandId == PopupMenuSettings::dismissCommandId)
  55834. dismissMenu (0);
  55835. }
  55836. void timerCallback()
  55837. {
  55838. if (! isVisible())
  55839. return;
  55840. if (componentAttachedTo != componentAttachedToOriginal)
  55841. {
  55842. dismissMenu (0);
  55843. return;
  55844. }
  55845. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55846. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55847. return;
  55848. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55849. // move rather than a real timer callback
  55850. const Point<int> globalMousePos (Desktop::getMousePosition());
  55851. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55852. const uint32 now = Time::getMillisecondCounter();
  55853. if (now > timeEnteredCurrentChildComp + 100
  55854. && reallyContains (localMousePos, true)
  55855. && currentChild != 0
  55856. && (! disableMouseMoves)
  55857. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55858. {
  55859. showSubMenuFor (currentChild);
  55860. }
  55861. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55862. {
  55863. highlightItemUnderMouse (globalMousePos, localMousePos);
  55864. }
  55865. bool overScrollArea = false;
  55866. if (isScrolling()
  55867. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55868. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55869. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55870. {
  55871. if (now > lastScroll + 20)
  55872. {
  55873. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55874. int amount = 0;
  55875. for (int i = 0; i < items.size() && amount == 0; ++i)
  55876. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55877. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55878. lastScroll = now;
  55879. }
  55880. overScrollArea = true;
  55881. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55882. }
  55883. else
  55884. {
  55885. scrollAcceleration = 1.0;
  55886. }
  55887. const bool wasDown = isDown;
  55888. bool isOverAny = isOverAnyMenu();
  55889. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55890. {
  55891. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55892. isOverAny = isOverAnyMenu();
  55893. }
  55894. if (hideOnExit && hasBeenOver && ! isOverAny)
  55895. {
  55896. hide (0, true);
  55897. }
  55898. else
  55899. {
  55900. isDown = hasBeenOver
  55901. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55902. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55903. bool anyFocused = Process::isForegroundProcess();
  55904. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55905. {
  55906. // because no component at all may have focus, our test here will
  55907. // only be triggered when something has focus and then loses it.
  55908. anyFocused = ! hasAnyJuceCompHadFocus;
  55909. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55910. {
  55911. if (ComponentPeer::getPeer (i)->isFocused())
  55912. {
  55913. anyFocused = true;
  55914. hasAnyJuceCompHadFocus = true;
  55915. break;
  55916. }
  55917. }
  55918. }
  55919. if (! anyFocused)
  55920. {
  55921. if (now > lastFocused + 10)
  55922. {
  55923. wasHiddenBecauseOfAppChange() = true;
  55924. dismissMenu (0);
  55925. return; // may have been deleted by the previous call..
  55926. }
  55927. }
  55928. else if (wasDown && now > menuCreationTime + 250
  55929. && ! (isDown || overScrollArea))
  55930. {
  55931. isOver = reallyContains (localMousePos, true);
  55932. if (isOver)
  55933. {
  55934. triggerCurrentlyHighlightedItem();
  55935. }
  55936. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55937. {
  55938. dismissMenu (0);
  55939. }
  55940. return; // may have been deleted by the previous calls..
  55941. }
  55942. else
  55943. {
  55944. lastFocused = now;
  55945. }
  55946. }
  55947. }
  55948. static Array<Window*>& getActiveWindows()
  55949. {
  55950. static Array<Window*> activeMenuWindows;
  55951. return activeMenuWindows;
  55952. }
  55953. static bool& wasHiddenBecauseOfAppChange() throw()
  55954. {
  55955. static bool b = false;
  55956. return b;
  55957. }
  55958. private:
  55959. Window* owner;
  55960. OwnedArray <PopupMenu::ItemComponent> items;
  55961. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55962. ScopedPointer <Window> activeSubMenu;
  55963. ApplicationCommandManager** managerOfChosenCommand;
  55964. Component::SafePointer<Component> componentAttachedTo;
  55965. Component* componentAttachedToOriginal;
  55966. Rectangle<int> windowPos;
  55967. Point<int> lastMouse;
  55968. int minimumWidth, maximumNumColumns, standardItemHeight;
  55969. bool isOver, hasBeenOver, isDown, needsToScroll;
  55970. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55971. int numColumns, contentHeight, childYOffset;
  55972. Array <int> columnWidths;
  55973. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55974. double scrollAcceleration;
  55975. bool overlaps (const Rectangle<int>& r) const
  55976. {
  55977. return r.intersects (getBounds())
  55978. || (owner != 0 && owner->overlaps (r));
  55979. }
  55980. bool isOverAnyMenu() const
  55981. {
  55982. return (owner != 0) ? owner->isOverAnyMenu()
  55983. : isOverChildren();
  55984. }
  55985. bool isOverChildren() const
  55986. {
  55987. return isVisible()
  55988. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55989. }
  55990. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55991. {
  55992. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55993. isOver = reallyContains (relPos, true);
  55994. if (activeSubMenu != 0)
  55995. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55996. }
  55997. bool treeContains (const Window* const window) const throw()
  55998. {
  55999. const Window* mw = this;
  56000. while (mw->owner != 0)
  56001. mw = mw->owner;
  56002. while (mw != 0)
  56003. {
  56004. if (mw == window)
  56005. return true;
  56006. mw = mw->activeSubMenu;
  56007. }
  56008. return false;
  56009. }
  56010. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56011. {
  56012. const Rectangle<int> mon (Desktop::getInstance()
  56013. .getMonitorAreaContaining (target.getCentre(),
  56014. #if JUCE_MAC
  56015. true));
  56016. #else
  56017. false)); // on windows, don't stop the menu overlapping the taskbar
  56018. #endif
  56019. int x, y, widthToUse, heightToUse;
  56020. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56021. if (alignToRectangle)
  56022. {
  56023. x = target.getX();
  56024. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56025. const int spaceOver = target.getY() - mon.getY();
  56026. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56027. y = target.getBottom();
  56028. else
  56029. y = target.getY() - heightToUse;
  56030. }
  56031. else
  56032. {
  56033. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56034. if (owner != 0)
  56035. {
  56036. if (owner->owner != 0)
  56037. {
  56038. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56039. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56040. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56041. tendTowardsRight = true;
  56042. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56043. tendTowardsRight = false;
  56044. }
  56045. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56046. {
  56047. tendTowardsRight = true;
  56048. }
  56049. }
  56050. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56051. target.getX() - mon.getX()) - 32;
  56052. if (biggestSpace < widthToUse)
  56053. {
  56054. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56055. if (numColumns > 1)
  56056. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56057. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56058. }
  56059. if (tendTowardsRight)
  56060. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56061. else
  56062. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56063. y = target.getY();
  56064. if (target.getCentreY() > mon.getCentreY())
  56065. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56066. }
  56067. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56068. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56069. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56070. // sets this flag if it's big enough to obscure any of its parent menus
  56071. hideOnExit = (owner != 0)
  56072. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56073. }
  56074. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56075. {
  56076. numColumns = 0;
  56077. contentHeight = 0;
  56078. const int maxMenuH = getParentHeight() - 24;
  56079. int totalW;
  56080. do
  56081. {
  56082. ++numColumns;
  56083. totalW = workOutBestSize (maxMenuW);
  56084. if (totalW > maxMenuW)
  56085. {
  56086. numColumns = jmax (1, numColumns - 1);
  56087. totalW = workOutBestSize (maxMenuW); // to update col widths
  56088. break;
  56089. }
  56090. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56091. {
  56092. break;
  56093. }
  56094. } while (numColumns < maximumNumColumns);
  56095. const int actualH = jmin (contentHeight, maxMenuH);
  56096. needsToScroll = contentHeight > actualH;
  56097. width = updateYPositions();
  56098. height = actualH + PopupMenuSettings::borderSize * 2;
  56099. }
  56100. int workOutBestSize (const int maxMenuW)
  56101. {
  56102. int totalW = 0;
  56103. contentHeight = 0;
  56104. int childNum = 0;
  56105. for (int col = 0; col < numColumns; ++col)
  56106. {
  56107. int i, colW = 50, colH = 0;
  56108. const int numChildren = jmin (items.size() - childNum,
  56109. (items.size() + numColumns - 1) / numColumns);
  56110. for (i = numChildren; --i >= 0;)
  56111. {
  56112. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56113. colH += items.getUnchecked (childNum + i)->getHeight();
  56114. }
  56115. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56116. columnWidths.set (col, colW);
  56117. totalW += colW;
  56118. contentHeight = jmax (contentHeight, colH);
  56119. childNum += numChildren;
  56120. }
  56121. if (totalW < minimumWidth)
  56122. {
  56123. totalW = minimumWidth;
  56124. for (int col = 0; col < numColumns; ++col)
  56125. columnWidths.set (0, totalW / numColumns);
  56126. }
  56127. return totalW;
  56128. }
  56129. void ensureItemIsVisible (const int itemId, int wantedY)
  56130. {
  56131. jassert (itemId != 0)
  56132. for (int i = items.size(); --i >= 0;)
  56133. {
  56134. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56135. if (m != 0
  56136. && m->itemInfo.itemId == itemId
  56137. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56138. {
  56139. const int currentY = m->getY();
  56140. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56141. {
  56142. if (wantedY < 0)
  56143. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56144. jmax (PopupMenuSettings::scrollZone,
  56145. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56146. currentY);
  56147. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56148. int deltaY = wantedY - currentY;
  56149. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56150. jmin (windowPos.getHeight(), mon.getHeight()));
  56151. const int newY = jlimit (mon.getY(),
  56152. mon.getBottom() - windowPos.getHeight(),
  56153. windowPos.getY() + deltaY);
  56154. deltaY -= newY - windowPos.getY();
  56155. childYOffset -= deltaY;
  56156. windowPos.setPosition (windowPos.getX(), newY);
  56157. updateYPositions();
  56158. }
  56159. break;
  56160. }
  56161. }
  56162. }
  56163. void resizeToBestWindowPos()
  56164. {
  56165. Rectangle<int> r (windowPos);
  56166. if (childYOffset < 0)
  56167. {
  56168. r.setBounds (r.getX(), r.getY() - childYOffset,
  56169. r.getWidth(), r.getHeight() + childYOffset);
  56170. }
  56171. else if (childYOffset > 0)
  56172. {
  56173. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56174. if (spaceAtBottom > 0)
  56175. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56176. }
  56177. setBounds (r);
  56178. updateYPositions();
  56179. }
  56180. void alterChildYPos (const int delta)
  56181. {
  56182. if (isScrolling())
  56183. {
  56184. childYOffset += delta;
  56185. if (delta < 0)
  56186. {
  56187. childYOffset = jmax (childYOffset, 0);
  56188. }
  56189. else if (delta > 0)
  56190. {
  56191. childYOffset = jmin (childYOffset,
  56192. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56193. }
  56194. updateYPositions();
  56195. }
  56196. else
  56197. {
  56198. childYOffset = 0;
  56199. }
  56200. resizeToBestWindowPos();
  56201. repaint();
  56202. }
  56203. int updateYPositions()
  56204. {
  56205. int x = 0;
  56206. int childNum = 0;
  56207. for (int col = 0; col < numColumns; ++col)
  56208. {
  56209. const int numChildren = jmin (items.size() - childNum,
  56210. (items.size() + numColumns - 1) / numColumns);
  56211. const int colW = columnWidths [col];
  56212. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56213. for (int i = 0; i < numChildren; ++i)
  56214. {
  56215. Component* const c = items.getUnchecked (childNum + i);
  56216. c->setBounds (x, y, colW, c->getHeight());
  56217. y += c->getHeight();
  56218. }
  56219. x += colW;
  56220. childNum += numChildren;
  56221. }
  56222. return x;
  56223. }
  56224. bool isScrolling() const throw()
  56225. {
  56226. return childYOffset != 0 || needsToScroll;
  56227. }
  56228. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56229. {
  56230. if (currentChild != 0)
  56231. currentChild->setHighlighted (false);
  56232. currentChild = child;
  56233. if (currentChild != 0)
  56234. {
  56235. currentChild->setHighlighted (true);
  56236. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56237. }
  56238. }
  56239. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56240. {
  56241. activeSubMenu = 0;
  56242. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56243. {
  56244. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56245. dismissOnMouseUp,
  56246. this,
  56247. childComp->getScreenBounds(),
  56248. 0, maximumNumColumns,
  56249. standardItemHeight,
  56250. false, 0, managerOfChosenCommand,
  56251. componentAttachedTo);
  56252. if (activeSubMenu != 0)
  56253. {
  56254. activeSubMenu->setVisible (true);
  56255. activeSubMenu->enterModalState (false);
  56256. activeSubMenu->toFront (false);
  56257. return true;
  56258. }
  56259. }
  56260. return false;
  56261. }
  56262. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56263. {
  56264. isOver = reallyContains (localMousePos, true);
  56265. if (isOver)
  56266. hasBeenOver = true;
  56267. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56268. {
  56269. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56270. if (disableMouseMoves && isOver)
  56271. disableMouseMoves = false;
  56272. }
  56273. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56274. return;
  56275. bool isMovingTowardsMenu = false;
  56276. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56277. {
  56278. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56279. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56280. // extends from the last mouse pos to the submenu's rectangle..
  56281. float subX = (float) activeSubMenu->getScreenX();
  56282. if (activeSubMenu->getX() > getX())
  56283. {
  56284. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56285. }
  56286. else
  56287. {
  56288. lastMouse += Point<int> (2, 0);
  56289. subX += activeSubMenu->getWidth();
  56290. }
  56291. Path areaTowardsSubMenu;
  56292. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56293. subX, (float) activeSubMenu->getScreenY(),
  56294. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56295. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56296. }
  56297. lastMouse = globalMousePos;
  56298. if (! isMovingTowardsMenu)
  56299. {
  56300. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56301. if (c == this)
  56302. c = 0;
  56303. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56304. if (mic == 0 && c != 0)
  56305. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56306. if (mic != currentChild
  56307. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56308. {
  56309. if (isOver && (c != 0) && (activeSubMenu != 0))
  56310. {
  56311. activeSubMenu->hide (0, true);
  56312. }
  56313. if (! isOver)
  56314. mic = 0;
  56315. setCurrentlyHighlightedChild (mic);
  56316. }
  56317. }
  56318. }
  56319. void triggerCurrentlyHighlightedItem()
  56320. {
  56321. if (currentChild != 0
  56322. && currentChild->itemInfo.canBeTriggered()
  56323. && (currentChild->itemInfo.customComp == 0
  56324. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56325. {
  56326. dismissMenu (&currentChild->itemInfo);
  56327. }
  56328. }
  56329. void selectNextItem (const int delta)
  56330. {
  56331. disableTimerUntilMouseMoves();
  56332. PopupMenu::ItemComponent* mic = 0;
  56333. bool wasLastOne = (currentChild == 0);
  56334. const int numItems = items.size();
  56335. for (int i = 0; i < numItems + 1; ++i)
  56336. {
  56337. int index = (delta > 0) ? i : (numItems - 1 - i);
  56338. index = (index + numItems) % numItems;
  56339. mic = items.getUnchecked (index);
  56340. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56341. && wasLastOne)
  56342. break;
  56343. if (mic == currentChild)
  56344. wasLastOne = true;
  56345. }
  56346. setCurrentlyHighlightedChild (mic);
  56347. }
  56348. void disableTimerUntilMouseMoves()
  56349. {
  56350. disableMouseMoves = true;
  56351. if (owner != 0)
  56352. owner->disableTimerUntilMouseMoves();
  56353. }
  56354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56355. };
  56356. PopupMenu::PopupMenu()
  56357. : lookAndFeel (0),
  56358. separatorPending (false)
  56359. {
  56360. }
  56361. PopupMenu::PopupMenu (const PopupMenu& other)
  56362. : lookAndFeel (other.lookAndFeel),
  56363. separatorPending (false)
  56364. {
  56365. items.addCopiesOf (other.items);
  56366. }
  56367. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56368. {
  56369. if (this != &other)
  56370. {
  56371. lookAndFeel = other.lookAndFeel;
  56372. clear();
  56373. items.addCopiesOf (other.items);
  56374. }
  56375. return *this;
  56376. }
  56377. PopupMenu::~PopupMenu()
  56378. {
  56379. clear();
  56380. }
  56381. void PopupMenu::clear()
  56382. {
  56383. items.clear();
  56384. separatorPending = false;
  56385. }
  56386. void PopupMenu::addSeparatorIfPending()
  56387. {
  56388. if (separatorPending)
  56389. {
  56390. separatorPending = false;
  56391. if (items.size() > 0)
  56392. items.add (new Item());
  56393. }
  56394. }
  56395. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56396. const bool isActive, const bool isTicked, const Image& iconToUse)
  56397. {
  56398. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56399. // didn't pick anything, so you shouldn't use it as the id
  56400. // for an item..
  56401. addSeparatorIfPending();
  56402. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56403. Colours::black, false, 0, 0, 0));
  56404. }
  56405. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56406. const int commandID,
  56407. const String& displayName)
  56408. {
  56409. jassert (commandManager != 0 && commandID != 0);
  56410. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56411. if (registeredInfo != 0)
  56412. {
  56413. ApplicationCommandInfo info (*registeredInfo);
  56414. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56415. addSeparatorIfPending();
  56416. items.add (new Item (commandID,
  56417. displayName.isNotEmpty() ? displayName
  56418. : info.shortName,
  56419. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56420. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56421. Image::null,
  56422. Colours::black,
  56423. false,
  56424. 0, 0,
  56425. commandManager));
  56426. }
  56427. }
  56428. void PopupMenu::addColouredItem (const int itemResultId,
  56429. const String& itemText,
  56430. const Colour& itemTextColour,
  56431. const bool isActive,
  56432. const bool isTicked,
  56433. const Image& iconToUse)
  56434. {
  56435. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56436. // didn't pick anything, so you shouldn't use it as the id
  56437. // for an item..
  56438. addSeparatorIfPending();
  56439. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56440. itemTextColour, true, 0, 0, 0));
  56441. }
  56442. void PopupMenu::addCustomItem (const int itemResultId,
  56443. PopupMenuCustomComponent* const customComponent)
  56444. {
  56445. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56446. // didn't pick anything, so you shouldn't use it as the id
  56447. // for an item..
  56448. addSeparatorIfPending();
  56449. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56450. Colours::black, false, customComponent, 0, 0));
  56451. }
  56452. class NormalComponentWrapper : public PopupMenuCustomComponent
  56453. {
  56454. public:
  56455. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56456. const bool triggerMenuItemAutomaticallyWhenClicked)
  56457. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56458. width (w), height (h)
  56459. {
  56460. addAndMakeVisible (comp);
  56461. }
  56462. ~NormalComponentWrapper() {}
  56463. void getIdealSize (int& idealWidth, int& idealHeight)
  56464. {
  56465. idealWidth = width;
  56466. idealHeight = height;
  56467. }
  56468. void resized()
  56469. {
  56470. if (getChildComponent(0) != 0)
  56471. getChildComponent(0)->setBounds (getLocalBounds());
  56472. }
  56473. private:
  56474. const int width, height;
  56475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56476. };
  56477. void PopupMenu::addCustomItem (const int itemResultId,
  56478. Component* customComponent,
  56479. int idealWidth, int idealHeight,
  56480. const bool triggerMenuItemAutomaticallyWhenClicked)
  56481. {
  56482. addCustomItem (itemResultId,
  56483. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56484. triggerMenuItemAutomaticallyWhenClicked));
  56485. }
  56486. void PopupMenu::addSubMenu (const String& subMenuName,
  56487. const PopupMenu& subMenu,
  56488. const bool isActive,
  56489. const Image& iconToUse,
  56490. const bool isTicked)
  56491. {
  56492. addSeparatorIfPending();
  56493. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56494. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56495. }
  56496. void PopupMenu::addSeparator()
  56497. {
  56498. separatorPending = true;
  56499. }
  56500. class HeaderItemComponent : public PopupMenuCustomComponent
  56501. {
  56502. public:
  56503. HeaderItemComponent (const String& name)
  56504. : PopupMenuCustomComponent (false)
  56505. {
  56506. setName (name);
  56507. }
  56508. void paint (Graphics& g)
  56509. {
  56510. Font f (getLookAndFeel().getPopupMenuFont());
  56511. f.setBold (true);
  56512. g.setFont (f);
  56513. g.setColour (findColour (PopupMenu::headerTextColourId));
  56514. g.drawFittedText (getName(),
  56515. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56516. Justification::bottomLeft, 1);
  56517. }
  56518. void getIdealSize (int& idealWidth,
  56519. int& idealHeight)
  56520. {
  56521. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56522. idealHeight += idealHeight / 2;
  56523. idealWidth += idealWidth / 4;
  56524. }
  56525. private:
  56526. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56527. };
  56528. void PopupMenu::addSectionHeader (const String& title)
  56529. {
  56530. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56531. }
  56532. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56533. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56534. {
  56535. public:
  56536. PopupMenuCompletionCallback()
  56537. : managerOfChosenCommand (0)
  56538. {
  56539. }
  56540. void modalStateFinished (int result)
  56541. {
  56542. if (managerOfChosenCommand != 0 && result != 0)
  56543. {
  56544. ApplicationCommandTarget::InvocationInfo info (result);
  56545. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56546. managerOfChosenCommand->invoke (info, true);
  56547. }
  56548. // (this would be the place to fade out the component, if that's what's required)
  56549. component = 0;
  56550. }
  56551. ApplicationCommandManager* managerOfChosenCommand;
  56552. ScopedPointer<Component> component;
  56553. private:
  56554. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56555. };
  56556. int PopupMenu::showMenu (const Rectangle<int>& target,
  56557. const int itemIdThatMustBeVisible,
  56558. const int minimumWidth,
  56559. const int maximumNumColumns,
  56560. const int standardItemHeight,
  56561. Component* const componentAttachedTo,
  56562. ModalComponentManager::Callback* userCallback)
  56563. {
  56564. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56565. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56566. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56567. Window::wasHiddenBecauseOfAppChange() = false;
  56568. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56569. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56570. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56571. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56572. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56573. &callback->managerOfChosenCommand, componentAttachedTo);
  56574. if (callback->component == 0)
  56575. return 0;
  56576. callback->component->enterModalState (false, userCallbackDeleter.release());
  56577. callback->component->toFront (false); // need to do this after making it modal, or it could
  56578. // be stuck behind other comps that are already modal..
  56579. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56580. callbackDeleter.release();
  56581. if (userCallback != 0)
  56582. return 0;
  56583. const int result = callback->component->runModalLoop();
  56584. if (! Window::wasHiddenBecauseOfAppChange())
  56585. {
  56586. if (prevTopLevel != 0)
  56587. prevTopLevel->toFront (true);
  56588. if (prevFocused != 0)
  56589. prevFocused->grabKeyboardFocus();
  56590. }
  56591. return result;
  56592. }
  56593. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56594. const int minimumWidth, const int maximumNumColumns,
  56595. const int standardItemHeight,
  56596. ModalComponentManager::Callback* callback)
  56597. {
  56598. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56599. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56600. standardItemHeight, 0, callback);
  56601. }
  56602. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56603. const int itemIdThatMustBeVisible,
  56604. const int minimumWidth, const int maximumNumColumns,
  56605. const int standardItemHeight,
  56606. ModalComponentManager::Callback* callback)
  56607. {
  56608. return showMenu (screenAreaToAttachTo,
  56609. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56610. standardItemHeight, 0, callback);
  56611. }
  56612. int PopupMenu::showAt (Component* componentToAttachTo,
  56613. const int itemIdThatMustBeVisible,
  56614. const int minimumWidth, const int maximumNumColumns,
  56615. const int standardItemHeight,
  56616. ModalComponentManager::Callback* callback)
  56617. {
  56618. if (componentToAttachTo != 0)
  56619. {
  56620. return showMenu (componentToAttachTo->getScreenBounds(),
  56621. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56622. standardItemHeight, componentToAttachTo, callback);
  56623. }
  56624. else
  56625. {
  56626. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56627. standardItemHeight, callback);
  56628. }
  56629. }
  56630. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56631. {
  56632. const int numWindows = Window::getActiveWindows().size();
  56633. for (int i = numWindows; --i >= 0;)
  56634. {
  56635. Window* const pmw = Window::getActiveWindows()[i];
  56636. if (pmw != 0)
  56637. pmw->dismissMenu (0);
  56638. }
  56639. return numWindows > 0;
  56640. }
  56641. int PopupMenu::getNumItems() const throw()
  56642. {
  56643. int num = 0;
  56644. for (int i = items.size(); --i >= 0;)
  56645. if (! (items.getUnchecked(i))->isSeparator)
  56646. ++num;
  56647. return num;
  56648. }
  56649. bool PopupMenu::containsCommandItem (const int commandID) const
  56650. {
  56651. for (int i = items.size(); --i >= 0;)
  56652. {
  56653. const Item* mi = items.getUnchecked (i);
  56654. if ((mi->itemId == commandID && mi->commandManager != 0)
  56655. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56656. {
  56657. return true;
  56658. }
  56659. }
  56660. return false;
  56661. }
  56662. bool PopupMenu::containsAnyActiveItems() const throw()
  56663. {
  56664. for (int i = items.size(); --i >= 0;)
  56665. {
  56666. const Item* const mi = items.getUnchecked (i);
  56667. if (mi->subMenu != 0)
  56668. {
  56669. if (mi->subMenu->containsAnyActiveItems())
  56670. return true;
  56671. }
  56672. else if (mi->active)
  56673. {
  56674. return true;
  56675. }
  56676. }
  56677. return false;
  56678. }
  56679. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56680. {
  56681. lookAndFeel = newLookAndFeel;
  56682. }
  56683. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56684. : isHighlighted (false),
  56685. isTriggeredAutomatically (isTriggeredAutomatically_)
  56686. {
  56687. }
  56688. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56689. {
  56690. }
  56691. void PopupMenuCustomComponent::triggerMenuItem()
  56692. {
  56693. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56694. if (mic != 0)
  56695. {
  56696. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56697. if (pmw != 0)
  56698. {
  56699. pmw->dismissMenu (&mic->itemInfo);
  56700. }
  56701. else
  56702. {
  56703. // something must have gone wrong with the component hierarchy if this happens..
  56704. jassertfalse;
  56705. }
  56706. }
  56707. else
  56708. {
  56709. // why isn't this component inside a menu? Not much point triggering the item if
  56710. // there's no menu.
  56711. jassertfalse;
  56712. }
  56713. }
  56714. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56715. : subMenu (0),
  56716. itemId (0),
  56717. isSeparator (false),
  56718. isTicked (false),
  56719. isEnabled (false),
  56720. isCustomComponent (false),
  56721. isSectionHeader (false),
  56722. customColour (0),
  56723. customImage (0),
  56724. menu (menu_),
  56725. index (0)
  56726. {
  56727. }
  56728. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56729. {
  56730. }
  56731. bool PopupMenu::MenuItemIterator::next()
  56732. {
  56733. if (index >= menu.items.size())
  56734. return false;
  56735. const Item* const item = menu.items.getUnchecked (index);
  56736. ++index;
  56737. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56738. subMenu = item->subMenu;
  56739. itemId = item->itemId;
  56740. isSeparator = item->isSeparator;
  56741. isTicked = item->isTicked;
  56742. isEnabled = item->active;
  56743. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <PopupMenuCustomComponent*> (item->customComp)) != 0;
  56744. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56745. customColour = item->usesColour ? &(item->textColour) : 0;
  56746. customImage = item->image;
  56747. commandManager = item->commandManager;
  56748. return true;
  56749. }
  56750. END_JUCE_NAMESPACE
  56751. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56752. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56753. BEGIN_JUCE_NAMESPACE
  56754. ComponentDragger::ComponentDragger()
  56755. {
  56756. }
  56757. ComponentDragger::~ComponentDragger()
  56758. {
  56759. }
  56760. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56761. {
  56762. jassert (componentToDrag != 0);
  56763. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56764. if (componentToDrag != 0)
  56765. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56766. }
  56767. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56768. ComponentBoundsConstrainer* const constrainer)
  56769. {
  56770. jassert (componentToDrag != 0);
  56771. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56772. if (componentToDrag != 0)
  56773. {
  56774. Rectangle<int> bounds (componentToDrag->getBounds());
  56775. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56776. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56777. // the current mouse position instead of the one that the event contains...
  56778. if (componentToDrag->isOnDesktop())
  56779. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56780. else
  56781. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56782. if (constrainer != 0)
  56783. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56784. else
  56785. componentToDrag->setBounds (bounds);
  56786. }
  56787. }
  56788. END_JUCE_NAMESPACE
  56789. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56790. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56791. BEGIN_JUCE_NAMESPACE
  56792. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56793. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56794. class DragImageComponent : public Component,
  56795. public Timer
  56796. {
  56797. public:
  56798. DragImageComponent (const Image& im,
  56799. const String& desc,
  56800. Component* const sourceComponent,
  56801. Component* const mouseDragSource_,
  56802. DragAndDropContainer* const o,
  56803. const Point<int>& imageOffset_)
  56804. : image (im),
  56805. source (sourceComponent),
  56806. mouseDragSource (mouseDragSource_),
  56807. owner (o),
  56808. dragDesc (desc),
  56809. imageOffset (imageOffset_),
  56810. hasCheckedForExternalDrag (false),
  56811. drawImage (true)
  56812. {
  56813. setSize (im.getWidth(), im.getHeight());
  56814. if (mouseDragSource == 0)
  56815. mouseDragSource = source;
  56816. mouseDragSource->addMouseListener (this, false);
  56817. startTimer (200);
  56818. setInterceptsMouseClicks (false, false);
  56819. setAlwaysOnTop (true);
  56820. }
  56821. ~DragImageComponent()
  56822. {
  56823. if (owner->dragImageComponent == this)
  56824. owner->dragImageComponent.release();
  56825. if (mouseDragSource != 0)
  56826. {
  56827. mouseDragSource->removeMouseListener (this);
  56828. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56829. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56830. }
  56831. }
  56832. void paint (Graphics& g)
  56833. {
  56834. if (isOpaque())
  56835. g.fillAll (Colours::white);
  56836. if (drawImage)
  56837. {
  56838. g.setOpacity (1.0f);
  56839. g.drawImageAt (image, 0, 0);
  56840. }
  56841. }
  56842. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56843. {
  56844. Component* hit = getParentComponent();
  56845. if (hit == 0)
  56846. {
  56847. hit = Desktop::getInstance().findComponentAt (screenPos);
  56848. }
  56849. else
  56850. {
  56851. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56852. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56853. }
  56854. // (note: use a local copy of the dragDesc member in case the callback runs
  56855. // a modal loop and deletes this object before the method completes)
  56856. const String dragDescLocal (dragDesc);
  56857. while (hit != 0)
  56858. {
  56859. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56860. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56861. {
  56862. relativePos = hit->getLocalPoint (0, screenPos);
  56863. return ddt;
  56864. }
  56865. hit = hit->getParentComponent();
  56866. }
  56867. return 0;
  56868. }
  56869. void mouseUp (const MouseEvent& e)
  56870. {
  56871. if (e.originalComponent != this)
  56872. {
  56873. if (mouseDragSource != 0)
  56874. mouseDragSource->removeMouseListener (this);
  56875. bool dropAccepted = false;
  56876. DragAndDropTarget* ddt = 0;
  56877. Point<int> relPos;
  56878. if (isVisible())
  56879. {
  56880. setVisible (false);
  56881. ddt = findTarget (e.getScreenPosition(), relPos);
  56882. // fade this component and remove it - it'll be deleted later by the timer callback
  56883. dropAccepted = ddt != 0;
  56884. setVisible (true);
  56885. if (dropAccepted || source == 0)
  56886. {
  56887. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56888. }
  56889. else
  56890. {
  56891. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56892. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56893. Desktop::getInstance().getAnimator().animateComponent (this,
  56894. getBounds() + (target - ourCentre),
  56895. 0.0f, 120,
  56896. true, 1.0, 1.0);
  56897. }
  56898. }
  56899. if (getParentComponent() != 0)
  56900. getParentComponent()->removeChildComponent (this);
  56901. if (dropAccepted && ddt != 0)
  56902. {
  56903. // (note: use a local copy of the dragDesc member in case the callback runs
  56904. // a modal loop and deletes this object before the method completes)
  56905. const String dragDescLocal (dragDesc);
  56906. currentlyOverComp = 0;
  56907. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56908. }
  56909. // careful - this object could now be deleted..
  56910. }
  56911. }
  56912. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56913. {
  56914. // (note: use a local copy of the dragDesc member in case the callback runs
  56915. // a modal loop and deletes this object before it returns)
  56916. const String dragDescLocal (dragDesc);
  56917. Point<int> newPos (screenPos + imageOffset);
  56918. if (getParentComponent() != 0)
  56919. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56920. //if (newX != getX() || newY != getY())
  56921. {
  56922. setTopLeftPosition (newPos.getX(), newPos.getY());
  56923. Point<int> relPos;
  56924. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56925. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56926. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56927. if (ddtComp != currentlyOverComp)
  56928. {
  56929. if (currentlyOverComp != 0 && source != 0
  56930. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56931. {
  56932. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56933. }
  56934. currentlyOverComp = ddtComp;
  56935. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56936. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56937. }
  56938. DragAndDropTarget* target = getCurrentlyOver();
  56939. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56940. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56941. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56942. {
  56943. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56944. {
  56945. hasCheckedForExternalDrag = true;
  56946. StringArray files;
  56947. bool canMoveFiles = false;
  56948. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56949. && files.size() > 0)
  56950. {
  56951. Component::SafePointer<Component> cdw (this);
  56952. setVisible (false);
  56953. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56954. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56955. if (cdw != 0)
  56956. delete this;
  56957. return;
  56958. }
  56959. }
  56960. }
  56961. }
  56962. }
  56963. void mouseDrag (const MouseEvent& e)
  56964. {
  56965. if (e.originalComponent != this)
  56966. updateLocation (true, e.getScreenPosition());
  56967. }
  56968. void timerCallback()
  56969. {
  56970. if (source == 0)
  56971. {
  56972. delete this;
  56973. }
  56974. else if (! isMouseButtonDownAnywhere())
  56975. {
  56976. if (mouseDragSource != 0)
  56977. mouseDragSource->removeMouseListener (this);
  56978. delete this;
  56979. }
  56980. }
  56981. private:
  56982. Image image;
  56983. Component::SafePointer<Component> source;
  56984. Component::SafePointer<Component> mouseDragSource;
  56985. DragAndDropContainer* const owner;
  56986. Component::SafePointer<Component> currentlyOverComp;
  56987. DragAndDropTarget* getCurrentlyOver()
  56988. {
  56989. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56990. }
  56991. String dragDesc;
  56992. const Point<int> imageOffset;
  56993. bool hasCheckedForExternalDrag, drawImage;
  56994. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56995. };
  56996. DragAndDropContainer::DragAndDropContainer()
  56997. {
  56998. }
  56999. DragAndDropContainer::~DragAndDropContainer()
  57000. {
  57001. dragImageComponent = 0;
  57002. }
  57003. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57004. Component* sourceComponent,
  57005. const Image& dragImage_,
  57006. const bool allowDraggingToExternalWindows,
  57007. const Point<int>* imageOffsetFromMouse)
  57008. {
  57009. Image dragImage (dragImage_);
  57010. if (dragImageComponent == 0)
  57011. {
  57012. Component* const thisComp = dynamic_cast <Component*> (this);
  57013. if (thisComp == 0)
  57014. {
  57015. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57016. return;
  57017. }
  57018. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57019. if (draggingSource == 0 || ! draggingSource->isDragging())
  57020. {
  57021. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57022. return;
  57023. }
  57024. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57025. Point<int> imageOffset;
  57026. if (dragImage.isNull())
  57027. {
  57028. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57029. .convertedToFormat (Image::ARGB);
  57030. dragImage.multiplyAllAlphas (0.6f);
  57031. const int lo = 150;
  57032. const int hi = 400;
  57033. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57034. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57035. for (int y = dragImage.getHeight(); --y >= 0;)
  57036. {
  57037. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57038. for (int x = dragImage.getWidth(); --x >= 0;)
  57039. {
  57040. const int dx = x - clipped.getX();
  57041. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57042. if (distance > lo)
  57043. {
  57044. const float alpha = (distance > hi) ? 0
  57045. : (hi - distance) / (float) (hi - lo)
  57046. + Random::getSystemRandom().nextFloat() * 0.008f;
  57047. dragImage.multiplyAlphaAt (x, y, alpha);
  57048. }
  57049. }
  57050. }
  57051. imageOffset = -clipped;
  57052. }
  57053. else
  57054. {
  57055. if (imageOffsetFromMouse == 0)
  57056. imageOffset = -dragImage.getBounds().getCentre();
  57057. else
  57058. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57059. }
  57060. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57061. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57062. currentDragDesc = sourceDescription;
  57063. if (allowDraggingToExternalWindows)
  57064. {
  57065. if (! Desktop::canUseSemiTransparentWindows())
  57066. dragImageComponent->setOpaque (true);
  57067. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57068. | ComponentPeer::windowIsTemporary
  57069. | ComponentPeer::windowIgnoresKeyPresses);
  57070. }
  57071. else
  57072. thisComp->addChildComponent (dragImageComponent);
  57073. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57074. dragImageComponent->setVisible (true);
  57075. }
  57076. }
  57077. bool DragAndDropContainer::isDragAndDropActive() const
  57078. {
  57079. return dragImageComponent != 0;
  57080. }
  57081. const String DragAndDropContainer::getCurrentDragDescription() const
  57082. {
  57083. return (dragImageComponent != 0) ? currentDragDesc
  57084. : String::empty;
  57085. }
  57086. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57087. {
  57088. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57089. }
  57090. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57091. {
  57092. return false;
  57093. }
  57094. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57095. {
  57096. }
  57097. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57098. {
  57099. }
  57100. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57101. {
  57102. }
  57103. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57104. {
  57105. return true;
  57106. }
  57107. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57108. {
  57109. }
  57110. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57111. {
  57112. }
  57113. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57114. {
  57115. }
  57116. END_JUCE_NAMESPACE
  57117. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57118. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57119. BEGIN_JUCE_NAMESPACE
  57120. class MouseCursor::SharedCursorHandle
  57121. {
  57122. public:
  57123. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57124. : handle (createStandardMouseCursor (type)),
  57125. refCount (1),
  57126. standardType (type),
  57127. isStandard (true)
  57128. {
  57129. }
  57130. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57131. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57132. refCount (1),
  57133. standardType (MouseCursor::NormalCursor),
  57134. isStandard (false)
  57135. {
  57136. }
  57137. ~SharedCursorHandle()
  57138. {
  57139. deleteMouseCursor (handle, isStandard);
  57140. }
  57141. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57142. {
  57143. const ScopedLock sl (getLock());
  57144. for (int i = 0; i < getCursors().size(); ++i)
  57145. {
  57146. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57147. if (sc->standardType == type)
  57148. return sc->retain();
  57149. }
  57150. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57151. getCursors().add (sc);
  57152. return sc;
  57153. }
  57154. SharedCursorHandle* retain() throw()
  57155. {
  57156. ++refCount;
  57157. return this;
  57158. }
  57159. void release()
  57160. {
  57161. if (--refCount == 0)
  57162. {
  57163. if (isStandard)
  57164. {
  57165. const ScopedLock sl (getLock());
  57166. getCursors().removeValue (this);
  57167. }
  57168. delete this;
  57169. }
  57170. }
  57171. void* getHandle() const throw() { return handle; }
  57172. private:
  57173. void* const handle;
  57174. Atomic <int> refCount;
  57175. const MouseCursor::StandardCursorType standardType;
  57176. const bool isStandard;
  57177. static CriticalSection& getLock()
  57178. {
  57179. static CriticalSection lock;
  57180. return lock;
  57181. }
  57182. static Array <SharedCursorHandle*>& getCursors()
  57183. {
  57184. static Array <SharedCursorHandle*> cursors;
  57185. return cursors;
  57186. }
  57187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57188. };
  57189. MouseCursor::MouseCursor()
  57190. : cursorHandle (0)
  57191. {
  57192. }
  57193. MouseCursor::MouseCursor (const StandardCursorType type)
  57194. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57195. {
  57196. }
  57197. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57198. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57199. {
  57200. }
  57201. MouseCursor::MouseCursor (const MouseCursor& other)
  57202. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57203. {
  57204. }
  57205. MouseCursor::~MouseCursor()
  57206. {
  57207. if (cursorHandle != 0)
  57208. cursorHandle->release();
  57209. }
  57210. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57211. {
  57212. if (other.cursorHandle != 0)
  57213. other.cursorHandle->retain();
  57214. if (cursorHandle != 0)
  57215. cursorHandle->release();
  57216. cursorHandle = other.cursorHandle;
  57217. return *this;
  57218. }
  57219. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57220. {
  57221. return getHandle() == other.getHandle();
  57222. }
  57223. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57224. {
  57225. return getHandle() != other.getHandle();
  57226. }
  57227. void* MouseCursor::getHandle() const throw()
  57228. {
  57229. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57230. }
  57231. void MouseCursor::showWaitCursor()
  57232. {
  57233. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57234. }
  57235. void MouseCursor::hideWaitCursor()
  57236. {
  57237. Desktop::getInstance().getMainMouseSource().revealCursor();
  57238. }
  57239. END_JUCE_NAMESPACE
  57240. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57241. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57242. BEGIN_JUCE_NAMESPACE
  57243. MouseEvent::MouseEvent (MouseInputSource& source_,
  57244. const Point<int>& position,
  57245. const ModifierKeys& mods_,
  57246. Component* const eventComponent_,
  57247. Component* const originator,
  57248. const Time& eventTime_,
  57249. const Point<int> mouseDownPos_,
  57250. const Time& mouseDownTime_,
  57251. const int numberOfClicks_,
  57252. const bool mouseWasDragged) throw()
  57253. : x (position.getX()),
  57254. y (position.getY()),
  57255. mods (mods_),
  57256. eventComponent (eventComponent_),
  57257. originalComponent (originator),
  57258. eventTime (eventTime_),
  57259. source (source_),
  57260. mouseDownPos (mouseDownPos_),
  57261. mouseDownTime (mouseDownTime_),
  57262. numberOfClicks (numberOfClicks_),
  57263. wasMovedSinceMouseDown (mouseWasDragged)
  57264. {
  57265. }
  57266. MouseEvent::~MouseEvent() throw()
  57267. {
  57268. }
  57269. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57270. {
  57271. if (otherComponent == 0)
  57272. {
  57273. jassertfalse;
  57274. return *this;
  57275. }
  57276. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57277. mods, otherComponent, originalComponent, eventTime,
  57278. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57279. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57280. }
  57281. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57282. {
  57283. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57284. eventTime, mouseDownPos, mouseDownTime,
  57285. numberOfClicks, wasMovedSinceMouseDown);
  57286. }
  57287. bool MouseEvent::mouseWasClicked() const throw()
  57288. {
  57289. return ! wasMovedSinceMouseDown;
  57290. }
  57291. int MouseEvent::getMouseDownX() const throw()
  57292. {
  57293. return mouseDownPos.getX();
  57294. }
  57295. int MouseEvent::getMouseDownY() const throw()
  57296. {
  57297. return mouseDownPos.getY();
  57298. }
  57299. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57300. {
  57301. return mouseDownPos;
  57302. }
  57303. int MouseEvent::getDistanceFromDragStartX() const throw()
  57304. {
  57305. return x - mouseDownPos.getX();
  57306. }
  57307. int MouseEvent::getDistanceFromDragStartY() const throw()
  57308. {
  57309. return y - mouseDownPos.getY();
  57310. }
  57311. int MouseEvent::getDistanceFromDragStart() const throw()
  57312. {
  57313. return mouseDownPos.getDistanceFrom (getPosition());
  57314. }
  57315. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57316. {
  57317. return getPosition() - mouseDownPos;
  57318. }
  57319. int MouseEvent::getLengthOfMousePress() const throw()
  57320. {
  57321. if (mouseDownTime.toMilliseconds() > 0)
  57322. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57323. return 0;
  57324. }
  57325. const Point<int> MouseEvent::getPosition() const throw()
  57326. {
  57327. return Point<int> (x, y);
  57328. }
  57329. int MouseEvent::getScreenX() const
  57330. {
  57331. return getScreenPosition().getX();
  57332. }
  57333. int MouseEvent::getScreenY() const
  57334. {
  57335. return getScreenPosition().getY();
  57336. }
  57337. const Point<int> MouseEvent::getScreenPosition() const
  57338. {
  57339. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57340. }
  57341. int MouseEvent::getMouseDownScreenX() const
  57342. {
  57343. return getMouseDownScreenPosition().getX();
  57344. }
  57345. int MouseEvent::getMouseDownScreenY() const
  57346. {
  57347. return getMouseDownScreenPosition().getY();
  57348. }
  57349. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57350. {
  57351. return eventComponent->localPointToGlobal (mouseDownPos);
  57352. }
  57353. int MouseEvent::doubleClickTimeOutMs = 400;
  57354. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57355. {
  57356. doubleClickTimeOutMs = newTime;
  57357. }
  57358. int MouseEvent::getDoubleClickTimeout() throw()
  57359. {
  57360. return doubleClickTimeOutMs;
  57361. }
  57362. END_JUCE_NAMESPACE
  57363. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57364. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57365. BEGIN_JUCE_NAMESPACE
  57366. class MouseInputSourceInternal : public AsyncUpdater
  57367. {
  57368. public:
  57369. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57370. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57371. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57372. mouseEventCounter (0), lastTime (0)
  57373. {
  57374. }
  57375. bool isDragging() const throw()
  57376. {
  57377. return buttonState.isAnyMouseButtonDown();
  57378. }
  57379. Component* getComponentUnderMouse() const
  57380. {
  57381. return static_cast <Component*> (componentUnderMouse);
  57382. }
  57383. const ModifierKeys getCurrentModifiers() const
  57384. {
  57385. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57386. }
  57387. ComponentPeer* getPeer()
  57388. {
  57389. if (! ComponentPeer::isValidPeer (lastPeer))
  57390. lastPeer = 0;
  57391. return lastPeer;
  57392. }
  57393. Component* findComponentAt (const Point<int>& screenPos)
  57394. {
  57395. ComponentPeer* const peer = getPeer();
  57396. if (peer != 0)
  57397. {
  57398. Component* const comp = peer->getComponent();
  57399. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57400. // (the contains() call is needed to test for overlapping desktop windows)
  57401. if (comp->contains (relativePos))
  57402. return comp->getComponentAt (relativePos);
  57403. }
  57404. return 0;
  57405. }
  57406. const Point<int> getScreenPosition() const
  57407. {
  57408. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57409. // value, because that can cause continuity problems.
  57410. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57411. : lastScreenPos);
  57412. }
  57413. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57414. {
  57415. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57416. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57417. }
  57418. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57419. {
  57420. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57421. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57422. }
  57423. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57424. {
  57425. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57426. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57427. }
  57428. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57429. {
  57430. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57431. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57432. }
  57433. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57434. {
  57435. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57436. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57437. }
  57438. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57439. {
  57440. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57441. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57442. }
  57443. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57444. {
  57445. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57446. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57447. }
  57448. // (returns true if the button change caused a modal event loop)
  57449. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57450. {
  57451. if (buttonState == newButtonState)
  57452. return false;
  57453. setScreenPos (screenPos, time, false);
  57454. // (ignore secondary clicks when there's already a button down)
  57455. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57456. {
  57457. buttonState = newButtonState;
  57458. return false;
  57459. }
  57460. const int lastCounter = mouseEventCounter;
  57461. if (buttonState.isAnyMouseButtonDown())
  57462. {
  57463. Component* const current = getComponentUnderMouse();
  57464. if (current != 0)
  57465. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57466. enableUnboundedMouseMovement (false, false);
  57467. }
  57468. buttonState = newButtonState;
  57469. if (buttonState.isAnyMouseButtonDown())
  57470. {
  57471. Desktop::getInstance().incrementMouseClickCounter();
  57472. Component* const current = getComponentUnderMouse();
  57473. if (current != 0)
  57474. {
  57475. registerMouseDown (screenPos, time, current, buttonState);
  57476. sendMouseDown (current, screenPos, time);
  57477. }
  57478. }
  57479. return lastCounter != mouseEventCounter;
  57480. }
  57481. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57482. {
  57483. Component* current = getComponentUnderMouse();
  57484. if (newComponent != current)
  57485. {
  57486. Component::SafePointer<Component> safeNewComp (newComponent);
  57487. const ModifierKeys originalButtonState (buttonState);
  57488. if (current != 0)
  57489. {
  57490. setButtons (screenPos, time, ModifierKeys());
  57491. sendMouseExit (current, screenPos, time);
  57492. buttonState = originalButtonState;
  57493. }
  57494. componentUnderMouse = safeNewComp;
  57495. current = getComponentUnderMouse();
  57496. if (current != 0)
  57497. sendMouseEnter (current, screenPos, time);
  57498. revealCursor (false);
  57499. setButtons (screenPos, time, originalButtonState);
  57500. }
  57501. }
  57502. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57503. {
  57504. ModifierKeys::updateCurrentModifiers();
  57505. if (newPeer != lastPeer)
  57506. {
  57507. setComponentUnderMouse (0, screenPos, time);
  57508. lastPeer = newPeer;
  57509. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57510. }
  57511. }
  57512. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57513. {
  57514. if (! isDragging())
  57515. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57516. if (newScreenPos != lastScreenPos || forceUpdate)
  57517. {
  57518. cancelPendingUpdate();
  57519. lastScreenPos = newScreenPos;
  57520. Component* const current = getComponentUnderMouse();
  57521. if (current != 0)
  57522. {
  57523. if (isDragging())
  57524. {
  57525. registerMouseDrag (newScreenPos);
  57526. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57527. if (isUnboundedMouseModeOn)
  57528. handleUnboundedDrag (current);
  57529. }
  57530. else
  57531. {
  57532. sendMouseMove (current, newScreenPos, time);
  57533. }
  57534. }
  57535. revealCursor (false);
  57536. }
  57537. }
  57538. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57539. {
  57540. jassert (newPeer != 0);
  57541. lastTime = time;
  57542. ++mouseEventCounter;
  57543. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57544. if (isDragging() && newMods.isAnyMouseButtonDown())
  57545. {
  57546. setScreenPos (screenPos, time, false);
  57547. }
  57548. else
  57549. {
  57550. setPeer (newPeer, screenPos, time);
  57551. ComponentPeer* peer = getPeer();
  57552. if (peer != 0)
  57553. {
  57554. if (setButtons (screenPos, time, newMods))
  57555. return; // some modal events have been dispatched, so the current event is now out-of-date
  57556. peer = getPeer();
  57557. if (peer != 0)
  57558. setScreenPos (screenPos, time, false);
  57559. }
  57560. }
  57561. }
  57562. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57563. {
  57564. jassert (peer != 0);
  57565. lastTime = time;
  57566. ++mouseEventCounter;
  57567. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57568. setPeer (peer, screenPos, time);
  57569. setScreenPos (screenPos, time, false);
  57570. triggerFakeMove();
  57571. if (! isDragging())
  57572. {
  57573. Component* current = getComponentUnderMouse();
  57574. if (current != 0)
  57575. sendMouseWheel (current, screenPos, time, x, y);
  57576. }
  57577. }
  57578. const Time getLastMouseDownTime() const throw()
  57579. {
  57580. return Time (mouseDowns[0].time);
  57581. }
  57582. const Point<int> getLastMouseDownPosition() const throw()
  57583. {
  57584. return mouseDowns[0].position;
  57585. }
  57586. int getNumberOfMultipleClicks() const throw()
  57587. {
  57588. int numClicks = 0;
  57589. if (mouseDowns[0].time != 0)
  57590. {
  57591. if (! mouseMovedSignificantlySincePressed)
  57592. ++numClicks;
  57593. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57594. {
  57595. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57596. ++numClicks;
  57597. else
  57598. break;
  57599. }
  57600. }
  57601. return numClicks;
  57602. }
  57603. bool hasMouseMovedSignificantlySincePressed() const throw()
  57604. {
  57605. return mouseMovedSignificantlySincePressed
  57606. || lastTime > mouseDowns[0].time + 300;
  57607. }
  57608. void triggerFakeMove()
  57609. {
  57610. triggerAsyncUpdate();
  57611. }
  57612. void handleAsyncUpdate()
  57613. {
  57614. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57615. }
  57616. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57617. {
  57618. enable = enable && isDragging();
  57619. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57620. if (enable != isUnboundedMouseModeOn)
  57621. {
  57622. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57623. {
  57624. // when released, return the mouse to within the component's bounds
  57625. Component* current = getComponentUnderMouse();
  57626. if (current != 0)
  57627. Desktop::setMousePosition (current->getScreenBounds()
  57628. .getConstrainedPoint (lastScreenPos));
  57629. }
  57630. isUnboundedMouseModeOn = enable;
  57631. unboundedMouseOffset = Point<int>();
  57632. revealCursor (true);
  57633. }
  57634. }
  57635. void handleUnboundedDrag (Component* current)
  57636. {
  57637. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57638. if (! screenArea.contains (lastScreenPos))
  57639. {
  57640. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57641. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57642. Desktop::setMousePosition (componentCentre);
  57643. }
  57644. else if (isCursorVisibleUntilOffscreen
  57645. && (! unboundedMouseOffset.isOrigin())
  57646. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57647. {
  57648. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57649. unboundedMouseOffset = Point<int>();
  57650. }
  57651. }
  57652. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57653. {
  57654. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57655. {
  57656. cursor = MouseCursor::NoCursor;
  57657. forcedUpdate = true;
  57658. }
  57659. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57660. {
  57661. currentCursorHandle = cursor.getHandle();
  57662. cursor.showInWindow (getPeer());
  57663. }
  57664. }
  57665. void hideCursor()
  57666. {
  57667. showMouseCursor (MouseCursor::NoCursor, true);
  57668. }
  57669. void revealCursor (bool forcedUpdate)
  57670. {
  57671. MouseCursor mc (MouseCursor::NormalCursor);
  57672. Component* current = getComponentUnderMouse();
  57673. if (current != 0)
  57674. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57675. showMouseCursor (mc, forcedUpdate);
  57676. }
  57677. const int index;
  57678. const bool isMouseDevice;
  57679. Point<int> lastScreenPos;
  57680. ModifierKeys buttonState;
  57681. private:
  57682. MouseInputSource& source;
  57683. Component::SafePointer<Component> componentUnderMouse;
  57684. ComponentPeer* lastPeer;
  57685. Point<int> unboundedMouseOffset;
  57686. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57687. void* currentCursorHandle;
  57688. int mouseEventCounter;
  57689. struct RecentMouseDown
  57690. {
  57691. RecentMouseDown()
  57692. : time (0), component (0)
  57693. {
  57694. }
  57695. Point<int> position;
  57696. int64 time;
  57697. Component* component;
  57698. ModifierKeys buttons;
  57699. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetween) const
  57700. {
  57701. return time - other.time < maxTimeBetween
  57702. && abs (position.getX() - other.position.getX()) < 8
  57703. && abs (position.getY() - other.position.getY()) < 8
  57704. && buttons == other.buttons;;
  57705. }
  57706. };
  57707. RecentMouseDown mouseDowns[4];
  57708. bool mouseMovedSignificantlySincePressed;
  57709. int64 lastTime;
  57710. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57711. Component* const component, const ModifierKeys& modifiers) throw()
  57712. {
  57713. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57714. mouseDowns[i] = mouseDowns[i - 1];
  57715. mouseDowns[0].position = screenPos;
  57716. mouseDowns[0].time = time;
  57717. mouseDowns[0].component = component;
  57718. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57719. mouseMovedSignificantlySincePressed = false;
  57720. }
  57721. void registerMouseDrag (const Point<int>& screenPos) throw()
  57722. {
  57723. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57724. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57725. }
  57726. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57727. };
  57728. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57729. {
  57730. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57731. }
  57732. MouseInputSource::~MouseInputSource()
  57733. {
  57734. }
  57735. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57736. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57737. bool MouseInputSource::canHover() const { return isMouse(); }
  57738. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57739. int MouseInputSource::getIndex() const { return pimpl->index; }
  57740. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57741. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57742. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57743. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57744. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57745. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57746. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57747. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57748. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57749. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57750. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57751. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57752. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57753. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57754. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57755. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57756. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57757. {
  57758. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57759. }
  57760. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57761. {
  57762. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57763. }
  57764. END_JUCE_NAMESPACE
  57765. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57766. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57767. BEGIN_JUCE_NAMESPACE
  57768. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57769. : source (0),
  57770. hoverTimeMillisecs (hoverTimeMillisecs_),
  57771. hasJustHovered (false)
  57772. {
  57773. internalTimer.owner = this;
  57774. }
  57775. MouseHoverDetector::~MouseHoverDetector()
  57776. {
  57777. setHoverComponent (0);
  57778. }
  57779. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57780. {
  57781. hoverTimeMillisecs = newTimeInMillisecs;
  57782. }
  57783. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57784. {
  57785. if (source != newSourceComponent)
  57786. {
  57787. internalTimer.stopTimer();
  57788. hasJustHovered = false;
  57789. if (source != 0)
  57790. source->removeMouseListener (&internalTimer);
  57791. source = newSourceComponent;
  57792. if (newSourceComponent != 0)
  57793. newSourceComponent->addMouseListener (&internalTimer, false);
  57794. }
  57795. }
  57796. void MouseHoverDetector::hoverTimerCallback()
  57797. {
  57798. internalTimer.stopTimer();
  57799. if (source != 0)
  57800. {
  57801. const Point<int> pos (source->getMouseXYRelative());
  57802. if (source->reallyContains (pos, false))
  57803. {
  57804. hasJustHovered = true;
  57805. mouseHovered (pos.getX(), pos.getY());
  57806. }
  57807. }
  57808. }
  57809. void MouseHoverDetector::checkJustHoveredCallback()
  57810. {
  57811. if (hasJustHovered)
  57812. {
  57813. hasJustHovered = false;
  57814. mouseMovedAfterHover();
  57815. }
  57816. }
  57817. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57818. {
  57819. owner->hoverTimerCallback();
  57820. }
  57821. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57822. {
  57823. stopTimer();
  57824. owner->checkJustHoveredCallback();
  57825. }
  57826. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57827. {
  57828. stopTimer();
  57829. owner->checkJustHoveredCallback();
  57830. }
  57831. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57832. {
  57833. stopTimer();
  57834. owner->checkJustHoveredCallback();
  57835. }
  57836. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57837. {
  57838. stopTimer();
  57839. owner->checkJustHoveredCallback();
  57840. }
  57841. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57842. {
  57843. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57844. {
  57845. lastX = e.x;
  57846. lastY = e.y;
  57847. if (owner->source != 0)
  57848. startTimer (owner->hoverTimeMillisecs);
  57849. owner->checkJustHoveredCallback();
  57850. }
  57851. }
  57852. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57853. {
  57854. stopTimer();
  57855. owner->checkJustHoveredCallback();
  57856. }
  57857. END_JUCE_NAMESPACE
  57858. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57859. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57860. BEGIN_JUCE_NAMESPACE
  57861. void MouseListener::mouseEnter (const MouseEvent&)
  57862. {
  57863. }
  57864. void MouseListener::mouseExit (const MouseEvent&)
  57865. {
  57866. }
  57867. void MouseListener::mouseDown (const MouseEvent&)
  57868. {
  57869. }
  57870. void MouseListener::mouseUp (const MouseEvent&)
  57871. {
  57872. }
  57873. void MouseListener::mouseDrag (const MouseEvent&)
  57874. {
  57875. }
  57876. void MouseListener::mouseMove (const MouseEvent&)
  57877. {
  57878. }
  57879. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57880. {
  57881. }
  57882. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57883. {
  57884. }
  57885. END_JUCE_NAMESPACE
  57886. /*** End of inlined file: juce_MouseListener.cpp ***/
  57887. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57888. BEGIN_JUCE_NAMESPACE
  57889. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57890. const String& buttonTextWhenTrue,
  57891. const String& buttonTextWhenFalse)
  57892. : PropertyComponent (name),
  57893. onText (buttonTextWhenTrue),
  57894. offText (buttonTextWhenFalse)
  57895. {
  57896. addAndMakeVisible (&button);
  57897. button.setClickingTogglesState (false);
  57898. button.addButtonListener (this);
  57899. }
  57900. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57901. const String& name,
  57902. const String& buttonText)
  57903. : PropertyComponent (name),
  57904. onText (buttonText),
  57905. offText (buttonText)
  57906. {
  57907. addAndMakeVisible (&button);
  57908. button.setClickingTogglesState (false);
  57909. button.setButtonText (buttonText);
  57910. button.getToggleStateValue().referTo (valueToControl);
  57911. button.setClickingTogglesState (true);
  57912. }
  57913. BooleanPropertyComponent::~BooleanPropertyComponent()
  57914. {
  57915. }
  57916. void BooleanPropertyComponent::setState (const bool newState)
  57917. {
  57918. button.setToggleState (newState, true);
  57919. }
  57920. bool BooleanPropertyComponent::getState() const
  57921. {
  57922. return button.getToggleState();
  57923. }
  57924. void BooleanPropertyComponent::paint (Graphics& g)
  57925. {
  57926. PropertyComponent::paint (g);
  57927. g.setColour (Colours::white);
  57928. g.fillRect (button.getBounds());
  57929. g.setColour (findColour (ComboBox::outlineColourId));
  57930. g.drawRect (button.getBounds());
  57931. }
  57932. void BooleanPropertyComponent::refresh()
  57933. {
  57934. button.setToggleState (getState(), false);
  57935. button.setButtonText (button.getToggleState() ? onText : offText);
  57936. }
  57937. void BooleanPropertyComponent::buttonClicked (Button*)
  57938. {
  57939. setState (! getState());
  57940. }
  57941. END_JUCE_NAMESPACE
  57942. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57943. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57944. BEGIN_JUCE_NAMESPACE
  57945. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57946. const bool triggerOnMouseDown)
  57947. : PropertyComponent (name)
  57948. {
  57949. addAndMakeVisible (&button);
  57950. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57951. button.addButtonListener (this);
  57952. }
  57953. ButtonPropertyComponent::~ButtonPropertyComponent()
  57954. {
  57955. }
  57956. void ButtonPropertyComponent::refresh()
  57957. {
  57958. button.setButtonText (getButtonText());
  57959. }
  57960. void ButtonPropertyComponent::buttonClicked (Button*)
  57961. {
  57962. buttonClicked();
  57963. }
  57964. END_JUCE_NAMESPACE
  57965. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57966. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57967. BEGIN_JUCE_NAMESPACE
  57968. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57969. public ValueListener
  57970. {
  57971. public:
  57972. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57973. : sourceValue (sourceValue_),
  57974. mappings (mappings_)
  57975. {
  57976. sourceValue.addListener (this);
  57977. }
  57978. ~RemapperValueSource() {}
  57979. const var getValue() const
  57980. {
  57981. return mappings.indexOf (sourceValue.getValue()) + 1;
  57982. }
  57983. void setValue (const var& newValue)
  57984. {
  57985. const var remappedVal (mappings [(int) newValue - 1]);
  57986. if (remappedVal != sourceValue)
  57987. sourceValue = remappedVal;
  57988. }
  57989. void valueChanged (Value&)
  57990. {
  57991. sendChangeMessage (true);
  57992. }
  57993. protected:
  57994. Value sourceValue;
  57995. Array<var> mappings;
  57996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57997. };
  57998. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57999. : PropertyComponent (name),
  58000. isCustomClass (true)
  58001. {
  58002. }
  58003. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58004. const String& name,
  58005. const StringArray& choices_,
  58006. const Array <var>& correspondingValues)
  58007. : PropertyComponent (name),
  58008. choices (choices_),
  58009. isCustomClass (false)
  58010. {
  58011. // The array of corresponding values must contain one value for each of the items in
  58012. // the choices array!
  58013. jassert (correspondingValues.size() == choices.size());
  58014. createComboBox();
  58015. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58016. }
  58017. ChoicePropertyComponent::~ChoicePropertyComponent()
  58018. {
  58019. }
  58020. void ChoicePropertyComponent::createComboBox()
  58021. {
  58022. addAndMakeVisible (&comboBox);
  58023. for (int i = 0; i < choices.size(); ++i)
  58024. {
  58025. if (choices[i].isNotEmpty())
  58026. comboBox.addItem (choices[i], i + 1);
  58027. else
  58028. comboBox.addSeparator();
  58029. }
  58030. comboBox.setEditableText (false);
  58031. }
  58032. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58033. {
  58034. jassertfalse; // you need to override this method in your subclass!
  58035. }
  58036. int ChoicePropertyComponent::getIndex() const
  58037. {
  58038. jassertfalse; // you need to override this method in your subclass!
  58039. return -1;
  58040. }
  58041. const StringArray& ChoicePropertyComponent::getChoices() const
  58042. {
  58043. return choices;
  58044. }
  58045. void ChoicePropertyComponent::refresh()
  58046. {
  58047. if (isCustomClass)
  58048. {
  58049. if (! comboBox.isVisible())
  58050. {
  58051. createComboBox();
  58052. comboBox.addListener (this);
  58053. }
  58054. comboBox.setSelectedId (getIndex() + 1, true);
  58055. }
  58056. }
  58057. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58058. {
  58059. if (isCustomClass)
  58060. {
  58061. const int newIndex = comboBox.getSelectedId() - 1;
  58062. if (newIndex != getIndex())
  58063. setIndex (newIndex);
  58064. }
  58065. }
  58066. END_JUCE_NAMESPACE
  58067. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58068. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58069. BEGIN_JUCE_NAMESPACE
  58070. PropertyComponent::PropertyComponent (const String& name,
  58071. const int preferredHeight_)
  58072. : Component (name),
  58073. preferredHeight (preferredHeight_)
  58074. {
  58075. jassert (name.isNotEmpty());
  58076. }
  58077. PropertyComponent::~PropertyComponent()
  58078. {
  58079. }
  58080. void PropertyComponent::paint (Graphics& g)
  58081. {
  58082. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58083. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58084. }
  58085. void PropertyComponent::resized()
  58086. {
  58087. if (getNumChildComponents() > 0)
  58088. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58089. }
  58090. void PropertyComponent::enablementChanged()
  58091. {
  58092. repaint();
  58093. }
  58094. END_JUCE_NAMESPACE
  58095. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58096. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58097. BEGIN_JUCE_NAMESPACE
  58098. class PropertySectionComponent : public Component
  58099. {
  58100. public:
  58101. PropertySectionComponent (const String& sectionTitle,
  58102. const Array <PropertyComponent*>& newProperties,
  58103. const bool sectionIsOpen_)
  58104. : Component (sectionTitle),
  58105. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58106. sectionIsOpen (sectionIsOpen_)
  58107. {
  58108. propertyComps.addArray (newProperties);
  58109. for (int i = propertyComps.size(); --i >= 0;)
  58110. {
  58111. addAndMakeVisible (propertyComps.getUnchecked(i));
  58112. propertyComps.getUnchecked(i)->refresh();
  58113. }
  58114. }
  58115. ~PropertySectionComponent()
  58116. {
  58117. propertyComps.clear();
  58118. }
  58119. void paint (Graphics& g)
  58120. {
  58121. if (titleHeight > 0)
  58122. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58123. }
  58124. void resized()
  58125. {
  58126. int y = titleHeight;
  58127. for (int i = 0; i < propertyComps.size(); ++i)
  58128. {
  58129. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58130. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58131. y = pec->getBottom();
  58132. }
  58133. }
  58134. int getPreferredHeight() const
  58135. {
  58136. int y = titleHeight;
  58137. if (isOpen())
  58138. {
  58139. for (int i = propertyComps.size(); --i >= 0;)
  58140. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58141. }
  58142. return y;
  58143. }
  58144. void setOpen (const bool open)
  58145. {
  58146. if (sectionIsOpen != open)
  58147. {
  58148. sectionIsOpen = open;
  58149. for (int i = propertyComps.size(); --i >= 0;)
  58150. propertyComps.getUnchecked(i)->setVisible (open);
  58151. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58152. if (pp != 0)
  58153. pp->resized();
  58154. }
  58155. }
  58156. bool isOpen() const
  58157. {
  58158. return sectionIsOpen;
  58159. }
  58160. void refreshAll() const
  58161. {
  58162. for (int i = propertyComps.size(); --i >= 0;)
  58163. propertyComps.getUnchecked (i)->refresh();
  58164. }
  58165. void mouseUp (const MouseEvent& e)
  58166. {
  58167. if (e.getMouseDownX() < titleHeight
  58168. && e.x < titleHeight
  58169. && e.y < titleHeight
  58170. && e.getNumberOfClicks() != 2)
  58171. {
  58172. setOpen (! isOpen());
  58173. }
  58174. }
  58175. void mouseDoubleClick (const MouseEvent& e)
  58176. {
  58177. if (e.y < titleHeight)
  58178. setOpen (! isOpen());
  58179. }
  58180. private:
  58181. OwnedArray <PropertyComponent> propertyComps;
  58182. int titleHeight;
  58183. bool sectionIsOpen;
  58184. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58185. };
  58186. class PropertyPanel::PropertyHolderComponent : public Component
  58187. {
  58188. public:
  58189. PropertyHolderComponent() {}
  58190. void paint (Graphics&) {}
  58191. void updateLayout (int width)
  58192. {
  58193. int y = 0;
  58194. for (int i = 0; i < sections.size(); ++i)
  58195. {
  58196. PropertySectionComponent* const section = sections.getUnchecked(i);
  58197. section->setBounds (0, y, width, section->getPreferredHeight());
  58198. y = section->getBottom();
  58199. }
  58200. setSize (width, y);
  58201. repaint();
  58202. }
  58203. void refreshAll() const
  58204. {
  58205. for (int i = 0; i < sections.size(); ++i)
  58206. sections.getUnchecked(i)->refreshAll();
  58207. }
  58208. void clear()
  58209. {
  58210. sections.clear();
  58211. }
  58212. void addSection (PropertySectionComponent* newSection)
  58213. {
  58214. sections.add (newSection);
  58215. addAndMakeVisible (newSection, 0);
  58216. }
  58217. int getNumSections() const throw() { return sections.size(); }
  58218. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58219. private:
  58220. OwnedArray<PropertySectionComponent> sections;
  58221. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58222. };
  58223. PropertyPanel::PropertyPanel()
  58224. {
  58225. messageWhenEmpty = TRANS("(nothing selected)");
  58226. addAndMakeVisible (&viewport);
  58227. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58228. viewport.setFocusContainer (true);
  58229. }
  58230. PropertyPanel::~PropertyPanel()
  58231. {
  58232. clear();
  58233. }
  58234. void PropertyPanel::paint (Graphics& g)
  58235. {
  58236. if (propertyHolderComponent->getNumSections() == 0)
  58237. {
  58238. g.setColour (Colours::black.withAlpha (0.5f));
  58239. g.setFont (14.0f);
  58240. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58241. Justification::centred, true);
  58242. }
  58243. }
  58244. void PropertyPanel::resized()
  58245. {
  58246. viewport.setBounds (getLocalBounds());
  58247. updatePropHolderLayout();
  58248. }
  58249. void PropertyPanel::clear()
  58250. {
  58251. if (propertyHolderComponent->getNumSections() > 0)
  58252. {
  58253. propertyHolderComponent->clear();
  58254. repaint();
  58255. }
  58256. }
  58257. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58258. {
  58259. if (propertyHolderComponent->getNumSections() == 0)
  58260. repaint();
  58261. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58262. updatePropHolderLayout();
  58263. }
  58264. void PropertyPanel::addSection (const String& sectionTitle,
  58265. const Array <PropertyComponent*>& newProperties,
  58266. const bool shouldBeOpen)
  58267. {
  58268. jassert (sectionTitle.isNotEmpty());
  58269. if (propertyHolderComponent->getNumSections() == 0)
  58270. repaint();
  58271. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58272. updatePropHolderLayout();
  58273. }
  58274. void PropertyPanel::updatePropHolderLayout() const
  58275. {
  58276. const int maxWidth = viewport.getMaximumVisibleWidth();
  58277. propertyHolderComponent->updateLayout (maxWidth);
  58278. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58279. if (maxWidth != newMaxWidth)
  58280. {
  58281. // need to do this twice because of scrollbars changing the size, etc.
  58282. propertyHolderComponent->updateLayout (newMaxWidth);
  58283. }
  58284. }
  58285. void PropertyPanel::refreshAll() const
  58286. {
  58287. propertyHolderComponent->refreshAll();
  58288. }
  58289. const StringArray PropertyPanel::getSectionNames() const
  58290. {
  58291. StringArray s;
  58292. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58293. {
  58294. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58295. if (section->getName().isNotEmpty())
  58296. s.add (section->getName());
  58297. }
  58298. return s;
  58299. }
  58300. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58301. {
  58302. int index = 0;
  58303. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58304. {
  58305. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58306. if (section->getName().isNotEmpty())
  58307. {
  58308. if (index == sectionIndex)
  58309. return section->isOpen();
  58310. ++index;
  58311. }
  58312. }
  58313. return false;
  58314. }
  58315. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58316. {
  58317. int index = 0;
  58318. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58319. {
  58320. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58321. if (section->getName().isNotEmpty())
  58322. {
  58323. if (index == sectionIndex)
  58324. {
  58325. section->setOpen (shouldBeOpen);
  58326. break;
  58327. }
  58328. ++index;
  58329. }
  58330. }
  58331. }
  58332. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58333. {
  58334. int index = 0;
  58335. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58336. {
  58337. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58338. if (section->getName().isNotEmpty())
  58339. {
  58340. if (index == sectionIndex)
  58341. {
  58342. section->setEnabled (shouldBeEnabled);
  58343. break;
  58344. }
  58345. ++index;
  58346. }
  58347. }
  58348. }
  58349. XmlElement* PropertyPanel::getOpennessState() const
  58350. {
  58351. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58352. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58353. const StringArray sections (getSectionNames());
  58354. for (int i = 0; i < sections.size(); ++i)
  58355. {
  58356. if (sections[i].isNotEmpty())
  58357. {
  58358. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58359. e->setAttribute ("name", sections[i]);
  58360. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58361. }
  58362. }
  58363. return xml;
  58364. }
  58365. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58366. {
  58367. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58368. {
  58369. const StringArray sections (getSectionNames());
  58370. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58371. {
  58372. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58373. e->getBoolAttribute ("open"));
  58374. }
  58375. viewport.setViewPosition (viewport.getViewPositionX(),
  58376. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58377. }
  58378. }
  58379. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58380. {
  58381. if (messageWhenEmpty != newMessage)
  58382. {
  58383. messageWhenEmpty = newMessage;
  58384. repaint();
  58385. }
  58386. }
  58387. const String& PropertyPanel::getMessageWhenEmpty() const
  58388. {
  58389. return messageWhenEmpty;
  58390. }
  58391. END_JUCE_NAMESPACE
  58392. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58393. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58394. BEGIN_JUCE_NAMESPACE
  58395. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58396. const double rangeMin,
  58397. const double rangeMax,
  58398. const double interval,
  58399. const double skewFactor)
  58400. : PropertyComponent (name)
  58401. {
  58402. addAndMakeVisible (&slider);
  58403. slider.setRange (rangeMin, rangeMax, interval);
  58404. slider.setSkewFactor (skewFactor);
  58405. slider.setSliderStyle (Slider::LinearBar);
  58406. slider.addListener (this);
  58407. }
  58408. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58409. const String& name,
  58410. const double rangeMin,
  58411. const double rangeMax,
  58412. const double interval,
  58413. const double skewFactor)
  58414. : PropertyComponent (name)
  58415. {
  58416. addAndMakeVisible (&slider);
  58417. slider.setRange (rangeMin, rangeMax, interval);
  58418. slider.setSkewFactor (skewFactor);
  58419. slider.setSliderStyle (Slider::LinearBar);
  58420. slider.getValueObject().referTo (valueToControl);
  58421. }
  58422. SliderPropertyComponent::~SliderPropertyComponent()
  58423. {
  58424. }
  58425. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58426. {
  58427. }
  58428. double SliderPropertyComponent::getValue() const
  58429. {
  58430. return slider.getValue();
  58431. }
  58432. void SliderPropertyComponent::refresh()
  58433. {
  58434. slider.setValue (getValue(), false);
  58435. }
  58436. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58437. {
  58438. if (getValue() != slider.getValue())
  58439. setValue (slider.getValue());
  58440. }
  58441. END_JUCE_NAMESPACE
  58442. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58443. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58444. BEGIN_JUCE_NAMESPACE
  58445. class TextPropLabel : public Label
  58446. {
  58447. public:
  58448. TextPropLabel (TextPropertyComponent& owner_,
  58449. const int maxChars_, const bool isMultiline_)
  58450. : Label (String::empty, String::empty),
  58451. owner (owner_),
  58452. maxChars (maxChars_),
  58453. isMultiline (isMultiline_)
  58454. {
  58455. setEditable (true, true, false);
  58456. setColour (backgroundColourId, Colours::white);
  58457. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58458. }
  58459. TextEditor* createEditorComponent()
  58460. {
  58461. TextEditor* const textEditor = Label::createEditorComponent();
  58462. textEditor->setInputRestrictions (maxChars);
  58463. if (isMultiline)
  58464. {
  58465. textEditor->setMultiLine (true, true);
  58466. textEditor->setReturnKeyStartsNewLine (true);
  58467. }
  58468. return textEditor;
  58469. }
  58470. void textWasEdited()
  58471. {
  58472. owner.textWasEdited();
  58473. }
  58474. private:
  58475. TextPropertyComponent& owner;
  58476. int maxChars;
  58477. bool isMultiline;
  58478. };
  58479. TextPropertyComponent::TextPropertyComponent (const String& name,
  58480. const int maxNumChars,
  58481. const bool isMultiLine)
  58482. : PropertyComponent (name)
  58483. {
  58484. createEditor (maxNumChars, isMultiLine);
  58485. }
  58486. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58487. const String& name,
  58488. const int maxNumChars,
  58489. const bool isMultiLine)
  58490. : PropertyComponent (name)
  58491. {
  58492. createEditor (maxNumChars, isMultiLine);
  58493. textEditor->getTextValue().referTo (valueToControl);
  58494. }
  58495. TextPropertyComponent::~TextPropertyComponent()
  58496. {
  58497. }
  58498. void TextPropertyComponent::setText (const String& newText)
  58499. {
  58500. textEditor->setText (newText, true);
  58501. }
  58502. const String TextPropertyComponent::getText() const
  58503. {
  58504. return textEditor->getText();
  58505. }
  58506. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58507. {
  58508. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58509. if (isMultiLine)
  58510. {
  58511. textEditor->setJustificationType (Justification::topLeft);
  58512. preferredHeight = 120;
  58513. }
  58514. }
  58515. void TextPropertyComponent::refresh()
  58516. {
  58517. textEditor->setText (getText(), false);
  58518. }
  58519. void TextPropertyComponent::textWasEdited()
  58520. {
  58521. const String newText (textEditor->getText());
  58522. if (getText() != newText)
  58523. setText (newText);
  58524. }
  58525. END_JUCE_NAMESPACE
  58526. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58527. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58528. BEGIN_JUCE_NAMESPACE
  58529. class SimpleDeviceManagerInputLevelMeter : public Component,
  58530. public Timer
  58531. {
  58532. public:
  58533. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58534. : manager (manager_),
  58535. level (0)
  58536. {
  58537. startTimer (50);
  58538. manager->enableInputLevelMeasurement (true);
  58539. }
  58540. ~SimpleDeviceManagerInputLevelMeter()
  58541. {
  58542. manager->enableInputLevelMeasurement (false);
  58543. }
  58544. void timerCallback()
  58545. {
  58546. const float newLevel = (float) manager->getCurrentInputLevel();
  58547. if (std::abs (level - newLevel) > 0.005f)
  58548. {
  58549. level = newLevel;
  58550. repaint();
  58551. }
  58552. }
  58553. void paint (Graphics& g)
  58554. {
  58555. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58556. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58557. }
  58558. private:
  58559. AudioDeviceManager* const manager;
  58560. float level;
  58561. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58562. };
  58563. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58564. public ListBoxModel
  58565. {
  58566. public:
  58567. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58568. const String& noItemsMessage_,
  58569. const int minNumber_,
  58570. const int maxNumber_)
  58571. : ListBox (String::empty, 0),
  58572. deviceManager (deviceManager_),
  58573. noItemsMessage (noItemsMessage_),
  58574. minNumber (minNumber_),
  58575. maxNumber (maxNumber_)
  58576. {
  58577. items = MidiInput::getDevices();
  58578. setModel (this);
  58579. setOutlineThickness (1);
  58580. }
  58581. ~MidiInputSelectorComponentListBox()
  58582. {
  58583. }
  58584. int getNumRows()
  58585. {
  58586. return items.size();
  58587. }
  58588. void paintListBoxItem (int row,
  58589. Graphics& g,
  58590. int width, int height,
  58591. bool rowIsSelected)
  58592. {
  58593. if (isPositiveAndBelow (row, items.size()))
  58594. {
  58595. if (rowIsSelected)
  58596. g.fillAll (findColour (TextEditor::highlightColourId)
  58597. .withMultipliedAlpha (0.3f));
  58598. const String item (items [row]);
  58599. bool enabled = deviceManager.isMidiInputEnabled (item);
  58600. const int x = getTickX();
  58601. const float tickW = height * 0.75f;
  58602. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58603. enabled, true, true, false);
  58604. g.setFont (height * 0.6f);
  58605. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58606. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58607. }
  58608. }
  58609. void listBoxItemClicked (int row, const MouseEvent& e)
  58610. {
  58611. selectRow (row);
  58612. if (e.x < getTickX())
  58613. flipEnablement (row);
  58614. }
  58615. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58616. {
  58617. flipEnablement (row);
  58618. }
  58619. void returnKeyPressed (int row)
  58620. {
  58621. flipEnablement (row);
  58622. }
  58623. void paint (Graphics& g)
  58624. {
  58625. ListBox::paint (g);
  58626. if (items.size() == 0)
  58627. {
  58628. g.setColour (Colours::grey);
  58629. g.setFont (13.0f);
  58630. g.drawText (noItemsMessage,
  58631. 0, 0, getWidth(), getHeight() / 2,
  58632. Justification::centred, true);
  58633. }
  58634. }
  58635. int getBestHeight (const int preferredHeight)
  58636. {
  58637. const int extra = getOutlineThickness() * 2;
  58638. return jmax (getRowHeight() * 2 + extra,
  58639. jmin (getRowHeight() * getNumRows() + extra,
  58640. preferredHeight));
  58641. }
  58642. private:
  58643. AudioDeviceManager& deviceManager;
  58644. const String noItemsMessage;
  58645. StringArray items;
  58646. int minNumber, maxNumber;
  58647. void flipEnablement (const int row)
  58648. {
  58649. if (isPositiveAndBelow (row, items.size()))
  58650. {
  58651. const String item (items [row]);
  58652. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58653. }
  58654. }
  58655. int getTickX() const
  58656. {
  58657. return getRowHeight() + 5;
  58658. }
  58659. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58660. };
  58661. class AudioDeviceSettingsPanel : public Component,
  58662. public ChangeListener,
  58663. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58664. public ButtonListener
  58665. {
  58666. public:
  58667. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58668. AudioIODeviceType::DeviceSetupDetails& setup_,
  58669. const bool hideAdvancedOptionsWithButton)
  58670. : type (type_),
  58671. setup (setup_)
  58672. {
  58673. if (hideAdvancedOptionsWithButton)
  58674. {
  58675. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58676. showAdvancedSettingsButton->addButtonListener (this);
  58677. }
  58678. type->scanForDevices();
  58679. setup.manager->addChangeListener (this);
  58680. changeListenerCallback (0);
  58681. }
  58682. ~AudioDeviceSettingsPanel()
  58683. {
  58684. setup.manager->removeChangeListener (this);
  58685. }
  58686. void resized()
  58687. {
  58688. const int lx = proportionOfWidth (0.35f);
  58689. const int w = proportionOfWidth (0.4f);
  58690. const int h = 24;
  58691. const int space = 6;
  58692. const int dh = h + space;
  58693. int y = 0;
  58694. if (outputDeviceDropDown != 0)
  58695. {
  58696. outputDeviceDropDown->setBounds (lx, y, w, h);
  58697. if (testButton != 0)
  58698. testButton->setBounds (proportionOfWidth (0.77f),
  58699. outputDeviceDropDown->getY(),
  58700. proportionOfWidth (0.18f),
  58701. h);
  58702. y += dh;
  58703. }
  58704. if (inputDeviceDropDown != 0)
  58705. {
  58706. inputDeviceDropDown->setBounds (lx, y, w, h);
  58707. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58708. inputDeviceDropDown->getY(),
  58709. proportionOfWidth (0.18f),
  58710. h);
  58711. y += dh;
  58712. }
  58713. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58714. if (outputChanList != 0)
  58715. {
  58716. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58717. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58718. y += bh + space;
  58719. }
  58720. if (inputChanList != 0)
  58721. {
  58722. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58723. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58724. y += bh + space;
  58725. }
  58726. y += space * 2;
  58727. if (showAdvancedSettingsButton != 0)
  58728. {
  58729. showAdvancedSettingsButton->changeWidthToFitText (h);
  58730. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58731. }
  58732. if (sampleRateDropDown != 0)
  58733. {
  58734. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58735. || ! showAdvancedSettingsButton->isVisible());
  58736. sampleRateDropDown->setBounds (lx, y, w, h);
  58737. y += dh;
  58738. }
  58739. if (bufferSizeDropDown != 0)
  58740. {
  58741. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58742. || ! showAdvancedSettingsButton->isVisible());
  58743. bufferSizeDropDown->setBounds (lx, y, w, h);
  58744. y += dh;
  58745. }
  58746. if (showUIButton != 0)
  58747. {
  58748. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58749. || ! showAdvancedSettingsButton->isVisible());
  58750. showUIButton->changeWidthToFitText (h);
  58751. showUIButton->setTopLeftPosition (lx, y);
  58752. }
  58753. }
  58754. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58755. {
  58756. if (comboBoxThatHasChanged == 0)
  58757. return;
  58758. AudioDeviceManager::AudioDeviceSetup config;
  58759. setup.manager->getAudioDeviceSetup (config);
  58760. String error;
  58761. if (comboBoxThatHasChanged == outputDeviceDropDown
  58762. || comboBoxThatHasChanged == inputDeviceDropDown)
  58763. {
  58764. if (outputDeviceDropDown != 0)
  58765. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58766. : outputDeviceDropDown->getText();
  58767. if (inputDeviceDropDown != 0)
  58768. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58769. : inputDeviceDropDown->getText();
  58770. if (! type->hasSeparateInputsAndOutputs())
  58771. config.inputDeviceName = config.outputDeviceName;
  58772. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58773. config.useDefaultInputChannels = true;
  58774. else
  58775. config.useDefaultOutputChannels = true;
  58776. error = setup.manager->setAudioDeviceSetup (config, true);
  58777. showCorrectDeviceName (inputDeviceDropDown, true);
  58778. showCorrectDeviceName (outputDeviceDropDown, false);
  58779. updateControlPanelButton();
  58780. resized();
  58781. }
  58782. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58783. {
  58784. if (sampleRateDropDown->getSelectedId() > 0)
  58785. {
  58786. config.sampleRate = sampleRateDropDown->getSelectedId();
  58787. error = setup.manager->setAudioDeviceSetup (config, true);
  58788. }
  58789. }
  58790. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58791. {
  58792. if (bufferSizeDropDown->getSelectedId() > 0)
  58793. {
  58794. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58795. error = setup.manager->setAudioDeviceSetup (config, true);
  58796. }
  58797. }
  58798. if (error.isNotEmpty())
  58799. {
  58800. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58801. "Error when trying to open audio device!",
  58802. error);
  58803. }
  58804. }
  58805. void buttonClicked (Button* button)
  58806. {
  58807. if (button == showAdvancedSettingsButton)
  58808. {
  58809. showAdvancedSettingsButton->setVisible (false);
  58810. resized();
  58811. }
  58812. else if (button == showUIButton)
  58813. {
  58814. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58815. if (device != 0 && device->showControlPanel())
  58816. {
  58817. setup.manager->closeAudioDevice();
  58818. setup.manager->restartLastAudioDevice();
  58819. getTopLevelComponent()->toFront (true);
  58820. }
  58821. }
  58822. else if (button == testButton && testButton != 0)
  58823. {
  58824. setup.manager->playTestSound();
  58825. }
  58826. }
  58827. void updateControlPanelButton()
  58828. {
  58829. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58830. showUIButton = 0;
  58831. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58832. {
  58833. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58834. TRANS ("opens the device's own control panel")));
  58835. showUIButton->addButtonListener (this);
  58836. }
  58837. resized();
  58838. }
  58839. void changeListenerCallback (ChangeBroadcaster*)
  58840. {
  58841. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58842. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58843. {
  58844. if (outputDeviceDropDown == 0)
  58845. {
  58846. outputDeviceDropDown = new ComboBox (String::empty);
  58847. outputDeviceDropDown->addListener (this);
  58848. addAndMakeVisible (outputDeviceDropDown);
  58849. outputDeviceLabel = new Label (String::empty,
  58850. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58851. : TRANS ("device:"));
  58852. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58853. if (setup.maxNumOutputChannels > 0)
  58854. {
  58855. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58856. testButton->addButtonListener (this);
  58857. }
  58858. }
  58859. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58860. }
  58861. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58862. {
  58863. if (inputDeviceDropDown == 0)
  58864. {
  58865. inputDeviceDropDown = new ComboBox (String::empty);
  58866. inputDeviceDropDown->addListener (this);
  58867. addAndMakeVisible (inputDeviceDropDown);
  58868. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58869. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58870. addAndMakeVisible (inputLevelMeter
  58871. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58872. }
  58873. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58874. }
  58875. updateControlPanelButton();
  58876. showCorrectDeviceName (inputDeviceDropDown, true);
  58877. showCorrectDeviceName (outputDeviceDropDown, false);
  58878. if (currentDevice != 0)
  58879. {
  58880. if (setup.maxNumOutputChannels > 0
  58881. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58882. {
  58883. if (outputChanList == 0)
  58884. {
  58885. addAndMakeVisible (outputChanList
  58886. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58887. TRANS ("(no audio output channels found)")));
  58888. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58889. outputChanLabel->attachToComponent (outputChanList, true);
  58890. }
  58891. outputChanList->refresh();
  58892. }
  58893. else
  58894. {
  58895. outputChanLabel = 0;
  58896. outputChanList = 0;
  58897. }
  58898. if (setup.maxNumInputChannels > 0
  58899. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58900. {
  58901. if (inputChanList == 0)
  58902. {
  58903. addAndMakeVisible (inputChanList
  58904. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58905. TRANS ("(no audio input channels found)")));
  58906. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58907. inputChanLabel->attachToComponent (inputChanList, true);
  58908. }
  58909. inputChanList->refresh();
  58910. }
  58911. else
  58912. {
  58913. inputChanLabel = 0;
  58914. inputChanList = 0;
  58915. }
  58916. // sample rate..
  58917. {
  58918. if (sampleRateDropDown == 0)
  58919. {
  58920. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58921. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58922. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58923. }
  58924. else
  58925. {
  58926. sampleRateDropDown->clear();
  58927. sampleRateDropDown->removeListener (this);
  58928. }
  58929. const int numRates = currentDevice->getNumSampleRates();
  58930. for (int i = 0; i < numRates; ++i)
  58931. {
  58932. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58933. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58934. }
  58935. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58936. sampleRateDropDown->addListener (this);
  58937. }
  58938. // buffer size
  58939. {
  58940. if (bufferSizeDropDown == 0)
  58941. {
  58942. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58943. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58944. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58945. }
  58946. else
  58947. {
  58948. bufferSizeDropDown->clear();
  58949. bufferSizeDropDown->removeListener (this);
  58950. }
  58951. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58952. double currentRate = currentDevice->getCurrentSampleRate();
  58953. if (currentRate == 0)
  58954. currentRate = 48000.0;
  58955. for (int i = 0; i < numBufferSizes; ++i)
  58956. {
  58957. const int bs = currentDevice->getBufferSizeSamples (i);
  58958. bufferSizeDropDown->addItem (String (bs)
  58959. + " samples ("
  58960. + String (bs * 1000.0 / currentRate, 1)
  58961. + " ms)",
  58962. bs);
  58963. }
  58964. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58965. bufferSizeDropDown->addListener (this);
  58966. }
  58967. }
  58968. else
  58969. {
  58970. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58971. sampleRateLabel = 0;
  58972. bufferSizeLabel = 0;
  58973. sampleRateDropDown = 0;
  58974. bufferSizeDropDown = 0;
  58975. if (outputDeviceDropDown != 0)
  58976. outputDeviceDropDown->setSelectedId (-1, true);
  58977. if (inputDeviceDropDown != 0)
  58978. inputDeviceDropDown->setSelectedId (-1, true);
  58979. }
  58980. resized();
  58981. setSize (getWidth(), getLowestY() + 4);
  58982. }
  58983. private:
  58984. AudioIODeviceType* const type;
  58985. const AudioIODeviceType::DeviceSetupDetails setup;
  58986. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58987. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58988. ScopedPointer<TextButton> testButton;
  58989. ScopedPointer<Component> inputLevelMeter;
  58990. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58991. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58992. {
  58993. if (box != 0)
  58994. {
  58995. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58996. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58997. box->setSelectedId (index + 1, true);
  58998. if (testButton != 0 && ! isInput)
  58999. testButton->setEnabled (index >= 0);
  59000. }
  59001. }
  59002. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59003. {
  59004. const StringArray devs (type->getDeviceNames (isInputs));
  59005. combo.clear (true);
  59006. for (int i = 0; i < devs.size(); ++i)
  59007. combo.addItem (devs[i], i + 1);
  59008. combo.addItem (TRANS("<< none >>"), -1);
  59009. combo.setSelectedId (-1, true);
  59010. }
  59011. int getLowestY() const
  59012. {
  59013. int y = 0;
  59014. for (int i = getNumChildComponents(); --i >= 0;)
  59015. y = jmax (y, getChildComponent (i)->getBottom());
  59016. return y;
  59017. }
  59018. public:
  59019. class ChannelSelectorListBox : public ListBox,
  59020. public ListBoxModel
  59021. {
  59022. public:
  59023. enum BoxType
  59024. {
  59025. audioInputType,
  59026. audioOutputType
  59027. };
  59028. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59029. const BoxType type_,
  59030. const String& noItemsMessage_)
  59031. : ListBox (String::empty, 0),
  59032. setup (setup_),
  59033. type (type_),
  59034. noItemsMessage (noItemsMessage_)
  59035. {
  59036. refresh();
  59037. setModel (this);
  59038. setOutlineThickness (1);
  59039. }
  59040. ~ChannelSelectorListBox()
  59041. {
  59042. }
  59043. void refresh()
  59044. {
  59045. items.clear();
  59046. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59047. if (currentDevice != 0)
  59048. {
  59049. if (type == audioInputType)
  59050. items = currentDevice->getInputChannelNames();
  59051. else if (type == audioOutputType)
  59052. items = currentDevice->getOutputChannelNames();
  59053. if (setup.useStereoPairs)
  59054. {
  59055. StringArray pairs;
  59056. for (int i = 0; i < items.size(); i += 2)
  59057. {
  59058. const String name (items[i]);
  59059. const String name2 (items[i + 1]);
  59060. String commonBit;
  59061. for (int j = 0; j < name.length(); ++j)
  59062. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59063. commonBit = name.substring (0, j);
  59064. // Make sure we only split the name at a space, because otherwise, things
  59065. // like "input 11" + "input 12" would become "input 11 + 2"
  59066. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59067. commonBit = commonBit.dropLastCharacters (1);
  59068. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59069. }
  59070. items = pairs;
  59071. }
  59072. }
  59073. updateContent();
  59074. repaint();
  59075. }
  59076. int getNumRows()
  59077. {
  59078. return items.size();
  59079. }
  59080. void paintListBoxItem (int row,
  59081. Graphics& g,
  59082. int width, int height,
  59083. bool rowIsSelected)
  59084. {
  59085. if (isPositiveAndBelow (row, items.size()))
  59086. {
  59087. if (rowIsSelected)
  59088. g.fillAll (findColour (TextEditor::highlightColourId)
  59089. .withMultipliedAlpha (0.3f));
  59090. const String item (items [row]);
  59091. bool enabled = false;
  59092. AudioDeviceManager::AudioDeviceSetup config;
  59093. setup.manager->getAudioDeviceSetup (config);
  59094. if (setup.useStereoPairs)
  59095. {
  59096. if (type == audioInputType)
  59097. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59098. else if (type == audioOutputType)
  59099. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59100. }
  59101. else
  59102. {
  59103. if (type == audioInputType)
  59104. enabled = config.inputChannels [row];
  59105. else if (type == audioOutputType)
  59106. enabled = config.outputChannels [row];
  59107. }
  59108. const int x = getTickX();
  59109. const float tickW = height * 0.75f;
  59110. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59111. enabled, true, true, false);
  59112. g.setFont (height * 0.6f);
  59113. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59114. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59115. }
  59116. }
  59117. void listBoxItemClicked (int row, const MouseEvent& e)
  59118. {
  59119. selectRow (row);
  59120. if (e.x < getTickX())
  59121. flipEnablement (row);
  59122. }
  59123. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59124. {
  59125. flipEnablement (row);
  59126. }
  59127. void returnKeyPressed (int row)
  59128. {
  59129. flipEnablement (row);
  59130. }
  59131. void paint (Graphics& g)
  59132. {
  59133. ListBox::paint (g);
  59134. if (items.size() == 0)
  59135. {
  59136. g.setColour (Colours::grey);
  59137. g.setFont (13.0f);
  59138. g.drawText (noItemsMessage,
  59139. 0, 0, getWidth(), getHeight() / 2,
  59140. Justification::centred, true);
  59141. }
  59142. }
  59143. int getBestHeight (int maxHeight)
  59144. {
  59145. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59146. getNumRows())
  59147. + getOutlineThickness() * 2;
  59148. }
  59149. private:
  59150. const AudioIODeviceType::DeviceSetupDetails setup;
  59151. const BoxType type;
  59152. const String noItemsMessage;
  59153. StringArray items;
  59154. void flipEnablement (const int row)
  59155. {
  59156. jassert (type == audioInputType || type == audioOutputType);
  59157. if (isPositiveAndBelow (row, items.size()))
  59158. {
  59159. AudioDeviceManager::AudioDeviceSetup config;
  59160. setup.manager->getAudioDeviceSetup (config);
  59161. if (setup.useStereoPairs)
  59162. {
  59163. BigInteger bits;
  59164. BigInteger& original = (type == audioInputType ? config.inputChannels
  59165. : config.outputChannels);
  59166. int i;
  59167. for (i = 0; i < 256; i += 2)
  59168. bits.setBit (i / 2, original [i] || original [i + 1]);
  59169. if (type == audioInputType)
  59170. {
  59171. config.useDefaultInputChannels = false;
  59172. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59173. }
  59174. else
  59175. {
  59176. config.useDefaultOutputChannels = false;
  59177. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59178. }
  59179. for (i = 0; i < 256; ++i)
  59180. original.setBit (i, bits [i / 2]);
  59181. }
  59182. else
  59183. {
  59184. if (type == audioInputType)
  59185. {
  59186. config.useDefaultInputChannels = false;
  59187. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59188. }
  59189. else
  59190. {
  59191. config.useDefaultOutputChannels = false;
  59192. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59193. }
  59194. }
  59195. String error (setup.manager->setAudioDeviceSetup (config, true));
  59196. if (! error.isEmpty())
  59197. {
  59198. //xxx
  59199. }
  59200. }
  59201. }
  59202. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59203. {
  59204. const int numActive = chans.countNumberOfSetBits();
  59205. if (chans [index])
  59206. {
  59207. if (numActive > minNumber)
  59208. chans.setBit (index, false);
  59209. }
  59210. else
  59211. {
  59212. if (numActive >= maxNumber)
  59213. {
  59214. const int firstActiveChan = chans.findNextSetBit();
  59215. chans.setBit (index > firstActiveChan
  59216. ? firstActiveChan : chans.getHighestBit(),
  59217. false);
  59218. }
  59219. chans.setBit (index, true);
  59220. }
  59221. }
  59222. int getTickX() const
  59223. {
  59224. return getRowHeight() + 5;
  59225. }
  59226. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59227. };
  59228. private:
  59229. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59230. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59231. };
  59232. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59233. const int minInputChannels_,
  59234. const int maxInputChannels_,
  59235. const int minOutputChannels_,
  59236. const int maxOutputChannels_,
  59237. const bool showMidiInputOptions,
  59238. const bool showMidiOutputSelector,
  59239. const bool showChannelsAsStereoPairs_,
  59240. const bool hideAdvancedOptionsWithButton_)
  59241. : deviceManager (deviceManager_),
  59242. deviceTypeDropDown (0),
  59243. deviceTypeDropDownLabel (0),
  59244. minOutputChannels (minOutputChannels_),
  59245. maxOutputChannels (maxOutputChannels_),
  59246. minInputChannels (minInputChannels_),
  59247. maxInputChannels (maxInputChannels_),
  59248. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59249. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59250. {
  59251. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59252. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59253. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59254. {
  59255. deviceTypeDropDown = new ComboBox (String::empty);
  59256. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59257. {
  59258. deviceTypeDropDown
  59259. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59260. i + 1);
  59261. }
  59262. addAndMakeVisible (deviceTypeDropDown);
  59263. deviceTypeDropDown->addListener (this);
  59264. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59265. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59266. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59267. }
  59268. if (showMidiInputOptions)
  59269. {
  59270. addAndMakeVisible (midiInputsList
  59271. = new MidiInputSelectorComponentListBox (deviceManager,
  59272. TRANS("(no midi inputs available)"),
  59273. 0, 0));
  59274. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59275. midiInputsLabel->setJustificationType (Justification::topRight);
  59276. midiInputsLabel->attachToComponent (midiInputsList, true);
  59277. }
  59278. else
  59279. {
  59280. midiInputsList = 0;
  59281. midiInputsLabel = 0;
  59282. }
  59283. if (showMidiOutputSelector)
  59284. {
  59285. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59286. midiOutputSelector->addListener (this);
  59287. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59288. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59289. }
  59290. else
  59291. {
  59292. midiOutputSelector = 0;
  59293. midiOutputLabel = 0;
  59294. }
  59295. deviceManager_.addChangeListener (this);
  59296. changeListenerCallback (0);
  59297. }
  59298. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59299. {
  59300. deviceManager.removeChangeListener (this);
  59301. }
  59302. void AudioDeviceSelectorComponent::resized()
  59303. {
  59304. const int lx = proportionOfWidth (0.35f);
  59305. const int w = proportionOfWidth (0.4f);
  59306. const int h = 24;
  59307. const int space = 6;
  59308. const int dh = h + space;
  59309. int y = 15;
  59310. if (deviceTypeDropDown != 0)
  59311. {
  59312. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59313. y += dh + space * 2;
  59314. }
  59315. if (audioDeviceSettingsComp != 0)
  59316. {
  59317. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59318. y += audioDeviceSettingsComp->getHeight() + space;
  59319. }
  59320. if (midiInputsList != 0)
  59321. {
  59322. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59323. midiInputsList->setBounds (lx, y, w, bh);
  59324. y += bh + space;
  59325. }
  59326. if (midiOutputSelector != 0)
  59327. midiOutputSelector->setBounds (lx, y, w, h);
  59328. }
  59329. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59330. {
  59331. if (child == audioDeviceSettingsComp)
  59332. resized();
  59333. }
  59334. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59335. {
  59336. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59337. if (device != 0 && device->hasControlPanel())
  59338. {
  59339. if (device->showControlPanel())
  59340. deviceManager.restartLastAudioDevice();
  59341. getTopLevelComponent()->toFront (true);
  59342. }
  59343. }
  59344. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59345. {
  59346. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59347. {
  59348. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59349. if (type != 0)
  59350. {
  59351. audioDeviceSettingsComp = 0;
  59352. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59353. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59354. }
  59355. }
  59356. else if (comboBoxThatHasChanged == midiOutputSelector)
  59357. {
  59358. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59359. }
  59360. }
  59361. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59362. {
  59363. if (deviceTypeDropDown != 0)
  59364. {
  59365. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59366. }
  59367. if (audioDeviceSettingsComp == 0
  59368. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59369. {
  59370. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59371. audioDeviceSettingsComp = 0;
  59372. AudioIODeviceType* const type
  59373. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59374. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59375. if (type != 0)
  59376. {
  59377. AudioIODeviceType::DeviceSetupDetails details;
  59378. details.manager = &deviceManager;
  59379. details.minNumInputChannels = minInputChannels;
  59380. details.maxNumInputChannels = maxInputChannels;
  59381. details.minNumOutputChannels = minOutputChannels;
  59382. details.maxNumOutputChannels = maxOutputChannels;
  59383. details.useStereoPairs = showChannelsAsStereoPairs;
  59384. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59385. if (audioDeviceSettingsComp != 0)
  59386. {
  59387. addAndMakeVisible (audioDeviceSettingsComp);
  59388. audioDeviceSettingsComp->resized();
  59389. }
  59390. }
  59391. }
  59392. if (midiInputsList != 0)
  59393. {
  59394. midiInputsList->updateContent();
  59395. midiInputsList->repaint();
  59396. }
  59397. if (midiOutputSelector != 0)
  59398. {
  59399. midiOutputSelector->clear();
  59400. const StringArray midiOuts (MidiOutput::getDevices());
  59401. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59402. midiOutputSelector->addSeparator();
  59403. for (int i = 0; i < midiOuts.size(); ++i)
  59404. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59405. int current = -1;
  59406. if (deviceManager.getDefaultMidiOutput() != 0)
  59407. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59408. midiOutputSelector->setSelectedId (current, true);
  59409. }
  59410. resized();
  59411. }
  59412. END_JUCE_NAMESPACE
  59413. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59414. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59415. BEGIN_JUCE_NAMESPACE
  59416. BubbleComponent::BubbleComponent()
  59417. : side (0),
  59418. allowablePlacements (above | below | left | right),
  59419. arrowTipX (0.0f),
  59420. arrowTipY (0.0f)
  59421. {
  59422. setInterceptsMouseClicks (false, false);
  59423. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59424. setComponentEffect (&shadow);
  59425. }
  59426. BubbleComponent::~BubbleComponent()
  59427. {
  59428. }
  59429. void BubbleComponent::paint (Graphics& g)
  59430. {
  59431. int x = content.getX();
  59432. int y = content.getY();
  59433. int w = content.getWidth();
  59434. int h = content.getHeight();
  59435. int cw, ch;
  59436. getContentSize (cw, ch);
  59437. if (side == 3)
  59438. x += w - cw;
  59439. else if (side != 1)
  59440. x += (w - cw) / 2;
  59441. w = cw;
  59442. if (side == 2)
  59443. y += h - ch;
  59444. else if (side != 0)
  59445. y += (h - ch) / 2;
  59446. h = ch;
  59447. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59448. (float) x, (float) y,
  59449. (float) w, (float) h);
  59450. const int cx = x + (w - cw) / 2;
  59451. const int cy = y + (h - ch) / 2;
  59452. const int indent = 3;
  59453. g.setOrigin (cx + indent, cy + indent);
  59454. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59455. paintContent (g, cw - indent * 2, ch - indent * 2);
  59456. }
  59457. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59458. {
  59459. allowablePlacements = newPlacement;
  59460. }
  59461. void BubbleComponent::setPosition (Component* componentToPointTo)
  59462. {
  59463. jassert (componentToPointTo != 0);
  59464. Point<int> pos;
  59465. if (getParentComponent() != 0)
  59466. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59467. else
  59468. pos = componentToPointTo->localPointToGlobal (pos);
  59469. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59470. }
  59471. void BubbleComponent::setPosition (const int arrowTipX_,
  59472. const int arrowTipY_)
  59473. {
  59474. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59475. }
  59476. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59477. {
  59478. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59479. : getParentMonitorArea());
  59480. int x = 0;
  59481. int y = 0;
  59482. int w = 150;
  59483. int h = 30;
  59484. getContentSize (w, h);
  59485. w += 30;
  59486. h += 30;
  59487. const float edgeIndent = 2.0f;
  59488. const int arrowLength = jmin (10, h / 3, w / 3);
  59489. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59490. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59491. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59492. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59493. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59494. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59495. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59496. {
  59497. spaceLeft = spaceRight = 0;
  59498. }
  59499. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59500. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59501. {
  59502. spaceAbove = spaceBelow = 0;
  59503. }
  59504. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59505. {
  59506. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59507. arrowTipX = w * 0.5f;
  59508. content.setSize (w, h - arrowLength);
  59509. if (spaceAbove >= spaceBelow)
  59510. {
  59511. // above
  59512. y = rectangleToPointTo.getY() - h;
  59513. content.setPosition (0, 0);
  59514. arrowTipY = h - edgeIndent;
  59515. side = 2;
  59516. }
  59517. else
  59518. {
  59519. // below
  59520. y = rectangleToPointTo.getBottom();
  59521. content.setPosition (0, arrowLength);
  59522. arrowTipY = edgeIndent;
  59523. side = 0;
  59524. }
  59525. }
  59526. else
  59527. {
  59528. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59529. arrowTipY = h * 0.5f;
  59530. content.setSize (w - arrowLength, h);
  59531. if (spaceLeft > spaceRight)
  59532. {
  59533. // on the left
  59534. x = rectangleToPointTo.getX() - w;
  59535. content.setPosition (0, 0);
  59536. arrowTipX = w - edgeIndent;
  59537. side = 3;
  59538. }
  59539. else
  59540. {
  59541. // on the right
  59542. x = rectangleToPointTo.getRight();
  59543. content.setPosition (arrowLength, 0);
  59544. arrowTipX = edgeIndent;
  59545. side = 1;
  59546. }
  59547. }
  59548. setBounds (x, y, w, h);
  59549. }
  59550. END_JUCE_NAMESPACE
  59551. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59552. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59553. BEGIN_JUCE_NAMESPACE
  59554. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59555. : fadeOutLength (fadeOutLengthMs),
  59556. deleteAfterUse (false)
  59557. {
  59558. }
  59559. BubbleMessageComponent::~BubbleMessageComponent()
  59560. {
  59561. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59562. }
  59563. void BubbleMessageComponent::showAt (int x, int y,
  59564. const String& text,
  59565. const int numMillisecondsBeforeRemoving,
  59566. const bool removeWhenMouseClicked,
  59567. const bool deleteSelfAfterUse)
  59568. {
  59569. textLayout.clear();
  59570. textLayout.setText (text, Font (14.0f));
  59571. textLayout.layout (256, Justification::centredLeft, true);
  59572. setPosition (x, y);
  59573. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59574. }
  59575. void BubbleMessageComponent::showAt (Component* const component,
  59576. const String& text,
  59577. const int numMillisecondsBeforeRemoving,
  59578. const bool removeWhenMouseClicked,
  59579. const bool deleteSelfAfterUse)
  59580. {
  59581. textLayout.clear();
  59582. textLayout.setText (text, Font (14.0f));
  59583. textLayout.layout (256, Justification::centredLeft, true);
  59584. setPosition (component);
  59585. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59586. }
  59587. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59588. const bool removeWhenMouseClicked,
  59589. const bool deleteSelfAfterUse)
  59590. {
  59591. setVisible (true);
  59592. deleteAfterUse = deleteSelfAfterUse;
  59593. if (numMillisecondsBeforeRemoving > 0)
  59594. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59595. else
  59596. expiryTime = 0;
  59597. startTimer (77);
  59598. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59599. if (! (removeWhenMouseClicked && isShowing()))
  59600. mouseClickCounter += 0xfffff;
  59601. repaint();
  59602. }
  59603. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59604. {
  59605. w = textLayout.getWidth() + 16;
  59606. h = textLayout.getHeight() + 16;
  59607. }
  59608. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59609. {
  59610. g.setColour (findColour (TooltipWindow::textColourId));
  59611. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59612. }
  59613. void BubbleMessageComponent::timerCallback()
  59614. {
  59615. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59616. {
  59617. stopTimer();
  59618. setVisible (false);
  59619. if (deleteAfterUse)
  59620. delete this;
  59621. }
  59622. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59623. {
  59624. stopTimer();
  59625. if (deleteAfterUse)
  59626. delete this;
  59627. else
  59628. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59629. }
  59630. }
  59631. END_JUCE_NAMESPACE
  59632. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59633. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59634. BEGIN_JUCE_NAMESPACE
  59635. class ColourComponentSlider : public Slider
  59636. {
  59637. public:
  59638. ColourComponentSlider (const String& name)
  59639. : Slider (name)
  59640. {
  59641. setRange (0.0, 255.0, 1.0);
  59642. }
  59643. const String getTextFromValue (double value)
  59644. {
  59645. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59646. }
  59647. double getValueFromText (const String& text)
  59648. {
  59649. return (double) text.getHexValue32();
  59650. }
  59651. private:
  59652. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59653. };
  59654. class ColourSpaceMarker : public Component
  59655. {
  59656. public:
  59657. ColourSpaceMarker()
  59658. {
  59659. setInterceptsMouseClicks (false, false);
  59660. }
  59661. void paint (Graphics& g)
  59662. {
  59663. g.setColour (Colour::greyLevel (0.1f));
  59664. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59665. g.setColour (Colour::greyLevel (0.9f));
  59666. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59667. }
  59668. private:
  59669. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59670. };
  59671. class ColourSelector::ColourSpaceView : public Component
  59672. {
  59673. public:
  59674. ColourSpaceView (ColourSelector& owner_,
  59675. float& h_, float& s_, float& v_,
  59676. const int edgeSize)
  59677. : owner (owner_),
  59678. h (h_), s (s_), v (v_),
  59679. lastHue (0.0f),
  59680. edge (edgeSize)
  59681. {
  59682. addAndMakeVisible (&marker);
  59683. setMouseCursor (MouseCursor::CrosshairCursor);
  59684. }
  59685. void paint (Graphics& g)
  59686. {
  59687. if (colours.isNull())
  59688. {
  59689. const int width = getWidth() / 2;
  59690. const int height = getHeight() / 2;
  59691. colours = Image (Image::RGB, width, height, false);
  59692. Image::BitmapData pixels (colours, true);
  59693. for (int y = 0; y < height; ++y)
  59694. {
  59695. const float val = 1.0f - y / (float) height;
  59696. for (int x = 0; x < width; ++x)
  59697. {
  59698. const float sat = x / (float) width;
  59699. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59700. }
  59701. }
  59702. }
  59703. g.setOpacity (1.0f);
  59704. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59705. 0, 0, colours.getWidth(), colours.getHeight());
  59706. }
  59707. void mouseDown (const MouseEvent& e)
  59708. {
  59709. mouseDrag (e);
  59710. }
  59711. void mouseDrag (const MouseEvent& e)
  59712. {
  59713. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59714. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59715. owner.setSV (sat, val);
  59716. }
  59717. void updateIfNeeded()
  59718. {
  59719. if (lastHue != h)
  59720. {
  59721. lastHue = h;
  59722. colours = Image::null;
  59723. repaint();
  59724. }
  59725. updateMarker();
  59726. }
  59727. void resized()
  59728. {
  59729. colours = Image::null;
  59730. updateMarker();
  59731. }
  59732. private:
  59733. ColourSelector& owner;
  59734. float& h;
  59735. float& s;
  59736. float& v;
  59737. float lastHue;
  59738. ColourSpaceMarker marker;
  59739. const int edge;
  59740. Image colours;
  59741. void updateMarker()
  59742. {
  59743. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59744. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59745. edge * 2, edge * 2);
  59746. }
  59747. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59748. };
  59749. class HueSelectorMarker : public Component
  59750. {
  59751. public:
  59752. HueSelectorMarker()
  59753. {
  59754. setInterceptsMouseClicks (false, false);
  59755. }
  59756. void paint (Graphics& g)
  59757. {
  59758. Path p;
  59759. p.addTriangle (1.0f, 1.0f,
  59760. getWidth() * 0.3f, getHeight() * 0.5f,
  59761. 1.0f, getHeight() - 1.0f);
  59762. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59763. getWidth() * 0.7f, getHeight() * 0.5f,
  59764. getWidth() - 1.0f, getHeight() - 1.0f);
  59765. g.setColour (Colours::white.withAlpha (0.75f));
  59766. g.fillPath (p);
  59767. g.setColour (Colours::black.withAlpha (0.75f));
  59768. g.strokePath (p, PathStrokeType (1.2f));
  59769. }
  59770. private:
  59771. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59772. };
  59773. class ColourSelector::HueSelectorComp : public Component
  59774. {
  59775. public:
  59776. HueSelectorComp (ColourSelector& owner_,
  59777. float& h_, float& s_, float& v_,
  59778. const int edgeSize)
  59779. : owner (owner_),
  59780. h (h_), s (s_), v (v_),
  59781. lastHue (0.0f),
  59782. edge (edgeSize)
  59783. {
  59784. addAndMakeVisible (&marker);
  59785. }
  59786. void paint (Graphics& g)
  59787. {
  59788. const float yScale = 1.0f / (getHeight() - edge * 2);
  59789. const Rectangle<int> clip (g.getClipBounds());
  59790. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59791. {
  59792. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59793. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59794. }
  59795. }
  59796. void resized()
  59797. {
  59798. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59799. getWidth(), edge * 2);
  59800. }
  59801. void mouseDown (const MouseEvent& e)
  59802. {
  59803. mouseDrag (e);
  59804. }
  59805. void mouseDrag (const MouseEvent& e)
  59806. {
  59807. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59808. }
  59809. void updateIfNeeded()
  59810. {
  59811. resized();
  59812. }
  59813. private:
  59814. ColourSelector& owner;
  59815. float& h;
  59816. float& s;
  59817. float& v;
  59818. float lastHue;
  59819. HueSelectorMarker marker;
  59820. const int edge;
  59821. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59822. };
  59823. class ColourSelector::SwatchComponent : public Component
  59824. {
  59825. public:
  59826. SwatchComponent (ColourSelector& owner_, int index_)
  59827. : owner (owner_), index (index_)
  59828. {
  59829. }
  59830. void paint (Graphics& g)
  59831. {
  59832. const Colour colour (owner.getSwatchColour (index));
  59833. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59834. Colour (0xffdddddd).overlaidWith (colour),
  59835. Colour (0xffffffff).overlaidWith (colour));
  59836. }
  59837. void mouseDown (const MouseEvent&)
  59838. {
  59839. PopupMenu m;
  59840. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59841. m.addSeparator();
  59842. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59843. const int r = m.showAt (this);
  59844. if (r == 1)
  59845. {
  59846. owner.setCurrentColour (owner.getSwatchColour (index));
  59847. }
  59848. else if (r == 2)
  59849. {
  59850. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59851. {
  59852. owner.setSwatchColour (index, owner.getCurrentColour());
  59853. repaint();
  59854. }
  59855. }
  59856. }
  59857. private:
  59858. ColourSelector& owner;
  59859. const int index;
  59860. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59861. };
  59862. ColourSelector::ColourSelector (const int flags_,
  59863. const int edgeGap_,
  59864. const int gapAroundColourSpaceComponent)
  59865. : colour (Colours::white),
  59866. flags (flags_),
  59867. edgeGap (edgeGap_)
  59868. {
  59869. // not much point having a selector with no components in it!
  59870. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59871. updateHSV();
  59872. if ((flags & showSliders) != 0)
  59873. {
  59874. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59875. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59876. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59877. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59878. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59879. for (int i = 4; --i >= 0;)
  59880. sliders[i]->addListener (this);
  59881. }
  59882. if ((flags & showColourspace) != 0)
  59883. {
  59884. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59885. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59886. }
  59887. update();
  59888. }
  59889. ColourSelector::~ColourSelector()
  59890. {
  59891. dispatchPendingMessages();
  59892. swatchComponents.clear();
  59893. }
  59894. const Colour ColourSelector::getCurrentColour() const
  59895. {
  59896. return ((flags & showAlphaChannel) != 0) ? colour
  59897. : colour.withAlpha ((uint8) 0xff);
  59898. }
  59899. void ColourSelector::setCurrentColour (const Colour& c)
  59900. {
  59901. if (c != colour)
  59902. {
  59903. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59904. updateHSV();
  59905. update();
  59906. }
  59907. }
  59908. void ColourSelector::setHue (float newH)
  59909. {
  59910. newH = jlimit (0.0f, 1.0f, newH);
  59911. if (h != newH)
  59912. {
  59913. h = newH;
  59914. colour = Colour (h, s, v, colour.getFloatAlpha());
  59915. update();
  59916. }
  59917. }
  59918. void ColourSelector::setSV (float newS, float newV)
  59919. {
  59920. newS = jlimit (0.0f, 1.0f, newS);
  59921. newV = jlimit (0.0f, 1.0f, newV);
  59922. if (s != newS || v != newV)
  59923. {
  59924. s = newS;
  59925. v = newV;
  59926. colour = Colour (h, s, v, colour.getFloatAlpha());
  59927. update();
  59928. }
  59929. }
  59930. void ColourSelector::updateHSV()
  59931. {
  59932. colour.getHSB (h, s, v);
  59933. }
  59934. void ColourSelector::update()
  59935. {
  59936. if (sliders[0] != 0)
  59937. {
  59938. sliders[0]->setValue ((int) colour.getRed());
  59939. sliders[1]->setValue ((int) colour.getGreen());
  59940. sliders[2]->setValue ((int) colour.getBlue());
  59941. sliders[3]->setValue ((int) colour.getAlpha());
  59942. }
  59943. if (colourSpace != 0)
  59944. {
  59945. colourSpace->updateIfNeeded();
  59946. hueSelector->updateIfNeeded();
  59947. }
  59948. if ((flags & showColourAtTop) != 0)
  59949. repaint (previewArea);
  59950. sendChangeMessage();
  59951. }
  59952. void ColourSelector::paint (Graphics& g)
  59953. {
  59954. g.fillAll (findColour (backgroundColourId));
  59955. if ((flags & showColourAtTop) != 0)
  59956. {
  59957. const Colour currentColour (getCurrentColour());
  59958. g.fillCheckerBoard (previewArea, 10, 10,
  59959. Colour (0xffdddddd).overlaidWith (currentColour),
  59960. Colour (0xffffffff).overlaidWith (currentColour));
  59961. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59962. g.setFont (14.0f, true);
  59963. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59964. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59965. Justification::centred, false);
  59966. }
  59967. if ((flags & showSliders) != 0)
  59968. {
  59969. g.setColour (findColour (labelTextColourId));
  59970. g.setFont (11.0f);
  59971. for (int i = 4; --i >= 0;)
  59972. {
  59973. if (sliders[i]->isVisible())
  59974. g.drawText (sliders[i]->getName() + ":",
  59975. 0, sliders[i]->getY(),
  59976. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59977. Justification::centredRight, false);
  59978. }
  59979. }
  59980. }
  59981. void ColourSelector::resized()
  59982. {
  59983. const int swatchesPerRow = 8;
  59984. const int swatchHeight = 22;
  59985. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59986. const int numSwatches = getNumSwatches();
  59987. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59988. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59989. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59990. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59991. int y = topSpace;
  59992. if ((flags & showColourspace) != 0)
  59993. {
  59994. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59995. colourSpace->setBounds (edgeGap, y,
  59996. getWidth() - hueWidth - edgeGap - 4,
  59997. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59998. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59999. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60000. colourSpace->getHeight());
  60001. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60002. }
  60003. if ((flags & showSliders) != 0)
  60004. {
  60005. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60006. for (int i = 0; i < numSliders; ++i)
  60007. {
  60008. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60009. proportionOfWidth (0.72f), sliderHeight - 2);
  60010. y += sliderHeight;
  60011. }
  60012. }
  60013. if (numSwatches > 0)
  60014. {
  60015. const int startX = 8;
  60016. const int xGap = 4;
  60017. const int yGap = 4;
  60018. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60019. y += edgeGap;
  60020. if (swatchComponents.size() != numSwatches)
  60021. {
  60022. swatchComponents.clear();
  60023. for (int i = 0; i < numSwatches; ++i)
  60024. {
  60025. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60026. swatchComponents.add (sc);
  60027. addAndMakeVisible (sc);
  60028. }
  60029. }
  60030. int x = startX;
  60031. for (int i = 0; i < swatchComponents.size(); ++i)
  60032. {
  60033. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60034. sc->setBounds (x + xGap / 2,
  60035. y + yGap / 2,
  60036. swatchWidth - xGap,
  60037. swatchHeight - yGap);
  60038. if (((i + 1) % swatchesPerRow) == 0)
  60039. {
  60040. x = startX;
  60041. y += swatchHeight;
  60042. }
  60043. else
  60044. {
  60045. x += swatchWidth;
  60046. }
  60047. }
  60048. }
  60049. }
  60050. void ColourSelector::sliderValueChanged (Slider*)
  60051. {
  60052. if (sliders[0] != 0)
  60053. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60054. (uint8) sliders[1]->getValue(),
  60055. (uint8) sliders[2]->getValue(),
  60056. (uint8) sliders[3]->getValue()));
  60057. }
  60058. int ColourSelector::getNumSwatches() const
  60059. {
  60060. return 0;
  60061. }
  60062. const Colour ColourSelector::getSwatchColour (const int) const
  60063. {
  60064. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60065. return Colours::black;
  60066. }
  60067. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60068. {
  60069. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60070. }
  60071. END_JUCE_NAMESPACE
  60072. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60073. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60074. BEGIN_JUCE_NAMESPACE
  60075. class ShadowWindow : public Component
  60076. {
  60077. Component* owner;
  60078. Image shadowImageSections [12];
  60079. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60080. public:
  60081. ShadowWindow (Component* const owner_,
  60082. const int type_,
  60083. const Image shadowImageSections_ [12])
  60084. : owner (owner_),
  60085. type (type_)
  60086. {
  60087. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60088. shadowImageSections [i] = shadowImageSections_ [i];
  60089. setInterceptsMouseClicks (false, false);
  60090. if (owner_->isOnDesktop())
  60091. {
  60092. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60093. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60094. | ComponentPeer::windowIsTemporary
  60095. | ComponentPeer::windowIgnoresKeyPresses);
  60096. }
  60097. else if (owner_->getParentComponent() != 0)
  60098. {
  60099. owner_->getParentComponent()->addChildComponent (this);
  60100. }
  60101. }
  60102. ~ShadowWindow()
  60103. {
  60104. }
  60105. void paint (Graphics& g)
  60106. {
  60107. const Image& topLeft = shadowImageSections [type * 3];
  60108. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60109. const Image& filler = shadowImageSections [type * 3 + 2];
  60110. g.setOpacity (1.0f);
  60111. if (type < 2)
  60112. {
  60113. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60114. g.drawImage (topLeft,
  60115. 0, 0, topLeft.getWidth(), imH,
  60116. 0, 0, topLeft.getWidth(), imH);
  60117. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60118. g.drawImage (bottomRight,
  60119. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60120. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60121. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60122. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60123. }
  60124. else
  60125. {
  60126. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60127. g.drawImage (topLeft,
  60128. 0, 0, imW, topLeft.getHeight(),
  60129. 0, 0, imW, topLeft.getHeight());
  60130. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60131. g.drawImage (bottomRight,
  60132. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60133. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60134. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60135. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60136. }
  60137. }
  60138. void resized()
  60139. {
  60140. repaint(); // (needed for correct repainting)
  60141. }
  60142. private:
  60143. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60144. };
  60145. DropShadower::DropShadower (const float alpha_,
  60146. const int xOffset_,
  60147. const int yOffset_,
  60148. const float blurRadius_)
  60149. : owner (0),
  60150. numShadows (0),
  60151. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60152. xOffset (xOffset_),
  60153. yOffset (yOffset_),
  60154. alpha (alpha_),
  60155. blurRadius (blurRadius_),
  60156. inDestructor (false),
  60157. reentrant (false)
  60158. {
  60159. }
  60160. DropShadower::~DropShadower()
  60161. {
  60162. if (owner != 0)
  60163. owner->removeComponentListener (this);
  60164. inDestructor = true;
  60165. deleteShadowWindows();
  60166. }
  60167. void DropShadower::deleteShadowWindows()
  60168. {
  60169. if (numShadows > 0)
  60170. {
  60171. int i;
  60172. for (i = numShadows; --i >= 0;)
  60173. delete shadowWindows[i];
  60174. numShadows = 0;
  60175. }
  60176. }
  60177. void DropShadower::setOwner (Component* componentToFollow)
  60178. {
  60179. if (componentToFollow != owner)
  60180. {
  60181. if (owner != 0)
  60182. owner->removeComponentListener (this);
  60183. // (the component can't be null)
  60184. jassert (componentToFollow != 0);
  60185. owner = componentToFollow;
  60186. jassert (owner != 0);
  60187. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60188. owner->addComponentListener (this);
  60189. updateShadows();
  60190. }
  60191. }
  60192. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60193. {
  60194. updateShadows();
  60195. }
  60196. void DropShadower::componentBroughtToFront (Component&)
  60197. {
  60198. bringShadowWindowsToFront();
  60199. }
  60200. void DropShadower::componentChildrenChanged (Component&)
  60201. {
  60202. }
  60203. void DropShadower::componentParentHierarchyChanged (Component&)
  60204. {
  60205. deleteShadowWindows();
  60206. updateShadows();
  60207. }
  60208. void DropShadower::componentVisibilityChanged (Component&)
  60209. {
  60210. updateShadows();
  60211. }
  60212. void DropShadower::updateShadows()
  60213. {
  60214. if (reentrant || inDestructor || (owner == 0))
  60215. return;
  60216. reentrant = true;
  60217. ComponentPeer* const nw = owner->getPeer();
  60218. const bool isOwnerVisible = owner->isVisible()
  60219. && (nw == 0 || ! nw->isMinimised());
  60220. const bool createShadowWindows = numShadows == 0
  60221. && owner->getWidth() > 0
  60222. && owner->getHeight() > 0
  60223. && isOwnerVisible
  60224. && (Desktop::canUseSemiTransparentWindows()
  60225. || owner->getParentComponent() != 0);
  60226. if (createShadowWindows)
  60227. {
  60228. // keep a cached version of the image to save doing the gaussian too often
  60229. String imageId;
  60230. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60231. const int hash = imageId.hashCode();
  60232. Image bigIm (ImageCache::getFromHashCode (hash));
  60233. if (bigIm.isNull())
  60234. {
  60235. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60236. Graphics bigG (bigIm);
  60237. bigG.setColour (Colours::black.withAlpha (alpha));
  60238. bigG.fillRect (shadowEdge + xOffset,
  60239. shadowEdge + yOffset,
  60240. bigIm.getWidth() - (shadowEdge * 2),
  60241. bigIm.getHeight() - (shadowEdge * 2));
  60242. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60243. blurKernel.createGaussianBlur (blurRadius);
  60244. blurKernel.applyToImage (bigIm, bigIm,
  60245. Rectangle<int> (xOffset, yOffset,
  60246. bigIm.getWidth(), bigIm.getHeight()));
  60247. ImageCache::addImageToCache (bigIm, hash);
  60248. }
  60249. const int iw = bigIm.getWidth();
  60250. const int ih = bigIm.getHeight();
  60251. const int shadowEdge2 = shadowEdge * 2;
  60252. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60253. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60254. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60255. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60256. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60257. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60258. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60259. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60260. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60261. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60262. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60263. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60264. for (int i = 0; i < 4; ++i)
  60265. {
  60266. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60267. ++numShadows;
  60268. }
  60269. }
  60270. if (numShadows > 0)
  60271. {
  60272. for (int i = numShadows; --i >= 0;)
  60273. {
  60274. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60275. shadowWindows[i]->setVisible (isOwnerVisible);
  60276. }
  60277. const int x = owner->getX();
  60278. const int y = owner->getY() - shadowEdge;
  60279. const int w = owner->getWidth();
  60280. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60281. shadowWindows[0]->setBounds (x - shadowEdge,
  60282. y,
  60283. shadowEdge,
  60284. h);
  60285. shadowWindows[1]->setBounds (x + w,
  60286. y,
  60287. shadowEdge,
  60288. h);
  60289. shadowWindows[2]->setBounds (x,
  60290. y,
  60291. w,
  60292. shadowEdge);
  60293. shadowWindows[3]->setBounds (x,
  60294. owner->getBottom(),
  60295. w,
  60296. shadowEdge);
  60297. }
  60298. reentrant = false;
  60299. if (createShadowWindows)
  60300. bringShadowWindowsToFront();
  60301. }
  60302. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60303. const int sx, const int sy)
  60304. {
  60305. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60306. Graphics g (shadowImageSections[num]);
  60307. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60308. }
  60309. void DropShadower::bringShadowWindowsToFront()
  60310. {
  60311. if (! (inDestructor || reentrant))
  60312. {
  60313. updateShadows();
  60314. reentrant = true;
  60315. for (int i = numShadows; --i >= 0;)
  60316. shadowWindows[i]->toBehind (owner);
  60317. reentrant = false;
  60318. }
  60319. }
  60320. END_JUCE_NAMESPACE
  60321. /*** End of inlined file: juce_DropShadower.cpp ***/
  60322. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60323. BEGIN_JUCE_NAMESPACE
  60324. class MagnifyingPeer : public ComponentPeer
  60325. {
  60326. public:
  60327. MagnifyingPeer (Component* const component_,
  60328. MagnifierComponent* const magnifierComp_)
  60329. : ComponentPeer (component_, 0),
  60330. magnifierComp (magnifierComp_)
  60331. {
  60332. }
  60333. ~MagnifyingPeer()
  60334. {
  60335. }
  60336. void* getNativeHandle() const { return 0; }
  60337. void setVisible (bool) {}
  60338. void setTitle (const String&) {}
  60339. void setPosition (int, int) {}
  60340. void setSize (int, int) {}
  60341. void setBounds (int, int, int, int, bool) {}
  60342. void setMinimised (bool) {}
  60343. void setAlpha (float /*newAlpha*/) {}
  60344. bool isMinimised() const { return false; }
  60345. void setFullScreen (bool) {}
  60346. bool isFullScreen() const { return false; }
  60347. const BorderSize getFrameSize() const { return BorderSize (0); }
  60348. bool setAlwaysOnTop (bool) { return true; }
  60349. void toFront (bool) {}
  60350. void toBehind (ComponentPeer*) {}
  60351. void setIcon (const Image&) {}
  60352. bool isFocused() const
  60353. {
  60354. return magnifierComp->hasKeyboardFocus (true);
  60355. }
  60356. void grabFocus()
  60357. {
  60358. ComponentPeer* peer = magnifierComp->getPeer();
  60359. if (peer != 0)
  60360. peer->grabFocus();
  60361. }
  60362. void textInputRequired (const Point<int>& position)
  60363. {
  60364. ComponentPeer* peer = magnifierComp->getPeer();
  60365. if (peer != 0)
  60366. peer->textInputRequired (position);
  60367. }
  60368. const Rectangle<int> getBounds() const
  60369. {
  60370. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60371. component->getWidth(), component->getHeight());
  60372. }
  60373. const Point<int> getScreenPosition() const
  60374. {
  60375. return magnifierComp->getScreenPosition();
  60376. }
  60377. const Point<int> localToGlobal (const Point<int>& relativePosition)
  60378. {
  60379. const double zoom = magnifierComp->getScaleFactor();
  60380. return magnifierComp->localPointToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60381. roundToInt (relativePosition.getY() * zoom)));
  60382. }
  60383. const Point<int> globalToLocal (const Point<int>& screenPosition)
  60384. {
  60385. const Point<int> p (magnifierComp->getLocalPoint (0, screenPosition));
  60386. const double zoom = magnifierComp->getScaleFactor();
  60387. return Point<int> (roundToInt (p.getX() / zoom),
  60388. roundToInt (p.getY() / zoom));
  60389. }
  60390. bool contains (const Point<int>& position, bool) const
  60391. {
  60392. return isPositiveAndBelow (position.getX(), magnifierComp->getWidth())
  60393. && isPositiveAndBelow (position.getY(), magnifierComp->getHeight());
  60394. }
  60395. void repaint (const Rectangle<int>& area)
  60396. {
  60397. const double zoom = magnifierComp->getScaleFactor();
  60398. magnifierComp->repaint ((int) (area.getX() * zoom),
  60399. (int) (area.getY() * zoom),
  60400. roundToInt (area.getWidth() * zoom) + 1,
  60401. roundToInt (area.getHeight() * zoom) + 1);
  60402. }
  60403. void performAnyPendingRepaintsNow()
  60404. {
  60405. }
  60406. private:
  60407. MagnifierComponent* const magnifierComp;
  60408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MagnifyingPeer);
  60409. };
  60410. class PeerHolderComp : public Component
  60411. {
  60412. public:
  60413. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60414. : magnifierComp (magnifierComp_)
  60415. {
  60416. setVisible (true);
  60417. }
  60418. ~PeerHolderComp()
  60419. {
  60420. }
  60421. ComponentPeer* createNewPeer (int, void*)
  60422. {
  60423. return new MagnifyingPeer (this, magnifierComp);
  60424. }
  60425. void childBoundsChanged (Component* c)
  60426. {
  60427. if (c != 0)
  60428. {
  60429. setSize (c->getWidth(), c->getHeight());
  60430. magnifierComp->childBoundsChanged (this);
  60431. }
  60432. }
  60433. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60434. {
  60435. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60436. Component* const p = magnifierComp->getParentComponent();
  60437. if (p != 0)
  60438. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60439. }
  60440. private:
  60441. MagnifierComponent* const magnifierComp;
  60442. JUCE_DECLARE_NON_COPYABLE (PeerHolderComp);
  60443. };
  60444. MagnifierComponent::MagnifierComponent (Component* const content_,
  60445. const bool deleteContentCompWhenNoLongerNeeded)
  60446. : content (content_),
  60447. scaleFactor (0.0),
  60448. peer (0),
  60449. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60450. quality (Graphics::lowResamplingQuality),
  60451. mouseSource (0, true)
  60452. {
  60453. holderComp = new PeerHolderComp (this);
  60454. setScaleFactor (1.0);
  60455. }
  60456. MagnifierComponent::~MagnifierComponent()
  60457. {
  60458. delete holderComp;
  60459. if (deleteContent)
  60460. delete content;
  60461. }
  60462. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60463. {
  60464. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60465. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60466. if (scaleFactor != newScaleFactor)
  60467. {
  60468. scaleFactor = newScaleFactor;
  60469. if (scaleFactor == 1.0)
  60470. {
  60471. holderComp->removeFromDesktop();
  60472. peer = 0;
  60473. addChildComponent (content);
  60474. childBoundsChanged (content);
  60475. }
  60476. else
  60477. {
  60478. holderComp->addAndMakeVisible (content);
  60479. holderComp->childBoundsChanged (content);
  60480. childBoundsChanged (holderComp);
  60481. holderComp->addToDesktop (0);
  60482. peer = holderComp->getPeer();
  60483. }
  60484. repaint();
  60485. }
  60486. }
  60487. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60488. {
  60489. quality = newQuality;
  60490. }
  60491. void MagnifierComponent::paint (Graphics& g)
  60492. {
  60493. const int w = holderComp->getWidth();
  60494. const int h = holderComp->getHeight();
  60495. if (w == 0 || h == 0)
  60496. return;
  60497. const Rectangle<int> r (g.getClipBounds());
  60498. const int srcX = (int) (r.getX() / scaleFactor);
  60499. const int srcY = (int) (r.getY() / scaleFactor);
  60500. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60501. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60502. if (scaleFactor >= 1.0)
  60503. {
  60504. ++srcW;
  60505. ++srcH;
  60506. }
  60507. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60508. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60509. temp.clear (area);
  60510. {
  60511. Graphics g2 (temp);
  60512. g2.reduceClipRegion (area);
  60513. holderComp->paintEntireComponent (g2, false);
  60514. }
  60515. g.setImageResamplingQuality (quality);
  60516. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60517. }
  60518. void MagnifierComponent::childBoundsChanged (Component* c)
  60519. {
  60520. if (c != 0)
  60521. setSize (roundToInt (c->getWidth() * scaleFactor),
  60522. roundToInt (c->getHeight() * scaleFactor));
  60523. }
  60524. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60525. {
  60526. if (peer != 0)
  60527. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60528. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60529. }
  60530. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60531. {
  60532. passOnMouseEventToPeer (e);
  60533. }
  60534. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60535. {
  60536. passOnMouseEventToPeer (e);
  60537. }
  60538. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60539. {
  60540. passOnMouseEventToPeer (e);
  60541. }
  60542. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60543. {
  60544. passOnMouseEventToPeer (e);
  60545. }
  60546. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60547. {
  60548. passOnMouseEventToPeer (e);
  60549. }
  60550. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60551. {
  60552. passOnMouseEventToPeer (e);
  60553. }
  60554. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60555. {
  60556. if (peer != 0)
  60557. peer->handleMouseWheel (e.source.getIndex(),
  60558. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60559. ix * 256.0f, iy * 256.0f);
  60560. else
  60561. Component::mouseWheelMove (e, ix, iy);
  60562. }
  60563. int MagnifierComponent::scaleInt (const int n) const
  60564. {
  60565. return roundToInt (n / scaleFactor);
  60566. }
  60567. END_JUCE_NAMESPACE
  60568. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60569. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60570. BEGIN_JUCE_NAMESPACE
  60571. class MidiKeyboardUpDownButton : public Button
  60572. {
  60573. public:
  60574. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60575. : Button (String::empty),
  60576. owner (owner_),
  60577. delta (delta_)
  60578. {
  60579. setOpaque (true);
  60580. }
  60581. void clicked()
  60582. {
  60583. int note = owner.getLowestVisibleKey();
  60584. if (delta < 0)
  60585. note = (note - 1) / 12;
  60586. else
  60587. note = note / 12 + 1;
  60588. owner.setLowestVisibleKey (note * 12);
  60589. }
  60590. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60591. {
  60592. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60593. isMouseOverButton, isButtonDown,
  60594. delta > 0);
  60595. }
  60596. private:
  60597. MidiKeyboardComponent& owner;
  60598. const int delta;
  60599. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60600. };
  60601. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60602. const Orientation orientation_)
  60603. : state (state_),
  60604. xOffset (0),
  60605. blackNoteLength (1),
  60606. keyWidth (16.0f),
  60607. orientation (orientation_),
  60608. midiChannel (1),
  60609. midiInChannelMask (0xffff),
  60610. velocity (1.0f),
  60611. noteUnderMouse (-1),
  60612. mouseDownNote (-1),
  60613. rangeStart (0),
  60614. rangeEnd (127),
  60615. firstKey (12 * 4),
  60616. canScroll (true),
  60617. mouseDragging (false),
  60618. useMousePositionForVelocity (true),
  60619. keyMappingOctave (6),
  60620. octaveNumForMiddleC (3)
  60621. {
  60622. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60623. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60624. // initialise with a default set of querty key-mappings..
  60625. const char* const keymap = "awsedftgyhujkolp;";
  60626. for (int i = String (keymap).length(); --i >= 0;)
  60627. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60628. setOpaque (true);
  60629. setWantsKeyboardFocus (true);
  60630. state.addListener (this);
  60631. }
  60632. MidiKeyboardComponent::~MidiKeyboardComponent()
  60633. {
  60634. state.removeListener (this);
  60635. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60636. }
  60637. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60638. {
  60639. keyWidth = widthInPixels;
  60640. resized();
  60641. }
  60642. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60643. {
  60644. if (orientation != newOrientation)
  60645. {
  60646. orientation = newOrientation;
  60647. resized();
  60648. }
  60649. }
  60650. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60651. const int highestNote)
  60652. {
  60653. jassert (lowestNote >= 0 && lowestNote <= 127);
  60654. jassert (highestNote >= 0 && highestNote <= 127);
  60655. jassert (lowestNote <= highestNote);
  60656. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60657. {
  60658. rangeStart = jlimit (0, 127, lowestNote);
  60659. rangeEnd = jlimit (0, 127, highestNote);
  60660. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60661. resized();
  60662. }
  60663. }
  60664. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60665. {
  60666. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60667. if (noteNumber != firstKey)
  60668. {
  60669. firstKey = noteNumber;
  60670. sendChangeMessage();
  60671. resized();
  60672. }
  60673. }
  60674. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60675. {
  60676. if (canScroll != canScroll_)
  60677. {
  60678. canScroll = canScroll_;
  60679. resized();
  60680. }
  60681. }
  60682. void MidiKeyboardComponent::colourChanged()
  60683. {
  60684. repaint();
  60685. }
  60686. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60687. {
  60688. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60689. if (midiChannel != midiChannelNumber)
  60690. {
  60691. resetAnyKeysInUse();
  60692. midiChannel = jlimit (1, 16, midiChannelNumber);
  60693. }
  60694. }
  60695. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60696. {
  60697. midiInChannelMask = midiChannelMask;
  60698. triggerAsyncUpdate();
  60699. }
  60700. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60701. {
  60702. velocity = jlimit (0.0f, 1.0f, velocity_);
  60703. useMousePositionForVelocity = useMousePositionForVelocity_;
  60704. }
  60705. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60706. {
  60707. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60708. static const float blackNoteWidth = 0.7f;
  60709. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60710. 1.0f, 2 - blackNoteWidth * 0.4f,
  60711. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60712. 4.0f, 5 - blackNoteWidth * 0.5f,
  60713. 5.0f, 6 - blackNoteWidth * 0.3f,
  60714. 6.0f };
  60715. static const float widths[] = { 1.0f, blackNoteWidth,
  60716. 1.0f, blackNoteWidth,
  60717. 1.0f, 1.0f, blackNoteWidth,
  60718. 1.0f, blackNoteWidth,
  60719. 1.0f, blackNoteWidth,
  60720. 1.0f };
  60721. const int octave = midiNoteNumber / 12;
  60722. const int note = midiNoteNumber % 12;
  60723. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60724. w = roundToInt (widths [note] * keyWidth_);
  60725. }
  60726. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60727. {
  60728. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60729. int rx, rw;
  60730. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60731. x -= xOffset + rx;
  60732. }
  60733. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60734. {
  60735. int x, y;
  60736. getKeyPos (midiNoteNumber, x, y);
  60737. return x;
  60738. }
  60739. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60740. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60741. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60742. {
  60743. if (! reallyContains (pos, false))
  60744. return -1;
  60745. Point<int> p (pos);
  60746. if (orientation != horizontalKeyboard)
  60747. {
  60748. p = Point<int> (p.getY(), p.getX());
  60749. if (orientation == verticalKeyboardFacingLeft)
  60750. p = Point<int> (p.getX(), getWidth() - p.getY());
  60751. else
  60752. p = Point<int> (getHeight() - p.getX(), p.getY());
  60753. }
  60754. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60755. }
  60756. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60757. {
  60758. if (pos.getY() < blackNoteLength)
  60759. {
  60760. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60761. {
  60762. for (int i = 0; i < 5; ++i)
  60763. {
  60764. const int note = octaveStart + blackNotes [i];
  60765. if (note >= rangeStart && note <= rangeEnd)
  60766. {
  60767. int kx, kw;
  60768. getKeyPos (note, kx, kw);
  60769. kx += xOffset;
  60770. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60771. {
  60772. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60773. return note;
  60774. }
  60775. }
  60776. }
  60777. }
  60778. }
  60779. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60780. {
  60781. for (int i = 0; i < 7; ++i)
  60782. {
  60783. const int note = octaveStart + whiteNotes [i];
  60784. if (note >= rangeStart && note <= rangeEnd)
  60785. {
  60786. int kx, kw;
  60787. getKeyPos (note, kx, kw);
  60788. kx += xOffset;
  60789. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60790. {
  60791. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60792. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60793. return note;
  60794. }
  60795. }
  60796. }
  60797. }
  60798. mousePositionVelocity = 0;
  60799. return -1;
  60800. }
  60801. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60802. {
  60803. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60804. {
  60805. int x, w;
  60806. getKeyPos (noteNum, x, w);
  60807. if (orientation == horizontalKeyboard)
  60808. repaint (x, 0, w, getHeight());
  60809. else if (orientation == verticalKeyboardFacingLeft)
  60810. repaint (0, x, getWidth(), w);
  60811. else if (orientation == verticalKeyboardFacingRight)
  60812. repaint (0, getHeight() - x - w, getWidth(), w);
  60813. }
  60814. }
  60815. void MidiKeyboardComponent::paint (Graphics& g)
  60816. {
  60817. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60818. const Colour lineColour (findColour (keySeparatorLineColourId));
  60819. const Colour textColour (findColour (textLabelColourId));
  60820. int x, w, octave;
  60821. for (octave = 0; octave < 128; octave += 12)
  60822. {
  60823. for (int white = 0; white < 7; ++white)
  60824. {
  60825. const int noteNum = octave + whiteNotes [white];
  60826. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60827. {
  60828. getKeyPos (noteNum, x, w);
  60829. if (orientation == horizontalKeyboard)
  60830. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60831. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60832. noteUnderMouse == noteNum,
  60833. lineColour, textColour);
  60834. else if (orientation == verticalKeyboardFacingLeft)
  60835. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60836. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60837. noteUnderMouse == noteNum,
  60838. lineColour, textColour);
  60839. else if (orientation == verticalKeyboardFacingRight)
  60840. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60841. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60842. noteUnderMouse == noteNum,
  60843. lineColour, textColour);
  60844. }
  60845. }
  60846. }
  60847. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60848. if (orientation == verticalKeyboardFacingLeft)
  60849. {
  60850. x1 = getWidth() - 1.0f;
  60851. x2 = getWidth() - 5.0f;
  60852. }
  60853. else if (orientation == verticalKeyboardFacingRight)
  60854. x2 = 5.0f;
  60855. else
  60856. y2 = 5.0f;
  60857. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60858. Colours::transparentBlack, x2, y2, false));
  60859. getKeyPos (rangeEnd, x, w);
  60860. x += w;
  60861. if (orientation == verticalKeyboardFacingLeft)
  60862. g.fillRect (getWidth() - 5, 0, 5, x);
  60863. else if (orientation == verticalKeyboardFacingRight)
  60864. g.fillRect (0, 0, 5, x);
  60865. else
  60866. g.fillRect (0, 0, x, 5);
  60867. g.setColour (lineColour);
  60868. if (orientation == verticalKeyboardFacingLeft)
  60869. g.fillRect (0, 0, 1, x);
  60870. else if (orientation == verticalKeyboardFacingRight)
  60871. g.fillRect (getWidth() - 1, 0, 1, x);
  60872. else
  60873. g.fillRect (0, getHeight() - 1, x, 1);
  60874. const Colour blackNoteColour (findColour (blackNoteColourId));
  60875. for (octave = 0; octave < 128; octave += 12)
  60876. {
  60877. for (int black = 0; black < 5; ++black)
  60878. {
  60879. const int noteNum = octave + blackNotes [black];
  60880. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60881. {
  60882. getKeyPos (noteNum, x, w);
  60883. if (orientation == horizontalKeyboard)
  60884. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60885. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60886. noteUnderMouse == noteNum,
  60887. blackNoteColour);
  60888. else if (orientation == verticalKeyboardFacingLeft)
  60889. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60890. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60891. noteUnderMouse == noteNum,
  60892. blackNoteColour);
  60893. else if (orientation == verticalKeyboardFacingRight)
  60894. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60895. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60896. noteUnderMouse == noteNum,
  60897. blackNoteColour);
  60898. }
  60899. }
  60900. }
  60901. }
  60902. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60903. Graphics& g, int x, int y, int w, int h,
  60904. bool isDown, bool isOver,
  60905. const Colour& lineColour,
  60906. const Colour& textColour)
  60907. {
  60908. Colour c (Colours::transparentWhite);
  60909. if (isDown)
  60910. c = findColour (keyDownOverlayColourId);
  60911. if (isOver)
  60912. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60913. g.setColour (c);
  60914. g.fillRect (x, y, w, h);
  60915. const String text (getWhiteNoteText (midiNoteNumber));
  60916. if (! text.isEmpty())
  60917. {
  60918. g.setColour (textColour);
  60919. Font f (jmin (12.0f, keyWidth * 0.9f));
  60920. f.setHorizontalScale (0.8f);
  60921. g.setFont (f);
  60922. Justification justification (Justification::centredBottom);
  60923. if (orientation == verticalKeyboardFacingLeft)
  60924. justification = Justification::centredLeft;
  60925. else if (orientation == verticalKeyboardFacingRight)
  60926. justification = Justification::centredRight;
  60927. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60928. }
  60929. g.setColour (lineColour);
  60930. if (orientation == horizontalKeyboard)
  60931. g.fillRect (x, y, 1, h);
  60932. else if (orientation == verticalKeyboardFacingLeft)
  60933. g.fillRect (x, y, w, 1);
  60934. else if (orientation == verticalKeyboardFacingRight)
  60935. g.fillRect (x, y + h - 1, w, 1);
  60936. if (midiNoteNumber == rangeEnd)
  60937. {
  60938. if (orientation == horizontalKeyboard)
  60939. g.fillRect (x + w, y, 1, h);
  60940. else if (orientation == verticalKeyboardFacingLeft)
  60941. g.fillRect (x, y + h, w, 1);
  60942. else if (orientation == verticalKeyboardFacingRight)
  60943. g.fillRect (x, y - 1, w, 1);
  60944. }
  60945. }
  60946. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60947. Graphics& g, int x, int y, int w, int h,
  60948. bool isDown, bool isOver,
  60949. const Colour& noteFillColour)
  60950. {
  60951. Colour c (noteFillColour);
  60952. if (isDown)
  60953. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60954. if (isOver)
  60955. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60956. g.setColour (c);
  60957. g.fillRect (x, y, w, h);
  60958. if (isDown)
  60959. {
  60960. g.setColour (noteFillColour);
  60961. g.drawRect (x, y, w, h);
  60962. }
  60963. else
  60964. {
  60965. const int xIndent = jmax (1, jmin (w, h) / 8);
  60966. g.setColour (c.brighter());
  60967. if (orientation == horizontalKeyboard)
  60968. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60969. else if (orientation == verticalKeyboardFacingLeft)
  60970. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60971. else if (orientation == verticalKeyboardFacingRight)
  60972. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60973. }
  60974. }
  60975. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60976. {
  60977. octaveNumForMiddleC = octaveNumForMiddleC_;
  60978. repaint();
  60979. }
  60980. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60981. {
  60982. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60983. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60984. return String::empty;
  60985. }
  60986. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60987. const bool isMouseOver_,
  60988. const bool isButtonDown,
  60989. const bool movesOctavesUp)
  60990. {
  60991. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60992. float angle;
  60993. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60994. angle = movesOctavesUp ? 0.0f : 0.5f;
  60995. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60996. angle = movesOctavesUp ? 0.25f : 0.75f;
  60997. else
  60998. angle = movesOctavesUp ? 0.75f : 0.25f;
  60999. Path path;
  61000. path.lineTo (0.0f, 1.0f);
  61001. path.lineTo (1.0f, 0.5f);
  61002. path.closeSubPath();
  61003. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61004. g.setColour (findColour (upDownButtonArrowColourId)
  61005. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61006. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61007. w - 2.0f,
  61008. h - 2.0f,
  61009. true));
  61010. }
  61011. void MidiKeyboardComponent::resized()
  61012. {
  61013. int w = getWidth();
  61014. int h = getHeight();
  61015. if (w > 0 && h > 0)
  61016. {
  61017. if (orientation != horizontalKeyboard)
  61018. swapVariables (w, h);
  61019. blackNoteLength = roundToInt (h * 0.7f);
  61020. int kx2, kw2;
  61021. getKeyPos (rangeEnd, kx2, kw2);
  61022. kx2 += kw2;
  61023. if (firstKey != rangeStart)
  61024. {
  61025. int kx1, kw1;
  61026. getKeyPos (rangeStart, kx1, kw1);
  61027. if (kx2 - kx1 <= w)
  61028. {
  61029. firstKey = rangeStart;
  61030. sendChangeMessage();
  61031. repaint();
  61032. }
  61033. }
  61034. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61035. scrollDown->setVisible (showScrollButtons);
  61036. scrollUp->setVisible (showScrollButtons);
  61037. xOffset = 0;
  61038. if (showScrollButtons)
  61039. {
  61040. const int scrollButtonW = jmin (12, w / 2);
  61041. if (orientation == horizontalKeyboard)
  61042. {
  61043. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61044. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61045. }
  61046. else if (orientation == verticalKeyboardFacingLeft)
  61047. {
  61048. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61049. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61050. }
  61051. else if (orientation == verticalKeyboardFacingRight)
  61052. {
  61053. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61054. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61055. }
  61056. int endOfLastKey, kw;
  61057. getKeyPos (rangeEnd, endOfLastKey, kw);
  61058. endOfLastKey += kw;
  61059. float mousePositionVelocity;
  61060. const int spaceAvailable = w - scrollButtonW * 2;
  61061. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61062. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61063. {
  61064. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61065. sendChangeMessage();
  61066. }
  61067. int newOffset = 0;
  61068. getKeyPos (firstKey, newOffset, kw);
  61069. xOffset = newOffset - scrollButtonW;
  61070. }
  61071. else
  61072. {
  61073. firstKey = rangeStart;
  61074. }
  61075. timerCallback();
  61076. repaint();
  61077. }
  61078. }
  61079. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61080. {
  61081. triggerAsyncUpdate();
  61082. }
  61083. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61084. {
  61085. triggerAsyncUpdate();
  61086. }
  61087. void MidiKeyboardComponent::handleAsyncUpdate()
  61088. {
  61089. for (int i = rangeStart; i <= rangeEnd; ++i)
  61090. {
  61091. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61092. {
  61093. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61094. repaintNote (i);
  61095. }
  61096. }
  61097. }
  61098. void MidiKeyboardComponent::resetAnyKeysInUse()
  61099. {
  61100. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61101. {
  61102. state.allNotesOff (midiChannel);
  61103. keysPressed.clear();
  61104. mouseDownNote = -1;
  61105. }
  61106. }
  61107. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61108. {
  61109. float mousePositionVelocity = 0.0f;
  61110. const int newNote = (mouseDragging || isMouseOver())
  61111. ? xyToNote (pos, mousePositionVelocity) : -1;
  61112. if (noteUnderMouse != newNote)
  61113. {
  61114. if (mouseDownNote >= 0)
  61115. {
  61116. state.noteOff (midiChannel, mouseDownNote);
  61117. mouseDownNote = -1;
  61118. }
  61119. if (mouseDragging && newNote >= 0)
  61120. {
  61121. if (! useMousePositionForVelocity)
  61122. mousePositionVelocity = 1.0f;
  61123. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61124. mouseDownNote = newNote;
  61125. }
  61126. repaintNote (noteUnderMouse);
  61127. noteUnderMouse = newNote;
  61128. repaintNote (noteUnderMouse);
  61129. }
  61130. else if (mouseDownNote >= 0 && ! mouseDragging)
  61131. {
  61132. state.noteOff (midiChannel, mouseDownNote);
  61133. mouseDownNote = -1;
  61134. }
  61135. }
  61136. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61137. {
  61138. updateNoteUnderMouse (e.getPosition());
  61139. stopTimer();
  61140. }
  61141. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61142. {
  61143. float mousePositionVelocity;
  61144. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61145. if (newNote >= 0)
  61146. mouseDraggedToKey (newNote, e);
  61147. updateNoteUnderMouse (e.getPosition());
  61148. }
  61149. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61150. {
  61151. return true;
  61152. }
  61153. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61154. {
  61155. }
  61156. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61157. {
  61158. float mousePositionVelocity;
  61159. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61160. mouseDragging = false;
  61161. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61162. {
  61163. repaintNote (noteUnderMouse);
  61164. noteUnderMouse = -1;
  61165. mouseDragging = true;
  61166. updateNoteUnderMouse (e.getPosition());
  61167. startTimer (500);
  61168. }
  61169. }
  61170. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61171. {
  61172. mouseDragging = false;
  61173. updateNoteUnderMouse (e.getPosition());
  61174. stopTimer();
  61175. }
  61176. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61177. {
  61178. updateNoteUnderMouse (e.getPosition());
  61179. }
  61180. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61181. {
  61182. updateNoteUnderMouse (e.getPosition());
  61183. }
  61184. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61185. {
  61186. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61187. }
  61188. void MidiKeyboardComponent::timerCallback()
  61189. {
  61190. updateNoteUnderMouse (getMouseXYRelative());
  61191. }
  61192. void MidiKeyboardComponent::clearKeyMappings()
  61193. {
  61194. resetAnyKeysInUse();
  61195. keyPressNotes.clear();
  61196. keyPresses.clear();
  61197. }
  61198. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61199. const int midiNoteOffsetFromC)
  61200. {
  61201. removeKeyPressForNote (midiNoteOffsetFromC);
  61202. keyPressNotes.add (midiNoteOffsetFromC);
  61203. keyPresses.add (key);
  61204. }
  61205. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61206. {
  61207. for (int i = keyPressNotes.size(); --i >= 0;)
  61208. {
  61209. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61210. {
  61211. keyPressNotes.remove (i);
  61212. keyPresses.remove (i);
  61213. }
  61214. }
  61215. }
  61216. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61217. {
  61218. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61219. keyMappingOctave = newOctaveNumber;
  61220. }
  61221. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61222. {
  61223. bool keyPressUsed = false;
  61224. for (int i = keyPresses.size(); --i >= 0;)
  61225. {
  61226. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61227. if (keyPresses.getReference(i).isCurrentlyDown())
  61228. {
  61229. if (! keysPressed [note])
  61230. {
  61231. keysPressed.setBit (note);
  61232. state.noteOn (midiChannel, note, velocity);
  61233. keyPressUsed = true;
  61234. }
  61235. }
  61236. else
  61237. {
  61238. if (keysPressed [note])
  61239. {
  61240. keysPressed.clearBit (note);
  61241. state.noteOff (midiChannel, note);
  61242. keyPressUsed = true;
  61243. }
  61244. }
  61245. }
  61246. return keyPressUsed;
  61247. }
  61248. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61249. {
  61250. resetAnyKeysInUse();
  61251. }
  61252. END_JUCE_NAMESPACE
  61253. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61254. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61255. #if JUCE_OPENGL
  61256. BEGIN_JUCE_NAMESPACE
  61257. extern void juce_glViewport (const int w, const int h);
  61258. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61259. const int alphaBits_,
  61260. const int depthBufferBits_,
  61261. const int stencilBufferBits_)
  61262. : redBits (bitsPerRGBComponent),
  61263. greenBits (bitsPerRGBComponent),
  61264. blueBits (bitsPerRGBComponent),
  61265. alphaBits (alphaBits_),
  61266. depthBufferBits (depthBufferBits_),
  61267. stencilBufferBits (stencilBufferBits_),
  61268. accumulationBufferRedBits (0),
  61269. accumulationBufferGreenBits (0),
  61270. accumulationBufferBlueBits (0),
  61271. accumulationBufferAlphaBits (0),
  61272. fullSceneAntiAliasingNumSamples (0)
  61273. {
  61274. }
  61275. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61276. : redBits (other.redBits),
  61277. greenBits (other.greenBits),
  61278. blueBits (other.blueBits),
  61279. alphaBits (other.alphaBits),
  61280. depthBufferBits (other.depthBufferBits),
  61281. stencilBufferBits (other.stencilBufferBits),
  61282. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61283. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61284. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61285. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61286. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61287. {
  61288. }
  61289. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61290. {
  61291. redBits = other.redBits;
  61292. greenBits = other.greenBits;
  61293. blueBits = other.blueBits;
  61294. alphaBits = other.alphaBits;
  61295. depthBufferBits = other.depthBufferBits;
  61296. stencilBufferBits = other.stencilBufferBits;
  61297. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61298. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61299. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61300. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61301. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61302. return *this;
  61303. }
  61304. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61305. {
  61306. return redBits == other.redBits
  61307. && greenBits == other.greenBits
  61308. && blueBits == other.blueBits
  61309. && alphaBits == other.alphaBits
  61310. && depthBufferBits == other.depthBufferBits
  61311. && stencilBufferBits == other.stencilBufferBits
  61312. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61313. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61314. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61315. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61316. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61317. }
  61318. static Array<OpenGLContext*> knownContexts;
  61319. OpenGLContext::OpenGLContext() throw()
  61320. {
  61321. knownContexts.add (this);
  61322. }
  61323. OpenGLContext::~OpenGLContext()
  61324. {
  61325. knownContexts.removeValue (this);
  61326. }
  61327. OpenGLContext* OpenGLContext::getCurrentContext()
  61328. {
  61329. for (int i = knownContexts.size(); --i >= 0;)
  61330. {
  61331. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61332. if (oglc->isActive())
  61333. return oglc;
  61334. }
  61335. return 0;
  61336. }
  61337. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61338. {
  61339. public:
  61340. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61341. : ComponentMovementWatcher (owner_),
  61342. owner (owner_),
  61343. wasShowing (false)
  61344. {
  61345. }
  61346. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61347. {
  61348. owner->updateContextPosition();
  61349. }
  61350. void componentPeerChanged()
  61351. {
  61352. const ScopedLock sl (owner->getContextLock());
  61353. owner->deleteContext();
  61354. }
  61355. void componentVisibilityChanged (Component&)
  61356. {
  61357. const bool isShowingNow = owner->isShowing();
  61358. if (wasShowing != isShowingNow)
  61359. {
  61360. wasShowing = isShowingNow;
  61361. if (! isShowingNow)
  61362. {
  61363. const ScopedLock sl (owner->getContextLock());
  61364. owner->deleteContext();
  61365. }
  61366. }
  61367. }
  61368. private:
  61369. OpenGLComponent* const owner;
  61370. bool wasShowing;
  61371. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61372. };
  61373. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61374. : type (type_),
  61375. contextToShareListsWith (0),
  61376. needToUpdateViewport (true)
  61377. {
  61378. setOpaque (true);
  61379. componentWatcher = new OpenGLComponentWatcher (this);
  61380. }
  61381. OpenGLComponent::~OpenGLComponent()
  61382. {
  61383. deleteContext();
  61384. componentWatcher = 0;
  61385. }
  61386. void OpenGLComponent::deleteContext()
  61387. {
  61388. const ScopedLock sl (contextLock);
  61389. context = 0;
  61390. }
  61391. void OpenGLComponent::updateContextPosition()
  61392. {
  61393. needToUpdateViewport = true;
  61394. if (getWidth() > 0 && getHeight() > 0)
  61395. {
  61396. Component* const topComp = getTopLevelComponent();
  61397. if (topComp->getPeer() != 0)
  61398. {
  61399. const ScopedLock sl (contextLock);
  61400. if (context != 0)
  61401. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61402. getScreenY() - topComp->getScreenY(),
  61403. getWidth(),
  61404. getHeight(),
  61405. topComp->getHeight());
  61406. }
  61407. }
  61408. }
  61409. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61410. {
  61411. OpenGLPixelFormat pf;
  61412. const ScopedLock sl (contextLock);
  61413. if (context != 0)
  61414. pf = context->getPixelFormat();
  61415. return pf;
  61416. }
  61417. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61418. {
  61419. if (! (preferredPixelFormat == formatToUse))
  61420. {
  61421. const ScopedLock sl (contextLock);
  61422. deleteContext();
  61423. preferredPixelFormat = formatToUse;
  61424. }
  61425. }
  61426. void OpenGLComponent::shareWith (OpenGLContext* c)
  61427. {
  61428. if (contextToShareListsWith != c)
  61429. {
  61430. const ScopedLock sl (contextLock);
  61431. deleteContext();
  61432. contextToShareListsWith = c;
  61433. }
  61434. }
  61435. bool OpenGLComponent::makeCurrentContextActive()
  61436. {
  61437. if (context == 0)
  61438. {
  61439. const ScopedLock sl (contextLock);
  61440. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61441. {
  61442. context = createContext();
  61443. if (context != 0)
  61444. {
  61445. updateContextPosition();
  61446. if (context->makeActive())
  61447. newOpenGLContextCreated();
  61448. }
  61449. }
  61450. }
  61451. return context != 0 && context->makeActive();
  61452. }
  61453. void OpenGLComponent::makeCurrentContextInactive()
  61454. {
  61455. if (context != 0)
  61456. context->makeInactive();
  61457. }
  61458. bool OpenGLComponent::isActiveContext() const throw()
  61459. {
  61460. return context != 0 && context->isActive();
  61461. }
  61462. void OpenGLComponent::swapBuffers()
  61463. {
  61464. if (context != 0)
  61465. context->swapBuffers();
  61466. }
  61467. void OpenGLComponent::paint (Graphics&)
  61468. {
  61469. if (renderAndSwapBuffers())
  61470. {
  61471. ComponentPeer* const peer = getPeer();
  61472. if (peer != 0)
  61473. {
  61474. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61475. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61476. }
  61477. }
  61478. }
  61479. bool OpenGLComponent::renderAndSwapBuffers()
  61480. {
  61481. const ScopedLock sl (contextLock);
  61482. if (! makeCurrentContextActive())
  61483. return false;
  61484. if (needToUpdateViewport)
  61485. {
  61486. needToUpdateViewport = false;
  61487. juce_glViewport (getWidth(), getHeight());
  61488. }
  61489. renderOpenGL();
  61490. swapBuffers();
  61491. return true;
  61492. }
  61493. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61494. {
  61495. Component::internalRepaint (x, y, w, h);
  61496. if (context != 0)
  61497. context->repaint();
  61498. }
  61499. END_JUCE_NAMESPACE
  61500. #endif
  61501. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61502. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61503. BEGIN_JUCE_NAMESPACE
  61504. PreferencesPanel::PreferencesPanel()
  61505. : buttonSize (70)
  61506. {
  61507. }
  61508. PreferencesPanel::~PreferencesPanel()
  61509. {
  61510. }
  61511. void PreferencesPanel::addSettingsPage (const String& title,
  61512. const Drawable* icon,
  61513. const Drawable* overIcon,
  61514. const Drawable* downIcon)
  61515. {
  61516. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61517. buttons.add (button);
  61518. button->setImages (icon, overIcon, downIcon);
  61519. button->setRadioGroupId (1);
  61520. button->addButtonListener (this);
  61521. button->setClickingTogglesState (true);
  61522. button->setWantsKeyboardFocus (false);
  61523. addAndMakeVisible (button);
  61524. resized();
  61525. if (currentPage == 0)
  61526. setCurrentPage (title);
  61527. }
  61528. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61529. {
  61530. DrawableImage icon, iconOver, iconDown;
  61531. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61532. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61533. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61534. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61535. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61536. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61537. }
  61538. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61539. {
  61540. setSize (dialogWidth, dialogHeight);
  61541. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61542. }
  61543. void PreferencesPanel::resized()
  61544. {
  61545. for (int i = 0; i < buttons.size(); ++i)
  61546. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61547. if (currentPage != 0)
  61548. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61549. }
  61550. void PreferencesPanel::paint (Graphics& g)
  61551. {
  61552. g.setColour (Colours::grey);
  61553. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61554. }
  61555. void PreferencesPanel::setCurrentPage (const String& pageName)
  61556. {
  61557. if (currentPageName != pageName)
  61558. {
  61559. currentPageName = pageName;
  61560. currentPage = 0;
  61561. currentPage = createComponentForPage (pageName);
  61562. if (currentPage != 0)
  61563. {
  61564. addAndMakeVisible (currentPage);
  61565. currentPage->toBack();
  61566. resized();
  61567. }
  61568. for (int i = 0; i < buttons.size(); ++i)
  61569. {
  61570. if (buttons.getUnchecked(i)->getName() == pageName)
  61571. {
  61572. buttons.getUnchecked(i)->setToggleState (true, false);
  61573. break;
  61574. }
  61575. }
  61576. }
  61577. }
  61578. void PreferencesPanel::buttonClicked (Button*)
  61579. {
  61580. for (int i = 0; i < buttons.size(); ++i)
  61581. {
  61582. if (buttons.getUnchecked(i)->getToggleState())
  61583. {
  61584. setCurrentPage (buttons.getUnchecked(i)->getName());
  61585. break;
  61586. }
  61587. }
  61588. }
  61589. END_JUCE_NAMESPACE
  61590. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61591. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61592. #if JUCE_WINDOWS || JUCE_LINUX
  61593. BEGIN_JUCE_NAMESPACE
  61594. SystemTrayIconComponent::SystemTrayIconComponent()
  61595. {
  61596. addToDesktop (0);
  61597. }
  61598. SystemTrayIconComponent::~SystemTrayIconComponent()
  61599. {
  61600. }
  61601. END_JUCE_NAMESPACE
  61602. #endif
  61603. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61604. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61605. BEGIN_JUCE_NAMESPACE
  61606. class AlertWindowTextEditor : public TextEditor
  61607. {
  61608. public:
  61609. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61610. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61611. {
  61612. setSelectAllWhenFocused (true);
  61613. }
  61614. void returnPressed()
  61615. {
  61616. // pass these up the component hierarchy to be trigger the buttons
  61617. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61618. }
  61619. void escapePressed()
  61620. {
  61621. // pass these up the component hierarchy to be trigger the buttons
  61622. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61623. }
  61624. private:
  61625. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61626. static juce_wchar getDefaultPasswordChar() throw()
  61627. {
  61628. #if JUCE_LINUX
  61629. return 0x2022;
  61630. #else
  61631. return 0x25cf;
  61632. #endif
  61633. }
  61634. };
  61635. AlertWindow::AlertWindow (const String& title,
  61636. const String& message,
  61637. AlertIconType iconType,
  61638. Component* associatedComponent_)
  61639. : TopLevelWindow (title, true),
  61640. alertIconType (iconType),
  61641. associatedComponent (associatedComponent_)
  61642. {
  61643. if (message.isEmpty())
  61644. text = " "; // to force an update if the message is empty
  61645. setMessage (message);
  61646. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61647. {
  61648. Component* const c = Desktop::getInstance().getComponent (i);
  61649. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61650. {
  61651. setAlwaysOnTop (true);
  61652. break;
  61653. }
  61654. }
  61655. if (! JUCEApplication::isStandaloneApp())
  61656. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61657. lookAndFeelChanged();
  61658. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61659. }
  61660. AlertWindow::~AlertWindow()
  61661. {
  61662. removeAllChildren();
  61663. }
  61664. void AlertWindow::userTriedToCloseWindow()
  61665. {
  61666. exitModalState (0);
  61667. }
  61668. void AlertWindow::setMessage (const String& message)
  61669. {
  61670. const String newMessage (message.substring (0, 2048));
  61671. if (text != newMessage)
  61672. {
  61673. text = newMessage;
  61674. font.setHeight (15.0f);
  61675. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61676. textLayout.setText (getName() + "\n\n", titleFont);
  61677. textLayout.appendText (text, font);
  61678. updateLayout (true);
  61679. repaint();
  61680. }
  61681. }
  61682. void AlertWindow::buttonClicked (Button* button)
  61683. {
  61684. if (button->getParentComponent() != 0)
  61685. button->getParentComponent()->exitModalState (button->getCommandID());
  61686. }
  61687. void AlertWindow::addButton (const String& name,
  61688. const int returnValue,
  61689. const KeyPress& shortcutKey1,
  61690. const KeyPress& shortcutKey2)
  61691. {
  61692. TextButton* const b = new TextButton (name, String::empty);
  61693. buttons.add (b);
  61694. b->setWantsKeyboardFocus (true);
  61695. b->setMouseClickGrabsKeyboardFocus (false);
  61696. b->setCommandToTrigger (0, returnValue, false);
  61697. b->addShortcut (shortcutKey1);
  61698. b->addShortcut (shortcutKey2);
  61699. b->addButtonListener (this);
  61700. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61701. addAndMakeVisible (b, 0);
  61702. updateLayout (false);
  61703. }
  61704. int AlertWindow::getNumButtons() const
  61705. {
  61706. return buttons.size();
  61707. }
  61708. void AlertWindow::triggerButtonClick (const String& buttonName)
  61709. {
  61710. for (int i = buttons.size(); --i >= 0;)
  61711. {
  61712. TextButton* const b = buttons.getUnchecked(i);
  61713. if (buttonName == b->getName())
  61714. {
  61715. b->triggerClick();
  61716. break;
  61717. }
  61718. }
  61719. }
  61720. void AlertWindow::addTextEditor (const String& name,
  61721. const String& initialContents,
  61722. const String& onScreenLabel,
  61723. const bool isPasswordBox)
  61724. {
  61725. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61726. textBoxes.add (tc);
  61727. allComps.add (tc);
  61728. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61729. tc->setFont (font);
  61730. tc->setText (initialContents);
  61731. tc->setCaretPosition (initialContents.length());
  61732. addAndMakeVisible (tc);
  61733. textboxNames.add (onScreenLabel);
  61734. updateLayout (false);
  61735. }
  61736. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61737. {
  61738. for (int i = textBoxes.size(); --i >= 0;)
  61739. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61740. return textBoxes.getUnchecked(i);
  61741. return 0;
  61742. }
  61743. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61744. {
  61745. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61746. return t != 0 ? t->getText() : String::empty;
  61747. }
  61748. void AlertWindow::addComboBox (const String& name,
  61749. const StringArray& items,
  61750. const String& onScreenLabel)
  61751. {
  61752. ComboBox* const cb = new ComboBox (name);
  61753. comboBoxes.add (cb);
  61754. allComps.add (cb);
  61755. for (int i = 0; i < items.size(); ++i)
  61756. cb->addItem (items[i], i + 1);
  61757. addAndMakeVisible (cb);
  61758. cb->setSelectedItemIndex (0);
  61759. comboBoxNames.add (onScreenLabel);
  61760. updateLayout (false);
  61761. }
  61762. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61763. {
  61764. for (int i = comboBoxes.size(); --i >= 0;)
  61765. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61766. return comboBoxes.getUnchecked(i);
  61767. return 0;
  61768. }
  61769. class AlertTextComp : public TextEditor
  61770. {
  61771. public:
  61772. AlertTextComp (const String& message,
  61773. const Font& font)
  61774. {
  61775. setReadOnly (true);
  61776. setMultiLine (true, true);
  61777. setCaretVisible (false);
  61778. setScrollbarsShown (true);
  61779. lookAndFeelChanged();
  61780. setWantsKeyboardFocus (false);
  61781. setFont (font);
  61782. setText (message, false);
  61783. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61784. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61785. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61786. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61787. }
  61788. ~AlertTextComp()
  61789. {
  61790. }
  61791. int getPreferredWidth() const throw() { return bestWidth; }
  61792. void updateLayout (const int width)
  61793. {
  61794. TextLayout text;
  61795. text.appendText (getText(), getFont());
  61796. text.layout (width - 8, Justification::topLeft, true);
  61797. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61798. }
  61799. private:
  61800. int bestWidth;
  61801. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61802. };
  61803. void AlertWindow::addTextBlock (const String& textBlock)
  61804. {
  61805. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61806. textBlocks.add (c);
  61807. allComps.add (c);
  61808. addAndMakeVisible (c);
  61809. updateLayout (false);
  61810. }
  61811. void AlertWindow::addProgressBarComponent (double& progressValue)
  61812. {
  61813. ProgressBar* const pb = new ProgressBar (progressValue);
  61814. progressBars.add (pb);
  61815. allComps.add (pb);
  61816. addAndMakeVisible (pb);
  61817. updateLayout (false);
  61818. }
  61819. void AlertWindow::addCustomComponent (Component* const component)
  61820. {
  61821. customComps.add (component);
  61822. allComps.add (component);
  61823. addAndMakeVisible (component);
  61824. updateLayout (false);
  61825. }
  61826. int AlertWindow::getNumCustomComponents() const
  61827. {
  61828. return customComps.size();
  61829. }
  61830. Component* AlertWindow::getCustomComponent (const int index) const
  61831. {
  61832. return customComps [index];
  61833. }
  61834. Component* AlertWindow::removeCustomComponent (const int index)
  61835. {
  61836. Component* const c = getCustomComponent (index);
  61837. if (c != 0)
  61838. {
  61839. customComps.removeValue (c);
  61840. allComps.removeValue (c);
  61841. removeChildComponent (c);
  61842. updateLayout (false);
  61843. }
  61844. return c;
  61845. }
  61846. void AlertWindow::paint (Graphics& g)
  61847. {
  61848. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61849. g.setColour (findColour (textColourId));
  61850. g.setFont (getLookAndFeel().getAlertWindowFont());
  61851. int i;
  61852. for (i = textBoxes.size(); --i >= 0;)
  61853. {
  61854. const TextEditor* const te = textBoxes.getUnchecked(i);
  61855. g.drawFittedText (textboxNames[i],
  61856. te->getX(), te->getY() - 14,
  61857. te->getWidth(), 14,
  61858. Justification::centredLeft, 1);
  61859. }
  61860. for (i = comboBoxNames.size(); --i >= 0;)
  61861. {
  61862. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61863. g.drawFittedText (comboBoxNames[i],
  61864. cb->getX(), cb->getY() - 14,
  61865. cb->getWidth(), 14,
  61866. Justification::centredLeft, 1);
  61867. }
  61868. for (i = customComps.size(); --i >= 0;)
  61869. {
  61870. const Component* const c = customComps.getUnchecked(i);
  61871. g.drawFittedText (c->getName(),
  61872. c->getX(), c->getY() - 14,
  61873. c->getWidth(), 14,
  61874. Justification::centredLeft, 1);
  61875. }
  61876. }
  61877. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61878. {
  61879. const int titleH = 24;
  61880. const int iconWidth = 80;
  61881. const int wid = jmax (font.getStringWidth (text),
  61882. font.getStringWidth (getName()));
  61883. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61884. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61885. const int edgeGap = 10;
  61886. const int labelHeight = 18;
  61887. int iconSpace;
  61888. if (alertIconType == NoIcon)
  61889. {
  61890. textLayout.layout (w, Justification::horizontallyCentred, true);
  61891. iconSpace = 0;
  61892. }
  61893. else
  61894. {
  61895. textLayout.layout (w, Justification::left, true);
  61896. iconSpace = iconWidth;
  61897. }
  61898. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61899. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61900. const int textLayoutH = textLayout.getHeight();
  61901. const int textBottom = 16 + titleH + textLayoutH;
  61902. int h = textBottom;
  61903. int buttonW = 40;
  61904. int i;
  61905. for (i = 0; i < buttons.size(); ++i)
  61906. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61907. w = jmax (buttonW, w);
  61908. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61909. if (buttons.size() > 0)
  61910. h += 20 + buttons.getUnchecked(0)->getHeight();
  61911. for (i = customComps.size(); --i >= 0;)
  61912. {
  61913. Component* c = customComps.getUnchecked(i);
  61914. w = jmax (w, (c->getWidth() * 100) / 80);
  61915. h += 10 + c->getHeight();
  61916. if (c->getName().isNotEmpty())
  61917. h += labelHeight;
  61918. }
  61919. for (i = textBlocks.size(); --i >= 0;)
  61920. {
  61921. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61922. w = jmax (w, ac->getPreferredWidth());
  61923. }
  61924. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61925. for (i = textBlocks.size(); --i >= 0;)
  61926. {
  61927. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61928. ac->updateLayout ((int) (w * 0.8f));
  61929. h += ac->getHeight() + 10;
  61930. }
  61931. h = jmin (getParentHeight() - 50, h);
  61932. if (onlyIncreaseSize)
  61933. {
  61934. w = jmax (w, getWidth());
  61935. h = jmax (h, getHeight());
  61936. }
  61937. if (! isVisible())
  61938. {
  61939. centreAroundComponent (associatedComponent, w, h);
  61940. }
  61941. else
  61942. {
  61943. const int cx = getX() + getWidth() / 2;
  61944. const int cy = getY() + getHeight() / 2;
  61945. setBounds (cx - w / 2,
  61946. cy - h / 2,
  61947. w, h);
  61948. }
  61949. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61950. const int spacer = 16;
  61951. int totalWidth = -spacer;
  61952. for (i = buttons.size(); --i >= 0;)
  61953. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61954. int x = (w - totalWidth) / 2;
  61955. int y = (int) (getHeight() * 0.95f);
  61956. for (i = 0; i < buttons.size(); ++i)
  61957. {
  61958. TextButton* const c = buttons.getUnchecked(i);
  61959. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61960. c->setTopLeftPosition (x, ny);
  61961. if (ny < y)
  61962. y = ny;
  61963. x += c->getWidth() + spacer;
  61964. c->toFront (false);
  61965. }
  61966. y = textBottom;
  61967. for (i = 0; i < allComps.size(); ++i)
  61968. {
  61969. Component* const c = allComps.getUnchecked(i);
  61970. h = 22;
  61971. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61972. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61973. y += labelHeight;
  61974. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61975. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61976. y += labelHeight;
  61977. if (customComps.contains (c))
  61978. {
  61979. if (c->getName().isNotEmpty())
  61980. y += labelHeight;
  61981. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61982. h = c->getHeight();
  61983. }
  61984. else if (textBlocks.contains (c))
  61985. {
  61986. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61987. h = c->getHeight();
  61988. }
  61989. else
  61990. {
  61991. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61992. }
  61993. y += h + 10;
  61994. }
  61995. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61996. }
  61997. bool AlertWindow::containsAnyExtraComponents() const
  61998. {
  61999. return allComps.size() > 0;
  62000. }
  62001. void AlertWindow::mouseDown (const MouseEvent& e)
  62002. {
  62003. dragger.startDraggingComponent (this, e);
  62004. }
  62005. void AlertWindow::mouseDrag (const MouseEvent& e)
  62006. {
  62007. dragger.dragComponent (this, e, &constrainer);
  62008. }
  62009. bool AlertWindow::keyPressed (const KeyPress& key)
  62010. {
  62011. for (int i = buttons.size(); --i >= 0;)
  62012. {
  62013. TextButton* const b = buttons.getUnchecked(i);
  62014. if (b->isRegisteredForShortcut (key))
  62015. {
  62016. b->triggerClick();
  62017. return true;
  62018. }
  62019. }
  62020. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62021. {
  62022. exitModalState (0);
  62023. return true;
  62024. }
  62025. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62026. {
  62027. buttons.getUnchecked(0)->triggerClick();
  62028. return true;
  62029. }
  62030. return false;
  62031. }
  62032. void AlertWindow::lookAndFeelChanged()
  62033. {
  62034. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62035. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62036. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62037. }
  62038. int AlertWindow::getDesktopWindowStyleFlags() const
  62039. {
  62040. return getLookAndFeel().getAlertBoxWindowFlags();
  62041. }
  62042. class AlertWindowInfo
  62043. {
  62044. public:
  62045. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  62046. AlertWindow::AlertIconType iconType_, int numButtons_)
  62047. : title (title_), message (message_), iconType (iconType_),
  62048. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  62049. {
  62050. }
  62051. String title, message, button1, button2, button3;
  62052. AlertWindow::AlertIconType iconType;
  62053. int numButtons, returnValue;
  62054. Component::SafePointer<Component> associatedComponent;
  62055. int showModal() const
  62056. {
  62057. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62058. return returnValue;
  62059. }
  62060. private:
  62061. void show()
  62062. {
  62063. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62064. : LookAndFeel::getDefaultLookAndFeel();
  62065. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62066. iconType, numButtons, associatedComponent));
  62067. jassert (alertBox != 0); // you have to return one of these!
  62068. returnValue = alertBox->runModalLoop();
  62069. }
  62070. static void* showCallback (void* userData)
  62071. {
  62072. static_cast <AlertWindowInfo*> (userData)->show();
  62073. return 0;
  62074. }
  62075. };
  62076. void AlertWindow::showMessageBox (AlertIconType iconType,
  62077. const String& title,
  62078. const String& message,
  62079. const String& buttonText,
  62080. Component* associatedComponent)
  62081. {
  62082. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  62083. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62084. info.showModal();
  62085. }
  62086. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62087. const String& title,
  62088. const String& message,
  62089. const String& button1Text,
  62090. const String& button2Text,
  62091. Component* associatedComponent)
  62092. {
  62093. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  62094. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62095. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62096. return info.showModal() != 0;
  62097. }
  62098. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62099. const String& title,
  62100. const String& message,
  62101. const String& button1Text,
  62102. const String& button2Text,
  62103. const String& button3Text,
  62104. Component* associatedComponent)
  62105. {
  62106. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  62107. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62108. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62109. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62110. return info.showModal();
  62111. }
  62112. END_JUCE_NAMESPACE
  62113. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62114. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62115. BEGIN_JUCE_NAMESPACE
  62116. CallOutBox::CallOutBox (Component& contentComponent,
  62117. Component& componentToPointTo,
  62118. Component* const parentComponent)
  62119. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62120. {
  62121. addAndMakeVisible (&content);
  62122. if (parentComponent != 0)
  62123. {
  62124. parentComponent->addChildComponent (this);
  62125. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62126. parentComponent->getLocalBounds());
  62127. setVisible (true);
  62128. }
  62129. else
  62130. {
  62131. if (! JUCEApplication::isStandaloneApp())
  62132. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62133. updatePosition (componentToPointTo.getScreenBounds(),
  62134. componentToPointTo.getParentMonitorArea());
  62135. addToDesktop (ComponentPeer::windowIsTemporary);
  62136. }
  62137. }
  62138. CallOutBox::~CallOutBox()
  62139. {
  62140. }
  62141. void CallOutBox::setArrowSize (const float newSize)
  62142. {
  62143. arrowSize = newSize;
  62144. borderSpace = jmax (20, (int) arrowSize);
  62145. refreshPath();
  62146. }
  62147. void CallOutBox::paint (Graphics& g)
  62148. {
  62149. if (background.isNull())
  62150. {
  62151. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62152. Graphics g (background);
  62153. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62154. }
  62155. g.setColour (Colours::black);
  62156. g.drawImageAt (background, 0, 0);
  62157. }
  62158. void CallOutBox::resized()
  62159. {
  62160. content.setTopLeftPosition (borderSpace, borderSpace);
  62161. refreshPath();
  62162. }
  62163. void CallOutBox::moved()
  62164. {
  62165. refreshPath();
  62166. }
  62167. void CallOutBox::childBoundsChanged (Component*)
  62168. {
  62169. updatePosition (targetArea, availableArea);
  62170. }
  62171. bool CallOutBox::hitTest (int x, int y)
  62172. {
  62173. return outline.contains ((float) x, (float) y);
  62174. }
  62175. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62176. void CallOutBox::inputAttemptWhenModal()
  62177. {
  62178. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62179. if (targetArea.contains (mousePos))
  62180. {
  62181. // if you click on the area that originally popped-up the callout, you expect it
  62182. // to get rid of the box, but deleting the box here allows the click to pass through and
  62183. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62184. postCommandMessage (callOutBoxDismissCommandId);
  62185. }
  62186. else
  62187. {
  62188. exitModalState (0);
  62189. setVisible (false);
  62190. }
  62191. }
  62192. void CallOutBox::handleCommandMessage (int commandId)
  62193. {
  62194. Component::handleCommandMessage (commandId);
  62195. if (commandId == callOutBoxDismissCommandId)
  62196. {
  62197. exitModalState (0);
  62198. setVisible (false);
  62199. }
  62200. }
  62201. bool CallOutBox::keyPressed (const KeyPress& key)
  62202. {
  62203. if (key.isKeyCode (KeyPress::escapeKey))
  62204. {
  62205. inputAttemptWhenModal();
  62206. return true;
  62207. }
  62208. return false;
  62209. }
  62210. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62211. {
  62212. targetArea = newAreaToPointTo;
  62213. availableArea = newAreaToFitIn;
  62214. Rectangle<int> bounds (0, 0,
  62215. content.getWidth() + borderSpace * 2,
  62216. content.getHeight() + borderSpace * 2);
  62217. const int hw = bounds.getWidth() / 2;
  62218. const int hh = bounds.getHeight() / 2;
  62219. const float hwReduced = (float) (hw - borderSpace * 3);
  62220. const float hhReduced = (float) (hh - borderSpace * 3);
  62221. const float arrowIndent = borderSpace - arrowSize;
  62222. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62223. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62224. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62225. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62226. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62227. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62228. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62229. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62230. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62231. float nearest = 1.0e9f;
  62232. for (int i = 0; i < 4; ++i)
  62233. {
  62234. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62235. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62236. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62237. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62238. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62239. distanceFromCentre *= 2.0f;
  62240. if (distanceFromCentre < nearest)
  62241. {
  62242. nearest = distanceFromCentre;
  62243. targetPoint = targets[i];
  62244. bounds.setPosition ((int) (centre.getX() - hw),
  62245. (int) (centre.getY() - hh));
  62246. }
  62247. }
  62248. setBounds (bounds);
  62249. }
  62250. void CallOutBox::refreshPath()
  62251. {
  62252. repaint();
  62253. background = Image::null;
  62254. outline.clear();
  62255. const float gap = 4.5f;
  62256. const float cornerSize = 9.0f;
  62257. const float cornerSize2 = 2.0f * cornerSize;
  62258. const float arrowBaseWidth = arrowSize * 0.7f;
  62259. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62260. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62261. outline.startNewSubPath (left + cornerSize, top);
  62262. if (targetY <= top)
  62263. {
  62264. outline.lineTo (targetX - arrowBaseWidth, top);
  62265. outline.lineTo (targetX, targetY);
  62266. outline.lineTo (targetX + arrowBaseWidth, top);
  62267. }
  62268. outline.lineTo (right - cornerSize, top);
  62269. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62270. if (targetX >= right)
  62271. {
  62272. outline.lineTo (right, targetY - arrowBaseWidth);
  62273. outline.lineTo (targetX, targetY);
  62274. outline.lineTo (right, targetY + arrowBaseWidth);
  62275. }
  62276. outline.lineTo (right, bottom - cornerSize);
  62277. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62278. if (targetY >= bottom)
  62279. {
  62280. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62281. outline.lineTo (targetX, targetY);
  62282. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62283. }
  62284. outline.lineTo (left + cornerSize, bottom);
  62285. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62286. if (targetX <= left)
  62287. {
  62288. outline.lineTo (left, targetY + arrowBaseWidth);
  62289. outline.lineTo (targetX, targetY);
  62290. outline.lineTo (left, targetY - arrowBaseWidth);
  62291. }
  62292. outline.lineTo (left, top + cornerSize);
  62293. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62294. outline.closeSubPath();
  62295. }
  62296. END_JUCE_NAMESPACE
  62297. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62298. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62299. BEGIN_JUCE_NAMESPACE
  62300. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62301. static Array <ComponentPeer*> heavyweightPeers;
  62302. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62303. : component (component_),
  62304. styleFlags (styleFlags_),
  62305. lastPaintTime (0),
  62306. constrainer (0),
  62307. lastDragAndDropCompUnderMouse (0),
  62308. fakeMouseMessageSent (false),
  62309. isWindowMinimised (false)
  62310. {
  62311. heavyweightPeers.add (this);
  62312. }
  62313. ComponentPeer::~ComponentPeer()
  62314. {
  62315. heavyweightPeers.removeValue (this);
  62316. Desktop::getInstance().triggerFocusCallback();
  62317. }
  62318. int ComponentPeer::getNumPeers() throw()
  62319. {
  62320. return heavyweightPeers.size();
  62321. }
  62322. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62323. {
  62324. return heavyweightPeers [index];
  62325. }
  62326. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62327. {
  62328. for (int i = heavyweightPeers.size(); --i >= 0;)
  62329. {
  62330. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62331. if (peer->getComponent() == component)
  62332. return peer;
  62333. }
  62334. return 0;
  62335. }
  62336. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62337. {
  62338. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62339. }
  62340. void ComponentPeer::updateCurrentModifiers() throw()
  62341. {
  62342. ModifierKeys::updateCurrentModifiers();
  62343. }
  62344. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62345. {
  62346. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62347. jassert (mouse != 0); // not enough sources!
  62348. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62349. }
  62350. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62351. {
  62352. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62353. jassert (mouse != 0); // not enough sources!
  62354. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62355. }
  62356. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62357. {
  62358. Graphics g (&contextToPaintTo);
  62359. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62360. g.saveState();
  62361. #endif
  62362. JUCE_TRY
  62363. {
  62364. component->paintEntireComponent (g, true);
  62365. }
  62366. JUCE_CATCH_EXCEPTION
  62367. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62368. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62369. // clearly when things are being repainted.
  62370. g.restoreState();
  62371. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62372. (uint8) Random::getSystemRandom().nextInt (255),
  62373. (uint8) Random::getSystemRandom().nextInt (255),
  62374. (uint8) 0x50));
  62375. #endif
  62376. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62377. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62378. mess up a lot of the calculations that the library needs to do.
  62379. */
  62380. jassert (roundToInt (10.1f) == 10);
  62381. }
  62382. bool ComponentPeer::handleKeyPress (const int keyCode,
  62383. const juce_wchar textCharacter)
  62384. {
  62385. updateCurrentModifiers();
  62386. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62387. ? Component::getCurrentlyFocusedComponent()
  62388. : component;
  62389. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62390. {
  62391. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62392. if (currentModalComp != 0)
  62393. target = currentModalComp;
  62394. }
  62395. const KeyPress keyInfo (keyCode,
  62396. ModifierKeys::getCurrentModifiers().getRawFlags()
  62397. & ModifierKeys::allKeyboardModifiers,
  62398. textCharacter);
  62399. bool keyWasUsed = false;
  62400. while (target != 0)
  62401. {
  62402. const Component::SafePointer<Component> deletionChecker (target);
  62403. if (target->keyListeners_ != 0)
  62404. {
  62405. for (int i = target->keyListeners_->size(); --i >= 0;)
  62406. {
  62407. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62408. if (keyWasUsed || deletionChecker == 0)
  62409. return keyWasUsed;
  62410. i = jmin (i, target->keyListeners_->size());
  62411. }
  62412. }
  62413. keyWasUsed = target->keyPressed (keyInfo);
  62414. if (keyWasUsed || deletionChecker == 0)
  62415. break;
  62416. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62417. {
  62418. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62419. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62420. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62421. break;
  62422. }
  62423. target = target->parentComponent_;
  62424. }
  62425. return keyWasUsed;
  62426. }
  62427. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62428. {
  62429. updateCurrentModifiers();
  62430. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62431. ? Component::getCurrentlyFocusedComponent()
  62432. : component;
  62433. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62434. {
  62435. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62436. if (currentModalComp != 0)
  62437. target = currentModalComp;
  62438. }
  62439. bool keyWasUsed = false;
  62440. while (target != 0)
  62441. {
  62442. const Component::SafePointer<Component> deletionChecker (target);
  62443. keyWasUsed = target->keyStateChanged (isKeyDown);
  62444. if (keyWasUsed || deletionChecker == 0)
  62445. break;
  62446. if (target->keyListeners_ != 0)
  62447. {
  62448. for (int i = target->keyListeners_->size(); --i >= 0;)
  62449. {
  62450. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62451. if (keyWasUsed || deletionChecker == 0)
  62452. return keyWasUsed;
  62453. i = jmin (i, target->keyListeners_->size());
  62454. }
  62455. }
  62456. target = target->parentComponent_;
  62457. }
  62458. return keyWasUsed;
  62459. }
  62460. void ComponentPeer::handleModifierKeysChange()
  62461. {
  62462. updateCurrentModifiers();
  62463. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62464. if (target == 0)
  62465. target = Component::getCurrentlyFocusedComponent();
  62466. if (target == 0)
  62467. target = component;
  62468. if (target != 0)
  62469. target->internalModifierKeysChanged();
  62470. }
  62471. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62472. {
  62473. Component* const c = Component::getCurrentlyFocusedComponent();
  62474. if (component->isParentOf (c))
  62475. {
  62476. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62477. if (ti != 0 && ti->isTextInputActive())
  62478. return ti;
  62479. }
  62480. return 0;
  62481. }
  62482. void ComponentPeer::handleBroughtToFront()
  62483. {
  62484. updateCurrentModifiers();
  62485. if (component != 0)
  62486. component->internalBroughtToFront();
  62487. }
  62488. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62489. {
  62490. constrainer = newConstrainer;
  62491. }
  62492. void ComponentPeer::handleMovedOrResized()
  62493. {
  62494. updateCurrentModifiers();
  62495. const bool nowMinimised = isMinimised();
  62496. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62497. {
  62498. const Component::SafePointer<Component> deletionChecker (component);
  62499. const Rectangle<int> newBounds (getBounds());
  62500. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62501. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62502. if (wasMoved || wasResized)
  62503. {
  62504. component->bounds_ = newBounds;
  62505. if (wasResized)
  62506. component->repaint();
  62507. component->sendMovedResizedMessages (wasMoved, wasResized);
  62508. if (deletionChecker == 0)
  62509. return;
  62510. }
  62511. }
  62512. if (isWindowMinimised != nowMinimised)
  62513. {
  62514. isWindowMinimised = nowMinimised;
  62515. component->minimisationStateChanged (nowMinimised);
  62516. component->sendVisibilityChangeMessage();
  62517. }
  62518. if (! isFullScreen())
  62519. lastNonFullscreenBounds = component->getBounds();
  62520. }
  62521. void ComponentPeer::handleFocusGain()
  62522. {
  62523. updateCurrentModifiers();
  62524. if (component->isParentOf (lastFocusedComponent))
  62525. {
  62526. Component::currentlyFocusedComponent = lastFocusedComponent;
  62527. Desktop::getInstance().triggerFocusCallback();
  62528. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62529. }
  62530. else
  62531. {
  62532. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62533. component->grabKeyboardFocus();
  62534. else
  62535. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62536. }
  62537. }
  62538. void ComponentPeer::handleFocusLoss()
  62539. {
  62540. updateCurrentModifiers();
  62541. if (component->hasKeyboardFocus (true))
  62542. {
  62543. lastFocusedComponent = Component::currentlyFocusedComponent;
  62544. if (lastFocusedComponent != 0)
  62545. {
  62546. Component::currentlyFocusedComponent = 0;
  62547. Desktop::getInstance().triggerFocusCallback();
  62548. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62549. }
  62550. }
  62551. }
  62552. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62553. {
  62554. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62555. ? static_cast <Component*> (lastFocusedComponent)
  62556. : component;
  62557. }
  62558. void ComponentPeer::handleScreenSizeChange()
  62559. {
  62560. updateCurrentModifiers();
  62561. component->parentSizeChanged();
  62562. handleMovedOrResized();
  62563. }
  62564. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62565. {
  62566. lastNonFullscreenBounds = newBounds;
  62567. }
  62568. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62569. {
  62570. return lastNonFullscreenBounds;
  62571. }
  62572. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62573. {
  62574. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62575. }
  62576. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62577. {
  62578. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62579. }
  62580. namespace ComponentPeerHelpers
  62581. {
  62582. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62583. const StringArray& files,
  62584. FileDragAndDropTarget* const lastOne)
  62585. {
  62586. while (c != 0)
  62587. {
  62588. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62589. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62590. return t;
  62591. c = c->getParentComponent();
  62592. }
  62593. return 0;
  62594. }
  62595. }
  62596. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62597. {
  62598. updateCurrentModifiers();
  62599. FileDragAndDropTarget* lastTarget
  62600. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62601. FileDragAndDropTarget* newTarget = 0;
  62602. Component* const compUnderMouse = component->getComponentAt (position);
  62603. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62604. {
  62605. lastDragAndDropCompUnderMouse = compUnderMouse;
  62606. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62607. if (newTarget != lastTarget)
  62608. {
  62609. if (lastTarget != 0)
  62610. lastTarget->fileDragExit (files);
  62611. dragAndDropTargetComponent = 0;
  62612. if (newTarget != 0)
  62613. {
  62614. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62615. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62616. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62617. }
  62618. }
  62619. }
  62620. else
  62621. {
  62622. newTarget = lastTarget;
  62623. }
  62624. if (newTarget != 0)
  62625. {
  62626. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62627. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62628. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62629. }
  62630. }
  62631. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62632. {
  62633. handleFileDragMove (files, Point<int> (-1, -1));
  62634. jassert (dragAndDropTargetComponent == 0);
  62635. lastDragAndDropCompUnderMouse = 0;
  62636. }
  62637. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62638. {
  62639. handleFileDragMove (files, position);
  62640. if (dragAndDropTargetComponent != 0)
  62641. {
  62642. FileDragAndDropTarget* const target
  62643. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62644. dragAndDropTargetComponent = 0;
  62645. lastDragAndDropCompUnderMouse = 0;
  62646. if (target != 0)
  62647. {
  62648. Component* const targetComp = dynamic_cast <Component*> (target);
  62649. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62650. {
  62651. targetComp->internalModalInputAttempt();
  62652. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62653. return;
  62654. }
  62655. // We'll use an async message to deliver the drop, because if the target decides
  62656. // to run a modal loop, it can gum-up the operating system..
  62657. class AsyncFileDropMessage : public CallbackMessage
  62658. {
  62659. public:
  62660. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62661. const Point<int>& position_, const StringArray& files_)
  62662. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62663. {
  62664. }
  62665. void messageCallback()
  62666. {
  62667. if (target != 0)
  62668. dropTarget->filesDropped (files, position.getX(), position.getY());
  62669. }
  62670. private:
  62671. Component::SafePointer<Component> target;
  62672. FileDragAndDropTarget* dropTarget;
  62673. Point<int> position;
  62674. StringArray files;
  62675. // (NB: don't make this non-copyable, which messes up in VC)
  62676. };
  62677. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62678. }
  62679. }
  62680. }
  62681. void ComponentPeer::handleUserClosingWindow()
  62682. {
  62683. updateCurrentModifiers();
  62684. component->userTriedToCloseWindow();
  62685. }
  62686. void ComponentPeer::clearMaskedRegion()
  62687. {
  62688. maskedRegion.clear();
  62689. }
  62690. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62691. {
  62692. maskedRegion.add (x, y, w, h);
  62693. }
  62694. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62695. {
  62696. StringArray s;
  62697. s.add ("Software Renderer");
  62698. return s;
  62699. }
  62700. int ComponentPeer::getCurrentRenderingEngine() throw()
  62701. {
  62702. return 0;
  62703. }
  62704. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62705. {
  62706. }
  62707. END_JUCE_NAMESPACE
  62708. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62709. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62710. BEGIN_JUCE_NAMESPACE
  62711. DialogWindow::DialogWindow (const String& name,
  62712. const Colour& backgroundColour_,
  62713. const bool escapeKeyTriggersCloseButton_,
  62714. const bool addToDesktop_)
  62715. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62716. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62717. {
  62718. }
  62719. DialogWindow::~DialogWindow()
  62720. {
  62721. }
  62722. void DialogWindow::resized()
  62723. {
  62724. DocumentWindow::resized();
  62725. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62726. if (escapeKeyTriggersCloseButton
  62727. && getCloseButton() != 0
  62728. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62729. {
  62730. getCloseButton()->addShortcut (esc);
  62731. }
  62732. }
  62733. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62734. // VC compiler complains about the undefined copy constructor)
  62735. class TempDialogWindow : public DialogWindow
  62736. {
  62737. public:
  62738. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62739. : DialogWindow (title, colour, escapeCloses, true)
  62740. {
  62741. if (! JUCEApplication::isStandaloneApp())
  62742. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62743. }
  62744. void closeButtonPressed()
  62745. {
  62746. setVisible (false);
  62747. }
  62748. private:
  62749. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62750. };
  62751. int DialogWindow::showModalDialog (const String& dialogTitle,
  62752. Component* contentComponent,
  62753. Component* componentToCentreAround,
  62754. const Colour& colour,
  62755. const bool escapeKeyTriggersCloseButton,
  62756. const bool shouldBeResizable,
  62757. const bool useBottomRightCornerResizer)
  62758. {
  62759. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62760. dw.setContentComponent (contentComponent, true, true);
  62761. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62762. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62763. const int result = dw.runModalLoop();
  62764. dw.setContentComponent (0, false);
  62765. return result;
  62766. }
  62767. END_JUCE_NAMESPACE
  62768. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62769. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62770. BEGIN_JUCE_NAMESPACE
  62771. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62772. {
  62773. public:
  62774. ButtonListenerProxy (DocumentWindow& owner_)
  62775. : owner (owner_)
  62776. {
  62777. }
  62778. void buttonClicked (Button* button)
  62779. {
  62780. if (button == owner.getMinimiseButton())
  62781. owner.minimiseButtonPressed();
  62782. else if (button == owner.getMaximiseButton())
  62783. owner.maximiseButtonPressed();
  62784. else if (button == owner.getCloseButton())
  62785. owner.closeButtonPressed();
  62786. }
  62787. private:
  62788. DocumentWindow& owner;
  62789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62790. };
  62791. DocumentWindow::DocumentWindow (const String& title,
  62792. const Colour& backgroundColour,
  62793. const int requiredButtons_,
  62794. const bool addToDesktop_)
  62795. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62796. titleBarHeight (26),
  62797. menuBarHeight (24),
  62798. requiredButtons (requiredButtons_),
  62799. #if JUCE_MAC
  62800. positionTitleBarButtonsOnLeft (true),
  62801. #else
  62802. positionTitleBarButtonsOnLeft (false),
  62803. #endif
  62804. drawTitleTextCentred (true),
  62805. menuBarModel (0)
  62806. {
  62807. setResizeLimits (128, 128, 32768, 32768);
  62808. lookAndFeelChanged();
  62809. }
  62810. DocumentWindow::~DocumentWindow()
  62811. {
  62812. // Don't delete or remove the resizer components yourself! They're managed by the
  62813. // DocumentWindow, and you should leave them alone! You may have deleted them
  62814. // accidentally by careless use of deleteAllChildren()..?
  62815. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62816. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62817. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62818. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62819. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62820. titleBarButtons[i] = 0;
  62821. menuBar = 0;
  62822. }
  62823. void DocumentWindow::repaintTitleBar()
  62824. {
  62825. repaint (getTitleBarArea());
  62826. }
  62827. void DocumentWindow::setName (const String& newName)
  62828. {
  62829. if (newName != getName())
  62830. {
  62831. Component::setName (newName);
  62832. repaintTitleBar();
  62833. }
  62834. }
  62835. void DocumentWindow::setIcon (const Image& imageToUse)
  62836. {
  62837. titleBarIcon = imageToUse;
  62838. repaintTitleBar();
  62839. }
  62840. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62841. {
  62842. titleBarHeight = newHeight;
  62843. resized();
  62844. repaintTitleBar();
  62845. }
  62846. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62847. const bool positionTitleBarButtonsOnLeft_)
  62848. {
  62849. requiredButtons = requiredButtons_;
  62850. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62851. lookAndFeelChanged();
  62852. }
  62853. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62854. {
  62855. drawTitleTextCentred = textShouldBeCentred;
  62856. repaintTitleBar();
  62857. }
  62858. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62859. const int menuBarHeight_)
  62860. {
  62861. if (menuBarModel != menuBarModel_)
  62862. {
  62863. menuBar = 0;
  62864. menuBarModel = menuBarModel_;
  62865. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62866. : getLookAndFeel().getDefaultMenuBarHeight();
  62867. if (menuBarModel != 0)
  62868. {
  62869. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62870. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62871. menuBar->setEnabled (isActiveWindow());
  62872. }
  62873. resized();
  62874. }
  62875. }
  62876. void DocumentWindow::closeButtonPressed()
  62877. {
  62878. /* If you've got a close button, you have to override this method to get
  62879. rid of your window!
  62880. If the window is just a pop-up, you should override this method and make
  62881. it delete the window in whatever way is appropriate for your app. E.g. you
  62882. might just want to call "delete this".
  62883. If your app is centred around this window such that the whole app should quit when
  62884. the window is closed, then you will probably want to use this method as an opportunity
  62885. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62886. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62887. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62888. or closing it via the taskbar icon on Windows).
  62889. */
  62890. jassertfalse;
  62891. }
  62892. void DocumentWindow::minimiseButtonPressed()
  62893. {
  62894. setMinimised (true);
  62895. }
  62896. void DocumentWindow::maximiseButtonPressed()
  62897. {
  62898. setFullScreen (! isFullScreen());
  62899. }
  62900. void DocumentWindow::paint (Graphics& g)
  62901. {
  62902. ResizableWindow::paint (g);
  62903. if (resizableBorder == 0)
  62904. {
  62905. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62906. const BorderSize border (getBorderThickness());
  62907. g.fillRect (0, 0, getWidth(), border.getTop());
  62908. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62909. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62910. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62911. }
  62912. const Rectangle<int> titleBarArea (getTitleBarArea());
  62913. g.reduceClipRegion (titleBarArea);
  62914. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62915. int titleSpaceX1 = 6;
  62916. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62917. for (int i = 0; i < 3; ++i)
  62918. {
  62919. if (titleBarButtons[i] != 0)
  62920. {
  62921. if (positionTitleBarButtonsOnLeft)
  62922. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62923. else
  62924. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62925. }
  62926. }
  62927. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62928. titleBarArea.getWidth(),
  62929. titleBarArea.getHeight(),
  62930. titleSpaceX1,
  62931. jmax (1, titleSpaceX2 - titleSpaceX1),
  62932. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62933. ! drawTitleTextCentred);
  62934. }
  62935. void DocumentWindow::resized()
  62936. {
  62937. ResizableWindow::resized();
  62938. if (titleBarButtons[1] != 0)
  62939. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62940. const Rectangle<int> titleBarArea (getTitleBarArea());
  62941. getLookAndFeel()
  62942. .positionDocumentWindowButtons (*this,
  62943. titleBarArea.getX(), titleBarArea.getY(),
  62944. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62945. titleBarButtons[0],
  62946. titleBarButtons[1],
  62947. titleBarButtons[2],
  62948. positionTitleBarButtonsOnLeft);
  62949. if (menuBar != 0)
  62950. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62951. titleBarArea.getWidth(), menuBarHeight);
  62952. }
  62953. const BorderSize DocumentWindow::getBorderThickness()
  62954. {
  62955. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62956. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62957. }
  62958. const BorderSize DocumentWindow::getContentComponentBorder()
  62959. {
  62960. BorderSize border (getBorderThickness());
  62961. border.setTop (border.getTop()
  62962. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62963. + (menuBar != 0 ? menuBarHeight : 0));
  62964. return border;
  62965. }
  62966. int DocumentWindow::getTitleBarHeight() const
  62967. {
  62968. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62969. }
  62970. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62971. {
  62972. const BorderSize border (getBorderThickness());
  62973. return Rectangle<int> (border.getLeft(), border.getTop(),
  62974. getWidth() - border.getLeftAndRight(),
  62975. getTitleBarHeight());
  62976. }
  62977. Button* DocumentWindow::getCloseButton() const throw()
  62978. {
  62979. return titleBarButtons[2];
  62980. }
  62981. Button* DocumentWindow::getMinimiseButton() const throw()
  62982. {
  62983. return titleBarButtons[0];
  62984. }
  62985. Button* DocumentWindow::getMaximiseButton() const throw()
  62986. {
  62987. return titleBarButtons[1];
  62988. }
  62989. int DocumentWindow::getDesktopWindowStyleFlags() const
  62990. {
  62991. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62992. if ((requiredButtons & minimiseButton) != 0)
  62993. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62994. if ((requiredButtons & maximiseButton) != 0)
  62995. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62996. if ((requiredButtons & closeButton) != 0)
  62997. styleFlags |= ComponentPeer::windowHasCloseButton;
  62998. return styleFlags;
  62999. }
  63000. void DocumentWindow::lookAndFeelChanged()
  63001. {
  63002. int i;
  63003. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63004. titleBarButtons[i] = 0;
  63005. if (! isUsingNativeTitleBar())
  63006. {
  63007. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63008. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63009. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63010. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63011. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63012. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63013. for (i = 0; i < 3; ++i)
  63014. {
  63015. if (titleBarButtons[i] != 0)
  63016. {
  63017. if (buttonListener == 0)
  63018. buttonListener = new ButtonListenerProxy (*this);
  63019. titleBarButtons[i]->addButtonListener (buttonListener);
  63020. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63021. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63022. Component::addAndMakeVisible (titleBarButtons[i]);
  63023. }
  63024. }
  63025. if (getCloseButton() != 0)
  63026. {
  63027. #if JUCE_MAC
  63028. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63029. #else
  63030. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63031. #endif
  63032. }
  63033. }
  63034. activeWindowStatusChanged();
  63035. ResizableWindow::lookAndFeelChanged();
  63036. }
  63037. void DocumentWindow::parentHierarchyChanged()
  63038. {
  63039. lookAndFeelChanged();
  63040. }
  63041. void DocumentWindow::activeWindowStatusChanged()
  63042. {
  63043. ResizableWindow::activeWindowStatusChanged();
  63044. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63045. if (titleBarButtons[i] != 0)
  63046. titleBarButtons[i]->setEnabled (isActiveWindow());
  63047. if (menuBar != 0)
  63048. menuBar->setEnabled (isActiveWindow());
  63049. }
  63050. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63051. {
  63052. if (getTitleBarArea().contains (e.x, e.y)
  63053. && getMaximiseButton() != 0)
  63054. {
  63055. getMaximiseButton()->triggerClick();
  63056. }
  63057. }
  63058. void DocumentWindow::userTriedToCloseWindow()
  63059. {
  63060. closeButtonPressed();
  63061. }
  63062. END_JUCE_NAMESPACE
  63063. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63064. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63065. BEGIN_JUCE_NAMESPACE
  63066. ResizableWindow::ResizableWindow (const String& name,
  63067. const bool addToDesktop_)
  63068. : TopLevelWindow (name, addToDesktop_),
  63069. resizeToFitContent (false),
  63070. fullscreen (false),
  63071. lastNonFullScreenPos (50, 50, 256, 256),
  63072. constrainer (0)
  63073. #if JUCE_DEBUG
  63074. , hasBeenResized (false)
  63075. #endif
  63076. {
  63077. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63078. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63079. if (addToDesktop_)
  63080. Component::addToDesktop (getDesktopWindowStyleFlags());
  63081. }
  63082. ResizableWindow::ResizableWindow (const String& name,
  63083. const Colour& backgroundColour_,
  63084. const bool addToDesktop_)
  63085. : TopLevelWindow (name, addToDesktop_),
  63086. resizeToFitContent (false),
  63087. fullscreen (false),
  63088. lastNonFullScreenPos (50, 50, 256, 256),
  63089. constrainer (0)
  63090. #if JUCE_DEBUG
  63091. , hasBeenResized (false)
  63092. #endif
  63093. {
  63094. setBackgroundColour (backgroundColour_);
  63095. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63096. if (addToDesktop_)
  63097. Component::addToDesktop (getDesktopWindowStyleFlags());
  63098. }
  63099. ResizableWindow::~ResizableWindow()
  63100. {
  63101. // Don't delete or remove the resizer components yourself! They're managed by the
  63102. // ResizableWindow, and you should leave them alone! You may have deleted them
  63103. // accidentally by careless use of deleteAllChildren()..?
  63104. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  63105. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  63106. resizableCorner = 0;
  63107. resizableBorder = 0;
  63108. contentComponent.deleteAndZero();
  63109. // have you been adding your own components directly to this window..? tut tut tut.
  63110. // Read the instructions for using a ResizableWindow!
  63111. jassert (getNumChildComponents() == 0);
  63112. }
  63113. int ResizableWindow::getDesktopWindowStyleFlags() const
  63114. {
  63115. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63116. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63117. styleFlags |= ComponentPeer::windowIsResizable;
  63118. return styleFlags;
  63119. }
  63120. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63121. const bool deleteOldOne,
  63122. const bool resizeToFit)
  63123. {
  63124. resizeToFitContent = resizeToFit;
  63125. if (newContentComponent != static_cast <Component*> (contentComponent))
  63126. {
  63127. if (deleteOldOne)
  63128. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63129. // external deletion of the content comp)
  63130. else
  63131. removeChildComponent (contentComponent);
  63132. contentComponent = newContentComponent;
  63133. Component::addAndMakeVisible (contentComponent);
  63134. }
  63135. if (resizeToFit)
  63136. childBoundsChanged (contentComponent);
  63137. resized(); // must always be called to position the new content comp
  63138. }
  63139. void ResizableWindow::setContentComponentSize (int width, int height)
  63140. {
  63141. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63142. const BorderSize border (getContentComponentBorder());
  63143. setSize (width + border.getLeftAndRight(),
  63144. height + border.getTopAndBottom());
  63145. }
  63146. const BorderSize ResizableWindow::getBorderThickness()
  63147. {
  63148. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63149. }
  63150. const BorderSize ResizableWindow::getContentComponentBorder()
  63151. {
  63152. return getBorderThickness();
  63153. }
  63154. void ResizableWindow::moved()
  63155. {
  63156. updateLastPos();
  63157. }
  63158. void ResizableWindow::visibilityChanged()
  63159. {
  63160. TopLevelWindow::visibilityChanged();
  63161. updateLastPos();
  63162. }
  63163. void ResizableWindow::resized()
  63164. {
  63165. if (resizableBorder != 0)
  63166. {
  63167. #if JUCE_WINDOWS || JUCE_LINUX
  63168. // hide the resizable border if the OS already provides one..
  63169. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63170. #else
  63171. resizableBorder->setVisible (! isFullScreen());
  63172. #endif
  63173. resizableBorder->setBorderThickness (getBorderThickness());
  63174. resizableBorder->setSize (getWidth(), getHeight());
  63175. resizableBorder->toBack();
  63176. }
  63177. if (resizableCorner != 0)
  63178. {
  63179. #if JUCE_MAC
  63180. // hide the resizable border if the OS already provides one..
  63181. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63182. #else
  63183. resizableCorner->setVisible (! isFullScreen());
  63184. #endif
  63185. const int resizerSize = 18;
  63186. resizableCorner->setBounds (getWidth() - resizerSize,
  63187. getHeight() - resizerSize,
  63188. resizerSize, resizerSize);
  63189. }
  63190. if (contentComponent != 0)
  63191. contentComponent->setBoundsInset (getContentComponentBorder());
  63192. updateLastPos();
  63193. #if JUCE_DEBUG
  63194. hasBeenResized = true;
  63195. #endif
  63196. }
  63197. void ResizableWindow::childBoundsChanged (Component* child)
  63198. {
  63199. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63200. {
  63201. // not going to look very good if this component has a zero size..
  63202. jassert (child->getWidth() > 0);
  63203. jassert (child->getHeight() > 0);
  63204. const BorderSize borders (getContentComponentBorder());
  63205. setSize (child->getWidth() + borders.getLeftAndRight(),
  63206. child->getHeight() + borders.getTopAndBottom());
  63207. }
  63208. }
  63209. void ResizableWindow::activeWindowStatusChanged()
  63210. {
  63211. const BorderSize border (getContentComponentBorder());
  63212. Rectangle<int> area (getLocalBounds());
  63213. repaint (area.removeFromTop (border.getTop()));
  63214. repaint (area.removeFromLeft (border.getLeft()));
  63215. repaint (area.removeFromRight (border.getRight()));
  63216. repaint (area.removeFromBottom (border.getBottom()));
  63217. }
  63218. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63219. const bool useBottomRightCornerResizer)
  63220. {
  63221. if (shouldBeResizable)
  63222. {
  63223. if (useBottomRightCornerResizer)
  63224. {
  63225. resizableBorder = 0;
  63226. if (resizableCorner == 0)
  63227. {
  63228. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63229. resizableCorner->setAlwaysOnTop (true);
  63230. }
  63231. }
  63232. else
  63233. {
  63234. resizableCorner = 0;
  63235. if (resizableBorder == 0)
  63236. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63237. }
  63238. }
  63239. else
  63240. {
  63241. resizableCorner = 0;
  63242. resizableBorder = 0;
  63243. }
  63244. if (isUsingNativeTitleBar())
  63245. recreateDesktopWindow();
  63246. childBoundsChanged (contentComponent);
  63247. resized();
  63248. }
  63249. bool ResizableWindow::isResizable() const throw()
  63250. {
  63251. return resizableCorner != 0
  63252. || resizableBorder != 0;
  63253. }
  63254. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63255. const int newMinimumHeight,
  63256. const int newMaximumWidth,
  63257. const int newMaximumHeight) throw()
  63258. {
  63259. // if you've set up a custom constrainer then these settings won't have any effect..
  63260. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63261. if (constrainer == 0)
  63262. setConstrainer (&defaultConstrainer);
  63263. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63264. newMaximumWidth, newMaximumHeight);
  63265. setBoundsConstrained (getBounds());
  63266. }
  63267. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63268. {
  63269. if (constrainer != newConstrainer)
  63270. {
  63271. constrainer = newConstrainer;
  63272. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63273. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63274. resizableCorner = 0;
  63275. resizableBorder = 0;
  63276. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63277. ComponentPeer* const peer = getPeer();
  63278. if (peer != 0)
  63279. peer->setConstrainer (newConstrainer);
  63280. }
  63281. }
  63282. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63283. {
  63284. if (constrainer != 0)
  63285. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63286. else
  63287. setBounds (bounds);
  63288. }
  63289. void ResizableWindow::paint (Graphics& g)
  63290. {
  63291. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63292. getBorderThickness(), *this);
  63293. if (! isFullScreen())
  63294. {
  63295. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63296. getBorderThickness(), *this);
  63297. }
  63298. #if JUCE_DEBUG
  63299. /* If this fails, then you've probably written a subclass with a resized()
  63300. callback but forgotten to make it call its parent class's resized() method.
  63301. It's important when you override methods like resized(), moved(),
  63302. etc., that you make sure the base class methods also get called.
  63303. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63304. because your content should all be inside the content component - and it's the
  63305. content component's resized() method that you should be using to do your
  63306. layout.
  63307. */
  63308. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63309. #endif
  63310. }
  63311. void ResizableWindow::lookAndFeelChanged()
  63312. {
  63313. resized();
  63314. if (isOnDesktop())
  63315. {
  63316. Component::addToDesktop (getDesktopWindowStyleFlags());
  63317. ComponentPeer* const peer = getPeer();
  63318. if (peer != 0)
  63319. peer->setConstrainer (constrainer);
  63320. }
  63321. }
  63322. const Colour ResizableWindow::getBackgroundColour() const throw()
  63323. {
  63324. return findColour (backgroundColourId, false);
  63325. }
  63326. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63327. {
  63328. Colour backgroundColour (newColour);
  63329. if (! Desktop::canUseSemiTransparentWindows())
  63330. backgroundColour = newColour.withAlpha (1.0f);
  63331. setColour (backgroundColourId, backgroundColour);
  63332. setOpaque (backgroundColour.isOpaque());
  63333. repaint();
  63334. }
  63335. bool ResizableWindow::isFullScreen() const
  63336. {
  63337. if (isOnDesktop())
  63338. {
  63339. ComponentPeer* const peer = getPeer();
  63340. return peer != 0 && peer->isFullScreen();
  63341. }
  63342. return fullscreen;
  63343. }
  63344. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63345. {
  63346. if (shouldBeFullScreen != isFullScreen())
  63347. {
  63348. updateLastPos();
  63349. fullscreen = shouldBeFullScreen;
  63350. if (isOnDesktop())
  63351. {
  63352. ComponentPeer* const peer = getPeer();
  63353. if (peer != 0)
  63354. {
  63355. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63356. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63357. peer->setFullScreen (shouldBeFullScreen);
  63358. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63359. setBounds (lastPos);
  63360. }
  63361. else
  63362. {
  63363. jassertfalse;
  63364. }
  63365. }
  63366. else
  63367. {
  63368. if (shouldBeFullScreen)
  63369. setBounds (0, 0, getParentWidth(), getParentHeight());
  63370. else
  63371. setBounds (lastNonFullScreenPos);
  63372. }
  63373. resized();
  63374. }
  63375. }
  63376. bool ResizableWindow::isMinimised() const
  63377. {
  63378. ComponentPeer* const peer = getPeer();
  63379. return (peer != 0) && peer->isMinimised();
  63380. }
  63381. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63382. {
  63383. if (shouldMinimise != isMinimised())
  63384. {
  63385. ComponentPeer* const peer = getPeer();
  63386. if (peer != 0)
  63387. {
  63388. updateLastPos();
  63389. peer->setMinimised (shouldMinimise);
  63390. }
  63391. else
  63392. {
  63393. jassertfalse;
  63394. }
  63395. }
  63396. }
  63397. void ResizableWindow::updateLastPos()
  63398. {
  63399. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63400. {
  63401. lastNonFullScreenPos = getBounds();
  63402. }
  63403. }
  63404. void ResizableWindow::parentSizeChanged()
  63405. {
  63406. if (isFullScreen() && getParentComponent() != 0)
  63407. {
  63408. setBounds (0, 0, getParentWidth(), getParentHeight());
  63409. }
  63410. }
  63411. const String ResizableWindow::getWindowStateAsString()
  63412. {
  63413. updateLastPos();
  63414. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63415. }
  63416. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63417. {
  63418. StringArray tokens;
  63419. tokens.addTokens (s, false);
  63420. tokens.removeEmptyStrings();
  63421. tokens.trim();
  63422. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63423. const int firstCoord = fs ? 1 : 0;
  63424. if (tokens.size() != firstCoord + 4)
  63425. return false;
  63426. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63427. tokens[firstCoord + 1].getIntValue(),
  63428. tokens[firstCoord + 2].getIntValue(),
  63429. tokens[firstCoord + 3].getIntValue());
  63430. if (newPos.isEmpty())
  63431. return false;
  63432. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63433. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63434. if (peer != 0)
  63435. peer->getFrameSize().addTo (newPos);
  63436. if (! screen.contains (newPos))
  63437. {
  63438. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63439. jmin (newPos.getHeight(), screen.getHeight()));
  63440. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63441. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63442. }
  63443. if (peer != 0)
  63444. {
  63445. peer->getFrameSize().subtractFrom (newPos);
  63446. peer->setNonFullScreenBounds (newPos);
  63447. }
  63448. lastNonFullScreenPos = newPos;
  63449. setFullScreen (fs);
  63450. if (! fs)
  63451. setBoundsConstrained (newPos);
  63452. return true;
  63453. }
  63454. void ResizableWindow::mouseDown (const MouseEvent& e)
  63455. {
  63456. if (! isFullScreen())
  63457. dragger.startDraggingComponent (this, e);
  63458. }
  63459. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63460. {
  63461. if (! isFullScreen())
  63462. dragger.dragComponent (this, e, constrainer);
  63463. }
  63464. #if JUCE_DEBUG
  63465. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63466. {
  63467. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63468. manages its child components automatically, and if you add your own it'll cause
  63469. trouble. Instead, use setContentComponent() to give it a component which
  63470. will be automatically resized and kept in the right place - then you can add
  63471. subcomponents to the content comp. See the notes for the ResizableWindow class
  63472. for more info.
  63473. If you really know what you're doing and want to avoid this assertion, just call
  63474. Component::addChildComponent directly.
  63475. */
  63476. jassertfalse;
  63477. Component::addChildComponent (child, zOrder);
  63478. }
  63479. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63480. {
  63481. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63482. manages its child components automatically, and if you add your own it'll cause
  63483. trouble. Instead, use setContentComponent() to give it a component which
  63484. will be automatically resized and kept in the right place - then you can add
  63485. subcomponents to the content comp. See the notes for the ResizableWindow class
  63486. for more info.
  63487. If you really know what you're doing and want to avoid this assertion, just call
  63488. Component::addAndMakeVisible directly.
  63489. */
  63490. jassertfalse;
  63491. Component::addAndMakeVisible (child, zOrder);
  63492. }
  63493. #endif
  63494. END_JUCE_NAMESPACE
  63495. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63496. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63497. BEGIN_JUCE_NAMESPACE
  63498. SplashScreen::SplashScreen()
  63499. {
  63500. setOpaque (true);
  63501. }
  63502. SplashScreen::~SplashScreen()
  63503. {
  63504. }
  63505. void SplashScreen::show (const String& title,
  63506. const Image& backgroundImage_,
  63507. const int minimumTimeToDisplayFor,
  63508. const bool useDropShadow,
  63509. const bool removeOnMouseClick)
  63510. {
  63511. backgroundImage = backgroundImage_;
  63512. jassert (backgroundImage_.isValid());
  63513. if (backgroundImage_.isValid())
  63514. {
  63515. setOpaque (! backgroundImage_.hasAlphaChannel());
  63516. show (title,
  63517. backgroundImage_.getWidth(),
  63518. backgroundImage_.getHeight(),
  63519. minimumTimeToDisplayFor,
  63520. useDropShadow,
  63521. removeOnMouseClick);
  63522. }
  63523. }
  63524. void SplashScreen::show (const String& title,
  63525. const int width,
  63526. const int height,
  63527. const int minimumTimeToDisplayFor,
  63528. const bool useDropShadow,
  63529. const bool removeOnMouseClick)
  63530. {
  63531. setName (title);
  63532. setAlwaysOnTop (true);
  63533. setVisible (true);
  63534. centreWithSize (width, height);
  63535. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63536. toFront (false);
  63537. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63538. repaint();
  63539. originalClickCounter = removeOnMouseClick
  63540. ? Desktop::getMouseButtonClickCounter()
  63541. : std::numeric_limits<int>::max();
  63542. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63543. startTimer (50);
  63544. }
  63545. void SplashScreen::paint (Graphics& g)
  63546. {
  63547. g.setOpacity (1.0f);
  63548. g.drawImage (backgroundImage,
  63549. 0, 0, getWidth(), getHeight(),
  63550. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63551. }
  63552. void SplashScreen::timerCallback()
  63553. {
  63554. if (Time::getCurrentTime() > earliestTimeToDelete
  63555. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63556. {
  63557. delete this;
  63558. }
  63559. }
  63560. END_JUCE_NAMESPACE
  63561. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63562. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63563. BEGIN_JUCE_NAMESPACE
  63564. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63565. const bool hasProgressBar,
  63566. const bool hasCancelButton,
  63567. const int timeOutMsWhenCancelling_,
  63568. const String& cancelButtonText)
  63569. : Thread ("Juce Progress Window"),
  63570. progress (0.0),
  63571. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63572. {
  63573. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63574. .createAlertWindow (title, String::empty, cancelButtonText,
  63575. String::empty, String::empty,
  63576. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63577. if (hasProgressBar)
  63578. alertWindow->addProgressBarComponent (progress);
  63579. }
  63580. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63581. {
  63582. stopThread (timeOutMsWhenCancelling);
  63583. }
  63584. bool ThreadWithProgressWindow::runThread (const int priority)
  63585. {
  63586. startThread (priority);
  63587. startTimer (100);
  63588. {
  63589. const ScopedLock sl (messageLock);
  63590. alertWindow->setMessage (message);
  63591. }
  63592. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63593. stopThread (timeOutMsWhenCancelling);
  63594. alertWindow->setVisible (false);
  63595. return finishedNaturally;
  63596. }
  63597. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63598. {
  63599. progress = newProgress;
  63600. }
  63601. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63602. {
  63603. const ScopedLock sl (messageLock);
  63604. message = newStatusMessage;
  63605. }
  63606. void ThreadWithProgressWindow::timerCallback()
  63607. {
  63608. if (! isThreadRunning())
  63609. {
  63610. // thread has finished normally..
  63611. alertWindow->exitModalState (1);
  63612. alertWindow->setVisible (false);
  63613. }
  63614. else
  63615. {
  63616. const ScopedLock sl (messageLock);
  63617. alertWindow->setMessage (message);
  63618. }
  63619. }
  63620. END_JUCE_NAMESPACE
  63621. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63622. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63623. BEGIN_JUCE_NAMESPACE
  63624. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63625. const int millisecondsBeforeTipAppears_)
  63626. : Component ("tooltip"),
  63627. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63628. mouseClicks (0),
  63629. lastHideTime (0),
  63630. lastComponentUnderMouse (0),
  63631. changedCompsSinceShown (true)
  63632. {
  63633. if (Desktop::getInstance().getMainMouseSource().canHover())
  63634. startTimer (123);
  63635. setAlwaysOnTop (true);
  63636. setOpaque (true);
  63637. if (parentComponent != 0)
  63638. parentComponent->addChildComponent (this);
  63639. }
  63640. TooltipWindow::~TooltipWindow()
  63641. {
  63642. hide();
  63643. }
  63644. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63645. {
  63646. millisecondsBeforeTipAppears = newTimeMs;
  63647. }
  63648. void TooltipWindow::paint (Graphics& g)
  63649. {
  63650. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63651. }
  63652. void TooltipWindow::mouseEnter (const MouseEvent&)
  63653. {
  63654. hide();
  63655. }
  63656. void TooltipWindow::showFor (const String& tip)
  63657. {
  63658. jassert (tip.isNotEmpty());
  63659. if (tipShowing != tip)
  63660. repaint();
  63661. tipShowing = tip;
  63662. Point<int> mousePos (Desktop::getMousePosition());
  63663. if (getParentComponent() != 0)
  63664. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63665. int x, y, w, h;
  63666. getLookAndFeel().getTooltipSize (tip, w, h);
  63667. if (mousePos.getX() > getParentWidth() / 2)
  63668. x = mousePos.getX() - (w + 12);
  63669. else
  63670. x = mousePos.getX() + 24;
  63671. if (mousePos.getY() > getParentHeight() / 2)
  63672. y = mousePos.getY() - (h + 6);
  63673. else
  63674. y = mousePos.getY() + 6;
  63675. setBounds (x, y, w, h);
  63676. setVisible (true);
  63677. if (getParentComponent() == 0)
  63678. {
  63679. addToDesktop (ComponentPeer::windowHasDropShadow
  63680. | ComponentPeer::windowIsTemporary
  63681. | ComponentPeer::windowIgnoresKeyPresses);
  63682. }
  63683. toFront (false);
  63684. }
  63685. const String TooltipWindow::getTipFor (Component* const c)
  63686. {
  63687. if (c != 0
  63688. && Process::isForegroundProcess()
  63689. && ! Component::isMouseButtonDownAnywhere())
  63690. {
  63691. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63692. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63693. return ttc->getTooltip();
  63694. }
  63695. return String::empty;
  63696. }
  63697. void TooltipWindow::hide()
  63698. {
  63699. tipShowing = String::empty;
  63700. removeFromDesktop();
  63701. setVisible (false);
  63702. }
  63703. void TooltipWindow::timerCallback()
  63704. {
  63705. const unsigned int now = Time::getApproximateMillisecondCounter();
  63706. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63707. const String newTip (getTipFor (newComp));
  63708. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63709. lastComponentUnderMouse = newComp;
  63710. lastTipUnderMouse = newTip;
  63711. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63712. const bool mouseWasClicked = clickCount > mouseClicks;
  63713. mouseClicks = clickCount;
  63714. const Point<int> mousePos (Desktop::getMousePosition());
  63715. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63716. lastMousePos = mousePos;
  63717. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63718. lastCompChangeTime = now;
  63719. if (isVisible() || now < lastHideTime + 500)
  63720. {
  63721. // if a tip is currently visible (or has just disappeared), update to a new one
  63722. // immediately if needed..
  63723. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63724. {
  63725. if (isVisible())
  63726. {
  63727. lastHideTime = now;
  63728. hide();
  63729. }
  63730. }
  63731. else if (tipChanged)
  63732. {
  63733. showFor (newTip);
  63734. }
  63735. }
  63736. else
  63737. {
  63738. // if there isn't currently a tip, but one is needed, only let it
  63739. // appear after a timeout..
  63740. if (newTip.isNotEmpty()
  63741. && newTip != tipShowing
  63742. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63743. {
  63744. showFor (newTip);
  63745. }
  63746. }
  63747. }
  63748. END_JUCE_NAMESPACE
  63749. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63750. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63751. BEGIN_JUCE_NAMESPACE
  63752. /** Keeps track of the active top level window.
  63753. */
  63754. class TopLevelWindowManager : public Timer,
  63755. public DeletedAtShutdown
  63756. {
  63757. public:
  63758. TopLevelWindowManager()
  63759. : currentActive (0)
  63760. {
  63761. }
  63762. ~TopLevelWindowManager()
  63763. {
  63764. clearSingletonInstance();
  63765. }
  63766. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63767. void timerCallback()
  63768. {
  63769. startTimer (jmin (1731, getTimerInterval() * 2));
  63770. TopLevelWindow* active = 0;
  63771. if (Process::isForegroundProcess())
  63772. {
  63773. active = currentActive;
  63774. Component* const c = Component::getCurrentlyFocusedComponent();
  63775. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63776. if (tlw == 0 && c != 0)
  63777. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63778. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63779. if (tlw != 0)
  63780. active = tlw;
  63781. }
  63782. if (active != currentActive)
  63783. {
  63784. currentActive = active;
  63785. for (int i = windows.size(); --i >= 0;)
  63786. {
  63787. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63788. tlw->setWindowActive (isWindowActive (tlw));
  63789. i = jmin (i, windows.size() - 1);
  63790. }
  63791. Desktop::getInstance().triggerFocusCallback();
  63792. }
  63793. }
  63794. bool addWindow (TopLevelWindow* const w)
  63795. {
  63796. windows.add (w);
  63797. startTimer (10);
  63798. return isWindowActive (w);
  63799. }
  63800. void removeWindow (TopLevelWindow* const w)
  63801. {
  63802. startTimer (10);
  63803. if (currentActive == w)
  63804. currentActive = 0;
  63805. windows.removeValue (w);
  63806. if (windows.size() == 0)
  63807. deleteInstance();
  63808. }
  63809. Array <TopLevelWindow*> windows;
  63810. private:
  63811. TopLevelWindow* currentActive;
  63812. bool isWindowActive (TopLevelWindow* const tlw) const
  63813. {
  63814. return (tlw == currentActive
  63815. || tlw->isParentOf (currentActive)
  63816. || tlw->hasKeyboardFocus (true))
  63817. && tlw->isShowing();
  63818. }
  63819. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63820. };
  63821. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63822. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63823. {
  63824. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63825. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63826. }
  63827. TopLevelWindow::TopLevelWindow (const String& name,
  63828. const bool addToDesktop_)
  63829. : Component (name),
  63830. useDropShadow (true),
  63831. useNativeTitleBar (false),
  63832. windowIsActive_ (false)
  63833. {
  63834. setOpaque (true);
  63835. if (addToDesktop_)
  63836. Component::addToDesktop (getDesktopWindowStyleFlags());
  63837. else
  63838. setDropShadowEnabled (true);
  63839. setWantsKeyboardFocus (true);
  63840. setBroughtToFrontOnMouseClick (true);
  63841. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63842. }
  63843. TopLevelWindow::~TopLevelWindow()
  63844. {
  63845. shadower = 0;
  63846. TopLevelWindowManager::getInstance()->removeWindow (this);
  63847. }
  63848. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63849. {
  63850. if (hasKeyboardFocus (true))
  63851. TopLevelWindowManager::getInstance()->timerCallback();
  63852. else
  63853. TopLevelWindowManager::getInstance()->startTimer (10);
  63854. }
  63855. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63856. {
  63857. if (windowIsActive_ != isNowActive)
  63858. {
  63859. windowIsActive_ = isNowActive;
  63860. activeWindowStatusChanged();
  63861. }
  63862. }
  63863. void TopLevelWindow::activeWindowStatusChanged()
  63864. {
  63865. }
  63866. void TopLevelWindow::parentHierarchyChanged()
  63867. {
  63868. setDropShadowEnabled (useDropShadow);
  63869. }
  63870. void TopLevelWindow::visibilityChanged()
  63871. {
  63872. if (isShowing())
  63873. toFront (true);
  63874. }
  63875. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63876. {
  63877. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63878. if (useDropShadow)
  63879. styleFlags |= ComponentPeer::windowHasDropShadow;
  63880. if (useNativeTitleBar)
  63881. styleFlags |= ComponentPeer::windowHasTitleBar;
  63882. return styleFlags;
  63883. }
  63884. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63885. {
  63886. useDropShadow = useShadow;
  63887. if (isOnDesktop())
  63888. {
  63889. shadower = 0;
  63890. Component::addToDesktop (getDesktopWindowStyleFlags());
  63891. }
  63892. else
  63893. {
  63894. if (useShadow && isOpaque())
  63895. {
  63896. if (shadower == 0)
  63897. {
  63898. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63899. if (shadower != 0)
  63900. shadower->setOwner (this);
  63901. }
  63902. }
  63903. else
  63904. {
  63905. shadower = 0;
  63906. }
  63907. }
  63908. }
  63909. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63910. {
  63911. if (useNativeTitleBar != useNativeTitleBar_)
  63912. {
  63913. useNativeTitleBar = useNativeTitleBar_;
  63914. recreateDesktopWindow();
  63915. sendLookAndFeelChange();
  63916. }
  63917. }
  63918. void TopLevelWindow::recreateDesktopWindow()
  63919. {
  63920. if (isOnDesktop())
  63921. {
  63922. Component::addToDesktop (getDesktopWindowStyleFlags());
  63923. toFront (true);
  63924. }
  63925. }
  63926. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63927. {
  63928. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63929. because this class needs to make sure its layout corresponds with settings like whether
  63930. it's got a native title bar or not.
  63931. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63932. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63933. method, then add or remove whatever flags are necessary from this value before returning it.
  63934. */
  63935. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63936. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63937. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63938. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63939. sendLookAndFeelChange();
  63940. }
  63941. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63942. {
  63943. if (c == 0)
  63944. c = TopLevelWindow::getActiveTopLevelWindow();
  63945. if (c == 0)
  63946. {
  63947. centreWithSize (width, height);
  63948. }
  63949. else
  63950. {
  63951. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63952. Rectangle<int> parentArea (c->getParentMonitorArea());
  63953. if (getParentComponent() != 0)
  63954. {
  63955. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63956. parentArea = getParentComponent()->getLocalBounds();
  63957. }
  63958. parentArea.reduce (12, 12);
  63959. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63960. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63961. width, height);
  63962. }
  63963. }
  63964. int TopLevelWindow::getNumTopLevelWindows() throw()
  63965. {
  63966. return TopLevelWindowManager::getInstance()->windows.size();
  63967. }
  63968. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63969. {
  63970. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63971. }
  63972. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63973. {
  63974. TopLevelWindow* best = 0;
  63975. int bestNumTWLParents = -1;
  63976. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63977. {
  63978. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63979. if (tlw->isActiveWindow())
  63980. {
  63981. int numTWLParents = 0;
  63982. const Component* c = tlw->getParentComponent();
  63983. while (c != 0)
  63984. {
  63985. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63986. ++numTWLParents;
  63987. c = c->getParentComponent();
  63988. }
  63989. if (bestNumTWLParents < numTWLParents)
  63990. {
  63991. best = tlw;
  63992. bestNumTWLParents = numTWLParents;
  63993. }
  63994. }
  63995. }
  63996. return best;
  63997. }
  63998. END_JUCE_NAMESPACE
  63999. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64000. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64001. BEGIN_JUCE_NAMESPACE
  64002. namespace RelativeCoordinateHelpers
  64003. {
  64004. void skipComma (const juce_wchar* const s, int& i)
  64005. {
  64006. while (CharacterFunctions::isWhitespace (s[i]))
  64007. ++i;
  64008. if (s[i] == ',')
  64009. ++i;
  64010. }
  64011. }
  64012. const String RelativeCoordinate::Strings::parent ("parent");
  64013. const String RelativeCoordinate::Strings::left ("left");
  64014. const String RelativeCoordinate::Strings::right ("right");
  64015. const String RelativeCoordinate::Strings::top ("top");
  64016. const String RelativeCoordinate::Strings::bottom ("bottom");
  64017. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64018. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64019. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64020. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64021. RelativeCoordinate::RelativeCoordinate()
  64022. {
  64023. }
  64024. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64025. : term (term_)
  64026. {
  64027. }
  64028. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64029. : term (other.term)
  64030. {
  64031. }
  64032. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64033. {
  64034. term = other.term;
  64035. return *this;
  64036. }
  64037. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64038. : term (absoluteDistanceFromOrigin)
  64039. {
  64040. }
  64041. RelativeCoordinate::RelativeCoordinate (const String& s)
  64042. {
  64043. try
  64044. {
  64045. term = Expression (s);
  64046. }
  64047. catch (...)
  64048. {}
  64049. }
  64050. RelativeCoordinate::~RelativeCoordinate()
  64051. {
  64052. }
  64053. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64054. {
  64055. return term.toString() == other.term.toString();
  64056. }
  64057. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64058. {
  64059. return ! operator== (other);
  64060. }
  64061. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64062. {
  64063. try
  64064. {
  64065. if (context != 0)
  64066. return term.evaluate (*context);
  64067. else
  64068. return term.evaluate();
  64069. }
  64070. catch (...)
  64071. {}
  64072. return 0.0;
  64073. }
  64074. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64075. {
  64076. try
  64077. {
  64078. if (context != 0)
  64079. term.evaluate (*context);
  64080. else
  64081. term.evaluate();
  64082. }
  64083. catch (...)
  64084. {
  64085. return true;
  64086. }
  64087. return false;
  64088. }
  64089. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64090. {
  64091. try
  64092. {
  64093. if (context != 0)
  64094. {
  64095. term = term.adjustedToGiveNewResult (newPos, *context);
  64096. }
  64097. else
  64098. {
  64099. Expression::EvaluationContext defaultContext;
  64100. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64101. }
  64102. }
  64103. catch (...)
  64104. {}
  64105. }
  64106. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64107. {
  64108. try
  64109. {
  64110. return term.referencesSymbol (coordName, context);
  64111. }
  64112. catch (...)
  64113. {}
  64114. return false;
  64115. }
  64116. bool RelativeCoordinate::isDynamic() const
  64117. {
  64118. return term.usesAnySymbols();
  64119. }
  64120. const String RelativeCoordinate::toString() const
  64121. {
  64122. return term.toString();
  64123. }
  64124. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64125. {
  64126. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64127. if (term.referencesSymbol (oldName, 0))
  64128. term = term.withRenamedSymbol (oldName, newName);
  64129. }
  64130. RelativePoint::RelativePoint()
  64131. {
  64132. }
  64133. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64134. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64135. {
  64136. }
  64137. RelativePoint::RelativePoint (const float x_, const float y_)
  64138. : x (x_), y (y_)
  64139. {
  64140. }
  64141. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64142. : x (x_), y (y_)
  64143. {
  64144. }
  64145. RelativePoint::RelativePoint (const String& s)
  64146. {
  64147. int i = 0;
  64148. x = RelativeCoordinate (Expression::parse (s, i));
  64149. RelativeCoordinateHelpers::skipComma (s, i);
  64150. y = RelativeCoordinate (Expression::parse (s, i));
  64151. }
  64152. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64153. {
  64154. return x == other.x && y == other.y;
  64155. }
  64156. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64157. {
  64158. return ! operator== (other);
  64159. }
  64160. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64161. {
  64162. return Point<float> ((float) x.resolve (context),
  64163. (float) y.resolve (context));
  64164. }
  64165. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64166. {
  64167. x.moveToAbsolute (newPos.getX(), context);
  64168. y.moveToAbsolute (newPos.getY(), context);
  64169. }
  64170. const String RelativePoint::toString() const
  64171. {
  64172. return x.toString() + ", " + y.toString();
  64173. }
  64174. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64175. {
  64176. x.renameSymbolIfUsed (oldName, newName);
  64177. y.renameSymbolIfUsed (oldName, newName);
  64178. }
  64179. bool RelativePoint::isDynamic() const
  64180. {
  64181. return x.isDynamic() || y.isDynamic();
  64182. }
  64183. RelativeRectangle::RelativeRectangle()
  64184. {
  64185. }
  64186. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64187. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64188. : left (left_), right (right_), top (top_), bottom (bottom_)
  64189. {
  64190. }
  64191. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64192. : left (rect.getX()),
  64193. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64194. top (rect.getY()),
  64195. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64196. {
  64197. }
  64198. RelativeRectangle::RelativeRectangle (const String& s)
  64199. {
  64200. int i = 0;
  64201. left = RelativeCoordinate (Expression::parse (s, i));
  64202. RelativeCoordinateHelpers::skipComma (s, i);
  64203. top = RelativeCoordinate (Expression::parse (s, i));
  64204. RelativeCoordinateHelpers::skipComma (s, i);
  64205. right = RelativeCoordinate (Expression::parse (s, i));
  64206. RelativeCoordinateHelpers::skipComma (s, i);
  64207. bottom = RelativeCoordinate (Expression::parse (s, i));
  64208. }
  64209. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64210. {
  64211. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64212. }
  64213. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64214. {
  64215. return ! operator== (other);
  64216. }
  64217. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64218. {
  64219. const double l = left.resolve (context);
  64220. const double r = right.resolve (context);
  64221. const double t = top.resolve (context);
  64222. const double b = bottom.resolve (context);
  64223. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64224. }
  64225. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64226. {
  64227. left.moveToAbsolute (newPos.getX(), context);
  64228. right.moveToAbsolute (newPos.getRight(), context);
  64229. top.moveToAbsolute (newPos.getY(), context);
  64230. bottom.moveToAbsolute (newPos.getBottom(), context);
  64231. }
  64232. const String RelativeRectangle::toString() const
  64233. {
  64234. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64235. }
  64236. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64237. {
  64238. left.renameSymbolIfUsed (oldName, newName);
  64239. right.renameSymbolIfUsed (oldName, newName);
  64240. top.renameSymbolIfUsed (oldName, newName);
  64241. bottom.renameSymbolIfUsed (oldName, newName);
  64242. }
  64243. RelativePointPath::RelativePointPath()
  64244. : usesNonZeroWinding (true),
  64245. containsDynamicPoints (false)
  64246. {
  64247. }
  64248. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64249. : usesNonZeroWinding (true),
  64250. containsDynamicPoints (false)
  64251. {
  64252. ValueTree state (DrawablePath::valueTreeType);
  64253. other.writeTo (state, 0);
  64254. parse (state);
  64255. }
  64256. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64257. : usesNonZeroWinding (true),
  64258. containsDynamicPoints (false)
  64259. {
  64260. parse (drawable);
  64261. }
  64262. RelativePointPath::RelativePointPath (const Path& path)
  64263. {
  64264. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64265. Path::Iterator i (path);
  64266. while (i.next())
  64267. {
  64268. switch (i.elementType)
  64269. {
  64270. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64271. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64272. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64273. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64274. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64275. default: jassertfalse; break;
  64276. }
  64277. }
  64278. }
  64279. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64280. {
  64281. DrawablePath::ValueTreeWrapper wrapper (state);
  64282. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64283. ValueTree pathTree (wrapper.getPathState());
  64284. pathTree.removeAllChildren (undoManager);
  64285. for (int i = 0; i < elements.size(); ++i)
  64286. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64287. }
  64288. void RelativePointPath::parse (const ValueTree& state)
  64289. {
  64290. DrawablePath::ValueTreeWrapper wrapper (state);
  64291. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64292. RelativePoint points[3];
  64293. const ValueTree pathTree (wrapper.getPathState());
  64294. const int num = pathTree.getNumChildren();
  64295. for (int i = 0; i < num; ++i)
  64296. {
  64297. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64298. const int numCps = e.getNumControlPoints();
  64299. for (int j = 0; j < numCps; ++j)
  64300. {
  64301. points[j] = e.getControlPoint (j);
  64302. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64303. }
  64304. const Identifier type (e.getType());
  64305. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64306. elements.add (new StartSubPath (points[0]));
  64307. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64308. elements.add (new CloseSubPath());
  64309. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64310. elements.add (new LineTo (points[0]));
  64311. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64312. elements.add (new QuadraticTo (points[0], points[1]));
  64313. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64314. elements.add (new CubicTo (points[0], points[1], points[2]));
  64315. else
  64316. jassertfalse;
  64317. }
  64318. }
  64319. RelativePointPath::~RelativePointPath()
  64320. {
  64321. }
  64322. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64323. {
  64324. elements.swapWithArray (other.elements);
  64325. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64326. }
  64327. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64328. {
  64329. for (int i = 0; i < elements.size(); ++i)
  64330. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64331. }
  64332. bool RelativePointPath::containsAnyDynamicPoints() const
  64333. {
  64334. return containsDynamicPoints;
  64335. }
  64336. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64337. {
  64338. }
  64339. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64340. : ElementBase (startSubPathElement), startPos (pos)
  64341. {
  64342. }
  64343. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64344. {
  64345. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64346. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64347. return v;
  64348. }
  64349. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64350. {
  64351. path.startNewSubPath (startPos.resolve (coordFinder));
  64352. }
  64353. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64354. {
  64355. numPoints = 1;
  64356. return &startPos;
  64357. }
  64358. RelativePointPath::CloseSubPath::CloseSubPath()
  64359. : ElementBase (closeSubPathElement)
  64360. {
  64361. }
  64362. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64363. {
  64364. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64365. }
  64366. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64367. {
  64368. path.closeSubPath();
  64369. }
  64370. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64371. {
  64372. numPoints = 0;
  64373. return 0;
  64374. }
  64375. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64376. : ElementBase (lineToElement), endPoint (endPoint_)
  64377. {
  64378. }
  64379. const ValueTree RelativePointPath::LineTo::createTree() const
  64380. {
  64381. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64382. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64383. return v;
  64384. }
  64385. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64386. {
  64387. path.lineTo (endPoint.resolve (coordFinder));
  64388. }
  64389. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64390. {
  64391. numPoints = 1;
  64392. return &endPoint;
  64393. }
  64394. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64395. : ElementBase (quadraticToElement)
  64396. {
  64397. controlPoints[0] = controlPoint;
  64398. controlPoints[1] = endPoint;
  64399. }
  64400. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64401. {
  64402. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64403. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64404. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64405. return v;
  64406. }
  64407. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64408. {
  64409. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64410. controlPoints[1].resolve (coordFinder));
  64411. }
  64412. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64413. {
  64414. numPoints = 2;
  64415. return controlPoints;
  64416. }
  64417. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64418. : ElementBase (cubicToElement)
  64419. {
  64420. controlPoints[0] = controlPoint1;
  64421. controlPoints[1] = controlPoint2;
  64422. controlPoints[2] = endPoint;
  64423. }
  64424. const ValueTree RelativePointPath::CubicTo::createTree() const
  64425. {
  64426. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64427. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64428. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64429. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64430. return v;
  64431. }
  64432. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64433. {
  64434. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64435. controlPoints[1].resolve (coordFinder),
  64436. controlPoints[2].resolve (coordFinder));
  64437. }
  64438. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64439. {
  64440. numPoints = 3;
  64441. return controlPoints;
  64442. }
  64443. RelativeParallelogram::RelativeParallelogram()
  64444. {
  64445. }
  64446. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64447. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64448. {
  64449. }
  64450. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64451. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64452. {
  64453. }
  64454. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64455. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64456. {
  64457. }
  64458. RelativeParallelogram::~RelativeParallelogram()
  64459. {
  64460. }
  64461. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64462. {
  64463. points[0] = topLeft.resolve (coordFinder);
  64464. points[1] = topRight.resolve (coordFinder);
  64465. points[2] = bottomLeft.resolve (coordFinder);
  64466. }
  64467. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64468. {
  64469. resolveThreePoints (points, coordFinder);
  64470. points[3] = points[1] + (points[2] - points[0]);
  64471. }
  64472. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64473. {
  64474. Point<float> points[4];
  64475. resolveFourCorners (points, coordFinder);
  64476. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64477. }
  64478. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64479. {
  64480. Point<float> points[4];
  64481. resolveFourCorners (points, coordFinder);
  64482. path.startNewSubPath (points[0]);
  64483. path.lineTo (points[1]);
  64484. path.lineTo (points[3]);
  64485. path.lineTo (points[2]);
  64486. path.closeSubPath();
  64487. }
  64488. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64489. {
  64490. Point<float> corners[3];
  64491. resolveThreePoints (corners, coordFinder);
  64492. const Line<float> top (corners[0], corners[1]);
  64493. const Line<float> left (corners[0], corners[2]);
  64494. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64495. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64496. topRight.moveToAbsolute (newTopRight, coordFinder);
  64497. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64498. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64499. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64500. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64501. }
  64502. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64503. {
  64504. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64505. }
  64506. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64507. {
  64508. return ! operator== (other);
  64509. }
  64510. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64511. {
  64512. const Point<float> tr (corners[1] - corners[0]);
  64513. const Point<float> bl (corners[2] - corners[0]);
  64514. target -= corners[0];
  64515. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64516. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64517. }
  64518. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64519. {
  64520. return corners[0]
  64521. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64522. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64523. }
  64524. END_JUCE_NAMESPACE
  64525. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64526. #endif
  64527. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64528. /*** Start of inlined file: juce_Colour.cpp ***/
  64529. BEGIN_JUCE_NAMESPACE
  64530. namespace ColourHelpers
  64531. {
  64532. uint8 floatAlphaToInt (const float alpha) throw()
  64533. {
  64534. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64535. }
  64536. void convertHSBtoRGB (float h, float s, float v,
  64537. uint8& r, uint8& g, uint8& b) throw()
  64538. {
  64539. v = jlimit (0.0f, 1.0f, v);
  64540. v *= 255.0f;
  64541. const uint8 intV = (uint8) roundToInt (v);
  64542. if (s <= 0)
  64543. {
  64544. r = intV;
  64545. g = intV;
  64546. b = intV;
  64547. }
  64548. else
  64549. {
  64550. s = jmin (1.0f, s);
  64551. h = jlimit (0.0f, 1.0f, h);
  64552. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64553. const float f = h - std::floor (h);
  64554. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64555. const float y = v * (1.0f - s * f);
  64556. const float z = v * (1.0f - (s * (1.0f - f)));
  64557. if (h < 1.0f)
  64558. {
  64559. r = intV;
  64560. g = (uint8) roundToInt (z);
  64561. b = x;
  64562. }
  64563. else if (h < 2.0f)
  64564. {
  64565. r = (uint8) roundToInt (y);
  64566. g = intV;
  64567. b = x;
  64568. }
  64569. else if (h < 3.0f)
  64570. {
  64571. r = x;
  64572. g = intV;
  64573. b = (uint8) roundToInt (z);
  64574. }
  64575. else if (h < 4.0f)
  64576. {
  64577. r = x;
  64578. g = (uint8) roundToInt (y);
  64579. b = intV;
  64580. }
  64581. else if (h < 5.0f)
  64582. {
  64583. r = (uint8) roundToInt (z);
  64584. g = x;
  64585. b = intV;
  64586. }
  64587. else if (h < 6.0f)
  64588. {
  64589. r = intV;
  64590. g = x;
  64591. b = (uint8) roundToInt (y);
  64592. }
  64593. else
  64594. {
  64595. r = 0;
  64596. g = 0;
  64597. b = 0;
  64598. }
  64599. }
  64600. }
  64601. }
  64602. Colour::Colour() throw()
  64603. : argb (0)
  64604. {
  64605. }
  64606. Colour::Colour (const Colour& other) throw()
  64607. : argb (other.argb)
  64608. {
  64609. }
  64610. Colour& Colour::operator= (const Colour& other) throw()
  64611. {
  64612. argb = other.argb;
  64613. return *this;
  64614. }
  64615. bool Colour::operator== (const Colour& other) const throw()
  64616. {
  64617. return argb.getARGB() == other.argb.getARGB();
  64618. }
  64619. bool Colour::operator!= (const Colour& other) const throw()
  64620. {
  64621. return argb.getARGB() != other.argb.getARGB();
  64622. }
  64623. Colour::Colour (const uint32 argb_) throw()
  64624. : argb (argb_)
  64625. {
  64626. }
  64627. Colour::Colour (const uint8 red,
  64628. const uint8 green,
  64629. const uint8 blue) throw()
  64630. {
  64631. argb.setARGB (0xff, red, green, blue);
  64632. }
  64633. const Colour Colour::fromRGB (const uint8 red,
  64634. const uint8 green,
  64635. const uint8 blue) throw()
  64636. {
  64637. return Colour (red, green, blue);
  64638. }
  64639. Colour::Colour (const uint8 red,
  64640. const uint8 green,
  64641. const uint8 blue,
  64642. const uint8 alpha) throw()
  64643. {
  64644. argb.setARGB (alpha, red, green, blue);
  64645. }
  64646. const Colour Colour::fromRGBA (const uint8 red,
  64647. const uint8 green,
  64648. const uint8 blue,
  64649. const uint8 alpha) throw()
  64650. {
  64651. return Colour (red, green, blue, alpha);
  64652. }
  64653. Colour::Colour (const uint8 red,
  64654. const uint8 green,
  64655. const uint8 blue,
  64656. const float alpha) throw()
  64657. {
  64658. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64659. }
  64660. const Colour Colour::fromRGBAFloat (const uint8 red,
  64661. const uint8 green,
  64662. const uint8 blue,
  64663. const float alpha) throw()
  64664. {
  64665. return Colour (red, green, blue, alpha);
  64666. }
  64667. Colour::Colour (const float hue,
  64668. const float saturation,
  64669. const float brightness,
  64670. const float alpha) throw()
  64671. {
  64672. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64673. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64674. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64675. }
  64676. const Colour Colour::fromHSV (const float hue,
  64677. const float saturation,
  64678. const float brightness,
  64679. const float alpha) throw()
  64680. {
  64681. return Colour (hue, saturation, brightness, alpha);
  64682. }
  64683. Colour::Colour (const float hue,
  64684. const float saturation,
  64685. const float brightness,
  64686. const uint8 alpha) throw()
  64687. {
  64688. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64689. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64690. argb.setARGB (alpha, r, g, b);
  64691. }
  64692. Colour::~Colour() throw()
  64693. {
  64694. }
  64695. const PixelARGB Colour::getPixelARGB() const throw()
  64696. {
  64697. PixelARGB p (argb);
  64698. p.premultiply();
  64699. return p;
  64700. }
  64701. uint32 Colour::getARGB() const throw()
  64702. {
  64703. return argb.getARGB();
  64704. }
  64705. bool Colour::isTransparent() const throw()
  64706. {
  64707. return getAlpha() == 0;
  64708. }
  64709. bool Colour::isOpaque() const throw()
  64710. {
  64711. return getAlpha() == 0xff;
  64712. }
  64713. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64714. {
  64715. PixelARGB newCol (argb);
  64716. newCol.setAlpha (newAlpha);
  64717. return Colour (newCol.getARGB());
  64718. }
  64719. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64720. {
  64721. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64722. PixelARGB newCol (argb);
  64723. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64724. return Colour (newCol.getARGB());
  64725. }
  64726. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64727. {
  64728. jassert (alphaMultiplier >= 0);
  64729. PixelARGB newCol (argb);
  64730. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64731. return Colour (newCol.getARGB());
  64732. }
  64733. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64734. {
  64735. const int destAlpha = getAlpha();
  64736. if (destAlpha > 0)
  64737. {
  64738. const int invA = 0xff - (int) src.getAlpha();
  64739. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64740. if (resA > 0)
  64741. {
  64742. const int da = (invA * destAlpha) / resA;
  64743. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64744. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64745. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64746. (uint8) resA);
  64747. }
  64748. return *this;
  64749. }
  64750. else
  64751. {
  64752. return src;
  64753. }
  64754. }
  64755. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64756. {
  64757. if (proportionOfOther <= 0)
  64758. return *this;
  64759. if (proportionOfOther >= 1.0f)
  64760. return other;
  64761. PixelARGB c1 (getPixelARGB());
  64762. const PixelARGB c2 (other.getPixelARGB());
  64763. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64764. c1.unpremultiply();
  64765. return Colour (c1.getARGB());
  64766. }
  64767. float Colour::getFloatRed() const throw()
  64768. {
  64769. return getRed() / 255.0f;
  64770. }
  64771. float Colour::getFloatGreen() const throw()
  64772. {
  64773. return getGreen() / 255.0f;
  64774. }
  64775. float Colour::getFloatBlue() const throw()
  64776. {
  64777. return getBlue() / 255.0f;
  64778. }
  64779. float Colour::getFloatAlpha() const throw()
  64780. {
  64781. return getAlpha() / 255.0f;
  64782. }
  64783. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64784. {
  64785. const int r = getRed();
  64786. const int g = getGreen();
  64787. const int b = getBlue();
  64788. const int hi = jmax (r, g, b);
  64789. const int lo = jmin (r, g, b);
  64790. if (hi != 0)
  64791. {
  64792. s = (hi - lo) / (float) hi;
  64793. if (s != 0)
  64794. {
  64795. const float invDiff = 1.0f / (hi - lo);
  64796. const float red = (hi - r) * invDiff;
  64797. const float green = (hi - g) * invDiff;
  64798. const float blue = (hi - b) * invDiff;
  64799. if (r == hi)
  64800. h = blue - green;
  64801. else if (g == hi)
  64802. h = 2.0f + red - blue;
  64803. else
  64804. h = 4.0f + green - red;
  64805. h *= 1.0f / 6.0f;
  64806. if (h < 0)
  64807. ++h;
  64808. }
  64809. else
  64810. {
  64811. h = 0;
  64812. }
  64813. }
  64814. else
  64815. {
  64816. s = 0;
  64817. h = 0;
  64818. }
  64819. v = hi / 255.0f;
  64820. }
  64821. float Colour::getHue() const throw()
  64822. {
  64823. float h, s, b;
  64824. getHSB (h, s, b);
  64825. return h;
  64826. }
  64827. const Colour Colour::withHue (const float hue) const throw()
  64828. {
  64829. float h, s, b;
  64830. getHSB (h, s, b);
  64831. return Colour (hue, s, b, getAlpha());
  64832. }
  64833. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64834. {
  64835. float h, s, b;
  64836. getHSB (h, s, b);
  64837. h += amountToRotate;
  64838. h -= std::floor (h);
  64839. return Colour (h, s, b, getAlpha());
  64840. }
  64841. float Colour::getSaturation() const throw()
  64842. {
  64843. float h, s, b;
  64844. getHSB (h, s, b);
  64845. return s;
  64846. }
  64847. const Colour Colour::withSaturation (const float saturation) const throw()
  64848. {
  64849. float h, s, b;
  64850. getHSB (h, s, b);
  64851. return Colour (h, saturation, b, getAlpha());
  64852. }
  64853. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64854. {
  64855. float h, s, b;
  64856. getHSB (h, s, b);
  64857. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64858. }
  64859. float Colour::getBrightness() const throw()
  64860. {
  64861. float h, s, b;
  64862. getHSB (h, s, b);
  64863. return b;
  64864. }
  64865. const Colour Colour::withBrightness (const float brightness) const throw()
  64866. {
  64867. float h, s, b;
  64868. getHSB (h, s, b);
  64869. return Colour (h, s, brightness, getAlpha());
  64870. }
  64871. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64872. {
  64873. float h, s, b;
  64874. getHSB (h, s, b);
  64875. b *= amount;
  64876. if (b > 1.0f)
  64877. b = 1.0f;
  64878. return Colour (h, s, b, getAlpha());
  64879. }
  64880. const Colour Colour::brighter (float amount) const throw()
  64881. {
  64882. amount = 1.0f / (1.0f + amount);
  64883. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64884. (uint8) (255 - (amount * (255 - getGreen()))),
  64885. (uint8) (255 - (amount * (255 - getBlue()))),
  64886. getAlpha());
  64887. }
  64888. const Colour Colour::darker (float amount) const throw()
  64889. {
  64890. amount = 1.0f / (1.0f + amount);
  64891. return Colour ((uint8) (amount * getRed()),
  64892. (uint8) (amount * getGreen()),
  64893. (uint8) (amount * getBlue()),
  64894. getAlpha());
  64895. }
  64896. const Colour Colour::greyLevel (const float brightness) throw()
  64897. {
  64898. const uint8 level
  64899. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64900. return Colour (level, level, level);
  64901. }
  64902. const Colour Colour::contrasting (const float amount) const throw()
  64903. {
  64904. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64905. ? Colours::black
  64906. : Colours::white).withAlpha (amount));
  64907. }
  64908. const Colour Colour::contrasting (const Colour& colour1,
  64909. const Colour& colour2) throw()
  64910. {
  64911. const float b1 = colour1.getBrightness();
  64912. const float b2 = colour2.getBrightness();
  64913. float best = 0.0f;
  64914. float bestDist = 0.0f;
  64915. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64916. {
  64917. const float d1 = std::abs (i - b1);
  64918. const float d2 = std::abs (i - b2);
  64919. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64920. if (dist > bestDist)
  64921. {
  64922. best = i;
  64923. bestDist = dist;
  64924. }
  64925. }
  64926. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64927. .withBrightness (best);
  64928. }
  64929. const String Colour::toString() const
  64930. {
  64931. return String::toHexString ((int) argb.getARGB());
  64932. }
  64933. const Colour Colour::fromString (const String& encodedColourString)
  64934. {
  64935. return Colour ((uint32) encodedColourString.getHexValue32());
  64936. }
  64937. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64938. {
  64939. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64940. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64941. .toUpperCase();
  64942. }
  64943. END_JUCE_NAMESPACE
  64944. /*** End of inlined file: juce_Colour.cpp ***/
  64945. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64946. BEGIN_JUCE_NAMESPACE
  64947. ColourGradient::ColourGradient() throw()
  64948. {
  64949. #if JUCE_DEBUG
  64950. point1.setX (987654.0f);
  64951. #endif
  64952. }
  64953. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64954. const Colour& colour2, const float x2_, const float y2_,
  64955. const bool isRadial_)
  64956. : point1 (x1_, y1_),
  64957. point2 (x2_, y2_),
  64958. isRadial (isRadial_)
  64959. {
  64960. colours.add (ColourPoint (0.0, colour1));
  64961. colours.add (ColourPoint (1.0, colour2));
  64962. }
  64963. ColourGradient::~ColourGradient()
  64964. {
  64965. }
  64966. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64967. {
  64968. return point1 == other.point1 && point2 == other.point2
  64969. && isRadial == other.isRadial
  64970. && colours == other.colours;
  64971. }
  64972. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64973. {
  64974. return ! operator== (other);
  64975. }
  64976. void ColourGradient::clearColours()
  64977. {
  64978. colours.clear();
  64979. }
  64980. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64981. {
  64982. // must be within the two end-points
  64983. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64984. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64985. int i;
  64986. for (i = 0; i < colours.size(); ++i)
  64987. if (colours.getReference(i).position > pos)
  64988. break;
  64989. colours.insert (i, ColourPoint (pos, colour));
  64990. return i;
  64991. }
  64992. void ColourGradient::removeColour (int index)
  64993. {
  64994. jassert (index > 0 && index < colours.size() - 1);
  64995. colours.remove (index);
  64996. }
  64997. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64998. {
  64999. for (int i = 0; i < colours.size(); ++i)
  65000. {
  65001. Colour& c = colours.getReference(i).colour;
  65002. c = c.withMultipliedAlpha (multiplier);
  65003. }
  65004. }
  65005. int ColourGradient::getNumColours() const throw()
  65006. {
  65007. return colours.size();
  65008. }
  65009. double ColourGradient::getColourPosition (const int index) const throw()
  65010. {
  65011. if (isPositiveAndBelow (index, colours.size()))
  65012. return colours.getReference (index).position;
  65013. return 0;
  65014. }
  65015. const Colour ColourGradient::getColour (const int index) const throw()
  65016. {
  65017. if (isPositiveAndBelow (index, colours.size()))
  65018. return colours.getReference (index).colour;
  65019. return Colour();
  65020. }
  65021. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65022. {
  65023. if (isPositiveAndBelow (index, colours.size()))
  65024. colours.getReference (index).colour = newColour;
  65025. }
  65026. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65027. {
  65028. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65029. if (position <= 0 || colours.size() <= 1)
  65030. return colours.getReference(0).colour;
  65031. int i = colours.size() - 1;
  65032. while (position < colours.getReference(i).position)
  65033. --i;
  65034. const ColourPoint& p1 = colours.getReference (i);
  65035. if (i >= colours.size() - 1)
  65036. return p1.colour;
  65037. const ColourPoint& p2 = colours.getReference (i + 1);
  65038. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65039. }
  65040. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65041. {
  65042. #if JUCE_DEBUG
  65043. // trying to use the object without setting its co-ordinates? Have a careful read of
  65044. // the comments for the constructors.
  65045. jassert (point1.getX() != 987654.0f);
  65046. #endif
  65047. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65048. 3 * (int) point1.transformedBy (transform)
  65049. .getDistanceFrom (point2.transformedBy (transform)));
  65050. lookupTable.malloc (numEntries);
  65051. if (colours.size() >= 2)
  65052. {
  65053. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65054. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65055. int index = 0;
  65056. for (int j = 1; j < colours.size(); ++j)
  65057. {
  65058. const ColourPoint& p = colours.getReference (j);
  65059. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65060. const PixelARGB pix2 (p.colour.getPixelARGB());
  65061. for (int i = 0; i < numToDo; ++i)
  65062. {
  65063. jassert (index >= 0 && index < numEntries);
  65064. lookupTable[index] = pix1;
  65065. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65066. ++index;
  65067. }
  65068. pix1 = pix2;
  65069. }
  65070. while (index < numEntries)
  65071. lookupTable [index++] = pix1;
  65072. }
  65073. else
  65074. {
  65075. jassertfalse; // no colours specified!
  65076. }
  65077. return numEntries;
  65078. }
  65079. bool ColourGradient::isOpaque() const throw()
  65080. {
  65081. for (int i = 0; i < colours.size(); ++i)
  65082. if (! colours.getReference(i).colour.isOpaque())
  65083. return false;
  65084. return true;
  65085. }
  65086. bool ColourGradient::isInvisible() const throw()
  65087. {
  65088. for (int i = 0; i < colours.size(); ++i)
  65089. if (! colours.getReference(i).colour.isTransparent())
  65090. return false;
  65091. return true;
  65092. }
  65093. END_JUCE_NAMESPACE
  65094. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65095. /*** Start of inlined file: juce_Colours.cpp ***/
  65096. BEGIN_JUCE_NAMESPACE
  65097. const Colour Colours::transparentBlack (0);
  65098. const Colour Colours::transparentWhite (0x00ffffff);
  65099. const Colour Colours::aliceblue (0xfff0f8ff);
  65100. const Colour Colours::antiquewhite (0xfffaebd7);
  65101. const Colour Colours::aqua (0xff00ffff);
  65102. const Colour Colours::aquamarine (0xff7fffd4);
  65103. const Colour Colours::azure (0xfff0ffff);
  65104. const Colour Colours::beige (0xfff5f5dc);
  65105. const Colour Colours::bisque (0xffffe4c4);
  65106. const Colour Colours::black (0xff000000);
  65107. const Colour Colours::blanchedalmond (0xffffebcd);
  65108. const Colour Colours::blue (0xff0000ff);
  65109. const Colour Colours::blueviolet (0xff8a2be2);
  65110. const Colour Colours::brown (0xffa52a2a);
  65111. const Colour Colours::burlywood (0xffdeb887);
  65112. const Colour Colours::cadetblue (0xff5f9ea0);
  65113. const Colour Colours::chartreuse (0xff7fff00);
  65114. const Colour Colours::chocolate (0xffd2691e);
  65115. const Colour Colours::coral (0xffff7f50);
  65116. const Colour Colours::cornflowerblue (0xff6495ed);
  65117. const Colour Colours::cornsilk (0xfffff8dc);
  65118. const Colour Colours::crimson (0xffdc143c);
  65119. const Colour Colours::cyan (0xff00ffff);
  65120. const Colour Colours::darkblue (0xff00008b);
  65121. const Colour Colours::darkcyan (0xff008b8b);
  65122. const Colour Colours::darkgoldenrod (0xffb8860b);
  65123. const Colour Colours::darkgrey (0xff555555);
  65124. const Colour Colours::darkgreen (0xff006400);
  65125. const Colour Colours::darkkhaki (0xffbdb76b);
  65126. const Colour Colours::darkmagenta (0xff8b008b);
  65127. const Colour Colours::darkolivegreen (0xff556b2f);
  65128. const Colour Colours::darkorange (0xffff8c00);
  65129. const Colour Colours::darkorchid (0xff9932cc);
  65130. const Colour Colours::darkred (0xff8b0000);
  65131. const Colour Colours::darksalmon (0xffe9967a);
  65132. const Colour Colours::darkseagreen (0xff8fbc8f);
  65133. const Colour Colours::darkslateblue (0xff483d8b);
  65134. const Colour Colours::darkslategrey (0xff2f4f4f);
  65135. const Colour Colours::darkturquoise (0xff00ced1);
  65136. const Colour Colours::darkviolet (0xff9400d3);
  65137. const Colour Colours::deeppink (0xffff1493);
  65138. const Colour Colours::deepskyblue (0xff00bfff);
  65139. const Colour Colours::dimgrey (0xff696969);
  65140. const Colour Colours::dodgerblue (0xff1e90ff);
  65141. const Colour Colours::firebrick (0xffb22222);
  65142. const Colour Colours::floralwhite (0xfffffaf0);
  65143. const Colour Colours::forestgreen (0xff228b22);
  65144. const Colour Colours::fuchsia (0xffff00ff);
  65145. const Colour Colours::gainsboro (0xffdcdcdc);
  65146. const Colour Colours::gold (0xffffd700);
  65147. const Colour Colours::goldenrod (0xffdaa520);
  65148. const Colour Colours::grey (0xff808080);
  65149. const Colour Colours::green (0xff008000);
  65150. const Colour Colours::greenyellow (0xffadff2f);
  65151. const Colour Colours::honeydew (0xfff0fff0);
  65152. const Colour Colours::hotpink (0xffff69b4);
  65153. const Colour Colours::indianred (0xffcd5c5c);
  65154. const Colour Colours::indigo (0xff4b0082);
  65155. const Colour Colours::ivory (0xfffffff0);
  65156. const Colour Colours::khaki (0xfff0e68c);
  65157. const Colour Colours::lavender (0xffe6e6fa);
  65158. const Colour Colours::lavenderblush (0xfffff0f5);
  65159. const Colour Colours::lemonchiffon (0xfffffacd);
  65160. const Colour Colours::lightblue (0xffadd8e6);
  65161. const Colour Colours::lightcoral (0xfff08080);
  65162. const Colour Colours::lightcyan (0xffe0ffff);
  65163. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65164. const Colour Colours::lightgreen (0xff90ee90);
  65165. const Colour Colours::lightgrey (0xffd3d3d3);
  65166. const Colour Colours::lightpink (0xffffb6c1);
  65167. const Colour Colours::lightsalmon (0xffffa07a);
  65168. const Colour Colours::lightseagreen (0xff20b2aa);
  65169. const Colour Colours::lightskyblue (0xff87cefa);
  65170. const Colour Colours::lightslategrey (0xff778899);
  65171. const Colour Colours::lightsteelblue (0xffb0c4de);
  65172. const Colour Colours::lightyellow (0xffffffe0);
  65173. const Colour Colours::lime (0xff00ff00);
  65174. const Colour Colours::limegreen (0xff32cd32);
  65175. const Colour Colours::linen (0xfffaf0e6);
  65176. const Colour Colours::magenta (0xffff00ff);
  65177. const Colour Colours::maroon (0xff800000);
  65178. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65179. const Colour Colours::mediumblue (0xff0000cd);
  65180. const Colour Colours::mediumorchid (0xffba55d3);
  65181. const Colour Colours::mediumpurple (0xff9370db);
  65182. const Colour Colours::mediumseagreen (0xff3cb371);
  65183. const Colour Colours::mediumslateblue (0xff7b68ee);
  65184. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65185. const Colour Colours::mediumturquoise (0xff48d1cc);
  65186. const Colour Colours::mediumvioletred (0xffc71585);
  65187. const Colour Colours::midnightblue (0xff191970);
  65188. const Colour Colours::mintcream (0xfff5fffa);
  65189. const Colour Colours::mistyrose (0xffffe4e1);
  65190. const Colour Colours::navajowhite (0xffffdead);
  65191. const Colour Colours::navy (0xff000080);
  65192. const Colour Colours::oldlace (0xfffdf5e6);
  65193. const Colour Colours::olive (0xff808000);
  65194. const Colour Colours::olivedrab (0xff6b8e23);
  65195. const Colour Colours::orange (0xffffa500);
  65196. const Colour Colours::orangered (0xffff4500);
  65197. const Colour Colours::orchid (0xffda70d6);
  65198. const Colour Colours::palegoldenrod (0xffeee8aa);
  65199. const Colour Colours::palegreen (0xff98fb98);
  65200. const Colour Colours::paleturquoise (0xffafeeee);
  65201. const Colour Colours::palevioletred (0xffdb7093);
  65202. const Colour Colours::papayawhip (0xffffefd5);
  65203. const Colour Colours::peachpuff (0xffffdab9);
  65204. const Colour Colours::peru (0xffcd853f);
  65205. const Colour Colours::pink (0xffffc0cb);
  65206. const Colour Colours::plum (0xffdda0dd);
  65207. const Colour Colours::powderblue (0xffb0e0e6);
  65208. const Colour Colours::purple (0xff800080);
  65209. const Colour Colours::red (0xffff0000);
  65210. const Colour Colours::rosybrown (0xffbc8f8f);
  65211. const Colour Colours::royalblue (0xff4169e1);
  65212. const Colour Colours::saddlebrown (0xff8b4513);
  65213. const Colour Colours::salmon (0xfffa8072);
  65214. const Colour Colours::sandybrown (0xfff4a460);
  65215. const Colour Colours::seagreen (0xff2e8b57);
  65216. const Colour Colours::seashell (0xfffff5ee);
  65217. const Colour Colours::sienna (0xffa0522d);
  65218. const Colour Colours::silver (0xffc0c0c0);
  65219. const Colour Colours::skyblue (0xff87ceeb);
  65220. const Colour Colours::slateblue (0xff6a5acd);
  65221. const Colour Colours::slategrey (0xff708090);
  65222. const Colour Colours::snow (0xfffffafa);
  65223. const Colour Colours::springgreen (0xff00ff7f);
  65224. const Colour Colours::steelblue (0xff4682b4);
  65225. const Colour Colours::tan (0xffd2b48c);
  65226. const Colour Colours::teal (0xff008080);
  65227. const Colour Colours::thistle (0xffd8bfd8);
  65228. const Colour Colours::tomato (0xffff6347);
  65229. const Colour Colours::turquoise (0xff40e0d0);
  65230. const Colour Colours::violet (0xffee82ee);
  65231. const Colour Colours::wheat (0xfff5deb3);
  65232. const Colour Colours::white (0xffffffff);
  65233. const Colour Colours::whitesmoke (0xfff5f5f5);
  65234. const Colour Colours::yellow (0xffffff00);
  65235. const Colour Colours::yellowgreen (0xff9acd32);
  65236. const Colour Colours::findColourForName (const String& colourName,
  65237. const Colour& defaultColour)
  65238. {
  65239. static const int presets[] =
  65240. {
  65241. // (first value is the string's hashcode, second is ARGB)
  65242. 0x05978fff, 0xff000000, /* black */
  65243. 0x06bdcc29, 0xffffffff, /* white */
  65244. 0x002e305a, 0xff0000ff, /* blue */
  65245. 0x00308adf, 0xff808080, /* grey */
  65246. 0x05e0cf03, 0xff008000, /* green */
  65247. 0x0001b891, 0xffff0000, /* red */
  65248. 0xd43c6474, 0xffffff00, /* yellow */
  65249. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65250. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65251. 0x002dcebc, 0xff00ffff, /* aqua */
  65252. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65253. 0x0590228f, 0xfff0ffff, /* azure */
  65254. 0x05947fe4, 0xfff5f5dc, /* beige */
  65255. 0xad388e35, 0xffffe4c4, /* bisque */
  65256. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65257. 0x39129959, 0xff8a2be2, /* blueviolet */
  65258. 0x059a8136, 0xffa52a2a, /* brown */
  65259. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65260. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65261. 0x6b748956, 0xff7fff00, /* chartreuse */
  65262. 0x2903623c, 0xffd2691e, /* chocolate */
  65263. 0x05a74431, 0xffff7f50, /* coral */
  65264. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65265. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65266. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65267. 0x002ed323, 0xff00ffff, /* cyan */
  65268. 0x67cc74d0, 0xff00008b, /* darkblue */
  65269. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65270. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65271. 0x67cecf55, 0xff555555, /* darkgrey */
  65272. 0x920b194d, 0xff006400, /* darkgreen */
  65273. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65274. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65275. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65276. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65277. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65278. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65279. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65280. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65281. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65282. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65283. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65284. 0xc8769375, 0xff9400d3, /* darkviolet */
  65285. 0x25832862, 0xffff1493, /* deeppink */
  65286. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65287. 0x634c8b67, 0xff696969, /* dimgrey */
  65288. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65289. 0xef19e3cb, 0xffb22222, /* firebrick */
  65290. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65291. 0xd086fd06, 0xff228b22, /* forestgreen */
  65292. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65293. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65294. 0x00308060, 0xffffd700, /* gold */
  65295. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65296. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65297. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65298. 0x41892743, 0xffff69b4, /* hotpink */
  65299. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65300. 0xb969fed2, 0xff4b0082, /* indigo */
  65301. 0x05fef6a9, 0xfffffff0, /* ivory */
  65302. 0x06149302, 0xfff0e68c, /* khaki */
  65303. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65304. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65305. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65306. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65307. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65308. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65309. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65310. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65311. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65312. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65313. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65314. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65315. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65316. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65317. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65318. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65319. 0x0032afd5, 0xff00ff00, /* lime */
  65320. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65321. 0x06234efa, 0xfffaf0e6, /* linen */
  65322. 0x316858a9, 0xffff00ff, /* magenta */
  65323. 0xbf8ca470, 0xff800000, /* maroon */
  65324. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65325. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65326. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65327. 0x07556b71, 0xff9370db, /* mediumpurple */
  65328. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65329. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65330. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65331. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65332. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65333. 0x168eb32a, 0xff191970, /* midnightblue */
  65334. 0x4306b960, 0xfff5fffa, /* mintcream */
  65335. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65336. 0xe97218a6, 0xffffdead, /* navajowhite */
  65337. 0x00337bb6, 0xff000080, /* navy */
  65338. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65339. 0x064ee1db, 0xff808000, /* olive */
  65340. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65341. 0xc3de262e, 0xffffa500, /* orange */
  65342. 0x58bebba3, 0xffff4500, /* orangered */
  65343. 0xc3def8a3, 0xffda70d6, /* orchid */
  65344. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65345. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65346. 0x74022737, 0xffafeeee, /* paleturquoise */
  65347. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65348. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65349. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65350. 0x003472f8, 0xffcd853f, /* peru */
  65351. 0x00348176, 0xffffc0cb, /* pink */
  65352. 0x00348d94, 0xffdda0dd, /* plum */
  65353. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65354. 0xc5c507bc, 0xff800080, /* purple */
  65355. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65356. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65357. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65358. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65359. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65360. 0x34636c14, 0xff2e8b57, /* seagreen */
  65361. 0x3507fb41, 0xfffff5ee, /* seashell */
  65362. 0xca348772, 0xffa0522d, /* sienna */
  65363. 0xca37d30d, 0xffc0c0c0, /* silver */
  65364. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65365. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65366. 0x44ab37f8, 0xff708090, /* slategrey */
  65367. 0x0035f183, 0xfffffafa, /* snow */
  65368. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65369. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65370. 0x0001bfa1, 0xffd2b48c, /* tan */
  65371. 0x0036425c, 0xff008080, /* teal */
  65372. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65373. 0xcc41600a, 0xffff6347, /* tomato */
  65374. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65375. 0xcf57947f, 0xffee82ee, /* violet */
  65376. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65377. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65378. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65379. };
  65380. const int hash = colourName.trim().toLowerCase().hashCode();
  65381. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65382. if (presets [i] == hash)
  65383. return Colour (presets [i + 1]);
  65384. return defaultColour;
  65385. }
  65386. END_JUCE_NAMESPACE
  65387. /*** End of inlined file: juce_Colours.cpp ***/
  65388. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65389. BEGIN_JUCE_NAMESPACE
  65390. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65391. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65392. const Path& path, const AffineTransform& transform)
  65393. : bounds (bounds_),
  65394. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65395. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65396. needToCheckEmptinesss (true)
  65397. {
  65398. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65399. int* t = table;
  65400. for (int i = bounds.getHeight(); --i >= 0;)
  65401. {
  65402. *t = 0;
  65403. t += lineStrideElements;
  65404. }
  65405. const int topLimit = bounds.getY() << 8;
  65406. const int heightLimit = bounds.getHeight() << 8;
  65407. const int leftLimit = bounds.getX() << 8;
  65408. const int rightLimit = bounds.getRight() << 8;
  65409. PathFlatteningIterator iter (path, transform);
  65410. while (iter.next())
  65411. {
  65412. int y1 = roundToInt (iter.y1 * 256.0f);
  65413. int y2 = roundToInt (iter.y2 * 256.0f);
  65414. if (y1 != y2)
  65415. {
  65416. y1 -= topLimit;
  65417. y2 -= topLimit;
  65418. const int startY = y1;
  65419. int direction = -1;
  65420. if (y1 > y2)
  65421. {
  65422. swapVariables (y1, y2);
  65423. direction = 1;
  65424. }
  65425. if (y1 < 0)
  65426. y1 = 0;
  65427. if (y2 > heightLimit)
  65428. y2 = heightLimit;
  65429. if (y1 < y2)
  65430. {
  65431. const double startX = 256.0f * iter.x1;
  65432. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65433. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65434. do
  65435. {
  65436. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65437. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65438. if (x < leftLimit)
  65439. x = leftLimit;
  65440. else if (x >= rightLimit)
  65441. x = rightLimit - 1;
  65442. addEdgePoint (x, y1 >> 8, direction * step);
  65443. y1 += step;
  65444. }
  65445. while (y1 < y2);
  65446. }
  65447. }
  65448. }
  65449. sanitiseLevels (path.isUsingNonZeroWinding());
  65450. }
  65451. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65452. : bounds (rectangleToAdd),
  65453. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65454. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65455. needToCheckEmptinesss (true)
  65456. {
  65457. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65458. table[0] = 0;
  65459. const int x1 = rectangleToAdd.getX() << 8;
  65460. const int x2 = rectangleToAdd.getRight() << 8;
  65461. int* t = table;
  65462. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65463. {
  65464. t[0] = 2;
  65465. t[1] = x1;
  65466. t[2] = 255;
  65467. t[3] = x2;
  65468. t[4] = 0;
  65469. t += lineStrideElements;
  65470. }
  65471. }
  65472. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65473. : bounds (rectanglesToAdd.getBounds()),
  65474. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65475. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65476. needToCheckEmptinesss (true)
  65477. {
  65478. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65479. int* t = table;
  65480. for (int i = bounds.getHeight(); --i >= 0;)
  65481. {
  65482. *t = 0;
  65483. t += lineStrideElements;
  65484. }
  65485. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65486. {
  65487. const Rectangle<int>* const r = iter.getRectangle();
  65488. const int x1 = r->getX() << 8;
  65489. const int x2 = r->getRight() << 8;
  65490. int y = r->getY() - bounds.getY();
  65491. for (int j = r->getHeight(); --j >= 0;)
  65492. {
  65493. addEdgePoint (x1, y, 255);
  65494. addEdgePoint (x2, y, -255);
  65495. ++y;
  65496. }
  65497. }
  65498. sanitiseLevels (true);
  65499. }
  65500. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65501. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65502. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65503. 2 + (int) rectangleToAdd.getWidth(),
  65504. 2 + (int) rectangleToAdd.getHeight())),
  65505. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65506. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65507. needToCheckEmptinesss (true)
  65508. {
  65509. jassert (! rectangleToAdd.isEmpty());
  65510. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65511. table[0] = 0;
  65512. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65513. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65514. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65515. jassert (y1 < 256);
  65516. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65517. if (x2 <= x1 || y2 <= y1)
  65518. {
  65519. bounds.setHeight (0);
  65520. return;
  65521. }
  65522. int lineY = 0;
  65523. int* t = table;
  65524. if ((y1 >> 8) == (y2 >> 8))
  65525. {
  65526. t[0] = 2;
  65527. t[1] = x1;
  65528. t[2] = y2 - y1;
  65529. t[3] = x2;
  65530. t[4] = 0;
  65531. ++lineY;
  65532. t += lineStrideElements;
  65533. }
  65534. else
  65535. {
  65536. t[0] = 2;
  65537. t[1] = x1;
  65538. t[2] = 255 - (y1 & 255);
  65539. t[3] = x2;
  65540. t[4] = 0;
  65541. ++lineY;
  65542. t += lineStrideElements;
  65543. while (lineY < (y2 >> 8))
  65544. {
  65545. t[0] = 2;
  65546. t[1] = x1;
  65547. t[2] = 255;
  65548. t[3] = x2;
  65549. t[4] = 0;
  65550. ++lineY;
  65551. t += lineStrideElements;
  65552. }
  65553. jassert (lineY < bounds.getHeight());
  65554. t[0] = 2;
  65555. t[1] = x1;
  65556. t[2] = y2 & 255;
  65557. t[3] = x2;
  65558. t[4] = 0;
  65559. ++lineY;
  65560. t += lineStrideElements;
  65561. }
  65562. while (lineY < bounds.getHeight())
  65563. {
  65564. t[0] = 0;
  65565. t += lineStrideElements;
  65566. ++lineY;
  65567. }
  65568. }
  65569. EdgeTable::EdgeTable (const EdgeTable& other)
  65570. {
  65571. operator= (other);
  65572. }
  65573. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65574. {
  65575. bounds = other.bounds;
  65576. maxEdgesPerLine = other.maxEdgesPerLine;
  65577. lineStrideElements = other.lineStrideElements;
  65578. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65579. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65580. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65581. return *this;
  65582. }
  65583. EdgeTable::~EdgeTable()
  65584. {
  65585. }
  65586. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65587. {
  65588. while (--numLines >= 0)
  65589. {
  65590. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65591. src += srcLineStride;
  65592. dest += destLineStride;
  65593. }
  65594. }
  65595. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65596. {
  65597. // Convert the table from relative windings to absolute levels..
  65598. int* lineStart = table;
  65599. for (int i = bounds.getHeight(); --i >= 0;)
  65600. {
  65601. int* line = lineStart;
  65602. lineStart += lineStrideElements;
  65603. int num = *line;
  65604. if (num == 0)
  65605. continue;
  65606. int level = 0;
  65607. if (useNonZeroWinding)
  65608. {
  65609. while (--num > 0)
  65610. {
  65611. line += 2;
  65612. level += *line;
  65613. int corrected = abs (level);
  65614. if (corrected >> 8)
  65615. corrected = 255;
  65616. *line = corrected;
  65617. }
  65618. }
  65619. else
  65620. {
  65621. while (--num > 0)
  65622. {
  65623. line += 2;
  65624. level += *line;
  65625. int corrected = abs (level);
  65626. if (corrected >> 8)
  65627. {
  65628. corrected &= 511;
  65629. if (corrected >> 8)
  65630. corrected = 511 - corrected;
  65631. }
  65632. *line = corrected;
  65633. }
  65634. }
  65635. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65636. }
  65637. }
  65638. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65639. {
  65640. if (newNumEdgesPerLine != maxEdgesPerLine)
  65641. {
  65642. maxEdgesPerLine = newNumEdgesPerLine;
  65643. jassert (bounds.getHeight() > 0);
  65644. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65645. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65646. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65647. table.swapWith (newTable);
  65648. lineStrideElements = newLineStrideElements;
  65649. }
  65650. }
  65651. void EdgeTable::optimiseTable()
  65652. {
  65653. int maxLineElements = 0;
  65654. for (int i = bounds.getHeight(); --i >= 0;)
  65655. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65656. remapTableForNumEdges (maxLineElements);
  65657. }
  65658. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65659. {
  65660. jassert (y >= 0 && y < bounds.getHeight());
  65661. int* line = table + lineStrideElements * y;
  65662. const int numPoints = line[0];
  65663. int n = numPoints << 1;
  65664. if (n > 0)
  65665. {
  65666. while (n > 0)
  65667. {
  65668. const int cx = line [n - 1];
  65669. if (cx <= x)
  65670. {
  65671. if (cx == x)
  65672. {
  65673. line [n] += winding;
  65674. return;
  65675. }
  65676. break;
  65677. }
  65678. n -= 2;
  65679. }
  65680. if (numPoints >= maxEdgesPerLine)
  65681. {
  65682. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65683. jassert (numPoints < maxEdgesPerLine);
  65684. line = table + lineStrideElements * y;
  65685. }
  65686. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65687. }
  65688. line [n + 1] = x;
  65689. line [n + 2] = winding;
  65690. line[0]++;
  65691. }
  65692. void EdgeTable::translate (float dx, const int dy) throw()
  65693. {
  65694. bounds.translate ((int) std::floor (dx), dy);
  65695. int* lineStart = table;
  65696. const int intDx = (int) (dx * 256.0f);
  65697. for (int i = bounds.getHeight(); --i >= 0;)
  65698. {
  65699. int* line = lineStart;
  65700. lineStart += lineStrideElements;
  65701. int num = *line++;
  65702. while (--num >= 0)
  65703. {
  65704. *line += intDx;
  65705. line += 2;
  65706. }
  65707. }
  65708. }
  65709. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65710. {
  65711. jassert (y >= 0 && y < bounds.getHeight());
  65712. int* dest = table + lineStrideElements * y;
  65713. if (dest[0] == 0)
  65714. return;
  65715. int otherNumPoints = *otherLine;
  65716. if (otherNumPoints == 0)
  65717. {
  65718. *dest = 0;
  65719. return;
  65720. }
  65721. const int right = bounds.getRight() << 8;
  65722. // optimise for the common case where our line lies entirely within a
  65723. // single pair of points, as happens when clipping to a simple rect.
  65724. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65725. {
  65726. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65727. return;
  65728. }
  65729. ++otherLine;
  65730. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65731. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65732. memcpy (temp, dest, lineSizeBytes);
  65733. const int* src1 = temp;
  65734. int srcNum1 = *src1++;
  65735. int x1 = *src1++;
  65736. const int* src2 = otherLine;
  65737. int srcNum2 = otherNumPoints;
  65738. int x2 = *src2++;
  65739. int destIndex = 0, destTotal = 0;
  65740. int level1 = 0, level2 = 0;
  65741. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65742. while (srcNum1 > 0 && srcNum2 > 0)
  65743. {
  65744. int nextX;
  65745. if (x1 < x2)
  65746. {
  65747. nextX = x1;
  65748. level1 = *src1++;
  65749. x1 = *src1++;
  65750. --srcNum1;
  65751. }
  65752. else if (x1 == x2)
  65753. {
  65754. nextX = x1;
  65755. level1 = *src1++;
  65756. level2 = *src2++;
  65757. x1 = *src1++;
  65758. x2 = *src2++;
  65759. --srcNum1;
  65760. --srcNum2;
  65761. }
  65762. else
  65763. {
  65764. nextX = x2;
  65765. level2 = *src2++;
  65766. x2 = *src2++;
  65767. --srcNum2;
  65768. }
  65769. if (nextX > lastX)
  65770. {
  65771. if (nextX >= right)
  65772. break;
  65773. lastX = nextX;
  65774. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65775. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65776. if (nextLevel != lastLevel)
  65777. {
  65778. if (destTotal >= maxEdgesPerLine)
  65779. {
  65780. dest[0] = destTotal;
  65781. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65782. dest = table + lineStrideElements * y;
  65783. }
  65784. ++destTotal;
  65785. lastLevel = nextLevel;
  65786. dest[++destIndex] = nextX;
  65787. dest[++destIndex] = nextLevel;
  65788. }
  65789. }
  65790. }
  65791. if (lastLevel > 0)
  65792. {
  65793. if (destTotal >= maxEdgesPerLine)
  65794. {
  65795. dest[0] = destTotal;
  65796. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65797. dest = table + lineStrideElements * y;
  65798. }
  65799. ++destTotal;
  65800. dest[++destIndex] = right;
  65801. dest[++destIndex] = 0;
  65802. }
  65803. dest[0] = destTotal;
  65804. #if JUCE_DEBUG
  65805. int last = std::numeric_limits<int>::min();
  65806. for (int i = 0; i < dest[0]; ++i)
  65807. {
  65808. jassert (dest[i * 2 + 1] > last);
  65809. last = dest[i * 2 + 1];
  65810. }
  65811. jassert (dest [dest[0] * 2] == 0);
  65812. #endif
  65813. }
  65814. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65815. {
  65816. int* lastItem = dest + (dest[0] * 2 - 1);
  65817. if (x2 < lastItem[0])
  65818. {
  65819. if (x2 <= dest[1])
  65820. {
  65821. dest[0] = 0;
  65822. return;
  65823. }
  65824. while (x2 < lastItem[-2])
  65825. {
  65826. --(dest[0]);
  65827. lastItem -= 2;
  65828. }
  65829. lastItem[0] = x2;
  65830. lastItem[1] = 0;
  65831. }
  65832. if (x1 > dest[1])
  65833. {
  65834. while (lastItem[0] > x1)
  65835. lastItem -= 2;
  65836. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65837. if (itemsRemoved > 0)
  65838. {
  65839. dest[0] -= itemsRemoved;
  65840. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65841. }
  65842. dest[1] = x1;
  65843. }
  65844. }
  65845. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65846. {
  65847. const Rectangle<int> clipped (r.getIntersection (bounds));
  65848. if (clipped.isEmpty())
  65849. {
  65850. needToCheckEmptinesss = false;
  65851. bounds.setHeight (0);
  65852. }
  65853. else
  65854. {
  65855. const int top = clipped.getY() - bounds.getY();
  65856. const int bottom = clipped.getBottom() - bounds.getY();
  65857. if (bottom < bounds.getHeight())
  65858. bounds.setHeight (bottom);
  65859. if (clipped.getRight() < bounds.getRight())
  65860. bounds.setRight (clipped.getRight());
  65861. for (int i = top; --i >= 0;)
  65862. table [lineStrideElements * i] = 0;
  65863. if (clipped.getX() > bounds.getX())
  65864. {
  65865. const int x1 = clipped.getX() << 8;
  65866. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65867. int* line = table + lineStrideElements * top;
  65868. for (int i = bottom - top; --i >= 0;)
  65869. {
  65870. if (line[0] != 0)
  65871. clipEdgeTableLineToRange (line, x1, x2);
  65872. line += lineStrideElements;
  65873. }
  65874. }
  65875. needToCheckEmptinesss = true;
  65876. }
  65877. }
  65878. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65879. {
  65880. const Rectangle<int> clipped (r.getIntersection (bounds));
  65881. if (! clipped.isEmpty())
  65882. {
  65883. const int top = clipped.getY() - bounds.getY();
  65884. const int bottom = clipped.getBottom() - bounds.getY();
  65885. //XXX optimise here by shortening the table if it fills top or bottom
  65886. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65887. clipped.getX() << 8, 0,
  65888. clipped.getRight() << 8, 255,
  65889. std::numeric_limits<int>::max(), 0 };
  65890. for (int i = top; i < bottom; ++i)
  65891. intersectWithEdgeTableLine (i, rectLine);
  65892. needToCheckEmptinesss = true;
  65893. }
  65894. }
  65895. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65896. {
  65897. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65898. if (clipped.isEmpty())
  65899. {
  65900. needToCheckEmptinesss = false;
  65901. bounds.setHeight (0);
  65902. }
  65903. else
  65904. {
  65905. const int top = clipped.getY() - bounds.getY();
  65906. const int bottom = clipped.getBottom() - bounds.getY();
  65907. if (bottom < bounds.getHeight())
  65908. bounds.setHeight (bottom);
  65909. if (clipped.getRight() < bounds.getRight())
  65910. bounds.setRight (clipped.getRight());
  65911. int i = 0;
  65912. for (i = top; --i >= 0;)
  65913. table [lineStrideElements * i] = 0;
  65914. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65915. for (i = top; i < bottom; ++i)
  65916. {
  65917. intersectWithEdgeTableLine (i, otherLine);
  65918. otherLine += other.lineStrideElements;
  65919. }
  65920. needToCheckEmptinesss = true;
  65921. }
  65922. }
  65923. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  65924. {
  65925. y -= bounds.getY();
  65926. if (y < 0 || y >= bounds.getHeight())
  65927. return;
  65928. needToCheckEmptinesss = true;
  65929. if (numPixels <= 0)
  65930. {
  65931. table [lineStrideElements * y] = 0;
  65932. return;
  65933. }
  65934. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  65935. int destIndex = 0, lastLevel = 0;
  65936. while (--numPixels >= 0)
  65937. {
  65938. const int alpha = *mask;
  65939. mask += maskStride;
  65940. if (alpha != lastLevel)
  65941. {
  65942. tempLine[++destIndex] = (x << 8);
  65943. tempLine[++destIndex] = alpha;
  65944. lastLevel = alpha;
  65945. }
  65946. ++x;
  65947. }
  65948. if (lastLevel > 0)
  65949. {
  65950. tempLine[++destIndex] = (x << 8);
  65951. tempLine[++destIndex] = 0;
  65952. }
  65953. tempLine[0] = destIndex >> 1;
  65954. intersectWithEdgeTableLine (y, tempLine);
  65955. }
  65956. bool EdgeTable::isEmpty() throw()
  65957. {
  65958. if (needToCheckEmptinesss)
  65959. {
  65960. needToCheckEmptinesss = false;
  65961. int* t = table;
  65962. for (int i = bounds.getHeight(); --i >= 0;)
  65963. {
  65964. if (t[0] > 1)
  65965. return false;
  65966. t += lineStrideElements;
  65967. }
  65968. bounds.setHeight (0);
  65969. }
  65970. return bounds.getHeight() == 0;
  65971. }
  65972. END_JUCE_NAMESPACE
  65973. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65974. /*** Start of inlined file: juce_FillType.cpp ***/
  65975. BEGIN_JUCE_NAMESPACE
  65976. FillType::FillType() throw()
  65977. : colour (0xff000000), image (0)
  65978. {
  65979. }
  65980. FillType::FillType (const Colour& colour_) throw()
  65981. : colour (colour_), image (0)
  65982. {
  65983. }
  65984. FillType::FillType (const ColourGradient& gradient_)
  65985. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65986. {
  65987. }
  65988. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65989. : colour (0xff000000), image (image_), transform (transform_)
  65990. {
  65991. }
  65992. FillType::FillType (const FillType& other)
  65993. : colour (other.colour),
  65994. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65995. image (other.image), transform (other.transform)
  65996. {
  65997. }
  65998. FillType& FillType::operator= (const FillType& other)
  65999. {
  66000. if (this != &other)
  66001. {
  66002. colour = other.colour;
  66003. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66004. image = other.image;
  66005. transform = other.transform;
  66006. }
  66007. return *this;
  66008. }
  66009. FillType::~FillType() throw()
  66010. {
  66011. }
  66012. bool FillType::operator== (const FillType& other) const
  66013. {
  66014. return colour == other.colour && image == other.image
  66015. && transform == other.transform
  66016. && (gradient == other.gradient
  66017. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66018. }
  66019. bool FillType::operator!= (const FillType& other) const
  66020. {
  66021. return ! operator== (other);
  66022. }
  66023. void FillType::setColour (const Colour& newColour) throw()
  66024. {
  66025. gradient = 0;
  66026. image = Image::null;
  66027. colour = newColour;
  66028. }
  66029. void FillType::setGradient (const ColourGradient& newGradient)
  66030. {
  66031. if (gradient != 0)
  66032. {
  66033. *gradient = newGradient;
  66034. }
  66035. else
  66036. {
  66037. image = Image::null;
  66038. gradient = new ColourGradient (newGradient);
  66039. colour = Colours::black;
  66040. }
  66041. }
  66042. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66043. {
  66044. gradient = 0;
  66045. image = image_;
  66046. transform = transform_;
  66047. colour = Colours::black;
  66048. }
  66049. void FillType::setOpacity (const float newOpacity) throw()
  66050. {
  66051. colour = colour.withAlpha (newOpacity);
  66052. }
  66053. bool FillType::isInvisible() const throw()
  66054. {
  66055. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66056. }
  66057. END_JUCE_NAMESPACE
  66058. /*** End of inlined file: juce_FillType.cpp ***/
  66059. /*** Start of inlined file: juce_Graphics.cpp ***/
  66060. BEGIN_JUCE_NAMESPACE
  66061. namespace
  66062. {
  66063. template <typename Type>
  66064. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66065. {
  66066. const int maxVal = 0x3fffffff;
  66067. return (int) x >= -maxVal && (int) x <= maxVal
  66068. && (int) y >= -maxVal && (int) y <= maxVal
  66069. && (int) w >= -maxVal && (int) w <= maxVal
  66070. && (int) h >= -maxVal && (int) h <= maxVal;
  66071. }
  66072. }
  66073. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66074. {
  66075. }
  66076. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66077. {
  66078. }
  66079. Graphics::Graphics (const Image& imageToDrawOnto)
  66080. : context (imageToDrawOnto.createLowLevelContext()),
  66081. contextToDelete (context),
  66082. saveStatePending (false)
  66083. {
  66084. }
  66085. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66086. : context (internalContext),
  66087. saveStatePending (false)
  66088. {
  66089. }
  66090. Graphics::~Graphics()
  66091. {
  66092. }
  66093. void Graphics::resetToDefaultState()
  66094. {
  66095. saveStateIfPending();
  66096. context->setFill (FillType());
  66097. context->setFont (Font());
  66098. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66099. }
  66100. bool Graphics::isVectorDevice() const
  66101. {
  66102. return context->isVectorDevice();
  66103. }
  66104. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66105. {
  66106. saveStateIfPending();
  66107. return context->clipToRectangle (area);
  66108. }
  66109. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66110. {
  66111. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66112. }
  66113. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66114. {
  66115. saveStateIfPending();
  66116. return context->clipToRectangleList (clipRegion);
  66117. }
  66118. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66119. {
  66120. saveStateIfPending();
  66121. context->clipToPath (path, transform);
  66122. return ! context->isClipEmpty();
  66123. }
  66124. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66125. {
  66126. saveStateIfPending();
  66127. context->clipToImageAlpha (image, transform);
  66128. return ! context->isClipEmpty();
  66129. }
  66130. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66131. {
  66132. saveStateIfPending();
  66133. context->excludeClipRectangle (rectangleToExclude);
  66134. }
  66135. bool Graphics::isClipEmpty() const
  66136. {
  66137. return context->isClipEmpty();
  66138. }
  66139. const Rectangle<int> Graphics::getClipBounds() const
  66140. {
  66141. return context->getClipBounds();
  66142. }
  66143. void Graphics::saveState()
  66144. {
  66145. saveStateIfPending();
  66146. saveStatePending = true;
  66147. }
  66148. void Graphics::restoreState()
  66149. {
  66150. if (saveStatePending)
  66151. saveStatePending = false;
  66152. else
  66153. context->restoreState();
  66154. }
  66155. void Graphics::saveStateIfPending()
  66156. {
  66157. if (saveStatePending)
  66158. {
  66159. saveStatePending = false;
  66160. context->saveState();
  66161. }
  66162. }
  66163. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66164. {
  66165. saveStateIfPending();
  66166. context->setOrigin (newOriginX, newOriginY);
  66167. }
  66168. void Graphics::addTransform (const AffineTransform& transform)
  66169. {
  66170. saveStateIfPending();
  66171. context->addTransform (transform);
  66172. }
  66173. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66174. {
  66175. return context->clipRegionIntersects (area);
  66176. }
  66177. void Graphics::beginTransparencyLayer (float layerOpacity)
  66178. {
  66179. saveStateIfPending();
  66180. context->beginTransparencyLayer (layerOpacity);
  66181. }
  66182. void Graphics::endTransparencyLayer()
  66183. {
  66184. context->endTransparencyLayer();
  66185. }
  66186. void Graphics::setColour (const Colour& newColour)
  66187. {
  66188. saveStateIfPending();
  66189. context->setFill (newColour);
  66190. }
  66191. void Graphics::setOpacity (const float newOpacity)
  66192. {
  66193. saveStateIfPending();
  66194. context->setOpacity (newOpacity);
  66195. }
  66196. void Graphics::setGradientFill (const ColourGradient& gradient)
  66197. {
  66198. setFillType (gradient);
  66199. }
  66200. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66201. {
  66202. saveStateIfPending();
  66203. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66204. context->setOpacity (opacity);
  66205. }
  66206. void Graphics::setFillType (const FillType& newFill)
  66207. {
  66208. saveStateIfPending();
  66209. context->setFill (newFill);
  66210. }
  66211. void Graphics::setFont (const Font& newFont)
  66212. {
  66213. saveStateIfPending();
  66214. context->setFont (newFont);
  66215. }
  66216. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66217. {
  66218. saveStateIfPending();
  66219. Font f (context->getFont());
  66220. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66221. context->setFont (f);
  66222. }
  66223. const Font Graphics::getCurrentFont() const
  66224. {
  66225. return context->getFont();
  66226. }
  66227. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66228. {
  66229. if (text.isNotEmpty()
  66230. && startX < context->getClipBounds().getRight())
  66231. {
  66232. GlyphArrangement arr;
  66233. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66234. arr.draw (*this);
  66235. }
  66236. }
  66237. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66238. {
  66239. if (text.isNotEmpty())
  66240. {
  66241. GlyphArrangement arr;
  66242. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66243. arr.draw (*this, transform);
  66244. }
  66245. }
  66246. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66247. {
  66248. if (text.isNotEmpty()
  66249. && startX < context->getClipBounds().getRight())
  66250. {
  66251. GlyphArrangement arr;
  66252. arr.addJustifiedText (context->getFont(), text,
  66253. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66254. Justification::left);
  66255. arr.draw (*this);
  66256. }
  66257. }
  66258. void Graphics::drawText (const String& text,
  66259. const int x, const int y, const int width, const int height,
  66260. const Justification& justificationType,
  66261. const bool useEllipsesIfTooBig) const
  66262. {
  66263. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66264. {
  66265. GlyphArrangement arr;
  66266. arr.addCurtailedLineOfText (context->getFont(), text,
  66267. 0.0f, 0.0f, (float) width,
  66268. useEllipsesIfTooBig);
  66269. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66270. (float) x, (float) y, (float) width, (float) height,
  66271. justificationType);
  66272. arr.draw (*this);
  66273. }
  66274. }
  66275. void Graphics::drawFittedText (const String& text,
  66276. const int x, const int y, const int width, const int height,
  66277. const Justification& justification,
  66278. const int maximumNumberOfLines,
  66279. const float minimumHorizontalScale) const
  66280. {
  66281. if (text.isNotEmpty()
  66282. && width > 0 && height > 0
  66283. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66284. {
  66285. GlyphArrangement arr;
  66286. arr.addFittedText (context->getFont(), text,
  66287. (float) x, (float) y, (float) width, (float) height,
  66288. justification,
  66289. maximumNumberOfLines,
  66290. minimumHorizontalScale);
  66291. arr.draw (*this);
  66292. }
  66293. }
  66294. void Graphics::fillRect (int x, int y, int width, int height) const
  66295. {
  66296. // passing in a silly number can cause maths problems in rendering!
  66297. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66298. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66299. }
  66300. void Graphics::fillRect (const Rectangle<int>& r) const
  66301. {
  66302. context->fillRect (r, false);
  66303. }
  66304. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66305. {
  66306. // passing in a silly number can cause maths problems in rendering!
  66307. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66308. Path p;
  66309. p.addRectangle (x, y, width, height);
  66310. fillPath (p);
  66311. }
  66312. void Graphics::setPixel (int x, int y) const
  66313. {
  66314. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66315. }
  66316. void Graphics::fillAll() const
  66317. {
  66318. fillRect (context->getClipBounds());
  66319. }
  66320. void Graphics::fillAll (const Colour& colourToUse) const
  66321. {
  66322. if (! colourToUse.isTransparent())
  66323. {
  66324. const Rectangle<int> clip (context->getClipBounds());
  66325. context->saveState();
  66326. context->setFill (colourToUse);
  66327. context->fillRect (clip, false);
  66328. context->restoreState();
  66329. }
  66330. }
  66331. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66332. {
  66333. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66334. context->fillPath (path, transform);
  66335. }
  66336. void Graphics::strokePath (const Path& path,
  66337. const PathStrokeType& strokeType,
  66338. const AffineTransform& transform) const
  66339. {
  66340. Path stroke;
  66341. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66342. fillPath (stroke);
  66343. }
  66344. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66345. const int lineThickness) const
  66346. {
  66347. // passing in a silly number can cause maths problems in rendering!
  66348. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66349. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66350. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66351. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66352. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66353. }
  66354. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66355. {
  66356. // passing in a silly number can cause maths problems in rendering!
  66357. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66358. Path p;
  66359. p.addRectangle (x, y, width, lineThickness);
  66360. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66361. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66362. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66363. fillPath (p);
  66364. }
  66365. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66366. {
  66367. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66368. }
  66369. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66370. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66371. const bool useGradient, const bool sharpEdgeOnOutside) const
  66372. {
  66373. // passing in a silly number can cause maths problems in rendering!
  66374. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66375. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66376. {
  66377. context->saveState();
  66378. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66379. const float ramp = oldOpacity / bevelThickness;
  66380. for (int i = bevelThickness; --i >= 0;)
  66381. {
  66382. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66383. : oldOpacity;
  66384. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66385. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66386. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66387. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66388. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66389. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66390. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66391. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66392. }
  66393. context->restoreState();
  66394. }
  66395. }
  66396. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66397. {
  66398. // passing in a silly number can cause maths problems in rendering!
  66399. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66400. Path p;
  66401. p.addEllipse (x, y, width, height);
  66402. fillPath (p);
  66403. }
  66404. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66405. const float lineThickness) const
  66406. {
  66407. // passing in a silly number can cause maths problems in rendering!
  66408. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66409. Path p;
  66410. p.addEllipse (x, y, width, height);
  66411. strokePath (p, PathStrokeType (lineThickness));
  66412. }
  66413. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66414. {
  66415. // passing in a silly number can cause maths problems in rendering!
  66416. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66417. Path p;
  66418. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66419. fillPath (p);
  66420. }
  66421. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66422. {
  66423. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66424. }
  66425. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66426. const float cornerSize, const float lineThickness) const
  66427. {
  66428. // passing in a silly number can cause maths problems in rendering!
  66429. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66430. Path p;
  66431. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66432. strokePath (p, PathStrokeType (lineThickness));
  66433. }
  66434. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66435. {
  66436. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66437. }
  66438. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66439. {
  66440. Path p;
  66441. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66442. fillPath (p);
  66443. }
  66444. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66445. const int checkWidth, const int checkHeight,
  66446. const Colour& colour1, const Colour& colour2) const
  66447. {
  66448. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66449. if (checkWidth > 0 && checkHeight > 0)
  66450. {
  66451. context->saveState();
  66452. if (colour1 == colour2)
  66453. {
  66454. context->setFill (colour1);
  66455. context->fillRect (area, false);
  66456. }
  66457. else
  66458. {
  66459. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66460. if (! clipped.isEmpty())
  66461. {
  66462. context->clipToRectangle (clipped);
  66463. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66464. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66465. const int startX = area.getX() + checkNumX * checkWidth;
  66466. const int startY = area.getY() + checkNumY * checkHeight;
  66467. const int right = clipped.getRight();
  66468. const int bottom = clipped.getBottom();
  66469. for (int i = 0; i < 2; ++i)
  66470. {
  66471. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66472. int cy = i;
  66473. for (int y = startY; y < bottom; y += checkHeight)
  66474. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66475. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66476. }
  66477. }
  66478. }
  66479. context->restoreState();
  66480. }
  66481. }
  66482. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66483. {
  66484. context->drawVerticalLine (x, top, bottom);
  66485. }
  66486. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66487. {
  66488. context->drawHorizontalLine (y, left, right);
  66489. }
  66490. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66491. {
  66492. context->drawLine (Line<float> (x1, y1, x2, y2));
  66493. }
  66494. void Graphics::drawLine (const float startX, const float startY,
  66495. const float endX, const float endY,
  66496. const float lineThickness) const
  66497. {
  66498. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66499. }
  66500. void Graphics::drawLine (const Line<float>& line) const
  66501. {
  66502. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66503. }
  66504. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66505. {
  66506. Path p;
  66507. p.addLineSegment (line, lineThickness);
  66508. fillPath (p);
  66509. }
  66510. void Graphics::drawDashedLine (const float startX, const float startY,
  66511. const float endX, const float endY,
  66512. const float* const dashLengths,
  66513. const int numDashLengths,
  66514. const float lineThickness) const
  66515. {
  66516. const double dx = endX - startX;
  66517. const double dy = endY - startY;
  66518. const double totalLen = juce_hypot (dx, dy);
  66519. if (totalLen >= 0.5)
  66520. {
  66521. const double onePixAlpha = 1.0 / totalLen;
  66522. double alpha = 0.0;
  66523. float x = startX;
  66524. float y = startY;
  66525. int n = 0;
  66526. while (alpha < 1.0f)
  66527. {
  66528. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66529. n = n % numDashLengths;
  66530. const float oldX = x;
  66531. const float oldY = y;
  66532. x = (float) (startX + dx * alpha);
  66533. y = (float) (startY + dy * alpha);
  66534. if ((n & 1) != 0)
  66535. {
  66536. if (lineThickness != 1.0f)
  66537. drawLine (oldX, oldY, x, y, lineThickness);
  66538. else
  66539. drawLine (oldX, oldY, x, y);
  66540. }
  66541. }
  66542. }
  66543. }
  66544. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66545. {
  66546. saveStateIfPending();
  66547. context->setInterpolationQuality (newQuality);
  66548. }
  66549. void Graphics::drawImageAt (const Image& imageToDraw,
  66550. const int topLeftX, const int topLeftY,
  66551. const bool fillAlphaChannelWithCurrentBrush) const
  66552. {
  66553. const int imageW = imageToDraw.getWidth();
  66554. const int imageH = imageToDraw.getHeight();
  66555. drawImage (imageToDraw,
  66556. topLeftX, topLeftY, imageW, imageH,
  66557. 0, 0, imageW, imageH,
  66558. fillAlphaChannelWithCurrentBrush);
  66559. }
  66560. void Graphics::drawImageWithin (const Image& imageToDraw,
  66561. const int destX, const int destY,
  66562. const int destW, const int destH,
  66563. const RectanglePlacement& placementWithinTarget,
  66564. const bool fillAlphaChannelWithCurrentBrush) const
  66565. {
  66566. // passing in a silly number can cause maths problems in rendering!
  66567. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66568. if (imageToDraw.isValid())
  66569. {
  66570. const int imageW = imageToDraw.getWidth();
  66571. const int imageH = imageToDraw.getHeight();
  66572. if (imageW > 0 && imageH > 0)
  66573. {
  66574. double newX = 0.0, newY = 0.0;
  66575. double newW = imageW;
  66576. double newH = imageH;
  66577. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66578. destX, destY, destW, destH);
  66579. if (newW > 0 && newH > 0)
  66580. {
  66581. drawImage (imageToDraw,
  66582. roundToInt (newX), roundToInt (newY),
  66583. roundToInt (newW), roundToInt (newH),
  66584. 0, 0, imageW, imageH,
  66585. fillAlphaChannelWithCurrentBrush);
  66586. }
  66587. }
  66588. }
  66589. }
  66590. void Graphics::drawImage (const Image& imageToDraw,
  66591. int dx, int dy, int dw, int dh,
  66592. int sx, int sy, int sw, int sh,
  66593. const bool fillAlphaChannelWithCurrentBrush) const
  66594. {
  66595. // passing in a silly number can cause maths problems in rendering!
  66596. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66597. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66598. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66599. {
  66600. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66601. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66602. .translated ((float) dx, (float) dy),
  66603. fillAlphaChannelWithCurrentBrush);
  66604. }
  66605. }
  66606. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66607. const AffineTransform& transform,
  66608. const bool fillAlphaChannelWithCurrentBrush) const
  66609. {
  66610. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66611. {
  66612. if (fillAlphaChannelWithCurrentBrush)
  66613. {
  66614. context->saveState();
  66615. context->clipToImageAlpha (imageToDraw, transform);
  66616. fillAll();
  66617. context->restoreState();
  66618. }
  66619. else
  66620. {
  66621. context->drawImage (imageToDraw, transform, false);
  66622. }
  66623. }
  66624. }
  66625. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66626. : context (g)
  66627. {
  66628. context.saveState();
  66629. }
  66630. Graphics::ScopedSaveState::~ScopedSaveState()
  66631. {
  66632. context.restoreState();
  66633. }
  66634. END_JUCE_NAMESPACE
  66635. /*** End of inlined file: juce_Graphics.cpp ***/
  66636. /*** Start of inlined file: juce_Justification.cpp ***/
  66637. BEGIN_JUCE_NAMESPACE
  66638. Justification::Justification (const Justification& other) throw()
  66639. : flags (other.flags)
  66640. {
  66641. }
  66642. Justification& Justification::operator= (const Justification& other) throw()
  66643. {
  66644. flags = other.flags;
  66645. return *this;
  66646. }
  66647. int Justification::getOnlyVerticalFlags() const throw()
  66648. {
  66649. return flags & (top | bottom | verticallyCentred);
  66650. }
  66651. int Justification::getOnlyHorizontalFlags() const throw()
  66652. {
  66653. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66654. }
  66655. void Justification::applyToRectangle (int& x, int& y,
  66656. const int w, const int h,
  66657. const int spaceX, const int spaceY,
  66658. const int spaceW, const int spaceH) const throw()
  66659. {
  66660. if ((flags & horizontallyCentred) != 0)
  66661. x = spaceX + ((spaceW - w) >> 1);
  66662. else if ((flags & right) != 0)
  66663. x = spaceX + spaceW - w;
  66664. else
  66665. x = spaceX;
  66666. if ((flags & verticallyCentred) != 0)
  66667. y = spaceY + ((spaceH - h) >> 1);
  66668. else if ((flags & bottom) != 0)
  66669. y = spaceY + spaceH - h;
  66670. else
  66671. y = spaceY;
  66672. }
  66673. END_JUCE_NAMESPACE
  66674. /*** End of inlined file: juce_Justification.cpp ***/
  66675. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66676. BEGIN_JUCE_NAMESPACE
  66677. // this will throw an assertion if you try to draw something that's not
  66678. // possible in postscript
  66679. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66680. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66681. #define notPossibleInPostscriptAssert jassertfalse
  66682. #else
  66683. #define notPossibleInPostscriptAssert
  66684. #endif
  66685. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66686. const String& documentTitle,
  66687. const int totalWidth_,
  66688. const int totalHeight_)
  66689. : out (resultingPostScript),
  66690. totalWidth (totalWidth_),
  66691. totalHeight (totalHeight_),
  66692. needToClip (true)
  66693. {
  66694. stateStack.add (new SavedState());
  66695. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66696. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66697. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66698. "\n%%BoundingBox: 0 0 600 824"
  66699. "\n%%Pages: 0"
  66700. "\n%%Creator: Raw Material Software JUCE"
  66701. "\n%%Title: " << documentTitle <<
  66702. "\n%%CreationDate: none"
  66703. "\n%%LanguageLevel: 2"
  66704. "\n%%EndComments"
  66705. "\n%%BeginProlog"
  66706. "\n%%BeginResource: JRes"
  66707. "\n/bd {bind def} bind def"
  66708. "\n/c {setrgbcolor} bd"
  66709. "\n/m {moveto} bd"
  66710. "\n/l {lineto} bd"
  66711. "\n/rl {rlineto} bd"
  66712. "\n/ct {curveto} bd"
  66713. "\n/cp {closepath} bd"
  66714. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66715. "\n/doclip {initclip newpath} bd"
  66716. "\n/endclip {clip newpath} bd"
  66717. "\n%%EndResource"
  66718. "\n%%EndProlog"
  66719. "\n%%BeginSetup"
  66720. "\n%%EndSetup"
  66721. "\n%%Page: 1 1"
  66722. "\n%%BeginPageSetup"
  66723. "\n%%EndPageSetup\n\n"
  66724. << "40 800 translate\n"
  66725. << scale << ' ' << scale << " scale\n\n";
  66726. }
  66727. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66728. {
  66729. }
  66730. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66731. {
  66732. return true;
  66733. }
  66734. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66735. {
  66736. if (x != 0 || y != 0)
  66737. {
  66738. stateStack.getLast()->xOffset += x;
  66739. stateStack.getLast()->yOffset += y;
  66740. needToClip = true;
  66741. }
  66742. }
  66743. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66744. {
  66745. //xxx
  66746. jassertfalse;
  66747. }
  66748. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66749. {
  66750. jassertfalse; //xxx
  66751. return 1.0f;
  66752. }
  66753. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66754. {
  66755. needToClip = true;
  66756. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66757. }
  66758. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66759. {
  66760. needToClip = true;
  66761. return stateStack.getLast()->clip.clipTo (clipRegion);
  66762. }
  66763. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66764. {
  66765. needToClip = true;
  66766. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66767. }
  66768. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66769. {
  66770. writeClip();
  66771. Path p (path);
  66772. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66773. writePath (p);
  66774. out << "clip\n";
  66775. }
  66776. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66777. {
  66778. needToClip = true;
  66779. jassertfalse; // xxx
  66780. }
  66781. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66782. {
  66783. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66784. }
  66785. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66786. {
  66787. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66788. -stateStack.getLast()->yOffset);
  66789. }
  66790. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66791. {
  66792. return stateStack.getLast()->clip.isEmpty();
  66793. }
  66794. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66795. : xOffset (0),
  66796. yOffset (0)
  66797. {
  66798. }
  66799. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66800. {
  66801. }
  66802. void LowLevelGraphicsPostScriptRenderer::saveState()
  66803. {
  66804. stateStack.add (new SavedState (*stateStack.getLast()));
  66805. }
  66806. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66807. {
  66808. jassert (stateStack.size() > 0);
  66809. if (stateStack.size() > 0)
  66810. stateStack.removeLast();
  66811. }
  66812. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66813. {
  66814. }
  66815. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66816. {
  66817. }
  66818. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66819. {
  66820. if (needToClip)
  66821. {
  66822. needToClip = false;
  66823. out << "doclip ";
  66824. int itemsOnLine = 0;
  66825. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66826. {
  66827. if (++itemsOnLine == 6)
  66828. {
  66829. itemsOnLine = 0;
  66830. out << '\n';
  66831. }
  66832. const Rectangle<int>& r = *i.getRectangle();
  66833. out << r.getX() << ' ' << -r.getY() << ' '
  66834. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66835. }
  66836. out << "endclip\n";
  66837. }
  66838. }
  66839. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66840. {
  66841. Colour c (Colours::white.overlaidWith (colour));
  66842. if (lastColour != c)
  66843. {
  66844. lastColour = c;
  66845. out << String (c.getFloatRed(), 3) << ' '
  66846. << String (c.getFloatGreen(), 3) << ' '
  66847. << String (c.getFloatBlue(), 3) << " c\n";
  66848. }
  66849. }
  66850. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66851. {
  66852. out << String (x, 2) << ' '
  66853. << String (-y, 2) << ' ';
  66854. }
  66855. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66856. {
  66857. out << "newpath ";
  66858. float lastX = 0.0f;
  66859. float lastY = 0.0f;
  66860. int itemsOnLine = 0;
  66861. Path::Iterator i (path);
  66862. while (i.next())
  66863. {
  66864. if (++itemsOnLine == 4)
  66865. {
  66866. itemsOnLine = 0;
  66867. out << '\n';
  66868. }
  66869. switch (i.elementType)
  66870. {
  66871. case Path::Iterator::startNewSubPath:
  66872. writeXY (i.x1, i.y1);
  66873. lastX = i.x1;
  66874. lastY = i.y1;
  66875. out << "m ";
  66876. break;
  66877. case Path::Iterator::lineTo:
  66878. writeXY (i.x1, i.y1);
  66879. lastX = i.x1;
  66880. lastY = i.y1;
  66881. out << "l ";
  66882. break;
  66883. case Path::Iterator::quadraticTo:
  66884. {
  66885. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66886. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66887. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66888. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66889. writeXY (cp1x, cp1y);
  66890. writeXY (cp2x, cp2y);
  66891. writeXY (i.x2, i.y2);
  66892. out << "ct ";
  66893. lastX = i.x2;
  66894. lastY = i.y2;
  66895. }
  66896. break;
  66897. case Path::Iterator::cubicTo:
  66898. writeXY (i.x1, i.y1);
  66899. writeXY (i.x2, i.y2);
  66900. writeXY (i.x3, i.y3);
  66901. out << "ct ";
  66902. lastX = i.x3;
  66903. lastY = i.y3;
  66904. break;
  66905. case Path::Iterator::closePath:
  66906. out << "cp ";
  66907. break;
  66908. default:
  66909. jassertfalse;
  66910. break;
  66911. }
  66912. }
  66913. out << '\n';
  66914. }
  66915. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66916. {
  66917. out << "[ "
  66918. << trans.mat00 << ' '
  66919. << trans.mat10 << ' '
  66920. << trans.mat01 << ' '
  66921. << trans.mat11 << ' '
  66922. << trans.mat02 << ' '
  66923. << trans.mat12 << " ] concat ";
  66924. }
  66925. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66926. {
  66927. stateStack.getLast()->fillType = fillType;
  66928. }
  66929. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66930. {
  66931. }
  66932. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66933. {
  66934. }
  66935. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66936. {
  66937. if (stateStack.getLast()->fillType.isColour())
  66938. {
  66939. writeClip();
  66940. writeColour (stateStack.getLast()->fillType.colour);
  66941. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66942. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66943. }
  66944. else
  66945. {
  66946. Path p;
  66947. p.addRectangle (r);
  66948. fillPath (p, AffineTransform::identity);
  66949. }
  66950. }
  66951. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66952. {
  66953. if (stateStack.getLast()->fillType.isColour())
  66954. {
  66955. writeClip();
  66956. Path p (path);
  66957. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66958. (float) stateStack.getLast()->yOffset));
  66959. writePath (p);
  66960. writeColour (stateStack.getLast()->fillType.colour);
  66961. out << "fill\n";
  66962. }
  66963. else if (stateStack.getLast()->fillType.isGradient())
  66964. {
  66965. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66966. // postscript can't do semi-transparent ones.
  66967. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66968. writeClip();
  66969. out << "gsave ";
  66970. {
  66971. Path p (path);
  66972. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66973. writePath (p);
  66974. out << "clip\n";
  66975. }
  66976. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66977. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66978. // time-being, this just fills it with the average colour..
  66979. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66980. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66981. out << "grestore\n";
  66982. }
  66983. }
  66984. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66985. const int sx, const int sy,
  66986. const int maxW, const int maxH) const
  66987. {
  66988. out << "{<\n";
  66989. const int w = jmin (maxW, im.getWidth());
  66990. const int h = jmin (maxH, im.getHeight());
  66991. int charsOnLine = 0;
  66992. const Image::BitmapData srcData (im, 0, 0, w, h);
  66993. Colour pixel;
  66994. for (int y = h; --y >= 0;)
  66995. {
  66996. for (int x = 0; x < w; ++x)
  66997. {
  66998. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66999. if (x >= sx && y >= sy)
  67000. {
  67001. if (im.isARGB())
  67002. {
  67003. PixelARGB p (*(const PixelARGB*) pixelData);
  67004. p.unpremultiply();
  67005. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67006. }
  67007. else if (im.isRGB())
  67008. {
  67009. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67010. }
  67011. else
  67012. {
  67013. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67014. }
  67015. }
  67016. else
  67017. {
  67018. pixel = Colours::transparentWhite;
  67019. }
  67020. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67021. out << String::toHexString (pixelValues, 3, 0);
  67022. charsOnLine += 3;
  67023. if (charsOnLine > 100)
  67024. {
  67025. out << '\n';
  67026. charsOnLine = 0;
  67027. }
  67028. }
  67029. }
  67030. out << "\n>}\n";
  67031. }
  67032. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67033. {
  67034. const int w = sourceImage.getWidth();
  67035. const int h = sourceImage.getHeight();
  67036. writeClip();
  67037. out << "gsave ";
  67038. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67039. .scaled (1.0f, -1.0f));
  67040. RectangleList imageClip;
  67041. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67042. out << "newpath ";
  67043. int itemsOnLine = 0;
  67044. for (RectangleList::Iterator i (imageClip); i.next();)
  67045. {
  67046. if (++itemsOnLine == 6)
  67047. {
  67048. out << '\n';
  67049. itemsOnLine = 0;
  67050. }
  67051. const Rectangle<int>& r = *i.getRectangle();
  67052. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67053. }
  67054. out << " clip newpath\n";
  67055. out << w << ' ' << h << " scale\n";
  67056. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67057. writeImage (sourceImage, 0, 0, w, h);
  67058. out << "false 3 colorimage grestore\n";
  67059. needToClip = true;
  67060. }
  67061. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67062. {
  67063. Path p;
  67064. p.addLineSegment (line, 1.0f);
  67065. fillPath (p, AffineTransform::identity);
  67066. }
  67067. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67068. {
  67069. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67070. }
  67071. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67072. {
  67073. drawLine (Line<float> (left, (float) y, right, (float) y));
  67074. }
  67075. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67076. {
  67077. stateStack.getLast()->font = newFont;
  67078. }
  67079. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67080. {
  67081. return stateStack.getLast()->font;
  67082. }
  67083. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67084. {
  67085. Path p;
  67086. Font& font = stateStack.getLast()->font;
  67087. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67088. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67089. }
  67090. END_JUCE_NAMESPACE
  67091. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67092. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67093. BEGIN_JUCE_NAMESPACE
  67094. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67095. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67096. #endif
  67097. #if JUCE_MSVC
  67098. #pragma warning (push)
  67099. #pragma warning (disable: 4127) // "expression is constant" warning
  67100. #if JUCE_DEBUG
  67101. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67102. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67103. #endif
  67104. #endif
  67105. namespace SoftwareRendererClasses
  67106. {
  67107. template <class PixelType, bool replaceExisting = false>
  67108. class SolidColourEdgeTableRenderer
  67109. {
  67110. public:
  67111. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67112. : data (data_),
  67113. sourceColour (colour)
  67114. {
  67115. if (sizeof (PixelType) == 3)
  67116. {
  67117. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67118. && sourceColour.getGreen() == sourceColour.getBlue();
  67119. filler[0].set (sourceColour);
  67120. filler[1].set (sourceColour);
  67121. filler[2].set (sourceColour);
  67122. filler[3].set (sourceColour);
  67123. }
  67124. }
  67125. forcedinline void setEdgeTableYPos (const int y) throw()
  67126. {
  67127. linePixels = (PixelType*) data.getLinePointer (y);
  67128. }
  67129. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67130. {
  67131. if (replaceExisting)
  67132. linePixels[x].set (sourceColour);
  67133. else
  67134. linePixels[x].blend (sourceColour, alphaLevel);
  67135. }
  67136. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67137. {
  67138. if (replaceExisting)
  67139. linePixels[x].set (sourceColour);
  67140. else
  67141. linePixels[x].blend (sourceColour);
  67142. }
  67143. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67144. {
  67145. PixelARGB p (sourceColour);
  67146. p.multiplyAlpha (alphaLevel);
  67147. PixelType* dest = linePixels + x;
  67148. if (replaceExisting || p.getAlpha() >= 0xff)
  67149. replaceLine (dest, p, width);
  67150. else
  67151. blendLine (dest, p, width);
  67152. }
  67153. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67154. {
  67155. PixelType* dest = linePixels + x;
  67156. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67157. replaceLine (dest, sourceColour, width);
  67158. else
  67159. blendLine (dest, sourceColour, width);
  67160. }
  67161. private:
  67162. const Image::BitmapData& data;
  67163. PixelType* linePixels;
  67164. PixelARGB sourceColour;
  67165. PixelRGB filler [4];
  67166. bool areRGBComponentsEqual;
  67167. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67168. {
  67169. do
  67170. {
  67171. dest->blend (colour);
  67172. ++dest;
  67173. } while (--width > 0);
  67174. }
  67175. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67176. {
  67177. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67178. {
  67179. memset (dest, colour.getRed(), width * 3);
  67180. }
  67181. else
  67182. {
  67183. if (width >> 5)
  67184. {
  67185. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67186. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67187. {
  67188. dest->set (colour);
  67189. ++dest;
  67190. --width;
  67191. }
  67192. while (width > 4)
  67193. {
  67194. int* d = reinterpret_cast<int*> (dest);
  67195. *d++ = intFiller[0];
  67196. *d++ = intFiller[1];
  67197. *d++ = intFiller[2];
  67198. dest = reinterpret_cast<PixelRGB*> (d);
  67199. width -= 4;
  67200. }
  67201. }
  67202. while (--width >= 0)
  67203. {
  67204. dest->set (colour);
  67205. ++dest;
  67206. }
  67207. }
  67208. }
  67209. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67210. {
  67211. memset (dest, colour.getAlpha(), width);
  67212. }
  67213. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67214. {
  67215. do
  67216. {
  67217. dest->set (colour);
  67218. ++dest;
  67219. } while (--width > 0);
  67220. }
  67221. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67222. };
  67223. class LinearGradientPixelGenerator
  67224. {
  67225. public:
  67226. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67227. : lookupTable (lookupTable_), numEntries (numEntries_)
  67228. {
  67229. jassert (numEntries_ >= 0);
  67230. Point<float> p1 (gradient.point1);
  67231. Point<float> p2 (gradient.point2);
  67232. if (! transform.isIdentity())
  67233. {
  67234. const Line<float> l (p2, p1);
  67235. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67236. p1.applyTransform (transform);
  67237. p2.applyTransform (transform);
  67238. p3.applyTransform (transform);
  67239. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67240. }
  67241. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67242. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67243. if (vertical)
  67244. {
  67245. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67246. start = roundToInt (p1.getY() * scale);
  67247. }
  67248. else if (horizontal)
  67249. {
  67250. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67251. start = roundToInt (p1.getX() * scale);
  67252. }
  67253. else
  67254. {
  67255. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67256. yTerm = p1.getY() - p1.getX() / grad;
  67257. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67258. grad *= scale;
  67259. }
  67260. }
  67261. forcedinline void setY (const int y) throw()
  67262. {
  67263. if (vertical)
  67264. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67265. else if (! horizontal)
  67266. start = roundToInt ((y - yTerm) * grad);
  67267. }
  67268. inline const PixelARGB getPixel (const int x) const throw()
  67269. {
  67270. return vertical ? linePix
  67271. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67272. }
  67273. private:
  67274. const PixelARGB* const lookupTable;
  67275. const int numEntries;
  67276. PixelARGB linePix;
  67277. int start, scale;
  67278. double grad, yTerm;
  67279. bool vertical, horizontal;
  67280. enum { numScaleBits = 12 };
  67281. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67282. };
  67283. class RadialGradientPixelGenerator
  67284. {
  67285. public:
  67286. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67287. const PixelARGB* const lookupTable_, const int numEntries_)
  67288. : lookupTable (lookupTable_),
  67289. numEntries (numEntries_),
  67290. gx1 (gradient.point1.getX()),
  67291. gy1 (gradient.point1.getY())
  67292. {
  67293. jassert (numEntries_ >= 0);
  67294. const Point<float> diff (gradient.point1 - gradient.point2);
  67295. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67296. invScale = numEntries / std::sqrt (maxDist);
  67297. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67298. }
  67299. forcedinline void setY (const int y) throw()
  67300. {
  67301. dy = y - gy1;
  67302. dy *= dy;
  67303. }
  67304. inline const PixelARGB getPixel (const int px) const throw()
  67305. {
  67306. double x = px - gx1;
  67307. x *= x;
  67308. x += dy;
  67309. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67310. }
  67311. protected:
  67312. const PixelARGB* const lookupTable;
  67313. const int numEntries;
  67314. const double gx1, gy1;
  67315. double maxDist, invScale, dy;
  67316. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67317. };
  67318. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67319. {
  67320. public:
  67321. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67322. const PixelARGB* const lookupTable_, const int numEntries_)
  67323. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67324. inverseTransform (transform.inverted())
  67325. {
  67326. tM10 = inverseTransform.mat10;
  67327. tM00 = inverseTransform.mat00;
  67328. }
  67329. forcedinline void setY (const int y) throw()
  67330. {
  67331. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67332. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67333. }
  67334. inline const PixelARGB getPixel (const int px) const throw()
  67335. {
  67336. double x = px;
  67337. const double y = tM10 * x + lineYM11;
  67338. x = tM00 * x + lineYM01;
  67339. x *= x;
  67340. x += y * y;
  67341. if (x >= maxDist)
  67342. return lookupTable [numEntries];
  67343. else
  67344. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67345. }
  67346. private:
  67347. double tM10, tM00, lineYM01, lineYM11;
  67348. const AffineTransform inverseTransform;
  67349. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67350. };
  67351. template <class PixelType, class GradientType>
  67352. class GradientEdgeTableRenderer : public GradientType
  67353. {
  67354. public:
  67355. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67356. const PixelARGB* const lookupTable_, const int numEntries_)
  67357. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67358. destData (destData_)
  67359. {
  67360. }
  67361. forcedinline void setEdgeTableYPos (const int y) throw()
  67362. {
  67363. linePixels = (PixelType*) destData.getLinePointer (y);
  67364. GradientType::setY (y);
  67365. }
  67366. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67367. {
  67368. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67369. }
  67370. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67371. {
  67372. linePixels[x].blend (GradientType::getPixel (x));
  67373. }
  67374. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67375. {
  67376. PixelType* dest = linePixels + x;
  67377. if (alphaLevel < 0xff)
  67378. {
  67379. do
  67380. {
  67381. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67382. } while (--width > 0);
  67383. }
  67384. else
  67385. {
  67386. do
  67387. {
  67388. (dest++)->blend (GradientType::getPixel (x++));
  67389. } while (--width > 0);
  67390. }
  67391. }
  67392. void handleEdgeTableLineFull (int x, int width) const throw()
  67393. {
  67394. PixelType* dest = linePixels + x;
  67395. do
  67396. {
  67397. (dest++)->blend (GradientType::getPixel (x++));
  67398. } while (--width > 0);
  67399. }
  67400. private:
  67401. const Image::BitmapData& destData;
  67402. PixelType* linePixels;
  67403. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67404. };
  67405. namespace RenderingHelpers
  67406. {
  67407. forcedinline int safeModulo (int n, const int divisor) throw()
  67408. {
  67409. jassert (divisor > 0);
  67410. n %= divisor;
  67411. return (n < 0) ? (n + divisor) : n;
  67412. }
  67413. }
  67414. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67415. class ImageFillEdgeTableRenderer
  67416. {
  67417. public:
  67418. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67419. const Image::BitmapData& srcData_,
  67420. const int extraAlpha_,
  67421. const int x, const int y)
  67422. : destData (destData_),
  67423. srcData (srcData_),
  67424. extraAlpha (extraAlpha_ + 1),
  67425. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67426. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67427. {
  67428. }
  67429. forcedinline void setEdgeTableYPos (int y) throw()
  67430. {
  67431. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67432. y -= yOffset;
  67433. if (repeatPattern)
  67434. {
  67435. jassert (y >= 0);
  67436. y %= srcData.height;
  67437. }
  67438. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67439. }
  67440. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67441. {
  67442. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67443. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67444. }
  67445. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67446. {
  67447. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67448. }
  67449. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67450. {
  67451. DestPixelType* dest = linePixels + x;
  67452. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67453. x -= xOffset;
  67454. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67455. if (alphaLevel < 0xfe)
  67456. {
  67457. do
  67458. {
  67459. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67460. } while (--width > 0);
  67461. }
  67462. else
  67463. {
  67464. if (repeatPattern)
  67465. {
  67466. do
  67467. {
  67468. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67469. } while (--width > 0);
  67470. }
  67471. else
  67472. {
  67473. copyRow (dest, sourceLineStart + x, width);
  67474. }
  67475. }
  67476. }
  67477. void handleEdgeTableLineFull (int x, int width) const throw()
  67478. {
  67479. DestPixelType* dest = linePixels + x;
  67480. x -= xOffset;
  67481. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67482. if (extraAlpha < 0xfe)
  67483. {
  67484. do
  67485. {
  67486. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67487. } while (--width > 0);
  67488. }
  67489. else
  67490. {
  67491. if (repeatPattern)
  67492. {
  67493. do
  67494. {
  67495. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67496. } while (--width > 0);
  67497. }
  67498. else
  67499. {
  67500. copyRow (dest, sourceLineStart + x, width);
  67501. }
  67502. }
  67503. }
  67504. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67505. {
  67506. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67507. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67508. uint8* mask = (uint8*) (s + x - xOffset);
  67509. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67510. mask += PixelARGB::indexA;
  67511. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67512. }
  67513. private:
  67514. const Image::BitmapData& destData;
  67515. const Image::BitmapData& srcData;
  67516. const int extraAlpha, xOffset, yOffset;
  67517. DestPixelType* linePixels;
  67518. SrcPixelType* sourceLineStart;
  67519. template <class PixelType1, class PixelType2>
  67520. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67521. {
  67522. do
  67523. {
  67524. dest++ ->blend (*src++);
  67525. } while (--width > 0);
  67526. }
  67527. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67528. {
  67529. memcpy (dest, src, width * sizeof (PixelRGB));
  67530. }
  67531. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67532. };
  67533. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67534. class TransformedImageFillEdgeTableRenderer
  67535. {
  67536. public:
  67537. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67538. const Image::BitmapData& srcData_,
  67539. const AffineTransform& transform,
  67540. const int extraAlpha_,
  67541. const bool betterQuality_)
  67542. : interpolator (transform,
  67543. betterQuality_ ? 0.5f : 0.0f,
  67544. betterQuality_ ? -128 : 0),
  67545. destData (destData_),
  67546. srcData (srcData_),
  67547. extraAlpha (extraAlpha_ + 1),
  67548. betterQuality (betterQuality_),
  67549. maxX (srcData_.width - 1),
  67550. maxY (srcData_.height - 1),
  67551. scratchSize (2048)
  67552. {
  67553. scratchBuffer.malloc (scratchSize);
  67554. }
  67555. forcedinline void setEdgeTableYPos (const int newY) throw()
  67556. {
  67557. y = newY;
  67558. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67559. }
  67560. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67561. {
  67562. SrcPixelType p;
  67563. generate (&p, x, 1);
  67564. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67565. }
  67566. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67567. {
  67568. SrcPixelType p;
  67569. generate (&p, x, 1);
  67570. linePixels[x].blend (p, extraAlpha);
  67571. }
  67572. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67573. {
  67574. if (width > scratchSize)
  67575. {
  67576. scratchSize = width;
  67577. scratchBuffer.malloc (scratchSize);
  67578. }
  67579. SrcPixelType* span = scratchBuffer;
  67580. generate (span, x, width);
  67581. DestPixelType* dest = linePixels + x;
  67582. alphaLevel *= extraAlpha;
  67583. alphaLevel >>= 8;
  67584. if (alphaLevel < 0xfe)
  67585. {
  67586. do
  67587. {
  67588. dest++ ->blend (*span++, alphaLevel);
  67589. } while (--width > 0);
  67590. }
  67591. else
  67592. {
  67593. do
  67594. {
  67595. dest++ ->blend (*span++);
  67596. } while (--width > 0);
  67597. }
  67598. }
  67599. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67600. {
  67601. handleEdgeTableLine (x, width, 255);
  67602. }
  67603. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67604. {
  67605. if (width > scratchSize)
  67606. {
  67607. scratchSize = width;
  67608. scratchBuffer.malloc (scratchSize);
  67609. }
  67610. y = y_;
  67611. generate (static_cast <SrcPixelType*> (scratchBuffer), x, width);
  67612. et.clipLineToMask (x, y_,
  67613. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67614. sizeof (SrcPixelType), width);
  67615. }
  67616. private:
  67617. template <class PixelType>
  67618. void generate (PixelType* dest, const int x, int numPixels) throw()
  67619. {
  67620. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67621. do
  67622. {
  67623. int hiResX, hiResY;
  67624. this->interpolator.next (hiResX, hiResY);
  67625. int loResX = hiResX >> 8;
  67626. int loResY = hiResY >> 8;
  67627. if (repeatPattern)
  67628. {
  67629. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67630. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67631. }
  67632. if (betterQuality)
  67633. {
  67634. if (isPositiveAndBelow (loResX, maxX))
  67635. {
  67636. if (isPositiveAndBelow (loResY, maxY))
  67637. {
  67638. // In the centre of the image..
  67639. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67640. hiResX & 255, hiResY & 255);
  67641. ++dest;
  67642. continue;
  67643. }
  67644. else
  67645. {
  67646. // At a top or bottom edge..
  67647. if (! repeatPattern)
  67648. {
  67649. if (loResY < 0)
  67650. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67651. else
  67652. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67653. ++dest;
  67654. continue;
  67655. }
  67656. }
  67657. }
  67658. else
  67659. {
  67660. if (isPositiveAndBelow (loResY, maxY))
  67661. {
  67662. // At a left or right hand edge..
  67663. if (! repeatPattern)
  67664. {
  67665. if (loResX < 0)
  67666. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67667. else
  67668. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67669. ++dest;
  67670. continue;
  67671. }
  67672. }
  67673. }
  67674. }
  67675. if (! repeatPattern)
  67676. {
  67677. if (loResX < 0) loResX = 0;
  67678. if (loResY < 0) loResY = 0;
  67679. if (loResX > maxX) loResX = maxX;
  67680. if (loResY > maxY) loResY = maxY;
  67681. }
  67682. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67683. ++dest;
  67684. } while (--numPixels > 0);
  67685. }
  67686. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67687. {
  67688. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67689. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67690. c[0] += weight * src[0];
  67691. c[1] += weight * src[1];
  67692. c[2] += weight * src[2];
  67693. c[3] += weight * src[3];
  67694. weight = subPixelX * (256 - subPixelY);
  67695. c[0] += weight * src[4];
  67696. c[1] += weight * src[5];
  67697. c[2] += weight * src[6];
  67698. c[3] += weight * src[7];
  67699. src += this->srcData.lineStride;
  67700. weight = (256 - subPixelX) * subPixelY;
  67701. c[0] += weight * src[0];
  67702. c[1] += weight * src[1];
  67703. c[2] += weight * src[2];
  67704. c[3] += weight * src[3];
  67705. weight = subPixelX * subPixelY;
  67706. c[0] += weight * src[4];
  67707. c[1] += weight * src[5];
  67708. c[2] += weight * src[6];
  67709. c[3] += weight * src[7];
  67710. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67711. (uint8) (c[PixelARGB::indexR] >> 16),
  67712. (uint8) (c[PixelARGB::indexG] >> 16),
  67713. (uint8) (c[PixelARGB::indexB] >> 16));
  67714. }
  67715. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67716. {
  67717. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67718. uint32 weight = (256 - subPixelX) * alpha;
  67719. c[0] += weight * src[0];
  67720. c[1] += weight * src[1];
  67721. c[2] += weight * src[2];
  67722. c[3] += weight * src[3];
  67723. weight = subPixelX * alpha;
  67724. c[0] += weight * src[4];
  67725. c[1] += weight * src[5];
  67726. c[2] += weight * src[6];
  67727. c[3] += weight * src[7];
  67728. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67729. (uint8) (c[PixelARGB::indexR] >> 16),
  67730. (uint8) (c[PixelARGB::indexG] >> 16),
  67731. (uint8) (c[PixelARGB::indexB] >> 16));
  67732. }
  67733. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67734. {
  67735. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67736. uint32 weight = (256 - subPixelY) * alpha;
  67737. c[0] += weight * src[0];
  67738. c[1] += weight * src[1];
  67739. c[2] += weight * src[2];
  67740. c[3] += weight * src[3];
  67741. src += this->srcData.lineStride;
  67742. weight = subPixelY * alpha;
  67743. c[0] += weight * src[0];
  67744. c[1] += weight * src[1];
  67745. c[2] += weight * src[2];
  67746. c[3] += weight * src[3];
  67747. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67748. (uint8) (c[PixelARGB::indexR] >> 16),
  67749. (uint8) (c[PixelARGB::indexG] >> 16),
  67750. (uint8) (c[PixelARGB::indexB] >> 16));
  67751. }
  67752. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67753. {
  67754. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67755. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67756. c[0] += weight * src[0];
  67757. c[1] += weight * src[1];
  67758. c[2] += weight * src[2];
  67759. weight = subPixelX * (256 - subPixelY);
  67760. c[0] += weight * src[3];
  67761. c[1] += weight * src[4];
  67762. c[2] += weight * src[5];
  67763. src += this->srcData.lineStride;
  67764. weight = (256 - subPixelX) * subPixelY;
  67765. c[0] += weight * src[0];
  67766. c[1] += weight * src[1];
  67767. c[2] += weight * src[2];
  67768. weight = subPixelX * subPixelY;
  67769. c[0] += weight * src[3];
  67770. c[1] += weight * src[4];
  67771. c[2] += weight * src[5];
  67772. dest->setARGB ((uint8) 255,
  67773. (uint8) (c[PixelRGB::indexR] >> 16),
  67774. (uint8) (c[PixelRGB::indexG] >> 16),
  67775. (uint8) (c[PixelRGB::indexB] >> 16));
  67776. }
  67777. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67778. {
  67779. uint32 c[3] = { 128, 128, 128 };
  67780. uint32 weight = (256 - subPixelX);
  67781. c[0] += weight * src[0];
  67782. c[1] += weight * src[1];
  67783. c[2] += weight * src[2];
  67784. c[0] += subPixelX * src[3];
  67785. c[1] += subPixelX * src[4];
  67786. c[2] += subPixelX * src[5];
  67787. dest->setARGB ((uint8) 255,
  67788. (uint8) (c[PixelRGB::indexR] >> 8),
  67789. (uint8) (c[PixelRGB::indexG] >> 8),
  67790. (uint8) (c[PixelRGB::indexB] >> 8));
  67791. }
  67792. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67793. {
  67794. uint32 c[3] = { 128, 128, 128 };
  67795. uint32 weight = (256 - subPixelY);
  67796. c[0] += weight * src[0];
  67797. c[1] += weight * src[1];
  67798. c[2] += weight * src[2];
  67799. src += this->srcData.lineStride;
  67800. c[0] += subPixelY * src[0];
  67801. c[1] += subPixelY * src[1];
  67802. c[2] += subPixelY * src[2];
  67803. dest->setARGB ((uint8) 255,
  67804. (uint8) (c[PixelRGB::indexR] >> 8),
  67805. (uint8) (c[PixelRGB::indexG] >> 8),
  67806. (uint8) (c[PixelRGB::indexB] >> 8));
  67807. }
  67808. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67809. {
  67810. uint32 c = 256 * 128;
  67811. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67812. c += src[1] * (subPixelX * (256 - subPixelY));
  67813. src += this->srcData.lineStride;
  67814. c += src[0] * ((256 - subPixelX) * subPixelY);
  67815. c += src[1] * (subPixelX * subPixelY);
  67816. *((uint8*) dest) = (uint8) (c >> 16);
  67817. }
  67818. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67819. {
  67820. uint32 c = 256 * 128;
  67821. c += src[0] * (256 - subPixelX) * alpha;
  67822. c += src[1] * subPixelX * alpha;
  67823. *((uint8*) dest) = (uint8) (c >> 16);
  67824. }
  67825. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67826. {
  67827. uint32 c = 256 * 128;
  67828. c += src[0] * (256 - subPixelY) * alpha;
  67829. src += this->srcData.lineStride;
  67830. c += src[0] * subPixelY * alpha;
  67831. *((uint8*) dest) = (uint8) (c >> 16);
  67832. }
  67833. class TransformedImageSpanInterpolator
  67834. {
  67835. public:
  67836. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67837. : inverseTransform (transform.inverted()),
  67838. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67839. {}
  67840. void setStartOfLine (float x, float y, const int numPixels) throw()
  67841. {
  67842. jassert (numPixels > 0);
  67843. x += pixelOffset;
  67844. y += pixelOffset;
  67845. float x1 = x, y1 = y;
  67846. x += numPixels;
  67847. inverseTransform.transformPoints (x1, y1, x, y);
  67848. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67849. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67850. }
  67851. void next (int& x, int& y) throw()
  67852. {
  67853. x = xBresenham.n;
  67854. xBresenham.stepToNext();
  67855. y = yBresenham.n;
  67856. yBresenham.stepToNext();
  67857. }
  67858. private:
  67859. class BresenhamInterpolator
  67860. {
  67861. public:
  67862. BresenhamInterpolator() throw() {}
  67863. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67864. {
  67865. numSteps = numSteps_;
  67866. step = (n2 - n1) / numSteps;
  67867. remainder = modulo = (n2 - n1) % numSteps;
  67868. n = n1 + pixelOffsetInt;
  67869. if (modulo <= 0)
  67870. {
  67871. modulo += numSteps;
  67872. remainder += numSteps;
  67873. --step;
  67874. }
  67875. modulo -= numSteps;
  67876. }
  67877. forcedinline void stepToNext() throw()
  67878. {
  67879. modulo += remainder;
  67880. n += step;
  67881. if (modulo > 0)
  67882. {
  67883. modulo -= numSteps;
  67884. ++n;
  67885. }
  67886. }
  67887. int n;
  67888. private:
  67889. int numSteps, step, modulo, remainder;
  67890. };
  67891. const AffineTransform inverseTransform;
  67892. BresenhamInterpolator xBresenham, yBresenham;
  67893. const float pixelOffset;
  67894. const int pixelOffsetInt;
  67895. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67896. };
  67897. TransformedImageSpanInterpolator interpolator;
  67898. const Image::BitmapData& destData;
  67899. const Image::BitmapData& srcData;
  67900. const int extraAlpha;
  67901. const bool betterQuality;
  67902. const int maxX, maxY;
  67903. int y;
  67904. DestPixelType* linePixels;
  67905. HeapBlock <SrcPixelType> scratchBuffer;
  67906. int scratchSize;
  67907. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67908. };
  67909. class ClipRegionBase : public ReferenceCountedObject
  67910. {
  67911. public:
  67912. ClipRegionBase() {}
  67913. virtual ~ClipRegionBase() {}
  67914. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67915. virtual const Ptr clone() const = 0;
  67916. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67917. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67918. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67919. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67920. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67921. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67922. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67923. virtual const Ptr translated (const Point<int>& delta) = 0;
  67924. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67925. virtual const Rectangle<int> getClipBounds() const = 0;
  67926. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67927. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67928. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67929. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67930. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67931. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67932. protected:
  67933. template <class Iterator>
  67934. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67935. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67936. {
  67937. switch (destData.pixelFormat)
  67938. {
  67939. case Image::ARGB:
  67940. switch (srcData.pixelFormat)
  67941. {
  67942. case Image::ARGB:
  67943. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67944. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67945. break;
  67946. case Image::RGB:
  67947. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67948. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67949. break;
  67950. default:
  67951. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67952. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67953. break;
  67954. }
  67955. break;
  67956. case Image::RGB:
  67957. switch (srcData.pixelFormat)
  67958. {
  67959. case Image::ARGB:
  67960. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67961. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67962. break;
  67963. case Image::RGB:
  67964. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67965. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67966. break;
  67967. default:
  67968. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67969. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67970. break;
  67971. }
  67972. break;
  67973. default:
  67974. switch (srcData.pixelFormat)
  67975. {
  67976. case Image::ARGB:
  67977. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67978. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67979. break;
  67980. case Image::RGB:
  67981. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67982. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67983. break;
  67984. default:
  67985. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67986. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67987. break;
  67988. }
  67989. break;
  67990. }
  67991. }
  67992. template <class Iterator>
  67993. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67994. {
  67995. switch (destData.pixelFormat)
  67996. {
  67997. case Image::ARGB:
  67998. switch (srcData.pixelFormat)
  67999. {
  68000. case Image::ARGB:
  68001. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68002. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68003. break;
  68004. case Image::RGB:
  68005. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68006. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68007. break;
  68008. default:
  68009. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68010. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68011. break;
  68012. }
  68013. break;
  68014. case Image::RGB:
  68015. switch (srcData.pixelFormat)
  68016. {
  68017. case Image::ARGB:
  68018. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68019. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68020. break;
  68021. case Image::RGB:
  68022. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68023. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68024. break;
  68025. default:
  68026. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68027. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68028. break;
  68029. }
  68030. break;
  68031. default:
  68032. switch (srcData.pixelFormat)
  68033. {
  68034. case Image::ARGB:
  68035. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68036. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68037. break;
  68038. case Image::RGB:
  68039. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68040. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68041. break;
  68042. default:
  68043. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68044. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68045. break;
  68046. }
  68047. break;
  68048. }
  68049. }
  68050. template <class Iterator, class DestPixelType>
  68051. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68052. {
  68053. jassert (destData.pixelStride == sizeof (DestPixelType));
  68054. if (replaceContents)
  68055. {
  68056. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68057. iter.iterate (r);
  68058. }
  68059. else
  68060. {
  68061. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68062. iter.iterate (r);
  68063. }
  68064. }
  68065. template <class Iterator, class DestPixelType>
  68066. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68067. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68068. {
  68069. jassert (destData.pixelStride == sizeof (DestPixelType));
  68070. if (g.isRadial)
  68071. {
  68072. if (isIdentity)
  68073. {
  68074. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68075. iter.iterate (renderer);
  68076. }
  68077. else
  68078. {
  68079. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68080. iter.iterate (renderer);
  68081. }
  68082. }
  68083. else
  68084. {
  68085. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68086. iter.iterate (renderer);
  68087. }
  68088. }
  68089. };
  68090. class ClipRegion_EdgeTable : public ClipRegionBase
  68091. {
  68092. public:
  68093. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68094. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68095. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68096. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68097. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68098. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68099. ~ClipRegion_EdgeTable() {}
  68100. const Ptr clone() const
  68101. {
  68102. return new ClipRegion_EdgeTable (*this);
  68103. }
  68104. const Ptr applyClipTo (const Ptr& target) const
  68105. {
  68106. return target->clipToEdgeTable (edgeTable);
  68107. }
  68108. const Ptr clipToRectangle (const Rectangle<int>& r)
  68109. {
  68110. edgeTable.clipToRectangle (r);
  68111. return edgeTable.isEmpty() ? 0 : this;
  68112. }
  68113. const Ptr clipToRectangleList (const RectangleList& r)
  68114. {
  68115. RectangleList inverse (edgeTable.getMaximumBounds());
  68116. if (inverse.subtract (r))
  68117. for (RectangleList::Iterator iter (inverse); iter.next();)
  68118. edgeTable.excludeRectangle (*iter.getRectangle());
  68119. return edgeTable.isEmpty() ? 0 : this;
  68120. }
  68121. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68122. {
  68123. edgeTable.excludeRectangle (r);
  68124. return edgeTable.isEmpty() ? 0 : this;
  68125. }
  68126. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68127. {
  68128. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68129. edgeTable.clipToEdgeTable (et);
  68130. return edgeTable.isEmpty() ? 0 : this;
  68131. }
  68132. const Ptr clipToEdgeTable (const EdgeTable& et)
  68133. {
  68134. edgeTable.clipToEdgeTable (et);
  68135. return edgeTable.isEmpty() ? 0 : this;
  68136. }
  68137. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68138. {
  68139. const Image::BitmapData srcData (image, false);
  68140. if (transform.isOnlyTranslation())
  68141. {
  68142. // If our translation doesn't involve any distortion, just use a simple blit..
  68143. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68144. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68145. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68146. {
  68147. const int imageX = ((tx + 128) >> 8);
  68148. const int imageY = ((ty + 128) >> 8);
  68149. if (image.getFormat() == Image::ARGB)
  68150. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68151. else
  68152. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68153. return edgeTable.isEmpty() ? 0 : this;
  68154. }
  68155. }
  68156. if (transform.isSingularity())
  68157. return 0;
  68158. {
  68159. Path p;
  68160. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68161. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68162. edgeTable.clipToEdgeTable (et2);
  68163. }
  68164. if (! edgeTable.isEmpty())
  68165. {
  68166. if (image.getFormat() == Image::ARGB)
  68167. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68168. else
  68169. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68170. }
  68171. return edgeTable.isEmpty() ? 0 : this;
  68172. }
  68173. const Ptr translated (const Point<int>& delta)
  68174. {
  68175. edgeTable.translate ((float) delta.getX(), delta.getY());
  68176. return edgeTable.isEmpty() ? 0 : this;
  68177. }
  68178. bool clipRegionIntersects (const Rectangle<int>& r) const
  68179. {
  68180. return edgeTable.getMaximumBounds().intersects (r);
  68181. }
  68182. const Rectangle<int> getClipBounds() const
  68183. {
  68184. return edgeTable.getMaximumBounds();
  68185. }
  68186. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68187. {
  68188. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68189. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68190. if (! clipped.isEmpty())
  68191. {
  68192. ClipRegion_EdgeTable et (clipped);
  68193. et.edgeTable.clipToEdgeTable (edgeTable);
  68194. et.fillAllWithColour (destData, colour, replaceContents);
  68195. }
  68196. }
  68197. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68198. {
  68199. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68200. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68201. if (! clipped.isEmpty())
  68202. {
  68203. ClipRegion_EdgeTable et (clipped);
  68204. et.edgeTable.clipToEdgeTable (edgeTable);
  68205. et.fillAllWithColour (destData, colour, false);
  68206. }
  68207. }
  68208. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68209. {
  68210. switch (destData.pixelFormat)
  68211. {
  68212. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68213. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68214. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68215. }
  68216. }
  68217. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68218. {
  68219. HeapBlock <PixelARGB> lookupTable;
  68220. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68221. jassert (numLookupEntries > 0);
  68222. switch (destData.pixelFormat)
  68223. {
  68224. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68225. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68226. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68227. }
  68228. }
  68229. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68230. {
  68231. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68232. }
  68233. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68234. {
  68235. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68236. }
  68237. EdgeTable edgeTable;
  68238. private:
  68239. template <class SrcPixelType>
  68240. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68241. {
  68242. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68243. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68244. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68245. edgeTable.getMaximumBounds().getWidth());
  68246. }
  68247. template <class SrcPixelType>
  68248. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68249. {
  68250. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68251. edgeTable.clipToRectangle (r);
  68252. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68253. for (int y = 0; y < r.getHeight(); ++y)
  68254. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68255. }
  68256. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68257. };
  68258. class ClipRegion_RectangleList : public ClipRegionBase
  68259. {
  68260. public:
  68261. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68262. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68263. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68264. ~ClipRegion_RectangleList() {}
  68265. const Ptr clone() const
  68266. {
  68267. return new ClipRegion_RectangleList (*this);
  68268. }
  68269. const Ptr applyClipTo (const Ptr& target) const
  68270. {
  68271. return target->clipToRectangleList (clip);
  68272. }
  68273. const Ptr clipToRectangle (const Rectangle<int>& r)
  68274. {
  68275. clip.clipTo (r);
  68276. return clip.isEmpty() ? 0 : this;
  68277. }
  68278. const Ptr clipToRectangleList (const RectangleList& r)
  68279. {
  68280. clip.clipTo (r);
  68281. return clip.isEmpty() ? 0 : this;
  68282. }
  68283. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68284. {
  68285. clip.subtract (r);
  68286. return clip.isEmpty() ? 0 : this;
  68287. }
  68288. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68289. {
  68290. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68291. }
  68292. const Ptr clipToEdgeTable (const EdgeTable& et)
  68293. {
  68294. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68295. }
  68296. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68297. {
  68298. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68299. }
  68300. const Ptr translated (const Point<int>& delta)
  68301. {
  68302. clip.offsetAll (delta.getX(), delta.getY());
  68303. return clip.isEmpty() ? 0 : this;
  68304. }
  68305. bool clipRegionIntersects (const Rectangle<int>& r) const
  68306. {
  68307. return clip.intersects (r);
  68308. }
  68309. const Rectangle<int> getClipBounds() const
  68310. {
  68311. return clip.getBounds();
  68312. }
  68313. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68314. {
  68315. SubRectangleIterator iter (clip, area);
  68316. switch (destData.pixelFormat)
  68317. {
  68318. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68319. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68320. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68321. }
  68322. }
  68323. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68324. {
  68325. SubRectangleIteratorFloat iter (clip, area);
  68326. switch (destData.pixelFormat)
  68327. {
  68328. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68329. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68330. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68331. }
  68332. }
  68333. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68334. {
  68335. switch (destData.pixelFormat)
  68336. {
  68337. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68338. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68339. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68340. }
  68341. }
  68342. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68343. {
  68344. HeapBlock <PixelARGB> lookupTable;
  68345. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68346. jassert (numLookupEntries > 0);
  68347. switch (destData.pixelFormat)
  68348. {
  68349. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68350. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68351. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68352. }
  68353. }
  68354. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68355. {
  68356. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68357. }
  68358. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68359. {
  68360. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68361. }
  68362. RectangleList clip;
  68363. template <class Renderer>
  68364. void iterate (Renderer& r) const throw()
  68365. {
  68366. RectangleList::Iterator iter (clip);
  68367. while (iter.next())
  68368. {
  68369. const Rectangle<int> rect (*iter.getRectangle());
  68370. const int x = rect.getX();
  68371. const int w = rect.getWidth();
  68372. jassert (w > 0);
  68373. const int bottom = rect.getBottom();
  68374. for (int y = rect.getY(); y < bottom; ++y)
  68375. {
  68376. r.setEdgeTableYPos (y);
  68377. r.handleEdgeTableLineFull (x, w);
  68378. }
  68379. }
  68380. }
  68381. private:
  68382. class SubRectangleIterator
  68383. {
  68384. public:
  68385. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68386. : clip (clip_), area (area_)
  68387. {
  68388. }
  68389. template <class Renderer>
  68390. void iterate (Renderer& r) const throw()
  68391. {
  68392. RectangleList::Iterator iter (clip);
  68393. while (iter.next())
  68394. {
  68395. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68396. if (! rect.isEmpty())
  68397. {
  68398. const int x = rect.getX();
  68399. const int w = rect.getWidth();
  68400. const int bottom = rect.getBottom();
  68401. for (int y = rect.getY(); y < bottom; ++y)
  68402. {
  68403. r.setEdgeTableYPos (y);
  68404. r.handleEdgeTableLineFull (x, w);
  68405. }
  68406. }
  68407. }
  68408. }
  68409. private:
  68410. const RectangleList& clip;
  68411. const Rectangle<int> area;
  68412. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68413. };
  68414. class SubRectangleIteratorFloat
  68415. {
  68416. public:
  68417. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68418. : clip (clip_), area (area_)
  68419. {
  68420. }
  68421. template <class Renderer>
  68422. void iterate (Renderer& r) const throw()
  68423. {
  68424. int left = roundToInt (area.getX() * 256.0f);
  68425. int top = roundToInt (area.getY() * 256.0f);
  68426. int right = roundToInt (area.getRight() * 256.0f);
  68427. int bottom = roundToInt (area.getBottom() * 256.0f);
  68428. int totalTop, totalLeft, totalBottom, totalRight;
  68429. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68430. if ((top >> 8) == (bottom >> 8))
  68431. {
  68432. topAlpha = bottom - top;
  68433. bottomAlpha = 0;
  68434. totalTop = top >> 8;
  68435. totalBottom = bottom = top = totalTop + 1;
  68436. }
  68437. else
  68438. {
  68439. if ((top & 255) == 0)
  68440. {
  68441. topAlpha = 0;
  68442. top = totalTop = (top >> 8);
  68443. }
  68444. else
  68445. {
  68446. topAlpha = 255 - (top & 255);
  68447. totalTop = (top >> 8);
  68448. top = totalTop + 1;
  68449. }
  68450. bottomAlpha = bottom & 255;
  68451. bottom >>= 8;
  68452. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68453. }
  68454. if ((left >> 8) == (right >> 8))
  68455. {
  68456. leftAlpha = right - left;
  68457. rightAlpha = 0;
  68458. totalLeft = (left >> 8);
  68459. totalRight = right = left = totalLeft + 1;
  68460. }
  68461. else
  68462. {
  68463. if ((left & 255) == 0)
  68464. {
  68465. leftAlpha = 0;
  68466. left = totalLeft = (left >> 8);
  68467. }
  68468. else
  68469. {
  68470. leftAlpha = 255 - (left & 255);
  68471. totalLeft = (left >> 8);
  68472. left = totalLeft + 1;
  68473. }
  68474. rightAlpha = right & 255;
  68475. right >>= 8;
  68476. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68477. }
  68478. RectangleList::Iterator iter (clip);
  68479. while (iter.next())
  68480. {
  68481. const int clipLeft = iter.getRectangle()->getX();
  68482. const int clipRight = iter.getRectangle()->getRight();
  68483. const int clipTop = iter.getRectangle()->getY();
  68484. const int clipBottom = iter.getRectangle()->getBottom();
  68485. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68486. {
  68487. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68488. {
  68489. if (topAlpha != 0 && totalTop >= clipTop)
  68490. {
  68491. r.setEdgeTableYPos (totalTop);
  68492. r.handleEdgeTablePixel (left, topAlpha);
  68493. }
  68494. const int endY = jmin (bottom, clipBottom);
  68495. for (int y = jmax (clipTop, top); y < endY; ++y)
  68496. {
  68497. r.setEdgeTableYPos (y);
  68498. r.handleEdgeTablePixelFull (left);
  68499. }
  68500. if (bottomAlpha != 0 && bottom < clipBottom)
  68501. {
  68502. r.setEdgeTableYPos (bottom);
  68503. r.handleEdgeTablePixel (left, bottomAlpha);
  68504. }
  68505. }
  68506. else
  68507. {
  68508. const int clippedLeft = jmax (left, clipLeft);
  68509. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68510. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68511. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68512. if (topAlpha != 0 && totalTop >= clipTop)
  68513. {
  68514. r.setEdgeTableYPos (totalTop);
  68515. if (doLeftAlpha)
  68516. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68517. if (clippedWidth > 0)
  68518. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68519. if (doRightAlpha)
  68520. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68521. }
  68522. const int endY = jmin (bottom, clipBottom);
  68523. for (int y = jmax (clipTop, top); y < endY; ++y)
  68524. {
  68525. r.setEdgeTableYPos (y);
  68526. if (doLeftAlpha)
  68527. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68528. if (clippedWidth > 0)
  68529. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68530. if (doRightAlpha)
  68531. r.handleEdgeTablePixel (right, rightAlpha);
  68532. }
  68533. if (bottomAlpha != 0 && bottom < clipBottom)
  68534. {
  68535. r.setEdgeTableYPos (bottom);
  68536. if (doLeftAlpha)
  68537. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68538. if (clippedWidth > 0)
  68539. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68540. if (doRightAlpha)
  68541. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68542. }
  68543. }
  68544. }
  68545. }
  68546. }
  68547. private:
  68548. const RectangleList& clip;
  68549. const Rectangle<float>& area;
  68550. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68551. };
  68552. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68553. };
  68554. }
  68555. class LowLevelGraphicsSoftwareRenderer::SavedState
  68556. {
  68557. public:
  68558. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68559. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68560. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68561. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68562. {
  68563. }
  68564. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68565. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68566. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68567. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68568. {
  68569. }
  68570. SavedState (const SavedState& other)
  68571. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68572. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68573. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68574. interpolationQuality (other.interpolationQuality)
  68575. {
  68576. }
  68577. void setOrigin (const int x, const int y) throw()
  68578. {
  68579. if (isOnlyTranslated)
  68580. {
  68581. xOffset += x;
  68582. yOffset += y;
  68583. }
  68584. else
  68585. {
  68586. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68587. }
  68588. }
  68589. void addTransform (const AffineTransform& t)
  68590. {
  68591. if ((! isOnlyTranslated)
  68592. || (! t.isOnlyTranslation())
  68593. || (int) (t.getTranslationX() * 256.0f) != 0
  68594. || (int) (t.getTranslationY() * 256.0f) != 0)
  68595. {
  68596. complexTransform = getTransformWith (t);
  68597. isOnlyTranslated = false;
  68598. }
  68599. else
  68600. {
  68601. xOffset += (int) t.getTranslationX();
  68602. yOffset += (int) t.getTranslationY();
  68603. }
  68604. }
  68605. float getScaleFactor() const
  68606. {
  68607. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68608. }
  68609. bool clipToRectangle (const Rectangle<int>& r)
  68610. {
  68611. if (clip != 0)
  68612. {
  68613. if (isOnlyTranslated)
  68614. {
  68615. cloneClipIfMultiplyReferenced();
  68616. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68617. }
  68618. else
  68619. {
  68620. Path p;
  68621. p.addRectangle (r);
  68622. clipToPath (p, AffineTransform::identity);
  68623. }
  68624. }
  68625. return clip != 0;
  68626. }
  68627. bool clipToRectangleList (const RectangleList& r)
  68628. {
  68629. if (clip != 0)
  68630. {
  68631. if (isOnlyTranslated)
  68632. {
  68633. cloneClipIfMultiplyReferenced();
  68634. RectangleList offsetList (r);
  68635. offsetList.offsetAll (xOffset, yOffset);
  68636. clip = clip->clipToRectangleList (offsetList);
  68637. }
  68638. else
  68639. {
  68640. clipToPath (r.toPath(), AffineTransform::identity);
  68641. }
  68642. }
  68643. return clip != 0;
  68644. }
  68645. bool excludeClipRectangle (const Rectangle<int>& r)
  68646. {
  68647. if (clip != 0)
  68648. {
  68649. cloneClipIfMultiplyReferenced();
  68650. if (isOnlyTranslated)
  68651. {
  68652. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68653. }
  68654. else
  68655. {
  68656. Path p;
  68657. p.addRectangle (r.toFloat());
  68658. p.applyTransform (complexTransform);
  68659. p.addRectangle (clip->getClipBounds().toFloat());
  68660. p.setUsingNonZeroWinding (false);
  68661. clip = clip->clipToPath (p, AffineTransform::identity);
  68662. }
  68663. }
  68664. return clip != 0;
  68665. }
  68666. void clipToPath (const Path& p, const AffineTransform& transform)
  68667. {
  68668. if (clip != 0)
  68669. {
  68670. cloneClipIfMultiplyReferenced();
  68671. clip = clip->clipToPath (p, getTransformWith (transform));
  68672. }
  68673. }
  68674. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68675. {
  68676. if (clip != 0)
  68677. {
  68678. if (image.hasAlphaChannel())
  68679. {
  68680. cloneClipIfMultiplyReferenced();
  68681. clip = clip->clipToImageAlpha (image, getTransformWith (t),
  68682. interpolationQuality != Graphics::lowResamplingQuality);
  68683. }
  68684. else
  68685. {
  68686. Path p;
  68687. p.addRectangle (image.getBounds());
  68688. clipToPath (p, t);
  68689. }
  68690. }
  68691. }
  68692. bool clipRegionIntersects (const Rectangle<int>& r) const
  68693. {
  68694. if (clip != 0)
  68695. {
  68696. if (isOnlyTranslated)
  68697. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68698. else
  68699. return getClipBounds().intersects (r);
  68700. }
  68701. return false;
  68702. }
  68703. const Rectangle<int> getUntransformedClipBounds() const
  68704. {
  68705. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68706. }
  68707. const Rectangle<int> getClipBounds() const
  68708. {
  68709. if (clip != 0)
  68710. {
  68711. if (isOnlyTranslated)
  68712. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68713. else
  68714. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68715. }
  68716. return Rectangle<int>();
  68717. }
  68718. SavedState* beginTransparencyLayer (float opacity)
  68719. {
  68720. const Rectangle<int> clip (getUntransformedClipBounds());
  68721. SavedState* s = new SavedState (*this);
  68722. s->image = Image (Image::ARGB, clip.getWidth(), clip.getHeight(), true);
  68723. s->compositionAlpha = opacity;
  68724. if (s->isOnlyTranslated)
  68725. {
  68726. s->xOffset -= clip.getX();
  68727. s->yOffset -= clip.getY();
  68728. }
  68729. else
  68730. {
  68731. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -clip.getX(),
  68732. (float) -clip.getY()));
  68733. }
  68734. s->cloneClipIfMultiplyReferenced();
  68735. s->clip = s->clip->translated (-clip.getPosition());
  68736. return s;
  68737. }
  68738. void endTransparencyLayer (SavedState& layerState)
  68739. {
  68740. const Rectangle<int> clip (getUntransformedClipBounds());
  68741. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68742. g->setOpacity (layerState.compositionAlpha);
  68743. g->drawImage (layerState.image, AffineTransform::translation ((float) clip.getX(),
  68744. (float) clip.getY()), false);
  68745. }
  68746. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68747. {
  68748. if (clip != 0)
  68749. {
  68750. if (isOnlyTranslated)
  68751. {
  68752. if (fillType.isColour())
  68753. {
  68754. Image::BitmapData destData (image, true);
  68755. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68756. }
  68757. else
  68758. {
  68759. const Rectangle<int> totalClip (clip->getClipBounds());
  68760. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68761. if (! clipped.isEmpty())
  68762. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68763. }
  68764. }
  68765. else
  68766. {
  68767. Path p;
  68768. p.addRectangle (r);
  68769. fillPath (p, AffineTransform::identity);
  68770. }
  68771. }
  68772. }
  68773. void fillRect (const Rectangle<float>& r)
  68774. {
  68775. if (clip != 0)
  68776. {
  68777. if (isOnlyTranslated)
  68778. {
  68779. if (fillType.isColour())
  68780. {
  68781. Image::BitmapData destData (image, true);
  68782. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68783. }
  68784. else
  68785. {
  68786. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68787. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68788. if (! clipped.isEmpty())
  68789. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68790. }
  68791. }
  68792. else
  68793. {
  68794. Path p;
  68795. p.addRectangle (r);
  68796. fillPath (p, AffineTransform::identity);
  68797. }
  68798. }
  68799. }
  68800. void fillPath (const Path& path, const AffineTransform& transform)
  68801. {
  68802. if (clip != 0)
  68803. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68804. }
  68805. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68806. {
  68807. jassert (isOnlyTranslated);
  68808. if (clip != 0)
  68809. {
  68810. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68811. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68812. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68813. fillShape (shapeToFill, false);
  68814. }
  68815. }
  68816. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68817. {
  68818. jassert (clip != 0);
  68819. shapeToFill = clip->applyClipTo (shapeToFill);
  68820. if (shapeToFill != 0)
  68821. {
  68822. Image::BitmapData destData (image, true);
  68823. if (fillType.isGradient())
  68824. {
  68825. jassert (! replaceContents); // that option is just for solid colours
  68826. ColourGradient g2 (*(fillType.gradient));
  68827. g2.multiplyOpacity (fillType.getOpacity());
  68828. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68829. const bool isIdentity = transform.isOnlyTranslation();
  68830. if (isIdentity)
  68831. {
  68832. // If our translation doesn't involve any distortion, we can speed it up..
  68833. g2.point1.applyTransform (transform);
  68834. g2.point2.applyTransform (transform);
  68835. transform = AffineTransform::identity;
  68836. }
  68837. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68838. }
  68839. else if (fillType.isTiledImage())
  68840. {
  68841. renderImage (fillType.image, fillType.transform, shapeToFill);
  68842. }
  68843. else
  68844. {
  68845. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68846. }
  68847. }
  68848. }
  68849. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68850. {
  68851. const AffineTransform transform (getTransformWith (t));
  68852. const Image::BitmapData destData (image, true);
  68853. const Image::BitmapData srcData (sourceImage, false);
  68854. const int alpha = fillType.colour.getAlpha();
  68855. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68856. if (transform.isOnlyTranslation())
  68857. {
  68858. // If our translation doesn't involve any distortion, just use a simple blit..
  68859. int tx = (int) (transform.getTranslationX() * 256.0f);
  68860. int ty = (int) (transform.getTranslationY() * 256.0f);
  68861. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68862. {
  68863. tx = ((tx + 128) >> 8);
  68864. ty = ((ty + 128) >> 8);
  68865. if (tiledFillClipRegion != 0)
  68866. {
  68867. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68868. }
  68869. else
  68870. {
  68871. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68872. c = clip->applyClipTo (c);
  68873. if (c != 0)
  68874. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68875. }
  68876. return;
  68877. }
  68878. }
  68879. if (transform.isSingularity())
  68880. return;
  68881. if (tiledFillClipRegion != 0)
  68882. {
  68883. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68884. }
  68885. else
  68886. {
  68887. Path p;
  68888. p.addRectangle (sourceImage.getBounds());
  68889. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68890. c = c->clipToPath (p, transform);
  68891. if (c != 0)
  68892. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68893. }
  68894. }
  68895. Image image;
  68896. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68897. private:
  68898. AffineTransform complexTransform;
  68899. int xOffset, yOffset;
  68900. float compositionAlpha;
  68901. public:
  68902. bool isOnlyTranslated;
  68903. Font font;
  68904. FillType fillType;
  68905. Graphics::ResamplingQuality interpolationQuality;
  68906. private:
  68907. void cloneClipIfMultiplyReferenced()
  68908. {
  68909. if (clip->getReferenceCount() > 1)
  68910. clip = clip->clone();
  68911. }
  68912. const AffineTransform getTransform() const
  68913. {
  68914. if (isOnlyTranslated)
  68915. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68916. return complexTransform;
  68917. }
  68918. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68919. {
  68920. if (isOnlyTranslated)
  68921. return userTransform.translated ((float) xOffset, (float) yOffset);
  68922. return userTransform.followedBy (complexTransform);
  68923. }
  68924. SavedState& operator= (const SavedState&);
  68925. };
  68926. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68927. : image (image_),
  68928. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  68929. {
  68930. }
  68931. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68932. const RectangleList& initialClip)
  68933. : image (image_),
  68934. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  68935. {
  68936. }
  68937. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68938. {
  68939. }
  68940. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68941. {
  68942. return false;
  68943. }
  68944. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68945. {
  68946. currentState->setOrigin (x, y);
  68947. }
  68948. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  68949. {
  68950. currentState->addTransform (transform);
  68951. }
  68952. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  68953. {
  68954. return currentState->getScaleFactor();
  68955. }
  68956. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68957. {
  68958. return currentState->clipToRectangle (r);
  68959. }
  68960. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68961. {
  68962. return currentState->clipToRectangleList (clipRegion);
  68963. }
  68964. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68965. {
  68966. currentState->excludeClipRectangle (r);
  68967. }
  68968. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68969. {
  68970. currentState->clipToPath (path, transform);
  68971. }
  68972. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68973. {
  68974. currentState->clipToImageAlpha (sourceImage, transform);
  68975. }
  68976. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68977. {
  68978. return currentState->clipRegionIntersects (r);
  68979. }
  68980. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68981. {
  68982. return currentState->getClipBounds();
  68983. }
  68984. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68985. {
  68986. return currentState->clip == 0;
  68987. }
  68988. void LowLevelGraphicsSoftwareRenderer::saveState()
  68989. {
  68990. stateStack.add (new SavedState (*currentState));
  68991. }
  68992. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68993. {
  68994. SavedState* const top = stateStack.getLast();
  68995. if (top != 0)
  68996. {
  68997. currentState = top;
  68998. stateStack.removeLast (1, false);
  68999. }
  69000. else
  69001. {
  69002. jassertfalse; // trying to pop with an empty stack!
  69003. }
  69004. }
  69005. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69006. {
  69007. saveState();
  69008. currentState = currentState->beginTransparencyLayer (opacity);
  69009. }
  69010. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69011. {
  69012. const ScopedPointer<SavedState> layer (currentState);
  69013. restoreState();
  69014. currentState->endTransparencyLayer (*layer);
  69015. }
  69016. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69017. {
  69018. currentState->fillType = fillType;
  69019. }
  69020. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69021. {
  69022. currentState->fillType.setOpacity (newOpacity);
  69023. }
  69024. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69025. {
  69026. currentState->interpolationQuality = quality;
  69027. }
  69028. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69029. {
  69030. currentState->fillRect (r, replaceExistingContents);
  69031. }
  69032. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69033. {
  69034. currentState->fillPath (path, transform);
  69035. }
  69036. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69037. {
  69038. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69039. }
  69040. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69041. {
  69042. Path p;
  69043. p.addLineSegment (line, 1.0f);
  69044. fillPath (p, AffineTransform::identity);
  69045. }
  69046. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69047. {
  69048. if (bottom > top)
  69049. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69050. }
  69051. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69052. {
  69053. if (right > left)
  69054. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69055. }
  69056. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69057. {
  69058. public:
  69059. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69060. ~CachedGlyph() {}
  69061. void draw (SavedState& state, const float x, const float y) const
  69062. {
  69063. if (edgeTable != 0)
  69064. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69065. }
  69066. void generate (const Font& newFont, const int glyphNumber)
  69067. {
  69068. font = newFont;
  69069. glyph = glyphNumber;
  69070. edgeTable = 0;
  69071. Path glyphPath;
  69072. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69073. if (! glyphPath.isEmpty())
  69074. {
  69075. const float fontHeight = font.getHeight();
  69076. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69077. #if JUCE_MAC || JUCE_IOS
  69078. .translated (0.0f, -0.5f)
  69079. #endif
  69080. );
  69081. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69082. glyphPath, transform);
  69083. }
  69084. }
  69085. int glyph, lastAccessCount;
  69086. Font font;
  69087. private:
  69088. ScopedPointer <EdgeTable> edgeTable;
  69089. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69090. };
  69091. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69092. {
  69093. public:
  69094. GlyphCache()
  69095. : accessCounter (0), hits (0), misses (0)
  69096. {
  69097. for (int i = 120; --i >= 0;)
  69098. glyphs.add (new CachedGlyph());
  69099. }
  69100. ~GlyphCache()
  69101. {
  69102. clearSingletonInstance();
  69103. }
  69104. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69105. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69106. {
  69107. ++accessCounter;
  69108. int oldestCounter = std::numeric_limits<int>::max();
  69109. CachedGlyph* oldest = 0;
  69110. for (int i = glyphs.size(); --i >= 0;)
  69111. {
  69112. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69113. if (glyph->glyph == glyphNumber && glyph->font == font)
  69114. {
  69115. ++hits;
  69116. glyph->lastAccessCount = accessCounter;
  69117. glyph->draw (state, x, y);
  69118. return;
  69119. }
  69120. if (glyph->lastAccessCount <= oldestCounter)
  69121. {
  69122. oldestCounter = glyph->lastAccessCount;
  69123. oldest = glyph;
  69124. }
  69125. }
  69126. if (hits + ++misses > (glyphs.size() << 4))
  69127. {
  69128. if (misses * 2 > hits)
  69129. {
  69130. for (int i = 32; --i >= 0;)
  69131. glyphs.add (new CachedGlyph());
  69132. }
  69133. hits = misses = 0;
  69134. oldest = glyphs.getLast();
  69135. }
  69136. jassert (oldest != 0);
  69137. oldest->lastAccessCount = accessCounter;
  69138. oldest->generate (font, glyphNumber);
  69139. oldest->draw (state, x, y);
  69140. }
  69141. private:
  69142. friend class OwnedArray <CachedGlyph>;
  69143. OwnedArray <CachedGlyph> glyphs;
  69144. int accessCounter, hits, misses;
  69145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69146. };
  69147. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69148. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69149. {
  69150. currentState->font = newFont;
  69151. }
  69152. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69153. {
  69154. return currentState->font;
  69155. }
  69156. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69157. {
  69158. Font& f = currentState->font;
  69159. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69160. {
  69161. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69162. transform.getTranslationX(),
  69163. transform.getTranslationY());
  69164. }
  69165. else
  69166. {
  69167. Path p;
  69168. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69169. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69170. }
  69171. }
  69172. #if JUCE_MSVC
  69173. #pragma warning (pop)
  69174. #if JUCE_DEBUG
  69175. #pragma optimize ("", on) // resets optimisations to the project defaults
  69176. #endif
  69177. #endif
  69178. END_JUCE_NAMESPACE
  69179. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69180. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69181. BEGIN_JUCE_NAMESPACE
  69182. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69183. : flags (other.flags)
  69184. {
  69185. }
  69186. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69187. {
  69188. flags = other.flags;
  69189. return *this;
  69190. }
  69191. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69192. const double dx, const double dy, const double dw, const double dh) const throw()
  69193. {
  69194. if (w == 0 || h == 0)
  69195. return;
  69196. if ((flags & stretchToFit) != 0)
  69197. {
  69198. x = dx;
  69199. y = dy;
  69200. w = dw;
  69201. h = dh;
  69202. }
  69203. else
  69204. {
  69205. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69206. : jmin (dw / w, dh / h);
  69207. if ((flags & onlyReduceInSize) != 0)
  69208. scale = jmin (scale, 1.0);
  69209. if ((flags & onlyIncreaseInSize) != 0)
  69210. scale = jmax (scale, 1.0);
  69211. w *= scale;
  69212. h *= scale;
  69213. if ((flags & xLeft) != 0)
  69214. x = dx;
  69215. else if ((flags & xRight) != 0)
  69216. x = dx + dw - w;
  69217. else
  69218. x = dx + (dw - w) * 0.5;
  69219. if ((flags & yTop) != 0)
  69220. y = dy;
  69221. else if ((flags & yBottom) != 0)
  69222. y = dy + dh - h;
  69223. else
  69224. y = dy + (dh - h) * 0.5;
  69225. }
  69226. }
  69227. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69228. {
  69229. if (source.isEmpty())
  69230. return AffineTransform::identity;
  69231. float newX = destination.getX();
  69232. float newY = destination.getY();
  69233. float scaleX = destination.getWidth() / source.getWidth();
  69234. float scaleY = destination.getHeight() / source.getHeight();
  69235. if ((flags & stretchToFit) == 0)
  69236. {
  69237. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69238. : jmin (scaleX, scaleY);
  69239. if ((flags & onlyReduceInSize) != 0)
  69240. scaleX = jmin (scaleX, 1.0f);
  69241. if ((flags & onlyIncreaseInSize) != 0)
  69242. scaleX = jmax (scaleX, 1.0f);
  69243. scaleY = scaleX;
  69244. if ((flags & xRight) != 0)
  69245. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69246. else if ((flags & xLeft) == 0)
  69247. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69248. if ((flags & yBottom) != 0)
  69249. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69250. else if ((flags & yTop) == 0)
  69251. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69252. }
  69253. return AffineTransform::translation (-source.getX(), -source.getY())
  69254. .scaled (scaleX, scaleY)
  69255. .translated (newX, newY);
  69256. }
  69257. END_JUCE_NAMESPACE
  69258. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69259. /*** Start of inlined file: juce_Drawable.cpp ***/
  69260. BEGIN_JUCE_NAMESPACE
  69261. Drawable::Drawable()
  69262. {
  69263. setInterceptsMouseClicks (false, false);
  69264. setPaintingIsUnclipped (true);
  69265. }
  69266. Drawable::~Drawable()
  69267. {
  69268. }
  69269. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69270. {
  69271. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69272. }
  69273. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69274. {
  69275. Graphics::ScopedSaveState ss (g);
  69276. const float oldOpacity = getAlpha();
  69277. setAlpha (opacity);
  69278. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69279. (float) -originRelativeToComponent.getY())
  69280. .followedBy (getTransform())
  69281. .followedBy (transform));
  69282. if (! g.isClipEmpty())
  69283. paintEntireComponent (g, false);
  69284. setAlpha (oldOpacity);
  69285. }
  69286. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69287. {
  69288. draw (g, opacity, AffineTransform::translation (x, y));
  69289. }
  69290. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69291. {
  69292. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69293. }
  69294. DrawableComposite* Drawable::getParent() const
  69295. {
  69296. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69297. }
  69298. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69299. {
  69300. g.setOrigin (originRelativeToComponent.getX(),
  69301. originRelativeToComponent.getY());
  69302. }
  69303. void Drawable::markerHasMoved()
  69304. {
  69305. }
  69306. void Drawable::parentHierarchyChanged()
  69307. {
  69308. setBoundsToEnclose (getDrawableBounds());
  69309. }
  69310. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69311. {
  69312. Drawable* const parent = getParent();
  69313. Point<int> parentOrigin;
  69314. if (parent != 0)
  69315. parentOrigin = parent->originRelativeToComponent;
  69316. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69317. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69318. setBounds (newBounds);
  69319. }
  69320. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69321. {
  69322. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69323. }
  69324. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69325. {
  69326. if (! area.isEmpty())
  69327. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69328. }
  69329. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69330. {
  69331. Drawable* result = 0;
  69332. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69333. if (image.isValid())
  69334. {
  69335. DrawableImage* const di = new DrawableImage();
  69336. di->setImage (image);
  69337. result = di;
  69338. }
  69339. else
  69340. {
  69341. const String asString (String::createStringFromData (data, (int) numBytes));
  69342. XmlDocument doc (asString);
  69343. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69344. if (outer != 0 && outer->hasTagName ("svg"))
  69345. {
  69346. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69347. if (svg != 0)
  69348. result = Drawable::createFromSVG (*svg);
  69349. }
  69350. }
  69351. return result;
  69352. }
  69353. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69354. {
  69355. MemoryOutputStream mo;
  69356. mo.writeFromInputStream (dataSource, -1);
  69357. return createFromImageData (mo.getData(), mo.getDataSize());
  69358. }
  69359. Drawable* Drawable::createFromImageFile (const File& file)
  69360. {
  69361. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69362. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69363. }
  69364. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69365. {
  69366. return createChildFromValueTree (0, tree, imageProvider);
  69367. }
  69368. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69369. {
  69370. const Identifier type (tree.getType());
  69371. Drawable* d = 0;
  69372. if (type == DrawablePath::valueTreeType) d = new DrawablePath();
  69373. else if (type == DrawableComposite::valueTreeType) d = new DrawableComposite();
  69374. else if (type == DrawableRectangle::valueTreeType) d = new DrawableRectangle();
  69375. else if (type == DrawableImage::valueTreeType) d = new DrawableImage();
  69376. else if (type == DrawableText::valueTreeType) d = new DrawableText();
  69377. if (d != 0)
  69378. {
  69379. if (parent != 0)
  69380. parent->insertDrawable (d);
  69381. d->refreshFromValueTree (tree, imageProvider);
  69382. }
  69383. return d;
  69384. }
  69385. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69386. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69387. : state (state_)
  69388. {
  69389. }
  69390. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69391. {
  69392. }
  69393. const String Drawable::ValueTreeWrapperBase::getID() const
  69394. {
  69395. return state [idProperty];
  69396. }
  69397. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69398. {
  69399. if (newID.isEmpty())
  69400. state.removeProperty (idProperty, undoManager);
  69401. else
  69402. state.setProperty (idProperty, newID, undoManager);
  69403. }
  69404. END_JUCE_NAMESPACE
  69405. /*** End of inlined file: juce_Drawable.cpp ***/
  69406. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69407. BEGIN_JUCE_NAMESPACE
  69408. DrawableShape::DrawableShape()
  69409. : strokeType (0.0f),
  69410. mainFill (Colours::black),
  69411. strokeFill (Colours::black)
  69412. {
  69413. }
  69414. DrawableShape::DrawableShape (const DrawableShape& other)
  69415. : strokeType (other.strokeType),
  69416. mainFill (other.mainFill),
  69417. strokeFill (other.strokeFill)
  69418. {
  69419. }
  69420. DrawableShape::~DrawableShape()
  69421. {
  69422. }
  69423. void DrawableShape::setFill (const FillType& newFill)
  69424. {
  69425. mainFill = newFill;
  69426. }
  69427. void DrawableShape::setStrokeFill (const FillType& newFill)
  69428. {
  69429. strokeFill = newFill;
  69430. }
  69431. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69432. {
  69433. strokeType = newStrokeType;
  69434. strokeChanged();
  69435. }
  69436. void DrawableShape::setStrokeThickness (const float newThickness)
  69437. {
  69438. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69439. }
  69440. bool DrawableShape::isStrokeVisible() const throw()
  69441. {
  69442. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69443. }
  69444. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69445. Expression::EvaluationContext* /*nameFinder*/,
  69446. ImageProvider* imageProvider)
  69447. {
  69448. bool hasChanged = false;
  69449. {
  69450. const FillType f (newState.getMainFill (getParent(), imageProvider));
  69451. if (mainFill != f)
  69452. {
  69453. hasChanged = true;
  69454. mainFill = f;
  69455. }
  69456. }
  69457. {
  69458. const FillType f (newState.getStrokeFill (getParent(), imageProvider));
  69459. if (strokeFill != f)
  69460. {
  69461. hasChanged = true;
  69462. strokeFill = f;
  69463. }
  69464. }
  69465. return hasChanged;
  69466. }
  69467. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69468. {
  69469. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69470. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69471. state.setStrokeType (strokeType, undoManager);
  69472. }
  69473. void DrawableShape::paint (Graphics& g)
  69474. {
  69475. transformContextToCorrectOrigin (g);
  69476. g.setFillType (mainFill);
  69477. g.fillPath (path);
  69478. if (isStrokeVisible())
  69479. {
  69480. g.setFillType (strokeFill);
  69481. g.fillPath (strokePath);
  69482. }
  69483. }
  69484. void DrawableShape::pathChanged()
  69485. {
  69486. strokeChanged();
  69487. }
  69488. void DrawableShape::strokeChanged()
  69489. {
  69490. strokePath.clear();
  69491. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69492. setBoundsToEnclose (getDrawableBounds());
  69493. repaint();
  69494. }
  69495. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69496. {
  69497. if (isStrokeVisible())
  69498. return strokePath.getBounds();
  69499. else
  69500. return path.getBounds();
  69501. }
  69502. bool DrawableShape::hitTest (int x, int y) const
  69503. {
  69504. const float globalX = (float) (x - originRelativeToComponent.getX());
  69505. const float globalY = (float) (y - originRelativeToComponent.getY());
  69506. return path.contains (globalX, globalY)
  69507. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69508. }
  69509. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69510. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69511. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69512. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69513. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69514. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69515. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69516. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69517. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69518. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69519. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69520. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69521. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69522. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69523. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69524. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69525. : Drawable::ValueTreeWrapperBase (state_)
  69526. {
  69527. }
  69528. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69529. ImageProvider* imageProvider) const
  69530. {
  69531. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69532. }
  69533. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69534. {
  69535. ValueTree v (state.getChildWithName (fill));
  69536. if (v.isValid())
  69537. return v;
  69538. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69539. return getMainFillState();
  69540. }
  69541. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69542. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69543. {
  69544. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69545. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69546. }
  69547. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69548. ImageProvider* imageProvider) const
  69549. {
  69550. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69551. }
  69552. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69553. {
  69554. ValueTree v (state.getChildWithName (stroke));
  69555. if (v.isValid())
  69556. return v;
  69557. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69558. return getStrokeFillState();
  69559. }
  69560. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69561. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69562. {
  69563. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69564. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69565. }
  69566. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69567. {
  69568. const String jointStyleString (state [jointStyle].toString());
  69569. const String capStyleString (state [capStyle].toString());
  69570. return PathStrokeType (state [strokeWidth],
  69571. jointStyleString == "curved" ? PathStrokeType::curved
  69572. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69573. : PathStrokeType::mitered),
  69574. capStyleString == "square" ? PathStrokeType::square
  69575. : (capStyleString == "round" ? PathStrokeType::rounded
  69576. : PathStrokeType::butt));
  69577. }
  69578. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69579. {
  69580. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69581. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69582. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69583. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69584. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69585. }
  69586. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69587. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69588. {
  69589. const String newType (v[type].toString());
  69590. if (newType == "solid")
  69591. {
  69592. const String colourString (v [colour].toString());
  69593. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69594. : (uint32) colourString.getHexValue32()));
  69595. }
  69596. else if (newType == "gradient")
  69597. {
  69598. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69599. ColourGradient g;
  69600. if (gp1 != 0) *gp1 = p1;
  69601. if (gp2 != 0) *gp2 = p2;
  69602. if (gp3 != 0) *gp3 = p3;
  69603. g.point1 = p1.resolve (nameFinder);
  69604. g.point2 = p2.resolve (nameFinder);
  69605. g.isRadial = v[radial];
  69606. StringArray colourSteps;
  69607. colourSteps.addTokens (v[colours].toString(), false);
  69608. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69609. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69610. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69611. FillType fillType (g);
  69612. if (g.isRadial)
  69613. {
  69614. const Point<float> point3 (p3.resolve (nameFinder));
  69615. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69616. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69617. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69618. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69619. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69620. }
  69621. return fillType;
  69622. }
  69623. else if (newType == "image")
  69624. {
  69625. Image im;
  69626. if (imageProvider != 0)
  69627. im = imageProvider->getImageForIdentifier (v[imageId]);
  69628. FillType f (im, AffineTransform::identity);
  69629. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69630. return f;
  69631. }
  69632. jassert (! v.isValid());
  69633. return FillType();
  69634. }
  69635. namespace DrawableShapeHelpers
  69636. {
  69637. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69638. {
  69639. const ColourGradient& g = *fillType.gradient;
  69640. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69641. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69642. return point3Source.transformedBy (fillType.transform);
  69643. }
  69644. }
  69645. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69646. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69647. ImageProvider* imageProvider, UndoManager* const undoManager)
  69648. {
  69649. if (fillType.isColour())
  69650. {
  69651. v.setProperty (type, "solid", undoManager);
  69652. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69653. }
  69654. else if (fillType.isGradient())
  69655. {
  69656. v.setProperty (type, "gradient", undoManager);
  69657. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69658. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69659. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69660. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69661. String s;
  69662. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69663. s << ' ' << fillType.gradient->getColourPosition (i)
  69664. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69665. v.setProperty (colours, s.trimStart(), undoManager);
  69666. }
  69667. else if (fillType.isTiledImage())
  69668. {
  69669. v.setProperty (type, "image", undoManager);
  69670. if (imageProvider != 0)
  69671. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69672. if (fillType.getOpacity() < 1.0f)
  69673. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69674. else
  69675. v.removeProperty (imageOpacity, undoManager);
  69676. }
  69677. else
  69678. {
  69679. jassertfalse;
  69680. }
  69681. }
  69682. END_JUCE_NAMESPACE
  69683. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69684. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69685. BEGIN_JUCE_NAMESPACE
  69686. DrawableComposite::DrawableComposite()
  69687. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69688. updateBoundsReentrant (false)
  69689. {
  69690. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69691. RelativeCoordinate (100.0),
  69692. RelativeCoordinate (0.0),
  69693. RelativeCoordinate (100.0)));
  69694. }
  69695. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69696. : bounds (other.bounds),
  69697. updateBoundsReentrant (false)
  69698. {
  69699. for (int i = 0; i < other.getNumDrawables(); ++i)
  69700. insertDrawable (other.getDrawable(i)->createCopy());
  69701. markersX.addCopiesOf (other.markersX);
  69702. markersY.addCopiesOf (other.markersY);
  69703. }
  69704. DrawableComposite::~DrawableComposite()
  69705. {
  69706. deleteAllChildren();
  69707. }
  69708. int DrawableComposite::getNumDrawables() const throw()
  69709. {
  69710. return getNumChildComponents();
  69711. }
  69712. Drawable* DrawableComposite::getDrawable (int index) const
  69713. {
  69714. return dynamic_cast <Drawable*> (getChildComponent (index));
  69715. }
  69716. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69717. {
  69718. if (drawable != 0)
  69719. addAndMakeVisible (drawable, index);
  69720. }
  69721. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69722. {
  69723. insertDrawable (drawable.createCopy(), index);
  69724. }
  69725. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69726. {
  69727. Drawable* const d = getDrawable (index);
  69728. if (deleteDrawable)
  69729. delete d;
  69730. else
  69731. removeChildComponent (d);
  69732. }
  69733. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69734. {
  69735. for (int i = getNumChildComponents(); --i >= 0;)
  69736. if (getChildComponent(i)->getName() == name)
  69737. return getDrawable (i);
  69738. return 0;
  69739. }
  69740. void DrawableComposite::bringToFront (const int index)
  69741. {
  69742. Drawable* d = getDrawable (index);
  69743. if (d != 0)
  69744. d->toFront (false);
  69745. }
  69746. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69747. {
  69748. Rectangle<float> r;
  69749. for (int i = getNumDrawables(); --i >= 0;)
  69750. {
  69751. Drawable* const d = getDrawable(i);
  69752. if (d != 0)
  69753. {
  69754. if (d->isTransformed())
  69755. r = r.getUnion (d->getDrawableBounds().transformed (d->getTransform()));
  69756. else
  69757. r = r.getUnion (d->getDrawableBounds());
  69758. }
  69759. }
  69760. return r;
  69761. }
  69762. void DrawableComposite::markerHasMoved()
  69763. {
  69764. for (int i = getNumDrawables(); --i >= 0;)
  69765. {
  69766. Drawable* const d = getDrawable(i);
  69767. if (d != 0)
  69768. d->markerHasMoved();
  69769. }
  69770. }
  69771. const RelativeRectangle DrawableComposite::getContentArea() const
  69772. {
  69773. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69774. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69775. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69776. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69777. }
  69778. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69779. {
  69780. setMarker (contentLeftMarkerName, true, newArea.left);
  69781. setMarker (contentRightMarkerName, true, newArea.right);
  69782. setMarker (contentTopMarkerName, false, newArea.top);
  69783. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69784. refreshTransformFromBounds();
  69785. }
  69786. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69787. {
  69788. bounds = newBoundingBox;
  69789. refreshTransformFromBounds();
  69790. }
  69791. void DrawableComposite::resetBoundingBoxToContentArea()
  69792. {
  69793. const RelativeRectangle content (getContentArea());
  69794. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69795. RelativePoint (content.right, content.top),
  69796. RelativePoint (content.left, content.bottom)));
  69797. }
  69798. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69799. {
  69800. const Rectangle<float> activeArea (getDrawableBounds());
  69801. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69802. RelativeCoordinate (activeArea.getRight()),
  69803. RelativeCoordinate (activeArea.getY()),
  69804. RelativeCoordinate (activeArea.getBottom())));
  69805. resetBoundingBoxToContentArea();
  69806. }
  69807. void DrawableComposite::refreshTransformFromBounds()
  69808. {
  69809. Point<float> resolved[3];
  69810. bounds.resolveThreePoints (resolved, getParent());
  69811. const Rectangle<float> content (getContentArea().resolve (getParent()));
  69812. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69813. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69814. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69815. if (t.isSingularity())
  69816. t = AffineTransform::identity;
  69817. setTransform (t);
  69818. }
  69819. void DrawableComposite::parentHierarchyChanged()
  69820. {
  69821. DrawableComposite* parent = getParent();
  69822. if (parent != 0)
  69823. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69824. }
  69825. void DrawableComposite::childBoundsChanged (Component*)
  69826. {
  69827. updateBoundsToFitChildren();
  69828. }
  69829. void DrawableComposite::childrenChanged()
  69830. {
  69831. updateBoundsToFitChildren();
  69832. }
  69833. struct RentrancyCheckSetter
  69834. {
  69835. RentrancyCheckSetter (bool& b_) : b (b_) { b_ = true; }
  69836. ~RentrancyCheckSetter() { b = false; }
  69837. private:
  69838. bool& b;
  69839. JUCE_DECLARE_NON_COPYABLE (RentrancyCheckSetter);
  69840. };
  69841. void DrawableComposite::updateBoundsToFitChildren()
  69842. {
  69843. if (! updateBoundsReentrant)
  69844. {
  69845. const RentrancyCheckSetter checkSetter (updateBoundsReentrant);
  69846. Rectangle<int> childArea;
  69847. for (int i = getNumChildComponents(); --i >= 0;)
  69848. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  69849. const Point<int> delta (childArea.getPosition());
  69850. childArea += getPosition();
  69851. if (childArea != getBounds())
  69852. {
  69853. if (! delta.isOrigin())
  69854. {
  69855. originRelativeToComponent -= delta;
  69856. for (int i = getNumChildComponents(); --i >= 0;)
  69857. {
  69858. Component* const c = getChildComponent(i);
  69859. if (c != 0)
  69860. c->setBounds (c->getBounds() - delta);
  69861. }
  69862. }
  69863. setBounds (childArea);
  69864. }
  69865. }
  69866. }
  69867. const char* const DrawableComposite::contentLeftMarkerName = "left";
  69868. const char* const DrawableComposite::contentRightMarkerName = "right";
  69869. const char* const DrawableComposite::contentTopMarkerName = "top";
  69870. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  69871. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69872. : name (other.name), position (other.position)
  69873. {
  69874. }
  69875. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69876. : name (name_), position (position_)
  69877. {
  69878. }
  69879. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69880. {
  69881. return name != other.name || position != other.position;
  69882. }
  69883. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69884. {
  69885. return (xAxis ? markersX : markersY).size();
  69886. }
  69887. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69888. {
  69889. return (xAxis ? markersX : markersY) [index];
  69890. }
  69891. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69892. {
  69893. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69894. for (int i = 0; i < markers.size(); ++i)
  69895. {
  69896. Marker* const m = markers.getUnchecked(i);
  69897. if (m->name == name)
  69898. {
  69899. if (m->position != position)
  69900. {
  69901. m->position = position;
  69902. markerHasMoved();
  69903. }
  69904. return;
  69905. }
  69906. }
  69907. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69908. markerHasMoved();
  69909. }
  69910. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69911. {
  69912. jassert (index >= 2);
  69913. if (index >= 2)
  69914. (xAxis ? markersX : markersY).remove (index);
  69915. }
  69916. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69917. {
  69918. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69919. int i;
  69920. for (i = 0; i < markersX.size(); ++i)
  69921. {
  69922. Marker* const m = markersX.getUnchecked(i);
  69923. if (m->name == symbol)
  69924. return m->position.getExpression();
  69925. }
  69926. for (i = 0; i < markersY.size(); ++i)
  69927. {
  69928. Marker* const m = markersY.getUnchecked(i);
  69929. if (m->name == symbol)
  69930. return m->position.getExpression();
  69931. }
  69932. throw Expression::EvaluationError (symbol, member);
  69933. }
  69934. Drawable* DrawableComposite::createCopy() const
  69935. {
  69936. return new DrawableComposite (*this);
  69937. }
  69938. const Identifier DrawableComposite::valueTreeType ("Group");
  69939. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69940. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69941. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69942. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69943. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69944. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69945. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69946. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69947. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69948. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69949. : ValueTreeWrapperBase (state_)
  69950. {
  69951. jassert (state.hasType (valueTreeType));
  69952. }
  69953. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69954. {
  69955. return state.getChildWithName (childGroupTag);
  69956. }
  69957. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69958. {
  69959. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69960. }
  69961. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69962. {
  69963. return getChildList().getNumChildren();
  69964. }
  69965. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69966. {
  69967. return getChildList().getChild (index);
  69968. }
  69969. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69970. {
  69971. if (getID() == objectId)
  69972. return state;
  69973. if (! recursive)
  69974. {
  69975. return getChildList().getChildWithProperty (idProperty, objectId);
  69976. }
  69977. else
  69978. {
  69979. const ValueTree childList (getChildList());
  69980. for (int i = getNumDrawables(); --i >= 0;)
  69981. {
  69982. const ValueTree& child = childList.getChild (i);
  69983. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69984. return child;
  69985. if (child.hasType (DrawableComposite::valueTreeType))
  69986. {
  69987. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69988. if (v.isValid())
  69989. return v;
  69990. }
  69991. }
  69992. return ValueTree::invalid;
  69993. }
  69994. }
  69995. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69996. {
  69997. return getChildList().indexOf (item);
  69998. }
  69999. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70000. {
  70001. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70002. }
  70003. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70004. {
  70005. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70006. }
  70007. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70008. {
  70009. getChildList().removeChild (child, undoManager);
  70010. }
  70011. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70012. {
  70013. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70014. state.getProperty (topRight, "100, 0"),
  70015. state.getProperty (bottomLeft, "0, 100"));
  70016. }
  70017. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70018. {
  70019. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70020. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70021. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70022. }
  70023. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70024. {
  70025. const RelativeRectangle content (getContentArea());
  70026. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70027. RelativePoint (content.right, content.top),
  70028. RelativePoint (content.left, content.bottom)), undoManager);
  70029. }
  70030. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70031. {
  70032. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70033. getMarker (true, getMarkerState (true, 1)).position,
  70034. getMarker (false, getMarkerState (false, 0)).position,
  70035. getMarker (false, getMarkerState (false, 1)).position);
  70036. }
  70037. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70038. {
  70039. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70040. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70041. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70042. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70043. }
  70044. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70045. {
  70046. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70047. }
  70048. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70049. {
  70050. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70051. }
  70052. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70053. {
  70054. return getMarkerList (xAxis).getNumChildren();
  70055. }
  70056. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70057. {
  70058. return getMarkerList (xAxis).getChild (index);
  70059. }
  70060. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70061. {
  70062. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70063. }
  70064. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70065. {
  70066. return state.isAChildOf (getMarkerList (xAxis));
  70067. }
  70068. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70069. {
  70070. (void) xAxis;
  70071. jassert (containsMarker (xAxis, state));
  70072. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70073. }
  70074. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70075. {
  70076. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70077. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70078. if (marker.isValid())
  70079. {
  70080. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70081. }
  70082. else
  70083. {
  70084. marker = ValueTree (markerTag);
  70085. marker.setProperty (nameProperty, m.name, 0);
  70086. marker.setProperty (posProperty, m.position.toString(), 0);
  70087. markerList.addChild (marker, -1, undoManager);
  70088. }
  70089. }
  70090. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70091. {
  70092. if (state [nameProperty].toString() != contentLeftMarkerName
  70093. && state [nameProperty].toString() != contentRightMarkerName
  70094. && state [nameProperty].toString() != contentTopMarkerName
  70095. && state [nameProperty].toString() != contentBottomMarkerName)
  70096. getMarkerList (xAxis).removeChild (state, undoManager);
  70097. }
  70098. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70099. {
  70100. const ValueTreeWrapper wrapper (tree);
  70101. setName (wrapper.getID());
  70102. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70103. if (bounds != newBounds)
  70104. bounds = newBounds;
  70105. const int numMarkersX = wrapper.getNumMarkers (true);
  70106. const int numMarkersY = wrapper.getNumMarkers (false);
  70107. // Remove deleted markers...
  70108. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70109. {
  70110. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70111. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70112. }
  70113. // Update markers and add new ones..
  70114. int i;
  70115. for (i = 0; i < numMarkersX; ++i)
  70116. {
  70117. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70118. Marker* m = markersX[i];
  70119. if (m == 0)
  70120. markersX.add (new Marker (newMarker));
  70121. else if (newMarker != *m)
  70122. *m = newMarker;
  70123. }
  70124. for (i = 0; i < numMarkersY; ++i)
  70125. {
  70126. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70127. Marker* m = markersY[i];
  70128. if (m == 0)
  70129. markersY.add (new Marker (newMarker));
  70130. else if (newMarker != *m)
  70131. *m = newMarker;
  70132. }
  70133. // Remove deleted drawables..
  70134. for (i = getNumDrawables(); --i >= wrapper.getNumDrawables();)
  70135. delete getDrawable(i);
  70136. // Update drawables and add new ones..
  70137. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70138. {
  70139. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70140. Drawable* d = getDrawable(i);
  70141. if (d != 0)
  70142. {
  70143. if (newDrawable.hasType (d->getValueTreeType()))
  70144. {
  70145. d->refreshFromValueTree (newDrawable, imageProvider);
  70146. }
  70147. else
  70148. {
  70149. delete d;
  70150. d = 0;
  70151. }
  70152. }
  70153. if (d == 0)
  70154. {
  70155. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70156. addAndMakeVisible (d, i);
  70157. }
  70158. }
  70159. refreshTransformFromBounds();
  70160. }
  70161. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70162. {
  70163. ValueTree tree (valueTreeType);
  70164. ValueTreeWrapper v (tree);
  70165. v.setID (getName(), 0);
  70166. v.setBoundingBox (bounds, 0);
  70167. int i;
  70168. for (i = 0; i < getNumDrawables(); ++i)
  70169. v.addDrawable (getDrawable(i)->createValueTree (imageProvider), -1, 0);
  70170. for (i = 0; i < markersX.size(); ++i)
  70171. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70172. for (i = 0; i < markersY.size(); ++i)
  70173. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70174. return tree;
  70175. }
  70176. END_JUCE_NAMESPACE
  70177. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70178. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70179. BEGIN_JUCE_NAMESPACE
  70180. DrawableImage::DrawableImage()
  70181. : image (0),
  70182. opacity (1.0f),
  70183. overlayColour (0x00000000)
  70184. {
  70185. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70186. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70187. }
  70188. DrawableImage::DrawableImage (const DrawableImage& other)
  70189. : image (other.image),
  70190. opacity (other.opacity),
  70191. overlayColour (other.overlayColour),
  70192. bounds (other.bounds)
  70193. {
  70194. }
  70195. DrawableImage::~DrawableImage()
  70196. {
  70197. }
  70198. void DrawableImage::setImage (const Image& imageToUse)
  70199. {
  70200. image = imageToUse;
  70201. setBounds (imageToUse.getBounds());
  70202. if (image.isValid())
  70203. {
  70204. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70205. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70206. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70207. }
  70208. refreshTransformFromBounds();
  70209. }
  70210. void DrawableImage::setOpacity (const float newOpacity)
  70211. {
  70212. opacity = newOpacity;
  70213. }
  70214. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70215. {
  70216. overlayColour = newOverlayColour;
  70217. }
  70218. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70219. {
  70220. bounds = newBounds;
  70221. refreshTransformFromBounds();
  70222. }
  70223. void DrawableImage::refreshTransformFromBounds()
  70224. {
  70225. if (! image.isNull())
  70226. {
  70227. Point<float> resolved[3];
  70228. bounds.resolveThreePoints (resolved, getParent());
  70229. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70230. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70231. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70232. tr.getX(), tr.getY(),
  70233. bl.getX(), bl.getY()));
  70234. if (! t.isSingularity())
  70235. setTransform (t);
  70236. }
  70237. }
  70238. void DrawableImage::paint (Graphics& g)
  70239. {
  70240. if (image.isValid())
  70241. {
  70242. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70243. {
  70244. g.setOpacity (opacity);
  70245. g.drawImageAt (image, 0, 0, false);
  70246. }
  70247. if (! overlayColour.isTransparent())
  70248. {
  70249. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70250. g.drawImageAt (image, 0, 0, true);
  70251. }
  70252. }
  70253. }
  70254. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70255. {
  70256. return image.getBounds().toFloat();
  70257. }
  70258. bool DrawableImage::hitTest (int x, int y) const
  70259. {
  70260. return (! image.isNull())
  70261. && image.getPixelAt (x, y).getAlpha() >= 127;
  70262. }
  70263. Drawable* DrawableImage::createCopy() const
  70264. {
  70265. return new DrawableImage (*this);
  70266. }
  70267. const Identifier DrawableImage::valueTreeType ("Image");
  70268. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70269. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70270. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70271. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70272. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70273. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70274. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70275. : ValueTreeWrapperBase (state_)
  70276. {
  70277. jassert (state.hasType (valueTreeType));
  70278. }
  70279. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70280. {
  70281. return state [image];
  70282. }
  70283. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70284. {
  70285. return state.getPropertyAsValue (image, undoManager);
  70286. }
  70287. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70288. {
  70289. state.setProperty (image, newIdentifier, undoManager);
  70290. }
  70291. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70292. {
  70293. return (float) state.getProperty (opacity, 1.0);
  70294. }
  70295. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70296. {
  70297. if (! state.hasProperty (opacity))
  70298. state.setProperty (opacity, 1.0, undoManager);
  70299. return state.getPropertyAsValue (opacity, undoManager);
  70300. }
  70301. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70302. {
  70303. state.setProperty (opacity, newOpacity, undoManager);
  70304. }
  70305. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70306. {
  70307. return Colour (state [overlay].toString().getHexValue32());
  70308. }
  70309. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70310. {
  70311. if (newColour.isTransparent())
  70312. state.removeProperty (overlay, undoManager);
  70313. else
  70314. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70315. }
  70316. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70317. {
  70318. return state.getPropertyAsValue (overlay, undoManager);
  70319. }
  70320. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70321. {
  70322. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70323. state.getProperty (topRight, "100, 0"),
  70324. state.getProperty (bottomLeft, "0, 100"));
  70325. }
  70326. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70327. {
  70328. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70329. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70330. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70331. }
  70332. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70333. {
  70334. const ValueTreeWrapper controller (tree);
  70335. setName (controller.getID());
  70336. const float newOpacity = controller.getOpacity();
  70337. const Colour newOverlayColour (controller.getOverlayColour());
  70338. Image newImage;
  70339. const var imageIdentifier (controller.getImageIdentifier());
  70340. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70341. if (imageProvider != 0)
  70342. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70343. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70344. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage)
  70345. {
  70346. repaint();
  70347. opacity = newOpacity;
  70348. overlayColour = newOverlayColour;
  70349. bounds = newBounds;
  70350. setImage (newImage);
  70351. }
  70352. }
  70353. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70354. {
  70355. ValueTree tree (valueTreeType);
  70356. ValueTreeWrapper v (tree);
  70357. v.setID (getName(), 0);
  70358. v.setOpacity (opacity, 0);
  70359. v.setOverlayColour (overlayColour, 0);
  70360. v.setBoundingBox (bounds, 0);
  70361. if (image.isValid())
  70362. {
  70363. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70364. if (imageProvider != 0)
  70365. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70366. }
  70367. return tree;
  70368. }
  70369. END_JUCE_NAMESPACE
  70370. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70371. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70372. BEGIN_JUCE_NAMESPACE
  70373. DrawablePath::DrawablePath()
  70374. {
  70375. }
  70376. DrawablePath::DrawablePath (const DrawablePath& other)
  70377. : DrawableShape (other)
  70378. {
  70379. if (other.relativePath != 0)
  70380. relativePath = new RelativePointPath (*other.relativePath);
  70381. else
  70382. setPath (other.path);
  70383. }
  70384. DrawablePath::~DrawablePath()
  70385. {
  70386. }
  70387. Drawable* DrawablePath::createCopy() const
  70388. {
  70389. return new DrawablePath (*this);
  70390. }
  70391. void DrawablePath::setPath (const Path& newPath)
  70392. {
  70393. path = newPath;
  70394. pathChanged();
  70395. }
  70396. const Path& DrawablePath::getPath() const
  70397. {
  70398. return path;
  70399. }
  70400. const Path& DrawablePath::getStrokePath() const
  70401. {
  70402. return strokePath;
  70403. }
  70404. bool DrawablePath::rebuildPath (Path& path) const
  70405. {
  70406. if (relativePath != 0)
  70407. {
  70408. path.clear();
  70409. relativePath->createPath (path, getParent());
  70410. return true;
  70411. }
  70412. return false;
  70413. }
  70414. const Identifier DrawablePath::valueTreeType ("Path");
  70415. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70416. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70417. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70418. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70419. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70420. : FillAndStrokeState (state_)
  70421. {
  70422. jassert (state.hasType (valueTreeType));
  70423. }
  70424. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70425. {
  70426. return state.getOrCreateChildWithName (path, 0);
  70427. }
  70428. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70429. {
  70430. return state [nonZeroWinding];
  70431. }
  70432. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70433. {
  70434. state.setProperty (nonZeroWinding, b, undoManager);
  70435. }
  70436. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70437. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70438. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70439. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70440. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70441. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70442. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70443. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70444. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70445. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70446. : state (state_)
  70447. {
  70448. }
  70449. DrawablePath::ValueTreeWrapper::Element::~Element()
  70450. {
  70451. }
  70452. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70453. {
  70454. return ValueTreeWrapper (state.getParent().getParent());
  70455. }
  70456. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70457. {
  70458. return Element (state.getSibling (-1));
  70459. }
  70460. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70461. {
  70462. const Identifier i (state.getType());
  70463. if (i == startSubPathElement || i == lineToElement) return 1;
  70464. if (i == quadraticToElement) return 2;
  70465. if (i == cubicToElement) return 3;
  70466. return 0;
  70467. }
  70468. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70469. {
  70470. jassert (index >= 0 && index < getNumControlPoints());
  70471. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70472. }
  70473. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70474. {
  70475. jassert (index >= 0 && index < getNumControlPoints());
  70476. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70477. }
  70478. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70479. {
  70480. jassert (index >= 0 && index < getNumControlPoints());
  70481. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70482. }
  70483. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70484. {
  70485. const Identifier i (state.getType());
  70486. if (i == startSubPathElement)
  70487. return getControlPoint (0);
  70488. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70489. return getPreviousElement().getEndPoint();
  70490. }
  70491. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70492. {
  70493. const Identifier i (state.getType());
  70494. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70495. if (i == quadraticToElement) return getControlPoint (1);
  70496. if (i == cubicToElement) return getControlPoint (2);
  70497. jassert (i == closeSubPathElement);
  70498. return RelativePoint();
  70499. }
  70500. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70501. {
  70502. const Identifier i (state.getType());
  70503. if (i == lineToElement || i == closeSubPathElement)
  70504. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70505. if (i == cubicToElement)
  70506. {
  70507. Path p;
  70508. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70509. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70510. return p.getLength();
  70511. }
  70512. if (i == quadraticToElement)
  70513. {
  70514. Path p;
  70515. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70516. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70517. return p.getLength();
  70518. }
  70519. jassert (i == startSubPathElement);
  70520. return 0;
  70521. }
  70522. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70523. {
  70524. return state [mode].toString();
  70525. }
  70526. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70527. {
  70528. if (state.hasType (cubicToElement))
  70529. state.setProperty (mode, newMode, undoManager);
  70530. }
  70531. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70532. {
  70533. const Identifier i (state.getType());
  70534. if (i == quadraticToElement || i == cubicToElement)
  70535. {
  70536. ValueTree newState (lineToElement);
  70537. Element e (newState);
  70538. e.setControlPoint (0, getEndPoint(), undoManager);
  70539. state = newState;
  70540. }
  70541. }
  70542. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70543. {
  70544. const Identifier i (state.getType());
  70545. if (i == lineToElement || i == quadraticToElement)
  70546. {
  70547. ValueTree newState (cubicToElement);
  70548. Element e (newState);
  70549. const RelativePoint start (getStartPoint());
  70550. const RelativePoint end (getEndPoint());
  70551. const Point<float> startResolved (start.resolve (nameFinder));
  70552. const Point<float> endResolved (end.resolve (nameFinder));
  70553. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70554. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70555. e.setControlPoint (2, end, undoManager);
  70556. state = newState;
  70557. }
  70558. }
  70559. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70560. {
  70561. const Identifier i (state.getType());
  70562. if (i != startSubPathElement)
  70563. {
  70564. ValueTree newState (startSubPathElement);
  70565. Element e (newState);
  70566. e.setControlPoint (0, getEndPoint(), undoManager);
  70567. state = newState;
  70568. }
  70569. }
  70570. namespace DrawablePathHelpers
  70571. {
  70572. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70573. {
  70574. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70575. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70576. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70577. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70578. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70579. return newCp1 + (newCp2 - newCp1) * proportion;
  70580. }
  70581. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70582. {
  70583. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70584. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70585. return mid1 + (mid2 - mid1) * proportion;
  70586. }
  70587. }
  70588. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70589. {
  70590. using namespace DrawablePathHelpers;
  70591. const Identifier i (state.getType());
  70592. float bestProp = 0;
  70593. if (i == cubicToElement)
  70594. {
  70595. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70596. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70597. float bestDistance = std::numeric_limits<float>::max();
  70598. for (int i = 110; --i >= 0;)
  70599. {
  70600. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70601. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70602. const float distance = centre.getDistanceFrom (targetPoint);
  70603. if (distance < bestDistance)
  70604. {
  70605. bestProp = prop;
  70606. bestDistance = distance;
  70607. }
  70608. }
  70609. }
  70610. else if (i == quadraticToElement)
  70611. {
  70612. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70613. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70614. float bestDistance = std::numeric_limits<float>::max();
  70615. for (int i = 110; --i >= 0;)
  70616. {
  70617. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70618. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70619. const float distance = centre.getDistanceFrom (targetPoint);
  70620. if (distance < bestDistance)
  70621. {
  70622. bestProp = prop;
  70623. bestDistance = distance;
  70624. }
  70625. }
  70626. }
  70627. else if (i == lineToElement)
  70628. {
  70629. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70630. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70631. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70632. }
  70633. return bestProp;
  70634. }
  70635. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70636. {
  70637. ValueTree newTree;
  70638. const Identifier i (state.getType());
  70639. if (i == cubicToElement)
  70640. {
  70641. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70642. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70643. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70644. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70645. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70646. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70647. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70648. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70649. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70650. setControlPoint (0, mid1, undoManager);
  70651. setControlPoint (1, newCp1, undoManager);
  70652. setControlPoint (2, newCentre, undoManager);
  70653. setModeOfEndPoint (roundedMode, undoManager);
  70654. Element newElement (newTree = ValueTree (cubicToElement));
  70655. newElement.setControlPoint (0, newCp2, 0);
  70656. newElement.setControlPoint (1, mid3, 0);
  70657. newElement.setControlPoint (2, rp4, 0);
  70658. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70659. }
  70660. else if (i == quadraticToElement)
  70661. {
  70662. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70663. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70664. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70665. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70666. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70667. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70668. setControlPoint (0, mid1, undoManager);
  70669. setControlPoint (1, newCentre, undoManager);
  70670. setModeOfEndPoint (roundedMode, undoManager);
  70671. Element newElement (newTree = ValueTree (quadraticToElement));
  70672. newElement.setControlPoint (0, mid2, 0);
  70673. newElement.setControlPoint (1, rp3, 0);
  70674. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70675. }
  70676. else if (i == lineToElement)
  70677. {
  70678. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70679. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70680. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70681. setControlPoint (0, newPoint, undoManager);
  70682. Element newElement (newTree = ValueTree (lineToElement));
  70683. newElement.setControlPoint (0, rp2, 0);
  70684. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70685. }
  70686. else if (i == closeSubPathElement)
  70687. {
  70688. }
  70689. return newTree;
  70690. }
  70691. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70692. {
  70693. state.getParent().removeChild (state, undoManager);
  70694. }
  70695. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70696. {
  70697. ValueTreeWrapper v (tree);
  70698. setName (v.getID());
  70699. if (refreshFillTypes (v, getParent(), imageProvider))
  70700. repaint();
  70701. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70702. Path newPath;
  70703. newRelativePath->createPath (newPath, getParent());
  70704. if (! newRelativePath->containsAnyDynamicPoints())
  70705. newRelativePath = 0;
  70706. const PathStrokeType newStroke (v.getStrokeType());
  70707. if (strokeType != newStroke || path != newPath)
  70708. {
  70709. path.swapWithPath (newPath);
  70710. strokeType = newStroke;
  70711. pathChanged();
  70712. }
  70713. relativePath = newRelativePath;
  70714. }
  70715. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70716. {
  70717. ValueTree tree (valueTreeType);
  70718. ValueTreeWrapper v (tree);
  70719. v.setID (getName(), 0);
  70720. writeTo (v, imageProvider, 0);
  70721. if (relativePath != 0)
  70722. {
  70723. relativePath->writeTo (tree, 0);
  70724. }
  70725. else
  70726. {
  70727. RelativePointPath rp (path);
  70728. rp.writeTo (tree, 0);
  70729. }
  70730. return tree;
  70731. }
  70732. END_JUCE_NAMESPACE
  70733. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70734. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70735. BEGIN_JUCE_NAMESPACE
  70736. DrawableRectangle::DrawableRectangle()
  70737. {
  70738. }
  70739. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70740. : DrawableShape (other)
  70741. {
  70742. }
  70743. DrawableRectangle::~DrawableRectangle()
  70744. {
  70745. }
  70746. Drawable* DrawableRectangle::createCopy() const
  70747. {
  70748. return new DrawableRectangle (*this);
  70749. }
  70750. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70751. {
  70752. bounds = newBounds;
  70753. pathChanged();
  70754. strokeChanged();
  70755. }
  70756. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70757. {
  70758. cornerSize = newSize;
  70759. pathChanged();
  70760. strokeChanged();
  70761. }
  70762. bool DrawableRectangle::rebuildPath (Path& path) const
  70763. {
  70764. Point<float> points[3];
  70765. bounds.resolveThreePoints (points, getParent());
  70766. const float w = Line<float> (points[0], points[1]).getLength();
  70767. const float h = Line<float> (points[0], points[2]).getLength();
  70768. const float cornerSizeX = (float) cornerSize.x.resolve (getParent());
  70769. const float cornerSizeY = (float) cornerSize.y.resolve (getParent());
  70770. path.clear();
  70771. if (cornerSizeX > 0 && cornerSizeY > 0)
  70772. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70773. else
  70774. path.addRectangle (0, 0, w, h);
  70775. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70776. w, 0, points[1].getX(), points[1].getY(),
  70777. 0, h, points[2].getX(), points[2].getY()));
  70778. return true;
  70779. }
  70780. const AffineTransform DrawableRectangle::calculateTransform() const
  70781. {
  70782. Point<float> resolved[3];
  70783. bounds.resolveThreePoints (resolved, getParent());
  70784. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70785. resolved[1].getX(), resolved[1].getY(),
  70786. resolved[2].getX(), resolved[2].getY());
  70787. }
  70788. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70789. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70790. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70791. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70792. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70793. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70794. : FillAndStrokeState (state_)
  70795. {
  70796. jassert (state.hasType (valueTreeType));
  70797. }
  70798. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70799. {
  70800. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70801. state.getProperty (topRight, "100, 0"),
  70802. state.getProperty (bottomLeft, "0, 100"));
  70803. }
  70804. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70805. {
  70806. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70807. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70808. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70809. }
  70810. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70811. {
  70812. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70813. }
  70814. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70815. {
  70816. return RelativePoint (state [cornerSize]);
  70817. }
  70818. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70819. {
  70820. return state.getPropertyAsValue (cornerSize, undoManager);
  70821. }
  70822. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70823. {
  70824. ValueTreeWrapper v (tree);
  70825. setName (v.getID());
  70826. if (refreshFillTypes (v, getParent(), imageProvider))
  70827. repaint();
  70828. RelativeParallelogram newBounds (v.getRectangle());
  70829. const PathStrokeType newStroke (v.getStrokeType());
  70830. const RelativePoint newCornerSize (v.getCornerSize());
  70831. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  70832. {
  70833. repaint();
  70834. bounds = newBounds;
  70835. strokeType = newStroke;
  70836. cornerSize = newCornerSize;
  70837. pathChanged();
  70838. }
  70839. }
  70840. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  70841. {
  70842. ValueTree tree (valueTreeType);
  70843. ValueTreeWrapper v (tree);
  70844. v.setID (getName(), 0);
  70845. writeTo (v, imageProvider, 0);
  70846. v.setRectangle (bounds, 0);
  70847. v.setCornerSize (cornerSize, 0);
  70848. return tree;
  70849. }
  70850. END_JUCE_NAMESPACE
  70851. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70852. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70853. BEGIN_JUCE_NAMESPACE
  70854. DrawableText::DrawableText()
  70855. : colour (Colours::black),
  70856. justification (Justification::centredLeft)
  70857. {
  70858. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70859. RelativePoint (50.0f, 0.0f),
  70860. RelativePoint (0.0f, 20.0f)));
  70861. setFont (Font (15.0f), true);
  70862. }
  70863. DrawableText::DrawableText (const DrawableText& other)
  70864. : bounds (other.bounds),
  70865. fontSizeControlPoint (other.fontSizeControlPoint),
  70866. font (other.font),
  70867. text (other.text),
  70868. colour (other.colour),
  70869. justification (other.justification)
  70870. {
  70871. }
  70872. DrawableText::~DrawableText()
  70873. {
  70874. }
  70875. void DrawableText::refreshBounds()
  70876. {
  70877. setBoundsToEnclose (getDrawableBounds());
  70878. repaint();
  70879. }
  70880. void DrawableText::setText (const String& newText)
  70881. {
  70882. text = newText;
  70883. refreshBounds();
  70884. }
  70885. void DrawableText::setColour (const Colour& newColour)
  70886. {
  70887. colour = newColour;
  70888. repaint();
  70889. }
  70890. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70891. {
  70892. font = newFont;
  70893. if (applySizeAndScale)
  70894. {
  70895. Point<float> corners[3];
  70896. bounds.resolveThreePoints (corners, getParent());
  70897. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70898. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70899. }
  70900. refreshBounds();
  70901. }
  70902. void DrawableText::setJustification (const Justification& newJustification)
  70903. {
  70904. justification = newJustification;
  70905. repaint();
  70906. }
  70907. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70908. {
  70909. bounds = newBounds;
  70910. refreshBounds();
  70911. }
  70912. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70913. {
  70914. fontSizeControlPoint = newPoint;
  70915. refreshBounds();
  70916. }
  70917. void DrawableText::paint (Graphics& g)
  70918. {
  70919. transformContextToCorrectOrigin (g);
  70920. Point<float> points[3];
  70921. bounds.resolveThreePoints (points, getParent());
  70922. const float w = Line<float> (points[0], points[1]).getLength();
  70923. const float h = Line<float> (points[0], points[2]).getLength();
  70924. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (getParent())));
  70925. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70926. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70927. Font f (font);
  70928. f.setHeight (fontHeight);
  70929. f.setHorizontalScale (fontWidth / fontHeight);
  70930. g.setColour (colour);
  70931. GlyphArrangement ga;
  70932. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70933. ga.draw (g, AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70934. w, 0, points[1].getX(), points[1].getY(),
  70935. 0, h, points[2].getX(), points[2].getY()));
  70936. }
  70937. const Rectangle<float> DrawableText::getDrawableBounds() const
  70938. {
  70939. return bounds.getBounds (getParent());
  70940. }
  70941. Drawable* DrawableText::createCopy() const
  70942. {
  70943. return new DrawableText (*this);
  70944. }
  70945. const Identifier DrawableText::valueTreeType ("Text");
  70946. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70947. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70948. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70949. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70950. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70951. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70952. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70953. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70954. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70955. : ValueTreeWrapperBase (state_)
  70956. {
  70957. jassert (state.hasType (valueTreeType));
  70958. }
  70959. const String DrawableText::ValueTreeWrapper::getText() const
  70960. {
  70961. return state [text].toString();
  70962. }
  70963. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70964. {
  70965. state.setProperty (text, newText, undoManager);
  70966. }
  70967. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70968. {
  70969. return state.getPropertyAsValue (text, undoManager);
  70970. }
  70971. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70972. {
  70973. return Colour::fromString (state [colour].toString());
  70974. }
  70975. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70976. {
  70977. state.setProperty (colour, newColour.toString(), undoManager);
  70978. }
  70979. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70980. {
  70981. return Justification ((int) state [justification]);
  70982. }
  70983. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70984. {
  70985. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70986. }
  70987. const Font DrawableText::ValueTreeWrapper::getFont() const
  70988. {
  70989. return Font::fromString (state [font]);
  70990. }
  70991. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70992. {
  70993. state.setProperty (font, newFont.toString(), undoManager);
  70994. }
  70995. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70996. {
  70997. return state.getPropertyAsValue (font, undoManager);
  70998. }
  70999. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71000. {
  71001. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71002. }
  71003. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71004. {
  71005. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71006. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71007. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71008. }
  71009. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71010. {
  71011. return state [fontSizeAnchor].toString();
  71012. }
  71013. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71014. {
  71015. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71016. }
  71017. void DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71018. {
  71019. ValueTreeWrapper v (tree);
  71020. setName (v.getID());
  71021. const RelativeParallelogram newBounds (v.getBoundingBox());
  71022. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71023. const Colour newColour (v.getColour());
  71024. const Justification newJustification (v.getJustification());
  71025. const String newText (v.getText());
  71026. const Font newFont (v.getFont());
  71027. if (text != newText || font != newFont || justification != newJustification
  71028. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71029. {
  71030. repaint();
  71031. setBoundingBox (newBounds);
  71032. setFontSizeControlPoint (newFontPoint);
  71033. setColour (newColour);
  71034. setFont (newFont, false);
  71035. setJustification (newJustification);
  71036. setText (newText);
  71037. }
  71038. }
  71039. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71040. {
  71041. ValueTree tree (valueTreeType);
  71042. ValueTreeWrapper v (tree);
  71043. v.setID (getName(), 0);
  71044. v.setText (text, 0);
  71045. v.setFont (font, 0);
  71046. v.setJustification (justification, 0);
  71047. v.setColour (colour, 0);
  71048. v.setBoundingBox (bounds, 0);
  71049. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71050. return tree;
  71051. }
  71052. END_JUCE_NAMESPACE
  71053. /*** End of inlined file: juce_DrawableText.cpp ***/
  71054. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71055. BEGIN_JUCE_NAMESPACE
  71056. class SVGState
  71057. {
  71058. public:
  71059. SVGState (const XmlElement* const topLevel)
  71060. : topLevelXml (topLevel),
  71061. elementX (0), elementY (0),
  71062. width (512), height (512),
  71063. viewBoxW (0), viewBoxH (0)
  71064. {
  71065. }
  71066. ~SVGState()
  71067. {
  71068. }
  71069. Drawable* parseSVGElement (const XmlElement& xml)
  71070. {
  71071. if (! xml.hasTagName ("svg"))
  71072. return 0;
  71073. DrawableComposite* const drawable = new DrawableComposite();
  71074. drawable->setName (xml.getStringAttribute ("id"));
  71075. SVGState newState (*this);
  71076. if (xml.hasAttribute ("transform"))
  71077. newState.addTransform (xml);
  71078. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71079. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71080. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71081. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71082. if (xml.hasAttribute ("viewBox"))
  71083. {
  71084. const String viewParams (xml.getStringAttribute ("viewBox"));
  71085. int i = 0;
  71086. float vx, vy, vw, vh;
  71087. if (parseCoords (viewParams, vx, vy, i, true)
  71088. && parseCoords (viewParams, vw, vh, i, true)
  71089. && vw > 0
  71090. && vh > 0)
  71091. {
  71092. newState.viewBoxW = vw;
  71093. newState.viewBoxH = vh;
  71094. int placementFlags = 0;
  71095. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71096. if (aspect.containsIgnoreCase ("none"))
  71097. {
  71098. placementFlags = RectanglePlacement::stretchToFit;
  71099. }
  71100. else
  71101. {
  71102. if (aspect.containsIgnoreCase ("slice"))
  71103. placementFlags |= RectanglePlacement::fillDestination;
  71104. if (aspect.containsIgnoreCase ("xMin"))
  71105. placementFlags |= RectanglePlacement::xLeft;
  71106. else if (aspect.containsIgnoreCase ("xMax"))
  71107. placementFlags |= RectanglePlacement::xRight;
  71108. else
  71109. placementFlags |= RectanglePlacement::xMid;
  71110. if (aspect.containsIgnoreCase ("yMin"))
  71111. placementFlags |= RectanglePlacement::yTop;
  71112. else if (aspect.containsIgnoreCase ("yMax"))
  71113. placementFlags |= RectanglePlacement::yBottom;
  71114. else
  71115. placementFlags |= RectanglePlacement::yMid;
  71116. }
  71117. const RectanglePlacement placement (placementFlags);
  71118. newState.transform
  71119. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71120. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71121. .followedBy (newState.transform);
  71122. }
  71123. }
  71124. else
  71125. {
  71126. if (viewBoxW == 0)
  71127. newState.viewBoxW = newState.width;
  71128. if (viewBoxH == 0)
  71129. newState.viewBoxH = newState.height;
  71130. }
  71131. newState.parseSubElements (xml, drawable);
  71132. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71133. return drawable;
  71134. }
  71135. private:
  71136. const XmlElement* const topLevelXml;
  71137. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71138. AffineTransform transform;
  71139. String cssStyleText;
  71140. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71141. {
  71142. forEachXmlChildElement (xml, e)
  71143. {
  71144. Drawable* d = 0;
  71145. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71146. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71147. else if (e->hasTagName ("path")) d = parsePath (*e);
  71148. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71149. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71150. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71151. else if (e->hasTagName ("line")) d = parseLine (*e);
  71152. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71153. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71154. else if (e->hasTagName ("text")) d = parseText (*e);
  71155. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71156. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71157. parentDrawable->insertDrawable (d);
  71158. }
  71159. }
  71160. DrawableComposite* parseSwitch (const XmlElement& xml)
  71161. {
  71162. const XmlElement* const group = xml.getChildByName ("g");
  71163. if (group != 0)
  71164. return parseGroupElement (*group);
  71165. return 0;
  71166. }
  71167. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71168. {
  71169. DrawableComposite* const drawable = new DrawableComposite();
  71170. drawable->setName (xml.getStringAttribute ("id"));
  71171. if (xml.hasAttribute ("transform"))
  71172. {
  71173. SVGState newState (*this);
  71174. newState.addTransform (xml);
  71175. newState.parseSubElements (xml, drawable);
  71176. }
  71177. else
  71178. {
  71179. parseSubElements (xml, drawable);
  71180. }
  71181. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71182. return drawable;
  71183. }
  71184. Drawable* parsePath (const XmlElement& xml) const
  71185. {
  71186. const String d (xml.getStringAttribute ("d").trimStart());
  71187. Path path;
  71188. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71189. path.setUsingNonZeroWinding (false);
  71190. int index = 0;
  71191. float lastX = 0, lastY = 0;
  71192. float lastX2 = 0, lastY2 = 0;
  71193. juce_wchar lastCommandChar = 0;
  71194. bool isRelative = true;
  71195. bool carryOn = true;
  71196. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71197. while (d[index] != 0)
  71198. {
  71199. float x, y, x2, y2, x3, y3;
  71200. if (validCommandChars.containsChar (d[index]))
  71201. {
  71202. lastCommandChar = d [index++];
  71203. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71204. }
  71205. switch (lastCommandChar)
  71206. {
  71207. case 'M':
  71208. case 'm':
  71209. case 'L':
  71210. case 'l':
  71211. if (parseCoords (d, x, y, index, false))
  71212. {
  71213. if (isRelative)
  71214. {
  71215. x += lastX;
  71216. y += lastY;
  71217. }
  71218. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71219. {
  71220. path.startNewSubPath (x, y);
  71221. lastCommandChar = 'l';
  71222. }
  71223. else
  71224. path.lineTo (x, y);
  71225. lastX2 = lastX;
  71226. lastY2 = lastY;
  71227. lastX = x;
  71228. lastY = y;
  71229. }
  71230. else
  71231. {
  71232. ++index;
  71233. }
  71234. break;
  71235. case 'H':
  71236. case 'h':
  71237. if (parseCoord (d, x, index, false, true))
  71238. {
  71239. if (isRelative)
  71240. x += lastX;
  71241. path.lineTo (x, lastY);
  71242. lastX2 = lastX;
  71243. lastX = x;
  71244. }
  71245. else
  71246. {
  71247. ++index;
  71248. }
  71249. break;
  71250. case 'V':
  71251. case 'v':
  71252. if (parseCoord (d, y, index, false, false))
  71253. {
  71254. if (isRelative)
  71255. y += lastY;
  71256. path.lineTo (lastX, y);
  71257. lastY2 = lastY;
  71258. lastY = y;
  71259. }
  71260. else
  71261. {
  71262. ++index;
  71263. }
  71264. break;
  71265. case 'C':
  71266. case 'c':
  71267. if (parseCoords (d, x, y, index, false)
  71268. && parseCoords (d, x2, y2, index, false)
  71269. && parseCoords (d, x3, y3, index, false))
  71270. {
  71271. if (isRelative)
  71272. {
  71273. x += lastX;
  71274. y += lastY;
  71275. x2 += lastX;
  71276. y2 += lastY;
  71277. x3 += lastX;
  71278. y3 += lastY;
  71279. }
  71280. path.cubicTo (x, y, x2, y2, x3, y3);
  71281. lastX2 = x2;
  71282. lastY2 = y2;
  71283. lastX = x3;
  71284. lastY = y3;
  71285. }
  71286. else
  71287. {
  71288. ++index;
  71289. }
  71290. break;
  71291. case 'S':
  71292. case 's':
  71293. if (parseCoords (d, x, y, index, false)
  71294. && parseCoords (d, x3, y3, index, false))
  71295. {
  71296. if (isRelative)
  71297. {
  71298. x += lastX;
  71299. y += lastY;
  71300. x3 += lastX;
  71301. y3 += lastY;
  71302. }
  71303. x2 = lastX + (lastX - lastX2);
  71304. y2 = lastY + (lastY - lastY2);
  71305. path.cubicTo (x2, y2, x, y, x3, y3);
  71306. lastX2 = x;
  71307. lastY2 = y;
  71308. lastX = x3;
  71309. lastY = y3;
  71310. }
  71311. else
  71312. {
  71313. ++index;
  71314. }
  71315. break;
  71316. case 'Q':
  71317. case 'q':
  71318. if (parseCoords (d, x, y, index, false)
  71319. && parseCoords (d, x2, y2, index, false))
  71320. {
  71321. if (isRelative)
  71322. {
  71323. x += lastX;
  71324. y += lastY;
  71325. x2 += lastX;
  71326. y2 += lastY;
  71327. }
  71328. path.quadraticTo (x, y, x2, y2);
  71329. lastX2 = x;
  71330. lastY2 = y;
  71331. lastX = x2;
  71332. lastY = y2;
  71333. }
  71334. else
  71335. {
  71336. ++index;
  71337. }
  71338. break;
  71339. case 'T':
  71340. case 't':
  71341. if (parseCoords (d, x, y, index, false))
  71342. {
  71343. if (isRelative)
  71344. {
  71345. x += lastX;
  71346. y += lastY;
  71347. }
  71348. x2 = lastX + (lastX - lastX2);
  71349. y2 = lastY + (lastY - lastY2);
  71350. path.quadraticTo (x2, y2, x, y);
  71351. lastX2 = x2;
  71352. lastY2 = y2;
  71353. lastX = x;
  71354. lastY = y;
  71355. }
  71356. else
  71357. {
  71358. ++index;
  71359. }
  71360. break;
  71361. case 'A':
  71362. case 'a':
  71363. if (parseCoords (d, x, y, index, false))
  71364. {
  71365. String num;
  71366. if (parseNextNumber (d, num, index, false))
  71367. {
  71368. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71369. if (parseNextNumber (d, num, index, false))
  71370. {
  71371. const bool largeArc = num.getIntValue() != 0;
  71372. if (parseNextNumber (d, num, index, false))
  71373. {
  71374. const bool sweep = num.getIntValue() != 0;
  71375. if (parseCoords (d, x2, y2, index, false))
  71376. {
  71377. if (isRelative)
  71378. {
  71379. x2 += lastX;
  71380. y2 += lastY;
  71381. }
  71382. if (lastX != x2 || lastY != y2)
  71383. {
  71384. double centreX, centreY, startAngle, deltaAngle;
  71385. double rx = x, ry = y;
  71386. endpointToCentreParameters (lastX, lastY, x2, y2,
  71387. angle, largeArc, sweep,
  71388. rx, ry, centreX, centreY,
  71389. startAngle, deltaAngle);
  71390. path.addCentredArc ((float) centreX, (float) centreY,
  71391. (float) rx, (float) ry,
  71392. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71393. false);
  71394. path.lineTo (x2, y2);
  71395. }
  71396. lastX2 = lastX;
  71397. lastY2 = lastY;
  71398. lastX = x2;
  71399. lastY = y2;
  71400. }
  71401. }
  71402. }
  71403. }
  71404. }
  71405. else
  71406. {
  71407. ++index;
  71408. }
  71409. break;
  71410. case 'Z':
  71411. case 'z':
  71412. path.closeSubPath();
  71413. while (CharacterFunctions::isWhitespace (d [index]))
  71414. ++index;
  71415. break;
  71416. default:
  71417. carryOn = false;
  71418. break;
  71419. }
  71420. if (! carryOn)
  71421. break;
  71422. }
  71423. return parseShape (xml, path);
  71424. }
  71425. Drawable* parseRect (const XmlElement& xml) const
  71426. {
  71427. Path rect;
  71428. const bool hasRX = xml.hasAttribute ("rx");
  71429. const bool hasRY = xml.hasAttribute ("ry");
  71430. if (hasRX || hasRY)
  71431. {
  71432. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71433. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71434. if (! hasRX)
  71435. rx = ry;
  71436. else if (! hasRY)
  71437. ry = rx;
  71438. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71439. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71440. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71441. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71442. rx, ry);
  71443. }
  71444. else
  71445. {
  71446. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71447. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71448. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71449. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71450. }
  71451. return parseShape (xml, rect);
  71452. }
  71453. Drawable* parseCircle (const XmlElement& xml) const
  71454. {
  71455. Path circle;
  71456. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71457. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71458. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71459. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71460. return parseShape (xml, circle);
  71461. }
  71462. Drawable* parseEllipse (const XmlElement& xml) const
  71463. {
  71464. Path ellipse;
  71465. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71466. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71467. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71468. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71469. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71470. return parseShape (xml, ellipse);
  71471. }
  71472. Drawable* parseLine (const XmlElement& xml) const
  71473. {
  71474. Path line;
  71475. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71476. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71477. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71478. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71479. line.startNewSubPath (x1, y1);
  71480. line.lineTo (x2, y2);
  71481. return parseShape (xml, line);
  71482. }
  71483. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71484. {
  71485. const String points (xml.getStringAttribute ("points"));
  71486. Path path;
  71487. int index = 0;
  71488. float x, y;
  71489. if (parseCoords (points, x, y, index, true))
  71490. {
  71491. float firstX = x;
  71492. float firstY = y;
  71493. float lastX = 0, lastY = 0;
  71494. path.startNewSubPath (x, y);
  71495. while (parseCoords (points, x, y, index, true))
  71496. {
  71497. lastX = x;
  71498. lastY = y;
  71499. path.lineTo (x, y);
  71500. }
  71501. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71502. path.closeSubPath();
  71503. }
  71504. return parseShape (xml, path);
  71505. }
  71506. Drawable* parseShape (const XmlElement& xml, Path& path,
  71507. const bool shouldParseTransform = true) const
  71508. {
  71509. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71510. {
  71511. SVGState newState (*this);
  71512. newState.addTransform (xml);
  71513. return newState.parseShape (xml, path, false);
  71514. }
  71515. DrawablePath* dp = new DrawablePath();
  71516. dp->setName (xml.getStringAttribute ("id"));
  71517. dp->setFill (Colours::transparentBlack);
  71518. path.applyTransform (transform);
  71519. dp->setPath (path);
  71520. Path::Iterator iter (path);
  71521. bool containsClosedSubPath = false;
  71522. while (iter.next())
  71523. {
  71524. if (iter.elementType == Path::Iterator::closePath)
  71525. {
  71526. containsClosedSubPath = true;
  71527. break;
  71528. }
  71529. }
  71530. dp->setFill (getPathFillType (path,
  71531. getStyleAttribute (&xml, "fill"),
  71532. getStyleAttribute (&xml, "fill-opacity"),
  71533. getStyleAttribute (&xml, "opacity"),
  71534. containsClosedSubPath ? Colours::black
  71535. : Colours::transparentBlack));
  71536. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71537. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71538. {
  71539. dp->setStrokeFill (getPathFillType (path, strokeType,
  71540. getStyleAttribute (&xml, "stroke-opacity"),
  71541. getStyleAttribute (&xml, "opacity"),
  71542. Colours::transparentBlack));
  71543. dp->setStrokeType (getStrokeFor (&xml));
  71544. }
  71545. return dp;
  71546. }
  71547. const XmlElement* findLinkedElement (const XmlElement* e) const
  71548. {
  71549. const String id (e->getStringAttribute ("xlink:href"));
  71550. if (! id.startsWithChar ('#'))
  71551. return 0;
  71552. return findElementForId (topLevelXml, id.substring (1));
  71553. }
  71554. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71555. {
  71556. if (fillXml == 0)
  71557. return;
  71558. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71559. {
  71560. int index = 0;
  71561. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71562. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71563. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71564. double offset = e->getDoubleAttribute ("offset");
  71565. if (e->getStringAttribute ("offset").containsChar ('%'))
  71566. offset *= 0.01;
  71567. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71568. }
  71569. }
  71570. const FillType getPathFillType (const Path& path,
  71571. const String& fill,
  71572. const String& fillOpacity,
  71573. const String& overallOpacity,
  71574. const Colour& defaultColour) const
  71575. {
  71576. float opacity = 1.0f;
  71577. if (overallOpacity.isNotEmpty())
  71578. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71579. if (fillOpacity.isNotEmpty())
  71580. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71581. if (fill.startsWithIgnoreCase ("url"))
  71582. {
  71583. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71584. .upToLastOccurrenceOf (")", false, false).trim());
  71585. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71586. if (fillXml != 0
  71587. && (fillXml->hasTagName ("linearGradient")
  71588. || fillXml->hasTagName ("radialGradient")))
  71589. {
  71590. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71591. ColourGradient gradient;
  71592. addGradientStopsIn (gradient, inheritedFrom);
  71593. addGradientStopsIn (gradient, fillXml);
  71594. if (gradient.getNumColours() > 0)
  71595. {
  71596. gradient.addColour (0.0, gradient.getColour (0));
  71597. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71598. }
  71599. else
  71600. {
  71601. gradient.addColour (0.0, Colours::black);
  71602. gradient.addColour (1.0, Colours::black);
  71603. }
  71604. if (overallOpacity.isNotEmpty())
  71605. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71606. jassert (gradient.getNumColours() > 0);
  71607. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71608. float gradientWidth = viewBoxW;
  71609. float gradientHeight = viewBoxH;
  71610. float dx = 0.0f;
  71611. float dy = 0.0f;
  71612. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71613. if (! userSpace)
  71614. {
  71615. const Rectangle<float> bounds (path.getBounds());
  71616. dx = bounds.getX();
  71617. dy = bounds.getY();
  71618. gradientWidth = bounds.getWidth();
  71619. gradientHeight = bounds.getHeight();
  71620. }
  71621. if (gradient.isRadial)
  71622. {
  71623. if (userSpace)
  71624. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71625. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71626. else
  71627. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71628. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71629. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71630. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71631. //xxx (the fx, fy focal point isn't handled properly here..)
  71632. }
  71633. else
  71634. {
  71635. if (userSpace)
  71636. {
  71637. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71638. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71639. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71640. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71641. }
  71642. else
  71643. {
  71644. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71645. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71646. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71647. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71648. }
  71649. if (gradient.point1 == gradient.point2)
  71650. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71651. }
  71652. FillType type (gradient);
  71653. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71654. .followedBy (transform);
  71655. return type;
  71656. }
  71657. }
  71658. if (fill.equalsIgnoreCase ("none"))
  71659. return Colours::transparentBlack;
  71660. int i = 0;
  71661. const Colour colour (parseColour (fill, i, defaultColour));
  71662. return colour.withMultipliedAlpha (opacity);
  71663. }
  71664. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71665. {
  71666. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71667. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71668. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71669. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71670. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71671. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71672. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71673. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71674. if (join.equalsIgnoreCase ("round"))
  71675. joinStyle = PathStrokeType::curved;
  71676. else if (join.equalsIgnoreCase ("bevel"))
  71677. joinStyle = PathStrokeType::beveled;
  71678. if (cap.equalsIgnoreCase ("round"))
  71679. capStyle = PathStrokeType::rounded;
  71680. else if (cap.equalsIgnoreCase ("square"))
  71681. capStyle = PathStrokeType::square;
  71682. float ox = 0.0f, oy = 0.0f;
  71683. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71684. transform.transformPoints (ox, oy, x, y);
  71685. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71686. joinStyle, capStyle);
  71687. }
  71688. Drawable* parseText (const XmlElement& xml)
  71689. {
  71690. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71691. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71692. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71693. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71694. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71695. //xxx not done text yet!
  71696. forEachXmlChildElement (xml, e)
  71697. {
  71698. if (e->isTextElement())
  71699. {
  71700. const String text (e->getText());
  71701. Path path;
  71702. Drawable* s = parseShape (*e, path);
  71703. delete s; // xxx not finished!
  71704. }
  71705. else if (e->hasTagName ("tspan"))
  71706. {
  71707. Drawable* s = parseText (*e);
  71708. delete s; // xxx not finished!
  71709. }
  71710. }
  71711. return 0;
  71712. }
  71713. void addTransform (const XmlElement& xml)
  71714. {
  71715. transform = parseTransform (xml.getStringAttribute ("transform"))
  71716. .followedBy (transform);
  71717. }
  71718. bool parseCoord (const String& s, float& value, int& index,
  71719. const bool allowUnits, const bool isX) const
  71720. {
  71721. String number;
  71722. if (! parseNextNumber (s, number, index, allowUnits))
  71723. {
  71724. value = 0;
  71725. return false;
  71726. }
  71727. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71728. return true;
  71729. }
  71730. bool parseCoords (const String& s, float& x, float& y,
  71731. int& index, const bool allowUnits) const
  71732. {
  71733. return parseCoord (s, x, index, allowUnits, true)
  71734. && parseCoord (s, y, index, allowUnits, false);
  71735. }
  71736. float getCoordLength (const String& s, const float sizeForProportions) const
  71737. {
  71738. float n = s.getFloatValue();
  71739. const int len = s.length();
  71740. if (len > 2)
  71741. {
  71742. const float dpi = 96.0f;
  71743. const juce_wchar n1 = s [len - 2];
  71744. const juce_wchar n2 = s [len - 1];
  71745. if (n1 == 'i' && n2 == 'n')
  71746. n *= dpi;
  71747. else if (n1 == 'm' && n2 == 'm')
  71748. n *= dpi / 25.4f;
  71749. else if (n1 == 'c' && n2 == 'm')
  71750. n *= dpi / 2.54f;
  71751. else if (n1 == 'p' && n2 == 'c')
  71752. n *= 15.0f;
  71753. else if (n2 == '%')
  71754. n *= 0.01f * sizeForProportions;
  71755. }
  71756. return n;
  71757. }
  71758. void getCoordList (Array <float>& coords, const String& list,
  71759. const bool allowUnits, const bool isX) const
  71760. {
  71761. int index = 0;
  71762. float value;
  71763. while (parseCoord (list, value, index, allowUnits, isX))
  71764. coords.add (value);
  71765. }
  71766. void parseCSSStyle (const XmlElement& xml)
  71767. {
  71768. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71769. }
  71770. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71771. const String& defaultValue = String::empty) const
  71772. {
  71773. if (xml->hasAttribute (attributeName))
  71774. return xml->getStringAttribute (attributeName, defaultValue);
  71775. const String styleAtt (xml->getStringAttribute ("style"));
  71776. if (styleAtt.isNotEmpty())
  71777. {
  71778. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71779. if (value.isNotEmpty())
  71780. return value;
  71781. }
  71782. else if (xml->hasAttribute ("class"))
  71783. {
  71784. const String className ("." + xml->getStringAttribute ("class"));
  71785. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71786. if (index < 0)
  71787. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71788. if (index >= 0)
  71789. {
  71790. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71791. if (openBracket > index)
  71792. {
  71793. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71794. if (closeBracket > openBracket)
  71795. {
  71796. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71797. if (value.isNotEmpty())
  71798. return value;
  71799. }
  71800. }
  71801. }
  71802. }
  71803. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71804. if (xml != 0)
  71805. return getStyleAttribute (xml, attributeName, defaultValue);
  71806. return defaultValue;
  71807. }
  71808. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71809. {
  71810. if (xml->hasAttribute (attributeName))
  71811. return xml->getStringAttribute (attributeName);
  71812. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71813. if (xml != 0)
  71814. return getInheritedAttribute (xml, attributeName);
  71815. return String::empty;
  71816. }
  71817. static bool isIdentifierChar (const juce_wchar c)
  71818. {
  71819. return CharacterFunctions::isLetter (c) || c == '-';
  71820. }
  71821. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71822. {
  71823. int i = 0;
  71824. for (;;)
  71825. {
  71826. i = list.indexOf (i, attributeName);
  71827. if (i < 0)
  71828. break;
  71829. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71830. && ! isIdentifierChar (list [i + attributeName.length()]))
  71831. {
  71832. i = list.indexOfChar (i, ':');
  71833. if (i < 0)
  71834. break;
  71835. int end = list.indexOfChar (i, ';');
  71836. if (end < 0)
  71837. end = 0x7ffff;
  71838. return list.substring (i + 1, end).trim();
  71839. }
  71840. ++i;
  71841. }
  71842. return defaultValue;
  71843. }
  71844. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71845. {
  71846. const juce_wchar* const s = source;
  71847. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71848. ++index;
  71849. int start = index;
  71850. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71851. ++index;
  71852. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71853. ++index;
  71854. if ((s[index] == 'e' || s[index] == 'E')
  71855. && (CharacterFunctions::isDigit (s[index + 1])
  71856. || s[index + 1] == '-'
  71857. || s[index + 1] == '+'))
  71858. {
  71859. index += 2;
  71860. while (CharacterFunctions::isDigit (s[index]))
  71861. ++index;
  71862. }
  71863. if (allowUnits)
  71864. {
  71865. while (CharacterFunctions::isLetter (s[index]))
  71866. ++index;
  71867. }
  71868. if (index == start)
  71869. return false;
  71870. value = String (s + start, index - start);
  71871. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71872. ++index;
  71873. return true;
  71874. }
  71875. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71876. {
  71877. if (s [index] == '#')
  71878. {
  71879. uint32 hex [6];
  71880. zeromem (hex, sizeof (hex));
  71881. int numChars = 0;
  71882. for (int i = 6; --i >= 0;)
  71883. {
  71884. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71885. if (hexValue >= 0)
  71886. hex [numChars++] = hexValue;
  71887. else
  71888. break;
  71889. }
  71890. if (numChars <= 3)
  71891. return Colour ((uint8) (hex [0] * 0x11),
  71892. (uint8) (hex [1] * 0x11),
  71893. (uint8) (hex [2] * 0x11));
  71894. else
  71895. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71896. (uint8) ((hex [2] << 4) + hex [3]),
  71897. (uint8) ((hex [4] << 4) + hex [5]));
  71898. }
  71899. else if (s [index] == 'r'
  71900. && s [index + 1] == 'g'
  71901. && s [index + 2] == 'b')
  71902. {
  71903. const int openBracket = s.indexOfChar (index, '(');
  71904. const int closeBracket = s.indexOfChar (openBracket, ')');
  71905. if (openBracket >= 3 && closeBracket > openBracket)
  71906. {
  71907. index = closeBracket;
  71908. StringArray tokens;
  71909. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71910. tokens.trim();
  71911. tokens.removeEmptyStrings();
  71912. if (tokens[0].containsChar ('%'))
  71913. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71914. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71915. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71916. else
  71917. return Colour ((uint8) tokens[0].getIntValue(),
  71918. (uint8) tokens[1].getIntValue(),
  71919. (uint8) tokens[2].getIntValue());
  71920. }
  71921. }
  71922. return Colours::findColourForName (s, defaultColour);
  71923. }
  71924. static const AffineTransform parseTransform (String t)
  71925. {
  71926. AffineTransform result;
  71927. while (t.isNotEmpty())
  71928. {
  71929. StringArray tokens;
  71930. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71931. .upToFirstOccurrenceOf (")", false, false),
  71932. ", ", String::empty);
  71933. tokens.removeEmptyStrings (true);
  71934. float numbers [6];
  71935. for (int i = 0; i < 6; ++i)
  71936. numbers[i] = tokens[i].getFloatValue();
  71937. AffineTransform trans;
  71938. if (t.startsWithIgnoreCase ("matrix"))
  71939. {
  71940. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71941. numbers[1], numbers[3], numbers[5]);
  71942. }
  71943. else if (t.startsWithIgnoreCase ("translate"))
  71944. {
  71945. jassert (tokens.size() == 2);
  71946. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71947. }
  71948. else if (t.startsWithIgnoreCase ("scale"))
  71949. {
  71950. if (tokens.size() == 1)
  71951. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71952. else
  71953. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71954. }
  71955. else if (t.startsWithIgnoreCase ("rotate"))
  71956. {
  71957. if (tokens.size() != 3)
  71958. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71959. else
  71960. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71961. numbers[1], numbers[2]);
  71962. }
  71963. else if (t.startsWithIgnoreCase ("skewX"))
  71964. {
  71965. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71966. 0.0f, 1.0f, 0.0f);
  71967. }
  71968. else if (t.startsWithIgnoreCase ("skewY"))
  71969. {
  71970. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71971. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71972. }
  71973. result = trans.followedBy (result);
  71974. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71975. }
  71976. return result;
  71977. }
  71978. static void endpointToCentreParameters (const double x1, const double y1,
  71979. const double x2, const double y2,
  71980. const double angle,
  71981. const bool largeArc, const bool sweep,
  71982. double& rx, double& ry,
  71983. double& centreX, double& centreY,
  71984. double& startAngle, double& deltaAngle)
  71985. {
  71986. const double midX = (x1 - x2) * 0.5;
  71987. const double midY = (y1 - y2) * 0.5;
  71988. const double cosAngle = cos (angle);
  71989. const double sinAngle = sin (angle);
  71990. const double xp = cosAngle * midX + sinAngle * midY;
  71991. const double yp = cosAngle * midY - sinAngle * midX;
  71992. const double xp2 = xp * xp;
  71993. const double yp2 = yp * yp;
  71994. double rx2 = rx * rx;
  71995. double ry2 = ry * ry;
  71996. const double s = (xp2 / rx2) + (yp2 / ry2);
  71997. double c;
  71998. if (s <= 1.0)
  71999. {
  72000. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72001. / (( rx2 * yp2) + (ry2 * xp2))));
  72002. if (largeArc == sweep)
  72003. c = -c;
  72004. }
  72005. else
  72006. {
  72007. const double s2 = std::sqrt (s);
  72008. rx *= s2;
  72009. ry *= s2;
  72010. rx2 = rx * rx;
  72011. ry2 = ry * ry;
  72012. c = 0;
  72013. }
  72014. const double cpx = ((rx * yp) / ry) * c;
  72015. const double cpy = ((-ry * xp) / rx) * c;
  72016. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72017. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72018. const double ux = (xp - cpx) / rx;
  72019. const double uy = (yp - cpy) / ry;
  72020. const double vx = (-xp - cpx) / rx;
  72021. const double vy = (-yp - cpy) / ry;
  72022. const double length = juce_hypot (ux, uy);
  72023. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72024. if (uy < 0)
  72025. startAngle = -startAngle;
  72026. startAngle += double_Pi * 0.5;
  72027. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72028. / (length * juce_hypot (vx, vy))));
  72029. if ((ux * vy) - (uy * vx) < 0)
  72030. deltaAngle = -deltaAngle;
  72031. if (sweep)
  72032. {
  72033. if (deltaAngle < 0)
  72034. deltaAngle += double_Pi * 2.0;
  72035. }
  72036. else
  72037. {
  72038. if (deltaAngle > 0)
  72039. deltaAngle -= double_Pi * 2.0;
  72040. }
  72041. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72042. }
  72043. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72044. {
  72045. forEachXmlChildElement (*parent, e)
  72046. {
  72047. if (e->compareAttribute ("id", id))
  72048. return e;
  72049. const XmlElement* const found = findElementForId (e, id);
  72050. if (found != 0)
  72051. return found;
  72052. }
  72053. return 0;
  72054. }
  72055. SVGState& operator= (const SVGState&);
  72056. };
  72057. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72058. {
  72059. SVGState state (&svgDocument);
  72060. return state.parseSVGElement (svgDocument);
  72061. }
  72062. END_JUCE_NAMESPACE
  72063. /*** End of inlined file: juce_SVGParser.cpp ***/
  72064. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72065. BEGIN_JUCE_NAMESPACE
  72066. #if JUCE_MSVC && JUCE_DEBUG
  72067. #pragma optimize ("t", on)
  72068. #endif
  72069. DropShadowEffect::DropShadowEffect()
  72070. : offsetX (0),
  72071. offsetY (0),
  72072. radius (4),
  72073. opacity (0.6f)
  72074. {
  72075. }
  72076. DropShadowEffect::~DropShadowEffect()
  72077. {
  72078. }
  72079. void DropShadowEffect::setShadowProperties (const float newRadius,
  72080. const float newOpacity,
  72081. const int newShadowOffsetX,
  72082. const int newShadowOffsetY)
  72083. {
  72084. radius = jmax (1.1f, newRadius);
  72085. offsetX = newShadowOffsetX;
  72086. offsetY = newShadowOffsetY;
  72087. opacity = newOpacity;
  72088. }
  72089. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72090. {
  72091. const int w = image.getWidth();
  72092. const int h = image.getHeight();
  72093. Image shadowImage (Image::SingleChannel, w, h, false);
  72094. const Image::BitmapData srcData (image, false);
  72095. const Image::BitmapData destData (shadowImage, true);
  72096. const int filter = roundToInt (63.0f / radius);
  72097. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72098. for (int x = w; --x >= 0;)
  72099. {
  72100. int shadowAlpha = 0;
  72101. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72102. uint8* shadowPix = destData.data + x;
  72103. for (int y = h; --y >= 0;)
  72104. {
  72105. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72106. *shadowPix = (uint8) shadowAlpha;
  72107. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72108. shadowPix += destData.lineStride;
  72109. }
  72110. }
  72111. for (int y = h; --y >= 0;)
  72112. {
  72113. int shadowAlpha = 0;
  72114. uint8* shadowPix = destData.getLinePointer (y);
  72115. for (int x = w; --x >= 0;)
  72116. {
  72117. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72118. *shadowPix++ = (uint8) shadowAlpha;
  72119. }
  72120. }
  72121. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72122. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72123. g.setOpacity (alpha);
  72124. g.drawImageAt (image, 0, 0);
  72125. }
  72126. #if JUCE_MSVC && JUCE_DEBUG
  72127. #pragma optimize ("", on) // resets optimisations to the project defaults
  72128. #endif
  72129. END_JUCE_NAMESPACE
  72130. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72131. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72132. BEGIN_JUCE_NAMESPACE
  72133. GlowEffect::GlowEffect()
  72134. : radius (2.0f),
  72135. colour (Colours::white)
  72136. {
  72137. }
  72138. GlowEffect::~GlowEffect()
  72139. {
  72140. }
  72141. void GlowEffect::setGlowProperties (const float newRadius,
  72142. const Colour& newColour)
  72143. {
  72144. radius = newRadius;
  72145. colour = newColour;
  72146. }
  72147. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72148. {
  72149. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72150. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72151. blurKernel.createGaussianBlur (radius);
  72152. blurKernel.rescaleAllValues (radius);
  72153. blurKernel.applyToImage (temp, image, image.getBounds());
  72154. g.setColour (colour.withMultipliedAlpha (alpha));
  72155. g.drawImageAt (temp, 0, 0, true);
  72156. g.setOpacity (alpha);
  72157. g.drawImageAt (image, 0, 0, false);
  72158. }
  72159. END_JUCE_NAMESPACE
  72160. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72161. /*** Start of inlined file: juce_Font.cpp ***/
  72162. BEGIN_JUCE_NAMESPACE
  72163. namespace FontValues
  72164. {
  72165. float limitFontHeight (const float height) throw()
  72166. {
  72167. return jlimit (0.1f, 10000.0f, height);
  72168. }
  72169. const float defaultFontHeight = 14.0f;
  72170. String fallbackFont;
  72171. }
  72172. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72173. const float kerning_, const float ascent_, const int styleFlags_,
  72174. Typeface* const typeface_) throw()
  72175. : typefaceName (typefaceName_),
  72176. height (height_),
  72177. horizontalScale (horizontalScale_),
  72178. kerning (kerning_),
  72179. ascent (ascent_),
  72180. styleFlags (styleFlags_),
  72181. typeface (typeface_)
  72182. {
  72183. }
  72184. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72185. : typefaceName (other.typefaceName),
  72186. height (other.height),
  72187. horizontalScale (other.horizontalScale),
  72188. kerning (other.kerning),
  72189. ascent (other.ascent),
  72190. styleFlags (other.styleFlags),
  72191. typeface (other.typeface)
  72192. {
  72193. }
  72194. Font::Font()
  72195. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72196. 1.0f, 0, 0, Font::plain, 0))
  72197. {
  72198. }
  72199. Font::Font (const float fontHeight, const int styleFlags_)
  72200. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72201. 1.0f, 0, 0, styleFlags_, 0))
  72202. {
  72203. }
  72204. Font::Font (const String& typefaceName_,
  72205. const float fontHeight,
  72206. const int styleFlags_)
  72207. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72208. 1.0f, 0, 0, styleFlags_, 0))
  72209. {
  72210. }
  72211. Font::Font (const Font& other) throw()
  72212. : font (other.font)
  72213. {
  72214. }
  72215. Font& Font::operator= (const Font& other) throw()
  72216. {
  72217. font = other.font;
  72218. return *this;
  72219. }
  72220. Font::~Font() throw()
  72221. {
  72222. }
  72223. Font::Font (const Typeface::Ptr& typeface)
  72224. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72225. 1.0f, 0, 0, Font::plain, typeface))
  72226. {
  72227. }
  72228. bool Font::operator== (const Font& other) const throw()
  72229. {
  72230. return font == other.font
  72231. || (font->height == other.font->height
  72232. && font->styleFlags == other.font->styleFlags
  72233. && font->horizontalScale == other.font->horizontalScale
  72234. && font->kerning == other.font->kerning
  72235. && font->typefaceName == other.font->typefaceName);
  72236. }
  72237. bool Font::operator!= (const Font& other) const throw()
  72238. {
  72239. return ! operator== (other);
  72240. }
  72241. void Font::dupeInternalIfShared()
  72242. {
  72243. if (font->getReferenceCount() > 1)
  72244. font = new SharedFontInternal (*font);
  72245. }
  72246. const String Font::getDefaultSansSerifFontName()
  72247. {
  72248. static const String name ("<Sans-Serif>");
  72249. return name;
  72250. }
  72251. const String Font::getDefaultSerifFontName()
  72252. {
  72253. static const String name ("<Serif>");
  72254. return name;
  72255. }
  72256. const String Font::getDefaultMonospacedFontName()
  72257. {
  72258. static const String name ("<Monospaced>");
  72259. return name;
  72260. }
  72261. void Font::setTypefaceName (const String& faceName)
  72262. {
  72263. if (faceName != font->typefaceName)
  72264. {
  72265. dupeInternalIfShared();
  72266. font->typefaceName = faceName;
  72267. font->typeface = 0;
  72268. font->ascent = 0;
  72269. }
  72270. }
  72271. const String Font::getFallbackFontName()
  72272. {
  72273. return FontValues::fallbackFont;
  72274. }
  72275. void Font::setFallbackFontName (const String& name)
  72276. {
  72277. FontValues::fallbackFont = name;
  72278. }
  72279. void Font::setHeight (float newHeight)
  72280. {
  72281. newHeight = FontValues::limitFontHeight (newHeight);
  72282. if (font->height != newHeight)
  72283. {
  72284. dupeInternalIfShared();
  72285. font->height = newHeight;
  72286. }
  72287. }
  72288. void Font::setHeightWithoutChangingWidth (float newHeight)
  72289. {
  72290. newHeight = FontValues::limitFontHeight (newHeight);
  72291. if (font->height != newHeight)
  72292. {
  72293. dupeInternalIfShared();
  72294. font->horizontalScale *= (font->height / newHeight);
  72295. font->height = newHeight;
  72296. }
  72297. }
  72298. void Font::setStyleFlags (const int newFlags)
  72299. {
  72300. if (font->styleFlags != newFlags)
  72301. {
  72302. dupeInternalIfShared();
  72303. font->styleFlags = newFlags;
  72304. font->typeface = 0;
  72305. font->ascent = 0;
  72306. }
  72307. }
  72308. void Font::setSizeAndStyle (float newHeight,
  72309. const int newStyleFlags,
  72310. const float newHorizontalScale,
  72311. const float newKerningAmount)
  72312. {
  72313. newHeight = FontValues::limitFontHeight (newHeight);
  72314. if (font->height != newHeight
  72315. || font->horizontalScale != newHorizontalScale
  72316. || font->kerning != newKerningAmount)
  72317. {
  72318. dupeInternalIfShared();
  72319. font->height = newHeight;
  72320. font->horizontalScale = newHorizontalScale;
  72321. font->kerning = newKerningAmount;
  72322. }
  72323. setStyleFlags (newStyleFlags);
  72324. }
  72325. void Font::setHorizontalScale (const float scaleFactor)
  72326. {
  72327. dupeInternalIfShared();
  72328. font->horizontalScale = scaleFactor;
  72329. }
  72330. void Font::setExtraKerningFactor (const float extraKerning)
  72331. {
  72332. dupeInternalIfShared();
  72333. font->kerning = extraKerning;
  72334. }
  72335. void Font::setBold (const bool shouldBeBold)
  72336. {
  72337. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72338. : (font->styleFlags & ~bold));
  72339. }
  72340. const Font Font::boldened() const
  72341. {
  72342. Font f (*this);
  72343. f.setBold (true);
  72344. return f;
  72345. }
  72346. bool Font::isBold() const throw()
  72347. {
  72348. return (font->styleFlags & bold) != 0;
  72349. }
  72350. void Font::setItalic (const bool shouldBeItalic)
  72351. {
  72352. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72353. : (font->styleFlags & ~italic));
  72354. }
  72355. const Font Font::italicised() const
  72356. {
  72357. Font f (*this);
  72358. f.setItalic (true);
  72359. return f;
  72360. }
  72361. bool Font::isItalic() const throw()
  72362. {
  72363. return (font->styleFlags & italic) != 0;
  72364. }
  72365. void Font::setUnderline (const bool shouldBeUnderlined)
  72366. {
  72367. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72368. : (font->styleFlags & ~underlined));
  72369. }
  72370. bool Font::isUnderlined() const throw()
  72371. {
  72372. return (font->styleFlags & underlined) != 0;
  72373. }
  72374. float Font::getAscent() const
  72375. {
  72376. if (font->ascent == 0)
  72377. font->ascent = getTypeface()->getAscent();
  72378. return font->height * font->ascent;
  72379. }
  72380. float Font::getDescent() const
  72381. {
  72382. return font->height - getAscent();
  72383. }
  72384. int Font::getStringWidth (const String& text) const
  72385. {
  72386. return roundToInt (getStringWidthFloat (text));
  72387. }
  72388. float Font::getStringWidthFloat (const String& text) const
  72389. {
  72390. float w = getTypeface()->getStringWidth (text);
  72391. if (font->kerning != 0)
  72392. w += font->kerning * text.length();
  72393. return w * font->height * font->horizontalScale;
  72394. }
  72395. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72396. {
  72397. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72398. const float scale = font->height * font->horizontalScale;
  72399. const int num = xOffsets.size();
  72400. if (num > 0)
  72401. {
  72402. float* const x = &(xOffsets.getReference(0));
  72403. if (font->kerning != 0)
  72404. {
  72405. for (int i = 0; i < num; ++i)
  72406. x[i] = (x[i] + i * font->kerning) * scale;
  72407. }
  72408. else
  72409. {
  72410. for (int i = 0; i < num; ++i)
  72411. x[i] *= scale;
  72412. }
  72413. }
  72414. }
  72415. void Font::findFonts (Array<Font>& destArray)
  72416. {
  72417. const StringArray names (findAllTypefaceNames());
  72418. for (int i = 0; i < names.size(); ++i)
  72419. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72420. }
  72421. const String Font::toString() const
  72422. {
  72423. String s (getTypefaceName());
  72424. if (s == getDefaultSansSerifFontName())
  72425. s = String::empty;
  72426. else
  72427. s += "; ";
  72428. s += String (getHeight(), 1);
  72429. if (isBold())
  72430. s += " bold";
  72431. if (isItalic())
  72432. s += " italic";
  72433. return s;
  72434. }
  72435. const Font Font::fromString (const String& fontDescription)
  72436. {
  72437. String name;
  72438. const int separator = fontDescription.indexOfChar (';');
  72439. if (separator > 0)
  72440. name = fontDescription.substring (0, separator).trim();
  72441. if (name.isEmpty())
  72442. name = getDefaultSansSerifFontName();
  72443. String sizeAndStyle (fontDescription.substring (separator + 1));
  72444. float height = sizeAndStyle.getFloatValue();
  72445. if (height <= 0)
  72446. height = 10.0f;
  72447. int flags = Font::plain;
  72448. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72449. flags |= Font::bold;
  72450. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72451. flags |= Font::italic;
  72452. return Font (name, height, flags);
  72453. }
  72454. class TypefaceCache : public DeletedAtShutdown
  72455. {
  72456. public:
  72457. TypefaceCache (int numToCache = 10)
  72458. : counter (1)
  72459. {
  72460. while (--numToCache >= 0)
  72461. faces.add (new CachedFace());
  72462. }
  72463. ~TypefaceCache()
  72464. {
  72465. clearSingletonInstance();
  72466. }
  72467. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72468. const Typeface::Ptr findTypefaceFor (const Font& font)
  72469. {
  72470. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72471. const String faceName (font.getTypefaceName());
  72472. int i;
  72473. for (i = faces.size(); --i >= 0;)
  72474. {
  72475. CachedFace* const face = faces.getUnchecked(i);
  72476. if (face->flags == flags
  72477. && face->typefaceName == faceName)
  72478. {
  72479. face->lastUsageCount = ++counter;
  72480. return face->typeFace;
  72481. }
  72482. }
  72483. int replaceIndex = 0;
  72484. int bestLastUsageCount = std::numeric_limits<int>::max();
  72485. for (i = faces.size(); --i >= 0;)
  72486. {
  72487. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72488. if (bestLastUsageCount > lu)
  72489. {
  72490. bestLastUsageCount = lu;
  72491. replaceIndex = i;
  72492. }
  72493. }
  72494. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72495. face->typefaceName = faceName;
  72496. face->flags = flags;
  72497. face->lastUsageCount = ++counter;
  72498. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72499. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72500. return face->typeFace;
  72501. }
  72502. private:
  72503. struct CachedFace
  72504. {
  72505. CachedFace() throw()
  72506. : lastUsageCount (0), flags (-1)
  72507. {
  72508. }
  72509. String typefaceName;
  72510. int lastUsageCount;
  72511. int flags;
  72512. Typeface::Ptr typeFace;
  72513. };
  72514. int counter;
  72515. OwnedArray <CachedFace> faces;
  72516. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72517. };
  72518. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72519. Typeface* Font::getTypeface() const
  72520. {
  72521. if (font->typeface == 0)
  72522. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72523. return font->typeface;
  72524. }
  72525. END_JUCE_NAMESPACE
  72526. /*** End of inlined file: juce_Font.cpp ***/
  72527. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72528. BEGIN_JUCE_NAMESPACE
  72529. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72530. const juce_wchar character_, const int glyph_)
  72531. : x (x_),
  72532. y (y_),
  72533. w (w_),
  72534. font (font_),
  72535. character (character_),
  72536. glyph (glyph_)
  72537. {
  72538. }
  72539. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72540. : x (other.x),
  72541. y (other.y),
  72542. w (other.w),
  72543. font (other.font),
  72544. character (other.character),
  72545. glyph (other.glyph)
  72546. {
  72547. }
  72548. void PositionedGlyph::draw (const Graphics& g) const
  72549. {
  72550. if (! isWhitespace())
  72551. {
  72552. g.getInternalContext()->setFont (font);
  72553. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72554. }
  72555. }
  72556. void PositionedGlyph::draw (const Graphics& g,
  72557. const AffineTransform& transform) const
  72558. {
  72559. if (! isWhitespace())
  72560. {
  72561. g.getInternalContext()->setFont (font);
  72562. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72563. .followedBy (transform));
  72564. }
  72565. }
  72566. void PositionedGlyph::createPath (Path& path) const
  72567. {
  72568. if (! isWhitespace())
  72569. {
  72570. Typeface* const t = font.getTypeface();
  72571. if (t != 0)
  72572. {
  72573. Path p;
  72574. t->getOutlineForGlyph (glyph, p);
  72575. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72576. .translated (x, y));
  72577. }
  72578. }
  72579. }
  72580. bool PositionedGlyph::hitTest (float px, float py) const
  72581. {
  72582. if (getBounds().contains (px, py) && ! isWhitespace())
  72583. {
  72584. Typeface* const t = font.getTypeface();
  72585. if (t != 0)
  72586. {
  72587. Path p;
  72588. t->getOutlineForGlyph (glyph, p);
  72589. AffineTransform::translation (-x, -y)
  72590. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72591. .transformPoint (px, py);
  72592. return p.contains (px, py);
  72593. }
  72594. }
  72595. return false;
  72596. }
  72597. void PositionedGlyph::moveBy (const float deltaX,
  72598. const float deltaY)
  72599. {
  72600. x += deltaX;
  72601. y += deltaY;
  72602. }
  72603. GlyphArrangement::GlyphArrangement()
  72604. {
  72605. glyphs.ensureStorageAllocated (128);
  72606. }
  72607. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72608. {
  72609. addGlyphArrangement (other);
  72610. }
  72611. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72612. {
  72613. if (this != &other)
  72614. {
  72615. clear();
  72616. addGlyphArrangement (other);
  72617. }
  72618. return *this;
  72619. }
  72620. GlyphArrangement::~GlyphArrangement()
  72621. {
  72622. }
  72623. void GlyphArrangement::clear()
  72624. {
  72625. glyphs.clear();
  72626. }
  72627. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72628. {
  72629. jassert (isPositiveAndBelow (index, glyphs.size()));
  72630. return *glyphs [index];
  72631. }
  72632. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72633. {
  72634. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72635. glyphs.addCopiesOf (other.glyphs);
  72636. }
  72637. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72638. {
  72639. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72640. }
  72641. void GlyphArrangement::addLineOfText (const Font& font,
  72642. const String& text,
  72643. const float xOffset,
  72644. const float yOffset)
  72645. {
  72646. addCurtailedLineOfText (font, text,
  72647. xOffset, yOffset,
  72648. 1.0e10f, false);
  72649. }
  72650. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72651. const String& text,
  72652. float xOffset,
  72653. const float yOffset,
  72654. const float maxWidthPixels,
  72655. const bool useEllipsis)
  72656. {
  72657. if (text.isNotEmpty())
  72658. {
  72659. Array <int> newGlyphs;
  72660. Array <float> xOffsets;
  72661. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72662. const int textLen = newGlyphs.size();
  72663. const juce_wchar* const unicodeText = text;
  72664. for (int i = 0; i < textLen; ++i)
  72665. {
  72666. const float thisX = xOffsets.getUnchecked (i);
  72667. const float nextX = xOffsets.getUnchecked (i + 1);
  72668. if (nextX > maxWidthPixels + 1.0f)
  72669. {
  72670. // curtail the string if it's too wide..
  72671. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72672. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72673. break;
  72674. }
  72675. else
  72676. {
  72677. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72678. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72679. }
  72680. }
  72681. }
  72682. }
  72683. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72684. const int startIndex, int endIndex)
  72685. {
  72686. int numDeleted = 0;
  72687. if (glyphs.size() > 0)
  72688. {
  72689. Array<int> dotGlyphs;
  72690. Array<float> dotXs;
  72691. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72692. const float dx = dotXs[1];
  72693. float xOffset = 0.0f, yOffset = 0.0f;
  72694. while (endIndex > startIndex)
  72695. {
  72696. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72697. xOffset = pg->x;
  72698. yOffset = pg->y;
  72699. glyphs.remove (endIndex);
  72700. ++numDeleted;
  72701. if (xOffset + dx * 3 <= maxXPos)
  72702. break;
  72703. }
  72704. for (int i = 3; --i >= 0;)
  72705. {
  72706. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72707. font, '.', dotGlyphs.getFirst()));
  72708. --numDeleted;
  72709. xOffset += dx;
  72710. if (xOffset > maxXPos)
  72711. break;
  72712. }
  72713. }
  72714. return numDeleted;
  72715. }
  72716. void GlyphArrangement::addJustifiedText (const Font& font,
  72717. const String& text,
  72718. float x, float y,
  72719. const float maxLineWidth,
  72720. const Justification& horizontalLayout)
  72721. {
  72722. int lineStartIndex = glyphs.size();
  72723. addLineOfText (font, text, x, y);
  72724. const float originalY = y;
  72725. while (lineStartIndex < glyphs.size())
  72726. {
  72727. int i = lineStartIndex;
  72728. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72729. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72730. ++i;
  72731. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72732. int lastWordBreakIndex = -1;
  72733. while (i < glyphs.size())
  72734. {
  72735. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72736. const juce_wchar c = pg->getCharacter();
  72737. if (c == '\r' || c == '\n')
  72738. {
  72739. ++i;
  72740. if (c == '\r' && i < glyphs.size()
  72741. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72742. ++i;
  72743. break;
  72744. }
  72745. else if (pg->isWhitespace())
  72746. {
  72747. lastWordBreakIndex = i + 1;
  72748. }
  72749. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72750. {
  72751. if (lastWordBreakIndex >= 0)
  72752. i = lastWordBreakIndex;
  72753. break;
  72754. }
  72755. ++i;
  72756. }
  72757. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72758. float currentLineEndX = currentLineStartX;
  72759. for (int j = i; --j >= lineStartIndex;)
  72760. {
  72761. if (! glyphs.getUnchecked (j)->isWhitespace())
  72762. {
  72763. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72764. break;
  72765. }
  72766. }
  72767. float deltaX = 0.0f;
  72768. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72769. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72770. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72771. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72772. else if (horizontalLayout.testFlags (Justification::right))
  72773. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72774. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72775. x + deltaX - currentLineStartX, y - originalY);
  72776. lineStartIndex = i;
  72777. y += font.getHeight();
  72778. }
  72779. }
  72780. void GlyphArrangement::addFittedText (const Font& f,
  72781. const String& text,
  72782. const float x, const float y,
  72783. const float width, const float height,
  72784. const Justification& layout,
  72785. int maximumLines,
  72786. const float minimumHorizontalScale)
  72787. {
  72788. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72789. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72790. if (text.containsAnyOf ("\r\n"))
  72791. {
  72792. GlyphArrangement ga;
  72793. ga.addJustifiedText (f, text, x, y, width, layout);
  72794. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72795. float dy = y - bb.getY();
  72796. if (layout.testFlags (Justification::verticallyCentred))
  72797. dy += (height - bb.getHeight()) * 0.5f;
  72798. else if (layout.testFlags (Justification::bottom))
  72799. dy += height - bb.getHeight();
  72800. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72801. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72802. for (int i = 0; i < ga.glyphs.size(); ++i)
  72803. glyphs.add (ga.glyphs.getUnchecked (i));
  72804. ga.glyphs.clear (false);
  72805. return;
  72806. }
  72807. int startIndex = glyphs.size();
  72808. addLineOfText (f, text.trim(), x, y);
  72809. if (glyphs.size() > startIndex)
  72810. {
  72811. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72812. - glyphs.getUnchecked (startIndex)->getLeft();
  72813. if (lineWidth <= 0)
  72814. return;
  72815. if (lineWidth * minimumHorizontalScale < width)
  72816. {
  72817. if (lineWidth > width)
  72818. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72819. width / lineWidth);
  72820. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72821. x, y, width, height, layout);
  72822. }
  72823. else if (maximumLines <= 1)
  72824. {
  72825. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72826. x, y, width, height, f, layout, minimumHorizontalScale);
  72827. }
  72828. else
  72829. {
  72830. Font font (f);
  72831. String txt (text.trim());
  72832. const int length = txt.length();
  72833. const int originalStartIndex = startIndex;
  72834. int numLines = 1;
  72835. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72836. maximumLines = 1;
  72837. maximumLines = jmin (maximumLines, length);
  72838. while (numLines < maximumLines)
  72839. {
  72840. ++numLines;
  72841. const float newFontHeight = height / (float) numLines;
  72842. if (newFontHeight < font.getHeight())
  72843. {
  72844. font.setHeight (jmax (8.0f, newFontHeight));
  72845. removeRangeOfGlyphs (startIndex, -1);
  72846. addLineOfText (font, txt, x, y);
  72847. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72848. - glyphs.getUnchecked (startIndex)->getLeft();
  72849. }
  72850. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72851. break;
  72852. }
  72853. if (numLines < 1)
  72854. numLines = 1;
  72855. float lineY = y;
  72856. float widthPerLine = lineWidth / numLines;
  72857. int lastLineStartIndex = 0;
  72858. for (int line = 0; line < numLines; ++line)
  72859. {
  72860. int i = startIndex;
  72861. lastLineStartIndex = i;
  72862. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72863. if (line == numLines - 1)
  72864. {
  72865. widthPerLine = width;
  72866. i = glyphs.size();
  72867. }
  72868. else
  72869. {
  72870. while (i < glyphs.size())
  72871. {
  72872. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72873. if (lineWidth > widthPerLine)
  72874. {
  72875. // got to a point where the line's too long, so skip forward to find a
  72876. // good place to break it..
  72877. const int searchStartIndex = i;
  72878. while (i < glyphs.size())
  72879. {
  72880. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72881. {
  72882. if (glyphs.getUnchecked (i)->isWhitespace()
  72883. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72884. {
  72885. ++i;
  72886. break;
  72887. }
  72888. }
  72889. else
  72890. {
  72891. // can't find a suitable break, so try looking backwards..
  72892. i = searchStartIndex;
  72893. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72894. {
  72895. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72896. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72897. {
  72898. i -= back - 1;
  72899. break;
  72900. }
  72901. }
  72902. break;
  72903. }
  72904. ++i;
  72905. }
  72906. break;
  72907. }
  72908. ++i;
  72909. }
  72910. int wsStart = i;
  72911. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72912. --wsStart;
  72913. int wsEnd = i;
  72914. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72915. ++wsEnd;
  72916. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72917. i = jmax (wsStart, startIndex + 1);
  72918. }
  72919. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72920. x, lineY, width, font.getHeight(), font,
  72921. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72922. minimumHorizontalScale);
  72923. startIndex = i;
  72924. lineY += font.getHeight();
  72925. if (startIndex >= glyphs.size())
  72926. break;
  72927. }
  72928. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72929. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72930. }
  72931. }
  72932. }
  72933. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72934. const float dx, const float dy)
  72935. {
  72936. jassert (startIndex >= 0);
  72937. if (dx != 0.0f || dy != 0.0f)
  72938. {
  72939. if (num < 0 || startIndex + num > glyphs.size())
  72940. num = glyphs.size() - startIndex;
  72941. while (--num >= 0)
  72942. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72943. }
  72944. }
  72945. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72946. const Justification& justification, float minimumHorizontalScale)
  72947. {
  72948. int numDeleted = 0;
  72949. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72950. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72951. if (lineWidth > w)
  72952. {
  72953. if (minimumHorizontalScale < 1.0f)
  72954. {
  72955. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72956. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72957. }
  72958. if (lineWidth > w)
  72959. {
  72960. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72961. numGlyphs -= numDeleted;
  72962. }
  72963. }
  72964. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72965. return numDeleted;
  72966. }
  72967. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72968. const float horizontalScaleFactor)
  72969. {
  72970. jassert (startIndex >= 0);
  72971. if (num < 0 || startIndex + num > glyphs.size())
  72972. num = glyphs.size() - startIndex;
  72973. if (num > 0)
  72974. {
  72975. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72976. while (--num >= 0)
  72977. {
  72978. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72979. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72980. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72981. pg->w *= horizontalScaleFactor;
  72982. }
  72983. }
  72984. }
  72985. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72986. {
  72987. jassert (startIndex >= 0);
  72988. if (num < 0 || startIndex + num > glyphs.size())
  72989. num = glyphs.size() - startIndex;
  72990. Rectangle<float> result;
  72991. while (--num >= 0)
  72992. {
  72993. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72994. if (includeWhitespace || ! pg->isWhitespace())
  72995. result = result.getUnion (pg->getBounds());
  72996. }
  72997. return result;
  72998. }
  72999. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73000. const float x, const float y, const float width, const float height,
  73001. const Justification& justification)
  73002. {
  73003. jassert (num >= 0 && startIndex >= 0);
  73004. if (glyphs.size() > 0 && num > 0)
  73005. {
  73006. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73007. | Justification::horizontallyCentred)));
  73008. float deltaX = 0.0f;
  73009. if (justification.testFlags (Justification::horizontallyJustified))
  73010. deltaX = x - bb.getX();
  73011. else if (justification.testFlags (Justification::horizontallyCentred))
  73012. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73013. else if (justification.testFlags (Justification::right))
  73014. deltaX = (x + width) - bb.getRight();
  73015. else
  73016. deltaX = x - bb.getX();
  73017. float deltaY = 0.0f;
  73018. if (justification.testFlags (Justification::top))
  73019. deltaY = y - bb.getY();
  73020. else if (justification.testFlags (Justification::bottom))
  73021. deltaY = (y + height) - bb.getBottom();
  73022. else
  73023. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73024. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73025. if (justification.testFlags (Justification::horizontallyJustified))
  73026. {
  73027. int lineStart = 0;
  73028. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73029. int i;
  73030. for (i = 0; i < num; ++i)
  73031. {
  73032. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73033. if (glyphY != baseY)
  73034. {
  73035. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73036. lineStart = i;
  73037. baseY = glyphY;
  73038. }
  73039. }
  73040. if (i > lineStart)
  73041. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73042. }
  73043. }
  73044. }
  73045. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73046. {
  73047. if (start + num < glyphs.size()
  73048. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73049. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73050. {
  73051. int numSpaces = 0;
  73052. int spacesAtEnd = 0;
  73053. for (int i = 0; i < num; ++i)
  73054. {
  73055. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73056. {
  73057. ++spacesAtEnd;
  73058. ++numSpaces;
  73059. }
  73060. else
  73061. {
  73062. spacesAtEnd = 0;
  73063. }
  73064. }
  73065. numSpaces -= spacesAtEnd;
  73066. if (numSpaces > 0)
  73067. {
  73068. const float startX = glyphs.getUnchecked (start)->getLeft();
  73069. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73070. const float extraPaddingBetweenWords
  73071. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73072. float deltaX = 0.0f;
  73073. for (int i = 0; i < num; ++i)
  73074. {
  73075. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73076. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73077. deltaX += extraPaddingBetweenWords;
  73078. }
  73079. }
  73080. }
  73081. }
  73082. void GlyphArrangement::draw (const Graphics& g) const
  73083. {
  73084. for (int i = 0; i < glyphs.size(); ++i)
  73085. {
  73086. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73087. if (pg->font.isUnderlined())
  73088. {
  73089. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73090. float nextX = pg->x + pg->w;
  73091. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73092. nextX = glyphs.getUnchecked (i + 1)->x;
  73093. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73094. nextX - pg->x, lineThickness);
  73095. }
  73096. pg->draw (g);
  73097. }
  73098. }
  73099. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73100. {
  73101. for (int i = 0; i < glyphs.size(); ++i)
  73102. {
  73103. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73104. if (pg->font.isUnderlined())
  73105. {
  73106. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73107. float nextX = pg->x + pg->w;
  73108. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73109. nextX = glyphs.getUnchecked (i + 1)->x;
  73110. Path p;
  73111. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73112. nextX, pg->y + lineThickness * 2.0f),
  73113. lineThickness);
  73114. g.fillPath (p, transform);
  73115. }
  73116. pg->draw (g, transform);
  73117. }
  73118. }
  73119. void GlyphArrangement::createPath (Path& path) const
  73120. {
  73121. for (int i = 0; i < glyphs.size(); ++i)
  73122. glyphs.getUnchecked (i)->createPath (path);
  73123. }
  73124. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73125. {
  73126. for (int i = 0; i < glyphs.size(); ++i)
  73127. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73128. return i;
  73129. return -1;
  73130. }
  73131. END_JUCE_NAMESPACE
  73132. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73133. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73134. BEGIN_JUCE_NAMESPACE
  73135. class TextLayout::Token
  73136. {
  73137. public:
  73138. Token (const String& t,
  73139. const Font& f,
  73140. const bool isWhitespace_)
  73141. : text (t),
  73142. font (f),
  73143. x(0),
  73144. y(0),
  73145. isWhitespace (isWhitespace_)
  73146. {
  73147. w = font.getStringWidth (t);
  73148. h = roundToInt (f.getHeight());
  73149. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73150. }
  73151. Token (const Token& other)
  73152. : text (other.text),
  73153. font (other.font),
  73154. x (other.x),
  73155. y (other.y),
  73156. w (other.w),
  73157. h (other.h),
  73158. line (other.line),
  73159. lineHeight (other.lineHeight),
  73160. isWhitespace (other.isWhitespace),
  73161. isNewLine (other.isNewLine)
  73162. {
  73163. }
  73164. void draw (Graphics& g,
  73165. const int xOffset,
  73166. const int yOffset)
  73167. {
  73168. if (! isWhitespace)
  73169. {
  73170. g.setFont (font);
  73171. g.drawSingleLineText (text.trimEnd(),
  73172. xOffset + x,
  73173. yOffset + y + (lineHeight - h)
  73174. + roundToInt (font.getAscent()));
  73175. }
  73176. }
  73177. String text;
  73178. Font font;
  73179. int x, y, w, h;
  73180. int line, lineHeight;
  73181. bool isWhitespace, isNewLine;
  73182. private:
  73183. JUCE_LEAK_DETECTOR (Token);
  73184. };
  73185. TextLayout::TextLayout()
  73186. : totalLines (0)
  73187. {
  73188. tokens.ensureStorageAllocated (64);
  73189. }
  73190. TextLayout::TextLayout (const String& text, const Font& font)
  73191. : totalLines (0)
  73192. {
  73193. tokens.ensureStorageAllocated (64);
  73194. appendText (text, font);
  73195. }
  73196. TextLayout::TextLayout (const TextLayout& other)
  73197. : totalLines (0)
  73198. {
  73199. *this = other;
  73200. }
  73201. TextLayout& TextLayout::operator= (const TextLayout& other)
  73202. {
  73203. if (this != &other)
  73204. {
  73205. clear();
  73206. totalLines = other.totalLines;
  73207. tokens.addCopiesOf (other.tokens);
  73208. }
  73209. return *this;
  73210. }
  73211. TextLayout::~TextLayout()
  73212. {
  73213. clear();
  73214. }
  73215. void TextLayout::clear()
  73216. {
  73217. tokens.clear();
  73218. totalLines = 0;
  73219. }
  73220. bool TextLayout::isEmpty() const
  73221. {
  73222. return tokens.size() == 0;
  73223. }
  73224. void TextLayout::appendText (const String& text, const Font& font)
  73225. {
  73226. const juce_wchar* t = text;
  73227. String currentString;
  73228. int lastCharType = 0;
  73229. for (;;)
  73230. {
  73231. const juce_wchar c = *t++;
  73232. if (c == 0)
  73233. break;
  73234. int charType;
  73235. if (c == '\r' || c == '\n')
  73236. {
  73237. charType = 0;
  73238. }
  73239. else if (CharacterFunctions::isWhitespace (c))
  73240. {
  73241. charType = 2;
  73242. }
  73243. else
  73244. {
  73245. charType = 1;
  73246. }
  73247. if (charType == 0 || charType != lastCharType)
  73248. {
  73249. if (currentString.isNotEmpty())
  73250. {
  73251. tokens.add (new Token (currentString, font,
  73252. lastCharType == 2 || lastCharType == 0));
  73253. }
  73254. currentString = String::charToString (c);
  73255. if (c == '\r' && *t == '\n')
  73256. currentString += *t++;
  73257. }
  73258. else
  73259. {
  73260. currentString += c;
  73261. }
  73262. lastCharType = charType;
  73263. }
  73264. if (currentString.isNotEmpty())
  73265. tokens.add (new Token (currentString, font, lastCharType == 2));
  73266. }
  73267. void TextLayout::setText (const String& text, const Font& font)
  73268. {
  73269. clear();
  73270. appendText (text, font);
  73271. }
  73272. void TextLayout::layout (int maxWidth,
  73273. const Justification& justification,
  73274. const bool attemptToBalanceLineLengths)
  73275. {
  73276. if (attemptToBalanceLineLengths)
  73277. {
  73278. const int originalW = maxWidth;
  73279. int bestWidth = maxWidth;
  73280. float bestLineProportion = 0.0f;
  73281. while (maxWidth > originalW / 2)
  73282. {
  73283. layout (maxWidth, justification, false);
  73284. if (getNumLines() <= 1)
  73285. return;
  73286. const int lastLineW = getLineWidth (getNumLines() - 1);
  73287. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73288. const float prop = lastLineW / (float) lastButOneLineW;
  73289. if (prop > 0.9f)
  73290. return;
  73291. if (prop > bestLineProportion)
  73292. {
  73293. bestLineProportion = prop;
  73294. bestWidth = maxWidth;
  73295. }
  73296. maxWidth -= 10;
  73297. }
  73298. layout (bestWidth, justification, false);
  73299. }
  73300. else
  73301. {
  73302. int x = 0;
  73303. int y = 0;
  73304. int h = 0;
  73305. totalLines = 0;
  73306. int i;
  73307. for (i = 0; i < tokens.size(); ++i)
  73308. {
  73309. Token* const t = tokens.getUnchecked(i);
  73310. t->x = x;
  73311. t->y = y;
  73312. t->line = totalLines;
  73313. x += t->w;
  73314. h = jmax (h, t->h);
  73315. const Token* nextTok = tokens [i + 1];
  73316. if (nextTok == 0)
  73317. break;
  73318. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73319. {
  73320. // finished a line, so go back and update the heights of the things on it
  73321. for (int j = i; j >= 0; --j)
  73322. {
  73323. Token* const tok = tokens.getUnchecked(j);
  73324. if (tok->line == totalLines)
  73325. tok->lineHeight = h;
  73326. else
  73327. break;
  73328. }
  73329. x = 0;
  73330. y += h;
  73331. h = 0;
  73332. ++totalLines;
  73333. }
  73334. }
  73335. // finished a line, so go back and update the heights of the things on it
  73336. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73337. {
  73338. Token* const t = tokens.getUnchecked(j);
  73339. if (t->line == totalLines)
  73340. t->lineHeight = h;
  73341. else
  73342. break;
  73343. }
  73344. ++totalLines;
  73345. if (! justification.testFlags (Justification::left))
  73346. {
  73347. int totalW = getWidth();
  73348. for (i = totalLines; --i >= 0;)
  73349. {
  73350. const int lineW = getLineWidth (i);
  73351. int dx = 0;
  73352. if (justification.testFlags (Justification::horizontallyCentred))
  73353. dx = (totalW - lineW) / 2;
  73354. else if (justification.testFlags (Justification::right))
  73355. dx = totalW - lineW;
  73356. for (int j = tokens.size(); --j >= 0;)
  73357. {
  73358. Token* const t = tokens.getUnchecked(j);
  73359. if (t->line == i)
  73360. t->x += dx;
  73361. }
  73362. }
  73363. }
  73364. }
  73365. }
  73366. int TextLayout::getLineWidth (const int lineNumber) const
  73367. {
  73368. int maxW = 0;
  73369. for (int i = tokens.size(); --i >= 0;)
  73370. {
  73371. const Token* const t = tokens.getUnchecked(i);
  73372. if (t->line == lineNumber && ! t->isWhitespace)
  73373. maxW = jmax (maxW, t->x + t->w);
  73374. }
  73375. return maxW;
  73376. }
  73377. int TextLayout::getWidth() const
  73378. {
  73379. int maxW = 0;
  73380. for (int i = tokens.size(); --i >= 0;)
  73381. {
  73382. const Token* const t = tokens.getUnchecked(i);
  73383. if (! t->isWhitespace)
  73384. maxW = jmax (maxW, t->x + t->w);
  73385. }
  73386. return maxW;
  73387. }
  73388. int TextLayout::getHeight() const
  73389. {
  73390. int maxH = 0;
  73391. for (int i = tokens.size(); --i >= 0;)
  73392. {
  73393. const Token* const t = tokens.getUnchecked(i);
  73394. if (! t->isWhitespace)
  73395. maxH = jmax (maxH, t->y + t->h);
  73396. }
  73397. return maxH;
  73398. }
  73399. void TextLayout::draw (Graphics& g,
  73400. const int xOffset,
  73401. const int yOffset) const
  73402. {
  73403. for (int i = tokens.size(); --i >= 0;)
  73404. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73405. }
  73406. void TextLayout::drawWithin (Graphics& g,
  73407. int x, int y, int w, int h,
  73408. const Justification& justification) const
  73409. {
  73410. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73411. x, y, w, h);
  73412. draw (g, x, y);
  73413. }
  73414. END_JUCE_NAMESPACE
  73415. /*** End of inlined file: juce_TextLayout.cpp ***/
  73416. /*** Start of inlined file: juce_Typeface.cpp ***/
  73417. BEGIN_JUCE_NAMESPACE
  73418. Typeface::Typeface (const String& name_) throw()
  73419. : name (name_), isFallbackFont (false)
  73420. {
  73421. }
  73422. Typeface::~Typeface()
  73423. {
  73424. }
  73425. const Typeface::Ptr Typeface::getFallbackTypeface()
  73426. {
  73427. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73428. Typeface* t = fallbackFont.getTypeface();
  73429. t->isFallbackFont = true;
  73430. return t;
  73431. }
  73432. class CustomTypeface::GlyphInfo
  73433. {
  73434. public:
  73435. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73436. : character (character_), path (path_), width (width_)
  73437. {
  73438. }
  73439. struct KerningPair
  73440. {
  73441. juce_wchar character2;
  73442. float kerningAmount;
  73443. };
  73444. void addKerningPair (const juce_wchar subsequentCharacter,
  73445. const float extraKerningAmount) throw()
  73446. {
  73447. KerningPair kp;
  73448. kp.character2 = subsequentCharacter;
  73449. kp.kerningAmount = extraKerningAmount;
  73450. kerningPairs.add (kp);
  73451. }
  73452. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73453. {
  73454. if (subsequentCharacter != 0)
  73455. {
  73456. for (int i = kerningPairs.size(); --i >= 0;)
  73457. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73458. return width + kerningPairs.getReference(i).kerningAmount;
  73459. }
  73460. return width;
  73461. }
  73462. const juce_wchar character;
  73463. const Path path;
  73464. float width;
  73465. Array <KerningPair> kerningPairs;
  73466. private:
  73467. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73468. };
  73469. CustomTypeface::CustomTypeface()
  73470. : Typeface (String::empty)
  73471. {
  73472. clear();
  73473. }
  73474. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73475. : Typeface (String::empty)
  73476. {
  73477. clear();
  73478. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73479. BufferedInputStream in (gzin, 32768);
  73480. name = in.readString();
  73481. isBold = in.readBool();
  73482. isItalic = in.readBool();
  73483. ascent = in.readFloat();
  73484. defaultCharacter = (juce_wchar) in.readShort();
  73485. int i, numChars = in.readInt();
  73486. for (i = 0; i < numChars; ++i)
  73487. {
  73488. const juce_wchar c = (juce_wchar) in.readShort();
  73489. const float width = in.readFloat();
  73490. Path p;
  73491. p.loadPathFromStream (in);
  73492. addGlyph (c, p, width);
  73493. }
  73494. const int numKerningPairs = in.readInt();
  73495. for (i = 0; i < numKerningPairs; ++i)
  73496. {
  73497. const juce_wchar char1 = (juce_wchar) in.readShort();
  73498. const juce_wchar char2 = (juce_wchar) in.readShort();
  73499. addKerningPair (char1, char2, in.readFloat());
  73500. }
  73501. }
  73502. CustomTypeface::~CustomTypeface()
  73503. {
  73504. }
  73505. void CustomTypeface::clear()
  73506. {
  73507. defaultCharacter = 0;
  73508. ascent = 1.0f;
  73509. isBold = isItalic = false;
  73510. zeromem (lookupTable, sizeof (lookupTable));
  73511. glyphs.clear();
  73512. }
  73513. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73514. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73515. {
  73516. name = name_;
  73517. defaultCharacter = defaultCharacter_;
  73518. ascent = ascent_;
  73519. isBold = isBold_;
  73520. isItalic = isItalic_;
  73521. }
  73522. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73523. {
  73524. // Check that you're not trying to add the same character twice..
  73525. jassert (findGlyph (character, false) == 0);
  73526. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73527. lookupTable [character] = (short) glyphs.size();
  73528. glyphs.add (new GlyphInfo (character, path, width));
  73529. }
  73530. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73531. {
  73532. if (extraAmount != 0)
  73533. {
  73534. GlyphInfo* const g = findGlyph (char1, true);
  73535. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73536. if (g != 0)
  73537. g->addKerningPair (char2, extraAmount);
  73538. }
  73539. }
  73540. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73541. {
  73542. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73543. return glyphs [(int) lookupTable [(int) character]];
  73544. for (int i = 0; i < glyphs.size(); ++i)
  73545. {
  73546. GlyphInfo* const g = glyphs.getUnchecked(i);
  73547. if (g->character == character)
  73548. return g;
  73549. }
  73550. if (loadIfNeeded && loadGlyphIfPossible (character))
  73551. return findGlyph (character, false);
  73552. return 0;
  73553. }
  73554. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73555. {
  73556. GlyphInfo* glyph = findGlyph (character, true);
  73557. if (glyph == 0)
  73558. {
  73559. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73560. glyph = findGlyph (L' ', true);
  73561. if (glyph == 0)
  73562. {
  73563. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73564. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73565. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73566. {
  73567. Path path;
  73568. fallbackTypeface->getOutlineForGlyph (character, path);
  73569. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73570. }
  73571. if (glyph == 0)
  73572. glyph = findGlyph (defaultCharacter, true);
  73573. }
  73574. }
  73575. return glyph;
  73576. }
  73577. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73578. {
  73579. return false;
  73580. }
  73581. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73582. {
  73583. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73584. for (int i = 0; i < numCharacters; ++i)
  73585. {
  73586. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73587. Array <int> glyphIndexes;
  73588. Array <float> offsets;
  73589. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73590. const int glyphIndex = glyphIndexes.getFirst();
  73591. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73592. {
  73593. const float glyphWidth = offsets[1];
  73594. Path p;
  73595. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73596. addGlyph (c, p, glyphWidth);
  73597. for (int j = glyphs.size() - 1; --j >= 0;)
  73598. {
  73599. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73600. glyphIndexes.clearQuick();
  73601. offsets.clearQuick();
  73602. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73603. if (offsets.size() > 1)
  73604. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73605. }
  73606. }
  73607. }
  73608. }
  73609. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73610. {
  73611. GZIPCompressorOutputStream out (&outputStream);
  73612. out.writeString (name);
  73613. out.writeBool (isBold);
  73614. out.writeBool (isItalic);
  73615. out.writeFloat (ascent);
  73616. out.writeShort ((short) (unsigned short) defaultCharacter);
  73617. out.writeInt (glyphs.size());
  73618. int i, numKerningPairs = 0;
  73619. for (i = 0; i < glyphs.size(); ++i)
  73620. {
  73621. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73622. out.writeShort ((short) (unsigned short) g->character);
  73623. out.writeFloat (g->width);
  73624. g->path.writePathToStream (out);
  73625. numKerningPairs += g->kerningPairs.size();
  73626. }
  73627. out.writeInt (numKerningPairs);
  73628. for (i = 0; i < glyphs.size(); ++i)
  73629. {
  73630. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73631. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73632. {
  73633. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73634. out.writeShort ((short) (unsigned short) g->character);
  73635. out.writeShort ((short) (unsigned short) p.character2);
  73636. out.writeFloat (p.kerningAmount);
  73637. }
  73638. }
  73639. return true;
  73640. }
  73641. float CustomTypeface::getAscent() const
  73642. {
  73643. return ascent;
  73644. }
  73645. float CustomTypeface::getDescent() const
  73646. {
  73647. return 1.0f - ascent;
  73648. }
  73649. float CustomTypeface::getStringWidth (const String& text)
  73650. {
  73651. float x = 0;
  73652. const juce_wchar* t = text;
  73653. while (*t != 0)
  73654. {
  73655. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73656. if (glyph == 0 && ! isFallbackFont)
  73657. {
  73658. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73659. if (fallbackTypeface != 0)
  73660. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73661. }
  73662. if (glyph != 0)
  73663. x += glyph->getHorizontalSpacing (*t);
  73664. }
  73665. return x;
  73666. }
  73667. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73668. {
  73669. xOffsets.add (0);
  73670. float x = 0;
  73671. const juce_wchar* t = text;
  73672. while (*t != 0)
  73673. {
  73674. const juce_wchar c = *t++;
  73675. const GlyphInfo* const glyph = findGlyph (c, true);
  73676. if (glyph == 0 && ! isFallbackFont)
  73677. {
  73678. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73679. if (fallbackTypeface != 0)
  73680. {
  73681. Array <int> subGlyphs;
  73682. Array <float> subOffsets;
  73683. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73684. if (subGlyphs.size() > 0)
  73685. {
  73686. resultGlyphs.add (subGlyphs.getFirst());
  73687. x += subOffsets[1];
  73688. xOffsets.add (x);
  73689. }
  73690. }
  73691. }
  73692. if (glyph != 0)
  73693. {
  73694. x += glyph->getHorizontalSpacing (*t);
  73695. resultGlyphs.add ((int) glyph->character);
  73696. xOffsets.add (x);
  73697. }
  73698. }
  73699. }
  73700. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73701. {
  73702. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73703. if (glyph == 0 && ! isFallbackFont)
  73704. {
  73705. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73706. if (fallbackTypeface != 0)
  73707. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73708. }
  73709. if (glyph != 0)
  73710. {
  73711. path = glyph->path;
  73712. return true;
  73713. }
  73714. return false;
  73715. }
  73716. END_JUCE_NAMESPACE
  73717. /*** End of inlined file: juce_Typeface.cpp ***/
  73718. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73719. BEGIN_JUCE_NAMESPACE
  73720. AffineTransform::AffineTransform() throw()
  73721. : mat00 (1.0f), mat01 (0), mat02 (0),
  73722. mat10 (0), mat11 (1.0f), mat12 (0)
  73723. {
  73724. }
  73725. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73726. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73727. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73728. {
  73729. }
  73730. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73731. const float mat10_, const float mat11_, const float mat12_) throw()
  73732. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73733. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73734. {
  73735. }
  73736. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73737. {
  73738. mat00 = other.mat00;
  73739. mat01 = other.mat01;
  73740. mat02 = other.mat02;
  73741. mat10 = other.mat10;
  73742. mat11 = other.mat11;
  73743. mat12 = other.mat12;
  73744. return *this;
  73745. }
  73746. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73747. {
  73748. return mat00 == other.mat00
  73749. && mat01 == other.mat01
  73750. && mat02 == other.mat02
  73751. && mat10 == other.mat10
  73752. && mat11 == other.mat11
  73753. && mat12 == other.mat12;
  73754. }
  73755. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73756. {
  73757. return ! operator== (other);
  73758. }
  73759. bool AffineTransform::isIdentity() const throw()
  73760. {
  73761. return (mat01 == 0)
  73762. && (mat02 == 0)
  73763. && (mat10 == 0)
  73764. && (mat12 == 0)
  73765. && (mat00 == 1.0f)
  73766. && (mat11 == 1.0f);
  73767. }
  73768. const AffineTransform AffineTransform::identity;
  73769. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73770. {
  73771. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73772. other.mat00 * mat01 + other.mat01 * mat11,
  73773. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73774. other.mat10 * mat00 + other.mat11 * mat10,
  73775. other.mat10 * mat01 + other.mat11 * mat11,
  73776. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73777. }
  73778. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73779. {
  73780. return AffineTransform (mat00, mat01, mat02 + dx,
  73781. mat10, mat11, mat12 + dy);
  73782. }
  73783. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73784. {
  73785. return AffineTransform (1.0f, 0, dx,
  73786. 0, 1.0f, dy);
  73787. }
  73788. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73789. {
  73790. const float cosRad = std::cos (rad);
  73791. const float sinRad = std::sin (rad);
  73792. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73793. cosRad * mat01 + -sinRad * mat11,
  73794. cosRad * mat02 + -sinRad * mat12,
  73795. sinRad * mat00 + cosRad * mat10,
  73796. sinRad * mat01 + cosRad * mat11,
  73797. sinRad * mat02 + cosRad * mat12);
  73798. }
  73799. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73800. {
  73801. const float cosRad = std::cos (rad);
  73802. const float sinRad = std::sin (rad);
  73803. return AffineTransform (cosRad, -sinRad, 0,
  73804. sinRad, cosRad, 0);
  73805. }
  73806. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73807. {
  73808. const float cosRad = std::cos (rad);
  73809. const float sinRad = std::sin (rad);
  73810. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73811. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73812. }
  73813. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73814. {
  73815. return followedBy (rotation (angle, pivotX, pivotY));
  73816. }
  73817. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73818. {
  73819. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73820. factorY * mat10, factorY * mat11, factorY * mat12);
  73821. }
  73822. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73823. {
  73824. return AffineTransform (factorX, 0, 0,
  73825. 0, factorY, 0);
  73826. }
  73827. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73828. const float pivotX, const float pivotY) const throw()
  73829. {
  73830. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73831. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73832. }
  73833. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73834. const float pivotX, const float pivotY) throw()
  73835. {
  73836. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73837. 0, factorY, pivotY * (1.0f - factorY));
  73838. }
  73839. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73840. {
  73841. return AffineTransform (1.0f, shearX, 0,
  73842. shearY, 1.0f, 0);
  73843. }
  73844. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73845. {
  73846. return AffineTransform (mat00 + shearX * mat10,
  73847. mat01 + shearX * mat11,
  73848. mat02 + shearX * mat12,
  73849. shearY * mat00 + mat10,
  73850. shearY * mat01 + mat11,
  73851. shearY * mat02 + mat12);
  73852. }
  73853. const AffineTransform AffineTransform::inverted() const throw()
  73854. {
  73855. double determinant = (mat00 * mat11 - mat10 * mat01);
  73856. if (determinant != 0.0)
  73857. {
  73858. determinant = 1.0 / determinant;
  73859. const float dst00 = (float) (mat11 * determinant);
  73860. const float dst10 = (float) (-mat10 * determinant);
  73861. const float dst01 = (float) (-mat01 * determinant);
  73862. const float dst11 = (float) (mat00 * determinant);
  73863. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73864. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73865. }
  73866. else
  73867. {
  73868. // singularity..
  73869. return *this;
  73870. }
  73871. }
  73872. bool AffineTransform::isSingularity() const throw()
  73873. {
  73874. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73875. }
  73876. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73877. const float x10, const float y10,
  73878. const float x01, const float y01) throw()
  73879. {
  73880. return AffineTransform (x10 - x00, x01 - x00, x00,
  73881. y10 - y00, y01 - y00, y00);
  73882. }
  73883. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73884. const float sx2, const float sy2, const float tx2, const float ty2,
  73885. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73886. {
  73887. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73888. .inverted()
  73889. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73890. }
  73891. bool AffineTransform::isOnlyTranslation() const throw()
  73892. {
  73893. return (mat01 == 0)
  73894. && (mat10 == 0)
  73895. && (mat00 == 1.0f)
  73896. && (mat11 == 1.0f);
  73897. }
  73898. float AffineTransform::getScaleFactor() const throw()
  73899. {
  73900. return juce_hypot (mat00 + mat01, mat10 + mat11);
  73901. }
  73902. END_JUCE_NAMESPACE
  73903. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73904. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73905. BEGIN_JUCE_NAMESPACE
  73906. BorderSize::BorderSize() throw()
  73907. : top (0),
  73908. left (0),
  73909. bottom (0),
  73910. right (0)
  73911. {
  73912. }
  73913. BorderSize::BorderSize (const BorderSize& other) throw()
  73914. : top (other.top),
  73915. left (other.left),
  73916. bottom (other.bottom),
  73917. right (other.right)
  73918. {
  73919. }
  73920. BorderSize::BorderSize (const int topGap,
  73921. const int leftGap,
  73922. const int bottomGap,
  73923. const int rightGap) throw()
  73924. : top (topGap),
  73925. left (leftGap),
  73926. bottom (bottomGap),
  73927. right (rightGap)
  73928. {
  73929. }
  73930. BorderSize::BorderSize (const int allGaps) throw()
  73931. : top (allGaps),
  73932. left (allGaps),
  73933. bottom (allGaps),
  73934. right (allGaps)
  73935. {
  73936. }
  73937. BorderSize::~BorderSize() throw()
  73938. {
  73939. }
  73940. void BorderSize::setTop (const int newTopGap) throw()
  73941. {
  73942. top = newTopGap;
  73943. }
  73944. void BorderSize::setLeft (const int newLeftGap) throw()
  73945. {
  73946. left = newLeftGap;
  73947. }
  73948. void BorderSize::setBottom (const int newBottomGap) throw()
  73949. {
  73950. bottom = newBottomGap;
  73951. }
  73952. void BorderSize::setRight (const int newRightGap) throw()
  73953. {
  73954. right = newRightGap;
  73955. }
  73956. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73957. {
  73958. return Rectangle<int> (r.getX() + left,
  73959. r.getY() + top,
  73960. r.getWidth() - (left + right),
  73961. r.getHeight() - (top + bottom));
  73962. }
  73963. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73964. {
  73965. r.setBounds (r.getX() + left,
  73966. r.getY() + top,
  73967. r.getWidth() - (left + right),
  73968. r.getHeight() - (top + bottom));
  73969. }
  73970. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73971. {
  73972. return Rectangle<int> (r.getX() - left,
  73973. r.getY() - top,
  73974. r.getWidth() + (left + right),
  73975. r.getHeight() + (top + bottom));
  73976. }
  73977. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73978. {
  73979. r.setBounds (r.getX() - left,
  73980. r.getY() - top,
  73981. r.getWidth() + (left + right),
  73982. r.getHeight() + (top + bottom));
  73983. }
  73984. bool BorderSize::operator== (const BorderSize& other) const throw()
  73985. {
  73986. return top == other.top
  73987. && left == other.left
  73988. && bottom == other.bottom
  73989. && right == other.right;
  73990. }
  73991. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73992. {
  73993. return ! operator== (other);
  73994. }
  73995. END_JUCE_NAMESPACE
  73996. /*** End of inlined file: juce_BorderSize.cpp ***/
  73997. /*** Start of inlined file: juce_Path.cpp ***/
  73998. BEGIN_JUCE_NAMESPACE
  73999. // tests that some co-ords aren't NaNs
  74000. #define CHECK_COORDS_ARE_VALID(x, y) \
  74001. jassert (x == x && y == y);
  74002. namespace PathHelpers
  74003. {
  74004. const float ellipseAngularIncrement = 0.05f;
  74005. const String nextToken (const juce_wchar*& t)
  74006. {
  74007. while (CharacterFunctions::isWhitespace (*t))
  74008. ++t;
  74009. const juce_wchar* const start = t;
  74010. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74011. ++t;
  74012. return String (start, (int) (t - start));
  74013. }
  74014. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74015. {
  74016. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74017. }
  74018. }
  74019. const float Path::lineMarker = 100001.0f;
  74020. const float Path::moveMarker = 100002.0f;
  74021. const float Path::quadMarker = 100003.0f;
  74022. const float Path::cubicMarker = 100004.0f;
  74023. const float Path::closeSubPathMarker = 100005.0f;
  74024. Path::Path()
  74025. : numElements (0),
  74026. pathXMin (0),
  74027. pathXMax (0),
  74028. pathYMin (0),
  74029. pathYMax (0),
  74030. useNonZeroWinding (true)
  74031. {
  74032. }
  74033. Path::~Path()
  74034. {
  74035. }
  74036. Path::Path (const Path& other)
  74037. : numElements (other.numElements),
  74038. pathXMin (other.pathXMin),
  74039. pathXMax (other.pathXMax),
  74040. pathYMin (other.pathYMin),
  74041. pathYMax (other.pathYMax),
  74042. useNonZeroWinding (other.useNonZeroWinding)
  74043. {
  74044. if (numElements > 0)
  74045. {
  74046. data.setAllocatedSize ((int) numElements);
  74047. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74048. }
  74049. }
  74050. Path& Path::operator= (const Path& other)
  74051. {
  74052. if (this != &other)
  74053. {
  74054. data.ensureAllocatedSize ((int) other.numElements);
  74055. numElements = other.numElements;
  74056. pathXMin = other.pathXMin;
  74057. pathXMax = other.pathXMax;
  74058. pathYMin = other.pathYMin;
  74059. pathYMax = other.pathYMax;
  74060. useNonZeroWinding = other.useNonZeroWinding;
  74061. if (numElements > 0)
  74062. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74063. }
  74064. return *this;
  74065. }
  74066. bool Path::operator== (const Path& other) const throw()
  74067. {
  74068. return ! operator!= (other);
  74069. }
  74070. bool Path::operator!= (const Path& other) const throw()
  74071. {
  74072. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74073. return true;
  74074. for (size_t i = 0; i < numElements; ++i)
  74075. if (data.elements[i] != other.data.elements[i])
  74076. return true;
  74077. return false;
  74078. }
  74079. void Path::clear() throw()
  74080. {
  74081. numElements = 0;
  74082. pathXMin = 0;
  74083. pathYMin = 0;
  74084. pathYMax = 0;
  74085. pathXMax = 0;
  74086. }
  74087. void Path::swapWithPath (Path& other) throw()
  74088. {
  74089. data.swapWith (other.data);
  74090. swapVariables <size_t> (numElements, other.numElements);
  74091. swapVariables <float> (pathXMin, other.pathXMin);
  74092. swapVariables <float> (pathXMax, other.pathXMax);
  74093. swapVariables <float> (pathYMin, other.pathYMin);
  74094. swapVariables <float> (pathYMax, other.pathYMax);
  74095. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74096. }
  74097. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74098. {
  74099. useNonZeroWinding = isNonZero;
  74100. }
  74101. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74102. const bool preserveProportions) throw()
  74103. {
  74104. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74105. }
  74106. bool Path::isEmpty() const throw()
  74107. {
  74108. size_t i = 0;
  74109. while (i < numElements)
  74110. {
  74111. const float type = data.elements [i++];
  74112. if (type == moveMarker)
  74113. {
  74114. i += 2;
  74115. }
  74116. else if (type == lineMarker
  74117. || type == quadMarker
  74118. || type == cubicMarker)
  74119. {
  74120. return false;
  74121. }
  74122. }
  74123. return true;
  74124. }
  74125. const Rectangle<float> Path::getBounds() const throw()
  74126. {
  74127. return Rectangle<float> (pathXMin, pathYMin,
  74128. pathXMax - pathXMin,
  74129. pathYMax - pathYMin);
  74130. }
  74131. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74132. {
  74133. return getBounds().transformed (transform);
  74134. }
  74135. void Path::startNewSubPath (const float x, const float y)
  74136. {
  74137. CHECK_COORDS_ARE_VALID (x, y);
  74138. if (numElements == 0)
  74139. {
  74140. pathXMin = pathXMax = x;
  74141. pathYMin = pathYMax = y;
  74142. }
  74143. else
  74144. {
  74145. pathXMin = jmin (pathXMin, x);
  74146. pathXMax = jmax (pathXMax, x);
  74147. pathYMin = jmin (pathYMin, y);
  74148. pathYMax = jmax (pathYMax, y);
  74149. }
  74150. data.ensureAllocatedSize ((int) numElements + 3);
  74151. data.elements [numElements++] = moveMarker;
  74152. data.elements [numElements++] = x;
  74153. data.elements [numElements++] = y;
  74154. }
  74155. void Path::startNewSubPath (const Point<float>& start)
  74156. {
  74157. startNewSubPath (start.getX(), start.getY());
  74158. }
  74159. void Path::lineTo (const float x, const float y)
  74160. {
  74161. CHECK_COORDS_ARE_VALID (x, y);
  74162. if (numElements == 0)
  74163. startNewSubPath (0, 0);
  74164. data.ensureAllocatedSize ((int) numElements + 3);
  74165. data.elements [numElements++] = lineMarker;
  74166. data.elements [numElements++] = x;
  74167. data.elements [numElements++] = y;
  74168. pathXMin = jmin (pathXMin, x);
  74169. pathXMax = jmax (pathXMax, x);
  74170. pathYMin = jmin (pathYMin, y);
  74171. pathYMax = jmax (pathYMax, y);
  74172. }
  74173. void Path::lineTo (const Point<float>& end)
  74174. {
  74175. lineTo (end.getX(), end.getY());
  74176. }
  74177. void Path::quadraticTo (const float x1, const float y1,
  74178. const float x2, const float y2)
  74179. {
  74180. CHECK_COORDS_ARE_VALID (x1, y1);
  74181. CHECK_COORDS_ARE_VALID (x2, y2);
  74182. if (numElements == 0)
  74183. startNewSubPath (0, 0);
  74184. data.ensureAllocatedSize ((int) numElements + 5);
  74185. data.elements [numElements++] = quadMarker;
  74186. data.elements [numElements++] = x1;
  74187. data.elements [numElements++] = y1;
  74188. data.elements [numElements++] = x2;
  74189. data.elements [numElements++] = y2;
  74190. pathXMin = jmin (pathXMin, x1, x2);
  74191. pathXMax = jmax (pathXMax, x1, x2);
  74192. pathYMin = jmin (pathYMin, y1, y2);
  74193. pathYMax = jmax (pathYMax, y1, y2);
  74194. }
  74195. void Path::quadraticTo (const Point<float>& controlPoint,
  74196. const Point<float>& endPoint)
  74197. {
  74198. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74199. endPoint.getX(), endPoint.getY());
  74200. }
  74201. void Path::cubicTo (const float x1, const float y1,
  74202. const float x2, const float y2,
  74203. const float x3, const float y3)
  74204. {
  74205. CHECK_COORDS_ARE_VALID (x1, y1);
  74206. CHECK_COORDS_ARE_VALID (x2, y2);
  74207. CHECK_COORDS_ARE_VALID (x3, y3);
  74208. if (numElements == 0)
  74209. startNewSubPath (0, 0);
  74210. data.ensureAllocatedSize ((int) numElements + 7);
  74211. data.elements [numElements++] = cubicMarker;
  74212. data.elements [numElements++] = x1;
  74213. data.elements [numElements++] = y1;
  74214. data.elements [numElements++] = x2;
  74215. data.elements [numElements++] = y2;
  74216. data.elements [numElements++] = x3;
  74217. data.elements [numElements++] = y3;
  74218. pathXMin = jmin (pathXMin, x1, x2, x3);
  74219. pathXMax = jmax (pathXMax, x1, x2, x3);
  74220. pathYMin = jmin (pathYMin, y1, y2, y3);
  74221. pathYMax = jmax (pathYMax, y1, y2, y3);
  74222. }
  74223. void Path::cubicTo (const Point<float>& controlPoint1,
  74224. const Point<float>& controlPoint2,
  74225. const Point<float>& endPoint)
  74226. {
  74227. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74228. controlPoint2.getX(), controlPoint2.getY(),
  74229. endPoint.getX(), endPoint.getY());
  74230. }
  74231. void Path::closeSubPath()
  74232. {
  74233. if (numElements > 0
  74234. && data.elements [numElements - 1] != closeSubPathMarker)
  74235. {
  74236. data.ensureAllocatedSize ((int) numElements + 1);
  74237. data.elements [numElements++] = closeSubPathMarker;
  74238. }
  74239. }
  74240. const Point<float> Path::getCurrentPosition() const
  74241. {
  74242. size_t i = numElements - 1;
  74243. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74244. {
  74245. while (i >= 0)
  74246. {
  74247. if (data.elements[i] == moveMarker)
  74248. {
  74249. i += 2;
  74250. break;
  74251. }
  74252. --i;
  74253. }
  74254. }
  74255. if (i > 0)
  74256. return Point<float> (data.elements [i - 1], data.elements [i]);
  74257. return Point<float>();
  74258. }
  74259. void Path::addRectangle (const float x, const float y,
  74260. const float w, const float h)
  74261. {
  74262. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74263. if (w < 0)
  74264. swapVariables (x1, x2);
  74265. if (h < 0)
  74266. swapVariables (y1, y2);
  74267. data.ensureAllocatedSize ((int) numElements + 13);
  74268. if (numElements == 0)
  74269. {
  74270. pathXMin = x1;
  74271. pathXMax = x2;
  74272. pathYMin = y1;
  74273. pathYMax = y2;
  74274. }
  74275. else
  74276. {
  74277. pathXMin = jmin (pathXMin, x1);
  74278. pathXMax = jmax (pathXMax, x2);
  74279. pathYMin = jmin (pathYMin, y1);
  74280. pathYMax = jmax (pathYMax, y2);
  74281. }
  74282. data.elements [numElements++] = moveMarker;
  74283. data.elements [numElements++] = x1;
  74284. data.elements [numElements++] = y2;
  74285. data.elements [numElements++] = lineMarker;
  74286. data.elements [numElements++] = x1;
  74287. data.elements [numElements++] = y1;
  74288. data.elements [numElements++] = lineMarker;
  74289. data.elements [numElements++] = x2;
  74290. data.elements [numElements++] = y1;
  74291. data.elements [numElements++] = lineMarker;
  74292. data.elements [numElements++] = x2;
  74293. data.elements [numElements++] = y2;
  74294. data.elements [numElements++] = closeSubPathMarker;
  74295. }
  74296. void Path::addRoundedRectangle (const float x, const float y,
  74297. const float w, const float h,
  74298. float csx,
  74299. float csy)
  74300. {
  74301. csx = jmin (csx, w * 0.5f);
  74302. csy = jmin (csy, h * 0.5f);
  74303. const float cs45x = csx * 0.45f;
  74304. const float cs45y = csy * 0.45f;
  74305. const float x2 = x + w;
  74306. const float y2 = y + h;
  74307. startNewSubPath (x + csx, y);
  74308. lineTo (x2 - csx, y);
  74309. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74310. lineTo (x2, y2 - csy);
  74311. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74312. lineTo (x + csx, y2);
  74313. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74314. lineTo (x, y + csy);
  74315. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74316. closeSubPath();
  74317. }
  74318. void Path::addRoundedRectangle (const float x, const float y,
  74319. const float w, const float h,
  74320. float cs)
  74321. {
  74322. addRoundedRectangle (x, y, w, h, cs, cs);
  74323. }
  74324. void Path::addTriangle (const float x1, const float y1,
  74325. const float x2, const float y2,
  74326. const float x3, const float y3)
  74327. {
  74328. startNewSubPath (x1, y1);
  74329. lineTo (x2, y2);
  74330. lineTo (x3, y3);
  74331. closeSubPath();
  74332. }
  74333. void Path::addQuadrilateral (const float x1, const float y1,
  74334. const float x2, const float y2,
  74335. const float x3, const float y3,
  74336. const float x4, const float y4)
  74337. {
  74338. startNewSubPath (x1, y1);
  74339. lineTo (x2, y2);
  74340. lineTo (x3, y3);
  74341. lineTo (x4, y4);
  74342. closeSubPath();
  74343. }
  74344. void Path::addEllipse (const float x, const float y,
  74345. const float w, const float h)
  74346. {
  74347. const float hw = w * 0.5f;
  74348. const float hw55 = hw * 0.55f;
  74349. const float hh = h * 0.5f;
  74350. const float hh55 = hh * 0.55f;
  74351. const float cx = x + hw;
  74352. const float cy = y + hh;
  74353. startNewSubPath (cx, cy - hh);
  74354. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74355. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74356. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74357. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74358. closeSubPath();
  74359. }
  74360. void Path::addArc (const float x, const float y,
  74361. const float w, const float h,
  74362. const float fromRadians,
  74363. const float toRadians,
  74364. const bool startAsNewSubPath)
  74365. {
  74366. const float radiusX = w / 2.0f;
  74367. const float radiusY = h / 2.0f;
  74368. addCentredArc (x + radiusX,
  74369. y + radiusY,
  74370. radiusX, radiusY,
  74371. 0.0f,
  74372. fromRadians, toRadians,
  74373. startAsNewSubPath);
  74374. }
  74375. void Path::addCentredArc (const float centreX, const float centreY,
  74376. const float radiusX, const float radiusY,
  74377. const float rotationOfEllipse,
  74378. const float fromRadians,
  74379. const float toRadians,
  74380. const bool startAsNewSubPath)
  74381. {
  74382. if (radiusX > 0.0f && radiusY > 0.0f)
  74383. {
  74384. const Point<float> centre (centreX, centreY);
  74385. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74386. float angle = fromRadians;
  74387. if (startAsNewSubPath)
  74388. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74389. if (fromRadians < toRadians)
  74390. {
  74391. if (startAsNewSubPath)
  74392. angle += PathHelpers::ellipseAngularIncrement;
  74393. while (angle < toRadians)
  74394. {
  74395. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74396. angle += PathHelpers::ellipseAngularIncrement;
  74397. }
  74398. }
  74399. else
  74400. {
  74401. if (startAsNewSubPath)
  74402. angle -= PathHelpers::ellipseAngularIncrement;
  74403. while (angle > toRadians)
  74404. {
  74405. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74406. angle -= PathHelpers::ellipseAngularIncrement;
  74407. }
  74408. }
  74409. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74410. }
  74411. }
  74412. void Path::addPieSegment (const float x, const float y,
  74413. const float width, const float height,
  74414. const float fromRadians,
  74415. const float toRadians,
  74416. const float innerCircleProportionalSize)
  74417. {
  74418. float radiusX = width * 0.5f;
  74419. float radiusY = height * 0.5f;
  74420. const Point<float> centre (x + radiusX, y + radiusY);
  74421. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74422. addArc (x, y, width, height, fromRadians, toRadians);
  74423. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74424. {
  74425. closeSubPath();
  74426. if (innerCircleProportionalSize > 0)
  74427. {
  74428. radiusX *= innerCircleProportionalSize;
  74429. radiusY *= innerCircleProportionalSize;
  74430. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74431. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74432. }
  74433. }
  74434. else
  74435. {
  74436. if (innerCircleProportionalSize > 0)
  74437. {
  74438. radiusX *= innerCircleProportionalSize;
  74439. radiusY *= innerCircleProportionalSize;
  74440. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74441. }
  74442. else
  74443. {
  74444. lineTo (centre);
  74445. }
  74446. }
  74447. closeSubPath();
  74448. }
  74449. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74450. {
  74451. const Line<float> reversed (line.reversed());
  74452. lineThickness *= 0.5f;
  74453. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74454. lineTo (line.getPointAlongLine (0, -lineThickness));
  74455. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74456. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74457. closeSubPath();
  74458. }
  74459. void Path::addArrow (const Line<float>& line, float lineThickness,
  74460. float arrowheadWidth, float arrowheadLength)
  74461. {
  74462. const Line<float> reversed (line.reversed());
  74463. lineThickness *= 0.5f;
  74464. arrowheadWidth *= 0.5f;
  74465. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74466. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74467. lineTo (line.getPointAlongLine (0, -lineThickness));
  74468. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74469. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74470. lineTo (line.getEnd());
  74471. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74472. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74473. closeSubPath();
  74474. }
  74475. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74476. const float radius, const float startAngle)
  74477. {
  74478. jassert (numberOfSides > 1); // this would be silly.
  74479. if (numberOfSides > 1)
  74480. {
  74481. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74482. for (int i = 0; i < numberOfSides; ++i)
  74483. {
  74484. const float angle = startAngle + i * angleBetweenPoints;
  74485. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74486. if (i == 0)
  74487. startNewSubPath (p);
  74488. else
  74489. lineTo (p);
  74490. }
  74491. closeSubPath();
  74492. }
  74493. }
  74494. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74495. const float innerRadius, const float outerRadius, const float startAngle)
  74496. {
  74497. jassert (numberOfPoints > 1); // this would be silly.
  74498. if (numberOfPoints > 1)
  74499. {
  74500. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74501. for (int i = 0; i < numberOfPoints; ++i)
  74502. {
  74503. const float angle = startAngle + i * angleBetweenPoints;
  74504. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74505. if (i == 0)
  74506. startNewSubPath (p);
  74507. else
  74508. lineTo (p);
  74509. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74510. }
  74511. closeSubPath();
  74512. }
  74513. }
  74514. void Path::addBubble (float x, float y,
  74515. float w, float h,
  74516. float cs,
  74517. float tipX,
  74518. float tipY,
  74519. int whichSide,
  74520. float arrowPos,
  74521. float arrowWidth)
  74522. {
  74523. if (w > 1.0f && h > 1.0f)
  74524. {
  74525. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74526. const float cs2 = 2.0f * cs;
  74527. startNewSubPath (x + cs, y);
  74528. if (whichSide == 0)
  74529. {
  74530. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74531. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74532. lineTo (arrowX1, y);
  74533. lineTo (tipX, tipY);
  74534. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74535. }
  74536. lineTo (x + w - cs, y);
  74537. if (cs > 0.0f)
  74538. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74539. if (whichSide == 3)
  74540. {
  74541. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74542. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74543. lineTo (x + w, arrowY1);
  74544. lineTo (tipX, tipY);
  74545. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74546. }
  74547. lineTo (x + w, y + h - cs);
  74548. if (cs > 0.0f)
  74549. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74550. if (whichSide == 2)
  74551. {
  74552. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74553. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74554. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74555. lineTo (tipX, tipY);
  74556. lineTo (arrowX1, y + h);
  74557. }
  74558. lineTo (x + cs, y + h);
  74559. if (cs > 0.0f)
  74560. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74561. if (whichSide == 1)
  74562. {
  74563. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74564. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74565. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74566. lineTo (tipX, tipY);
  74567. lineTo (x, arrowY1);
  74568. }
  74569. lineTo (x, y + cs);
  74570. if (cs > 0.0f)
  74571. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74572. closeSubPath();
  74573. }
  74574. }
  74575. void Path::addPath (const Path& other)
  74576. {
  74577. size_t i = 0;
  74578. while (i < other.numElements)
  74579. {
  74580. const float type = other.data.elements [i++];
  74581. if (type == moveMarker)
  74582. {
  74583. startNewSubPath (other.data.elements [i],
  74584. other.data.elements [i + 1]);
  74585. i += 2;
  74586. }
  74587. else if (type == lineMarker)
  74588. {
  74589. lineTo (other.data.elements [i],
  74590. other.data.elements [i + 1]);
  74591. i += 2;
  74592. }
  74593. else if (type == quadMarker)
  74594. {
  74595. quadraticTo (other.data.elements [i],
  74596. other.data.elements [i + 1],
  74597. other.data.elements [i + 2],
  74598. other.data.elements [i + 3]);
  74599. i += 4;
  74600. }
  74601. else if (type == cubicMarker)
  74602. {
  74603. cubicTo (other.data.elements [i],
  74604. other.data.elements [i + 1],
  74605. other.data.elements [i + 2],
  74606. other.data.elements [i + 3],
  74607. other.data.elements [i + 4],
  74608. other.data.elements [i + 5]);
  74609. i += 6;
  74610. }
  74611. else if (type == closeSubPathMarker)
  74612. {
  74613. closeSubPath();
  74614. }
  74615. else
  74616. {
  74617. // something's gone wrong with the element list!
  74618. jassertfalse;
  74619. }
  74620. }
  74621. }
  74622. void Path::addPath (const Path& other,
  74623. const AffineTransform& transformToApply)
  74624. {
  74625. size_t i = 0;
  74626. while (i < other.numElements)
  74627. {
  74628. const float type = other.data.elements [i++];
  74629. if (type == closeSubPathMarker)
  74630. {
  74631. closeSubPath();
  74632. }
  74633. else
  74634. {
  74635. float x = other.data.elements [i++];
  74636. float y = other.data.elements [i++];
  74637. transformToApply.transformPoint (x, y);
  74638. if (type == moveMarker)
  74639. {
  74640. startNewSubPath (x, y);
  74641. }
  74642. else if (type == lineMarker)
  74643. {
  74644. lineTo (x, y);
  74645. }
  74646. else if (type == quadMarker)
  74647. {
  74648. float x2 = other.data.elements [i++];
  74649. float y2 = other.data.elements [i++];
  74650. transformToApply.transformPoint (x2, y2);
  74651. quadraticTo (x, y, x2, y2);
  74652. }
  74653. else if (type == cubicMarker)
  74654. {
  74655. float x2 = other.data.elements [i++];
  74656. float y2 = other.data.elements [i++];
  74657. float x3 = other.data.elements [i++];
  74658. float y3 = other.data.elements [i++];
  74659. transformToApply.transformPoints (x2, y2, x3, y3);
  74660. cubicTo (x, y, x2, y2, x3, y3);
  74661. }
  74662. else
  74663. {
  74664. // something's gone wrong with the element list!
  74665. jassertfalse;
  74666. }
  74667. }
  74668. }
  74669. }
  74670. void Path::applyTransform (const AffineTransform& transform) throw()
  74671. {
  74672. size_t i = 0;
  74673. pathYMin = pathXMin = 0;
  74674. pathYMax = pathXMax = 0;
  74675. bool setMaxMin = false;
  74676. while (i < numElements)
  74677. {
  74678. const float type = data.elements [i++];
  74679. if (type == moveMarker)
  74680. {
  74681. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74682. if (setMaxMin)
  74683. {
  74684. pathXMin = jmin (pathXMin, data.elements [i]);
  74685. pathXMax = jmax (pathXMax, data.elements [i]);
  74686. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74687. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74688. }
  74689. else
  74690. {
  74691. pathXMin = pathXMax = data.elements [i];
  74692. pathYMin = pathYMax = data.elements [i + 1];
  74693. setMaxMin = true;
  74694. }
  74695. i += 2;
  74696. }
  74697. else if (type == lineMarker)
  74698. {
  74699. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74700. pathXMin = jmin (pathXMin, data.elements [i]);
  74701. pathXMax = jmax (pathXMax, data.elements [i]);
  74702. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74703. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74704. i += 2;
  74705. }
  74706. else if (type == quadMarker)
  74707. {
  74708. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74709. data.elements [i + 2], data.elements [i + 3]);
  74710. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74711. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74712. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74713. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74714. i += 4;
  74715. }
  74716. else if (type == cubicMarker)
  74717. {
  74718. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74719. data.elements [i + 2], data.elements [i + 3],
  74720. data.elements [i + 4], data.elements [i + 5]);
  74721. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74722. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74723. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74724. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74725. i += 6;
  74726. }
  74727. }
  74728. }
  74729. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74730. const float w, const float h,
  74731. const bool preserveProportions,
  74732. const Justification& justification) const
  74733. {
  74734. Rectangle<float> bounds (getBounds());
  74735. if (preserveProportions)
  74736. {
  74737. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74738. return AffineTransform::identity;
  74739. float newW, newH;
  74740. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74741. if (srcRatio > h / w)
  74742. {
  74743. newW = h / srcRatio;
  74744. newH = h;
  74745. }
  74746. else
  74747. {
  74748. newW = w;
  74749. newH = w * srcRatio;
  74750. }
  74751. float newXCentre = x;
  74752. float newYCentre = y;
  74753. if (justification.testFlags (Justification::left))
  74754. newXCentre += newW * 0.5f;
  74755. else if (justification.testFlags (Justification::right))
  74756. newXCentre += w - newW * 0.5f;
  74757. else
  74758. newXCentre += w * 0.5f;
  74759. if (justification.testFlags (Justification::top))
  74760. newYCentre += newH * 0.5f;
  74761. else if (justification.testFlags (Justification::bottom))
  74762. newYCentre += h - newH * 0.5f;
  74763. else
  74764. newYCentre += h * 0.5f;
  74765. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74766. bounds.getHeight() * -0.5f - bounds.getY())
  74767. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74768. .translated (newXCentre, newYCentre);
  74769. }
  74770. else
  74771. {
  74772. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74773. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74774. .translated (x, y);
  74775. }
  74776. }
  74777. bool Path::contains (const float x, const float y, const float tolerance) const
  74778. {
  74779. if (x <= pathXMin || x >= pathXMax
  74780. || y <= pathYMin || y >= pathYMax)
  74781. return false;
  74782. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74783. int positiveCrossings = 0;
  74784. int negativeCrossings = 0;
  74785. while (i.next())
  74786. {
  74787. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74788. {
  74789. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74790. if (intersectX <= x)
  74791. {
  74792. if (i.y1 < i.y2)
  74793. ++positiveCrossings;
  74794. else
  74795. ++negativeCrossings;
  74796. }
  74797. }
  74798. }
  74799. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74800. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74801. }
  74802. bool Path::contains (const Point<float>& point, const float tolerance) const
  74803. {
  74804. return contains (point.getX(), point.getY(), tolerance);
  74805. }
  74806. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74807. {
  74808. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74809. Point<float> intersection;
  74810. while (i.next())
  74811. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74812. return true;
  74813. return false;
  74814. }
  74815. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74816. {
  74817. Line<float> result (line);
  74818. const bool startInside = contains (line.getStart());
  74819. const bool endInside = contains (line.getEnd());
  74820. if (startInside == endInside)
  74821. {
  74822. if (keepSectionOutsidePath == startInside)
  74823. result = Line<float>();
  74824. }
  74825. else
  74826. {
  74827. PathFlatteningIterator i (*this, AffineTransform::identity);
  74828. Point<float> intersection;
  74829. while (i.next())
  74830. {
  74831. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74832. {
  74833. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74834. result.setStart (intersection);
  74835. else
  74836. result.setEnd (intersection);
  74837. }
  74838. }
  74839. }
  74840. return result;
  74841. }
  74842. float Path::getLength (const AffineTransform& transform) const
  74843. {
  74844. float length = 0;
  74845. PathFlatteningIterator i (*this, transform);
  74846. while (i.next())
  74847. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74848. return length;
  74849. }
  74850. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74851. {
  74852. PathFlatteningIterator i (*this, transform);
  74853. while (i.next())
  74854. {
  74855. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74856. const float lineLength = line.getLength();
  74857. if (distanceFromStart <= lineLength)
  74858. return line.getPointAlongLine (distanceFromStart);
  74859. distanceFromStart -= lineLength;
  74860. }
  74861. return Point<float> (i.x2, i.y2);
  74862. }
  74863. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74864. const AffineTransform& transform) const
  74865. {
  74866. PathFlatteningIterator i (*this, transform);
  74867. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74868. float length = 0;
  74869. Point<float> pointOnLine;
  74870. while (i.next())
  74871. {
  74872. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74873. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74874. if (distance < bestDistance)
  74875. {
  74876. bestDistance = distance;
  74877. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74878. pointOnPath = pointOnLine;
  74879. }
  74880. length += line.getLength();
  74881. }
  74882. return bestPosition;
  74883. }
  74884. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74885. {
  74886. if (cornerRadius <= 0.01f)
  74887. return *this;
  74888. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74889. size_t n = 0;
  74890. bool lastWasLine = false, firstWasLine = false;
  74891. Path p;
  74892. while (n < numElements)
  74893. {
  74894. const float type = data.elements [n++];
  74895. if (type == moveMarker)
  74896. {
  74897. indexOfPathStart = p.numElements;
  74898. indexOfPathStartThis = n - 1;
  74899. const float x = data.elements [n++];
  74900. const float y = data.elements [n++];
  74901. p.startNewSubPath (x, y);
  74902. lastWasLine = false;
  74903. firstWasLine = (data.elements [n] == lineMarker);
  74904. }
  74905. else if (type == lineMarker || type == closeSubPathMarker)
  74906. {
  74907. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74908. if (type == lineMarker)
  74909. {
  74910. endX = data.elements [n++];
  74911. endY = data.elements [n++];
  74912. if (n > 8)
  74913. {
  74914. startX = data.elements [n - 8];
  74915. startY = data.elements [n - 7];
  74916. joinX = data.elements [n - 5];
  74917. joinY = data.elements [n - 4];
  74918. }
  74919. }
  74920. else
  74921. {
  74922. endX = data.elements [indexOfPathStartThis + 1];
  74923. endY = data.elements [indexOfPathStartThis + 2];
  74924. if (n > 6)
  74925. {
  74926. startX = data.elements [n - 6];
  74927. startY = data.elements [n - 5];
  74928. joinX = data.elements [n - 3];
  74929. joinY = data.elements [n - 2];
  74930. }
  74931. }
  74932. if (lastWasLine)
  74933. {
  74934. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74935. if (len1 > 0)
  74936. {
  74937. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74938. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74939. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74940. }
  74941. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74942. if (len2 > 0)
  74943. {
  74944. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74945. p.quadraticTo (joinX, joinY,
  74946. (float) (joinX + (endX - joinX) * propNeeded),
  74947. (float) (joinY + (endY - joinY) * propNeeded));
  74948. }
  74949. p.lineTo (endX, endY);
  74950. }
  74951. else if (type == lineMarker)
  74952. {
  74953. p.lineTo (endX, endY);
  74954. lastWasLine = true;
  74955. }
  74956. if (type == closeSubPathMarker)
  74957. {
  74958. if (firstWasLine)
  74959. {
  74960. startX = data.elements [n - 3];
  74961. startY = data.elements [n - 2];
  74962. joinX = endX;
  74963. joinY = endY;
  74964. endX = data.elements [indexOfPathStartThis + 4];
  74965. endY = data.elements [indexOfPathStartThis + 5];
  74966. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74967. if (len1 > 0)
  74968. {
  74969. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74970. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74971. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74972. }
  74973. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74974. if (len2 > 0)
  74975. {
  74976. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74977. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74978. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74979. p.quadraticTo (joinX, joinY, endX, endY);
  74980. p.data.elements [indexOfPathStart + 1] = endX;
  74981. p.data.elements [indexOfPathStart + 2] = endY;
  74982. }
  74983. }
  74984. p.closeSubPath();
  74985. }
  74986. }
  74987. else if (type == quadMarker)
  74988. {
  74989. lastWasLine = false;
  74990. const float x1 = data.elements [n++];
  74991. const float y1 = data.elements [n++];
  74992. const float x2 = data.elements [n++];
  74993. const float y2 = data.elements [n++];
  74994. p.quadraticTo (x1, y1, x2, y2);
  74995. }
  74996. else if (type == cubicMarker)
  74997. {
  74998. lastWasLine = false;
  74999. const float x1 = data.elements [n++];
  75000. const float y1 = data.elements [n++];
  75001. const float x2 = data.elements [n++];
  75002. const float y2 = data.elements [n++];
  75003. const float x3 = data.elements [n++];
  75004. const float y3 = data.elements [n++];
  75005. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75006. }
  75007. }
  75008. return p;
  75009. }
  75010. void Path::loadPathFromStream (InputStream& source)
  75011. {
  75012. while (! source.isExhausted())
  75013. {
  75014. switch (source.readByte())
  75015. {
  75016. case 'm':
  75017. {
  75018. const float x = source.readFloat();
  75019. const float y = source.readFloat();
  75020. startNewSubPath (x, y);
  75021. break;
  75022. }
  75023. case 'l':
  75024. {
  75025. const float x = source.readFloat();
  75026. const float y = source.readFloat();
  75027. lineTo (x, y);
  75028. break;
  75029. }
  75030. case 'q':
  75031. {
  75032. const float x1 = source.readFloat();
  75033. const float y1 = source.readFloat();
  75034. const float x2 = source.readFloat();
  75035. const float y2 = source.readFloat();
  75036. quadraticTo (x1, y1, x2, y2);
  75037. break;
  75038. }
  75039. case 'b':
  75040. {
  75041. const float x1 = source.readFloat();
  75042. const float y1 = source.readFloat();
  75043. const float x2 = source.readFloat();
  75044. const float y2 = source.readFloat();
  75045. const float x3 = source.readFloat();
  75046. const float y3 = source.readFloat();
  75047. cubicTo (x1, y1, x2, y2, x3, y3);
  75048. break;
  75049. }
  75050. case 'c':
  75051. closeSubPath();
  75052. break;
  75053. case 'n':
  75054. useNonZeroWinding = true;
  75055. break;
  75056. case 'z':
  75057. useNonZeroWinding = false;
  75058. break;
  75059. case 'e':
  75060. return; // end of path marker
  75061. default:
  75062. jassertfalse; // illegal char in the stream
  75063. break;
  75064. }
  75065. }
  75066. }
  75067. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75068. {
  75069. MemoryInputStream in (pathData, numberOfBytes, false);
  75070. loadPathFromStream (in);
  75071. }
  75072. void Path::writePathToStream (OutputStream& dest) const
  75073. {
  75074. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75075. size_t i = 0;
  75076. while (i < numElements)
  75077. {
  75078. const float type = data.elements [i++];
  75079. if (type == moveMarker)
  75080. {
  75081. dest.writeByte ('m');
  75082. dest.writeFloat (data.elements [i++]);
  75083. dest.writeFloat (data.elements [i++]);
  75084. }
  75085. else if (type == lineMarker)
  75086. {
  75087. dest.writeByte ('l');
  75088. dest.writeFloat (data.elements [i++]);
  75089. dest.writeFloat (data.elements [i++]);
  75090. }
  75091. else if (type == quadMarker)
  75092. {
  75093. dest.writeByte ('q');
  75094. dest.writeFloat (data.elements [i++]);
  75095. dest.writeFloat (data.elements [i++]);
  75096. dest.writeFloat (data.elements [i++]);
  75097. dest.writeFloat (data.elements [i++]);
  75098. }
  75099. else if (type == cubicMarker)
  75100. {
  75101. dest.writeByte ('b');
  75102. dest.writeFloat (data.elements [i++]);
  75103. dest.writeFloat (data.elements [i++]);
  75104. dest.writeFloat (data.elements [i++]);
  75105. dest.writeFloat (data.elements [i++]);
  75106. dest.writeFloat (data.elements [i++]);
  75107. dest.writeFloat (data.elements [i++]);
  75108. }
  75109. else if (type == closeSubPathMarker)
  75110. {
  75111. dest.writeByte ('c');
  75112. }
  75113. }
  75114. dest.writeByte ('e'); // marks the end-of-path
  75115. }
  75116. const String Path::toString() const
  75117. {
  75118. MemoryOutputStream s (2048);
  75119. if (! useNonZeroWinding)
  75120. s << 'a';
  75121. size_t i = 0;
  75122. float lastMarker = 0.0f;
  75123. while (i < numElements)
  75124. {
  75125. const float marker = data.elements [i++];
  75126. char markerChar = 0;
  75127. int numCoords = 0;
  75128. if (marker == moveMarker)
  75129. {
  75130. markerChar = 'm';
  75131. numCoords = 2;
  75132. }
  75133. else if (marker == lineMarker)
  75134. {
  75135. markerChar = 'l';
  75136. numCoords = 2;
  75137. }
  75138. else if (marker == quadMarker)
  75139. {
  75140. markerChar = 'q';
  75141. numCoords = 4;
  75142. }
  75143. else if (marker == cubicMarker)
  75144. {
  75145. markerChar = 'c';
  75146. numCoords = 6;
  75147. }
  75148. else
  75149. {
  75150. jassert (marker == closeSubPathMarker);
  75151. markerChar = 'z';
  75152. }
  75153. if (marker != lastMarker)
  75154. {
  75155. if (s.getDataSize() != 0)
  75156. s << ' ';
  75157. s << markerChar;
  75158. lastMarker = marker;
  75159. }
  75160. while (--numCoords >= 0 && i < numElements)
  75161. {
  75162. String coord (data.elements [i++], 3);
  75163. while (coord.endsWithChar ('0') && coord != "0")
  75164. coord = coord.dropLastCharacters (1);
  75165. if (coord.endsWithChar ('.'))
  75166. coord = coord.dropLastCharacters (1);
  75167. if (s.getDataSize() != 0)
  75168. s << ' ';
  75169. s << coord;
  75170. }
  75171. }
  75172. return s.toUTF8();
  75173. }
  75174. void Path::restoreFromString (const String& stringVersion)
  75175. {
  75176. clear();
  75177. setUsingNonZeroWinding (true);
  75178. const juce_wchar* t = stringVersion;
  75179. juce_wchar marker = 'm';
  75180. int numValues = 2;
  75181. float values [6];
  75182. for (;;)
  75183. {
  75184. const String token (PathHelpers::nextToken (t));
  75185. const juce_wchar firstChar = token[0];
  75186. int startNum = 0;
  75187. if (firstChar == 0)
  75188. break;
  75189. if (firstChar == 'm' || firstChar == 'l')
  75190. {
  75191. marker = firstChar;
  75192. numValues = 2;
  75193. }
  75194. else if (firstChar == 'q')
  75195. {
  75196. marker = firstChar;
  75197. numValues = 4;
  75198. }
  75199. else if (firstChar == 'c')
  75200. {
  75201. marker = firstChar;
  75202. numValues = 6;
  75203. }
  75204. else if (firstChar == 'z')
  75205. {
  75206. marker = firstChar;
  75207. numValues = 0;
  75208. }
  75209. else if (firstChar == 'a')
  75210. {
  75211. setUsingNonZeroWinding (false);
  75212. continue;
  75213. }
  75214. else
  75215. {
  75216. ++startNum;
  75217. values [0] = token.getFloatValue();
  75218. }
  75219. for (int i = startNum; i < numValues; ++i)
  75220. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75221. switch (marker)
  75222. {
  75223. case 'm': startNewSubPath (values[0], values[1]); break;
  75224. case 'l': lineTo (values[0], values[1]); break;
  75225. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75226. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75227. case 'z': closeSubPath(); break;
  75228. default: jassertfalse; break; // illegal string format?
  75229. }
  75230. }
  75231. }
  75232. Path::Iterator::Iterator (const Path& path_)
  75233. : path (path_),
  75234. index (0)
  75235. {
  75236. }
  75237. Path::Iterator::~Iterator()
  75238. {
  75239. }
  75240. bool Path::Iterator::next()
  75241. {
  75242. const float* const elements = path.data.elements;
  75243. if (index < path.numElements)
  75244. {
  75245. const float type = elements [index++];
  75246. if (type == moveMarker)
  75247. {
  75248. elementType = startNewSubPath;
  75249. x1 = elements [index++];
  75250. y1 = elements [index++];
  75251. }
  75252. else if (type == lineMarker)
  75253. {
  75254. elementType = lineTo;
  75255. x1 = elements [index++];
  75256. y1 = elements [index++];
  75257. }
  75258. else if (type == quadMarker)
  75259. {
  75260. elementType = quadraticTo;
  75261. x1 = elements [index++];
  75262. y1 = elements [index++];
  75263. x2 = elements [index++];
  75264. y2 = elements [index++];
  75265. }
  75266. else if (type == cubicMarker)
  75267. {
  75268. elementType = cubicTo;
  75269. x1 = elements [index++];
  75270. y1 = elements [index++];
  75271. x2 = elements [index++];
  75272. y2 = elements [index++];
  75273. x3 = elements [index++];
  75274. y3 = elements [index++];
  75275. }
  75276. else if (type == closeSubPathMarker)
  75277. {
  75278. elementType = closePath;
  75279. }
  75280. return true;
  75281. }
  75282. return false;
  75283. }
  75284. END_JUCE_NAMESPACE
  75285. /*** End of inlined file: juce_Path.cpp ***/
  75286. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75287. BEGIN_JUCE_NAMESPACE
  75288. #if JUCE_MSVC && JUCE_DEBUG
  75289. #pragma optimize ("t", on)
  75290. #endif
  75291. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75292. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75293. const AffineTransform& transform_,
  75294. const float tolerance)
  75295. : x2 (0),
  75296. y2 (0),
  75297. closesSubPath (false),
  75298. subPathIndex (-1),
  75299. path (path_),
  75300. transform (transform_),
  75301. points (path_.data.elements),
  75302. toleranceSquared (tolerance * tolerance),
  75303. subPathCloseX (0),
  75304. subPathCloseY (0),
  75305. isIdentityTransform (transform_.isIdentity()),
  75306. stackBase (32),
  75307. index (0),
  75308. stackSize (32)
  75309. {
  75310. stackPos = stackBase;
  75311. }
  75312. PathFlatteningIterator::~PathFlatteningIterator()
  75313. {
  75314. }
  75315. bool PathFlatteningIterator::next()
  75316. {
  75317. x1 = x2;
  75318. y1 = y2;
  75319. float x3 = 0;
  75320. float y3 = 0;
  75321. float x4 = 0;
  75322. float y4 = 0;
  75323. float type;
  75324. for (;;)
  75325. {
  75326. if (stackPos == stackBase)
  75327. {
  75328. if (index >= path.numElements)
  75329. {
  75330. return false;
  75331. }
  75332. else
  75333. {
  75334. type = points [index++];
  75335. if (type != Path::closeSubPathMarker)
  75336. {
  75337. x2 = points [index++];
  75338. y2 = points [index++];
  75339. if (type == Path::quadMarker)
  75340. {
  75341. x3 = points [index++];
  75342. y3 = points [index++];
  75343. if (! isIdentityTransform)
  75344. transform.transformPoints (x2, y2, x3, y3);
  75345. }
  75346. else if (type == Path::cubicMarker)
  75347. {
  75348. x3 = points [index++];
  75349. y3 = points [index++];
  75350. x4 = points [index++];
  75351. y4 = points [index++];
  75352. if (! isIdentityTransform)
  75353. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75354. }
  75355. else
  75356. {
  75357. if (! isIdentityTransform)
  75358. transform.transformPoint (x2, y2);
  75359. }
  75360. }
  75361. }
  75362. }
  75363. else
  75364. {
  75365. type = *--stackPos;
  75366. if (type != Path::closeSubPathMarker)
  75367. {
  75368. x2 = *--stackPos;
  75369. y2 = *--stackPos;
  75370. if (type == Path::quadMarker)
  75371. {
  75372. x3 = *--stackPos;
  75373. y3 = *--stackPos;
  75374. }
  75375. else if (type == Path::cubicMarker)
  75376. {
  75377. x3 = *--stackPos;
  75378. y3 = *--stackPos;
  75379. x4 = *--stackPos;
  75380. y4 = *--stackPos;
  75381. }
  75382. }
  75383. }
  75384. if (type == Path::lineMarker)
  75385. {
  75386. ++subPathIndex;
  75387. closesSubPath = (stackPos == stackBase)
  75388. && (index < path.numElements)
  75389. && (points [index] == Path::closeSubPathMarker)
  75390. && x2 == subPathCloseX
  75391. && y2 == subPathCloseY;
  75392. return true;
  75393. }
  75394. else if (type == Path::quadMarker)
  75395. {
  75396. const size_t offset = (size_t) (stackPos - stackBase);
  75397. if (offset >= stackSize - 10)
  75398. {
  75399. stackSize <<= 1;
  75400. stackBase.realloc (stackSize);
  75401. stackPos = stackBase + offset;
  75402. }
  75403. const float m1x = (x1 + x2) * 0.5f;
  75404. const float m1y = (y1 + y2) * 0.5f;
  75405. const float m2x = (x2 + x3) * 0.5f;
  75406. const float m2y = (y2 + y3) * 0.5f;
  75407. const float m3x = (m1x + m2x) * 0.5f;
  75408. const float m3y = (m1y + m2y) * 0.5f;
  75409. const float errorX = m3x - x2;
  75410. const float errorY = m3y - y2;
  75411. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75412. {
  75413. *stackPos++ = y3;
  75414. *stackPos++ = x3;
  75415. *stackPos++ = m2y;
  75416. *stackPos++ = m2x;
  75417. *stackPos++ = Path::quadMarker;
  75418. *stackPos++ = m3y;
  75419. *stackPos++ = m3x;
  75420. *stackPos++ = m1y;
  75421. *stackPos++ = m1x;
  75422. *stackPos++ = Path::quadMarker;
  75423. }
  75424. else
  75425. {
  75426. *stackPos++ = y3;
  75427. *stackPos++ = x3;
  75428. *stackPos++ = Path::lineMarker;
  75429. *stackPos++ = m3y;
  75430. *stackPos++ = m3x;
  75431. *stackPos++ = Path::lineMarker;
  75432. }
  75433. jassert (stackPos < stackBase + stackSize);
  75434. }
  75435. else if (type == Path::cubicMarker)
  75436. {
  75437. const size_t offset = (size_t) (stackPos - stackBase);
  75438. if (offset >= stackSize - 16)
  75439. {
  75440. stackSize <<= 1;
  75441. stackBase.realloc (stackSize);
  75442. stackPos = stackBase + offset;
  75443. }
  75444. const float m1x = (x1 + x2) * 0.5f;
  75445. const float m1y = (y1 + y2) * 0.5f;
  75446. const float m2x = (x3 + x2) * 0.5f;
  75447. const float m2y = (y3 + y2) * 0.5f;
  75448. const float m3x = (x3 + x4) * 0.5f;
  75449. const float m3y = (y3 + y4) * 0.5f;
  75450. const float m4x = (m1x + m2x) * 0.5f;
  75451. const float m4y = (m1y + m2y) * 0.5f;
  75452. const float m5x = (m3x + m2x) * 0.5f;
  75453. const float m5y = (m3y + m2y) * 0.5f;
  75454. const float error1X = m4x - x2;
  75455. const float error1Y = m4y - y2;
  75456. const float error2X = m5x - x3;
  75457. const float error2Y = m5y - y3;
  75458. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75459. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75460. {
  75461. *stackPos++ = y4;
  75462. *stackPos++ = x4;
  75463. *stackPos++ = m3y;
  75464. *stackPos++ = m3x;
  75465. *stackPos++ = m5y;
  75466. *stackPos++ = m5x;
  75467. *stackPos++ = Path::cubicMarker;
  75468. *stackPos++ = (m4y + m5y) * 0.5f;
  75469. *stackPos++ = (m4x + m5x) * 0.5f;
  75470. *stackPos++ = m4y;
  75471. *stackPos++ = m4x;
  75472. *stackPos++ = m1y;
  75473. *stackPos++ = m1x;
  75474. *stackPos++ = Path::cubicMarker;
  75475. }
  75476. else
  75477. {
  75478. *stackPos++ = y4;
  75479. *stackPos++ = x4;
  75480. *stackPos++ = Path::lineMarker;
  75481. *stackPos++ = m5y;
  75482. *stackPos++ = m5x;
  75483. *stackPos++ = Path::lineMarker;
  75484. *stackPos++ = m4y;
  75485. *stackPos++ = m4x;
  75486. *stackPos++ = Path::lineMarker;
  75487. }
  75488. }
  75489. else if (type == Path::closeSubPathMarker)
  75490. {
  75491. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75492. {
  75493. x1 = x2;
  75494. y1 = y2;
  75495. x2 = subPathCloseX;
  75496. y2 = subPathCloseY;
  75497. closesSubPath = true;
  75498. return true;
  75499. }
  75500. }
  75501. else
  75502. {
  75503. jassert (type == Path::moveMarker);
  75504. subPathIndex = -1;
  75505. subPathCloseX = x1 = x2;
  75506. subPathCloseY = y1 = y2;
  75507. }
  75508. }
  75509. }
  75510. #if JUCE_MSVC && JUCE_DEBUG
  75511. #pragma optimize ("", on) // resets optimisations to the project defaults
  75512. #endif
  75513. END_JUCE_NAMESPACE
  75514. /*** End of inlined file: juce_PathIterator.cpp ***/
  75515. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75516. BEGIN_JUCE_NAMESPACE
  75517. PathStrokeType::PathStrokeType (const float strokeThickness,
  75518. const JointStyle jointStyle_,
  75519. const EndCapStyle endStyle_) throw()
  75520. : thickness (strokeThickness),
  75521. jointStyle (jointStyle_),
  75522. endStyle (endStyle_)
  75523. {
  75524. }
  75525. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75526. : thickness (other.thickness),
  75527. jointStyle (other.jointStyle),
  75528. endStyle (other.endStyle)
  75529. {
  75530. }
  75531. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75532. {
  75533. thickness = other.thickness;
  75534. jointStyle = other.jointStyle;
  75535. endStyle = other.endStyle;
  75536. return *this;
  75537. }
  75538. PathStrokeType::~PathStrokeType() throw()
  75539. {
  75540. }
  75541. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75542. {
  75543. return thickness == other.thickness
  75544. && jointStyle == other.jointStyle
  75545. && endStyle == other.endStyle;
  75546. }
  75547. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75548. {
  75549. return ! operator== (other);
  75550. }
  75551. namespace PathStrokeHelpers
  75552. {
  75553. bool lineIntersection (const float x1, const float y1,
  75554. const float x2, const float y2,
  75555. const float x3, const float y3,
  75556. const float x4, const float y4,
  75557. float& intersectionX,
  75558. float& intersectionY,
  75559. float& distanceBeyondLine1EndSquared) throw()
  75560. {
  75561. if (x2 != x3 || y2 != y3)
  75562. {
  75563. const float dx1 = x2 - x1;
  75564. const float dy1 = y2 - y1;
  75565. const float dx2 = x4 - x3;
  75566. const float dy2 = y4 - y3;
  75567. const float divisor = dx1 * dy2 - dx2 * dy1;
  75568. if (divisor == 0)
  75569. {
  75570. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75571. {
  75572. if (dy1 == 0 && dy2 != 0)
  75573. {
  75574. const float along = (y1 - y3) / dy2;
  75575. intersectionX = x3 + along * dx2;
  75576. intersectionY = y1;
  75577. distanceBeyondLine1EndSquared = intersectionX - x2;
  75578. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75579. if ((x2 > x1) == (intersectionX < x2))
  75580. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75581. return along >= 0 && along <= 1.0f;
  75582. }
  75583. else if (dy2 == 0 && dy1 != 0)
  75584. {
  75585. const float along = (y3 - y1) / dy1;
  75586. intersectionX = x1 + along * dx1;
  75587. intersectionY = y3;
  75588. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75589. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75590. if (along < 1.0f)
  75591. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75592. return along >= 0 && along <= 1.0f;
  75593. }
  75594. else if (dx1 == 0 && dx2 != 0)
  75595. {
  75596. const float along = (x1 - x3) / dx2;
  75597. intersectionX = x1;
  75598. intersectionY = y3 + along * dy2;
  75599. distanceBeyondLine1EndSquared = intersectionY - y2;
  75600. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75601. if ((y2 > y1) == (intersectionY < y2))
  75602. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75603. return along >= 0 && along <= 1.0f;
  75604. }
  75605. else if (dx2 == 0 && dx1 != 0)
  75606. {
  75607. const float along = (x3 - x1) / dx1;
  75608. intersectionX = x3;
  75609. intersectionY = y1 + along * dy1;
  75610. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75611. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75612. if (along < 1.0f)
  75613. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75614. return along >= 0 && along <= 1.0f;
  75615. }
  75616. }
  75617. intersectionX = 0.5f * (x2 + x3);
  75618. intersectionY = 0.5f * (y2 + y3);
  75619. distanceBeyondLine1EndSquared = 0.0f;
  75620. return false;
  75621. }
  75622. else
  75623. {
  75624. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75625. intersectionX = x1 + along1 * dx1;
  75626. intersectionY = y1 + along1 * dy1;
  75627. if (along1 >= 0 && along1 <= 1.0f)
  75628. {
  75629. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75630. if (along2 >= 0 && along2 <= divisor)
  75631. {
  75632. distanceBeyondLine1EndSquared = 0.0f;
  75633. return true;
  75634. }
  75635. }
  75636. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75637. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75638. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75639. if (along1 < 1.0f)
  75640. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75641. return false;
  75642. }
  75643. }
  75644. intersectionX = x2;
  75645. intersectionY = y2;
  75646. distanceBeyondLine1EndSquared = 0.0f;
  75647. return true;
  75648. }
  75649. void addEdgeAndJoint (Path& destPath,
  75650. const PathStrokeType::JointStyle style,
  75651. const float maxMiterExtensionSquared, const float width,
  75652. const float x1, const float y1,
  75653. const float x2, const float y2,
  75654. const float x3, const float y3,
  75655. const float x4, const float y4,
  75656. const float midX, const float midY)
  75657. {
  75658. if (style == PathStrokeType::beveled
  75659. || (x3 == x4 && y3 == y4)
  75660. || (x1 == x2 && y1 == y2))
  75661. {
  75662. destPath.lineTo (x2, y2);
  75663. destPath.lineTo (x3, y3);
  75664. }
  75665. else
  75666. {
  75667. float jx, jy, distanceBeyondLine1EndSquared;
  75668. // if they intersect, use this point..
  75669. if (lineIntersection (x1, y1, x2, y2,
  75670. x3, y3, x4, y4,
  75671. jx, jy, distanceBeyondLine1EndSquared))
  75672. {
  75673. destPath.lineTo (jx, jy);
  75674. }
  75675. else
  75676. {
  75677. if (style == PathStrokeType::mitered)
  75678. {
  75679. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75680. && distanceBeyondLine1EndSquared > 0.0f)
  75681. {
  75682. destPath.lineTo (jx, jy);
  75683. }
  75684. else
  75685. {
  75686. // the end sticks out too far, so just use a blunt joint
  75687. destPath.lineTo (x2, y2);
  75688. destPath.lineTo (x3, y3);
  75689. }
  75690. }
  75691. else
  75692. {
  75693. // curved joints
  75694. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75695. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75696. const float angleIncrement = 0.1f;
  75697. destPath.lineTo (x2, y2);
  75698. if (std::abs (angle1 - angle2) > angleIncrement)
  75699. {
  75700. if (angle2 > angle1 + float_Pi
  75701. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75702. {
  75703. if (angle2 > angle1)
  75704. angle2 -= float_Pi * 2.0f;
  75705. jassert (angle1 <= angle2 + float_Pi);
  75706. angle1 -= angleIncrement;
  75707. while (angle1 > angle2)
  75708. {
  75709. destPath.lineTo (midX + width * std::sin (angle1),
  75710. midY + width * std::cos (angle1));
  75711. angle1 -= angleIncrement;
  75712. }
  75713. }
  75714. else
  75715. {
  75716. if (angle1 > angle2)
  75717. angle1 -= float_Pi * 2.0f;
  75718. jassert (angle1 >= angle2 - float_Pi);
  75719. angle1 += angleIncrement;
  75720. while (angle1 < angle2)
  75721. {
  75722. destPath.lineTo (midX + width * std::sin (angle1),
  75723. midY + width * std::cos (angle1));
  75724. angle1 += angleIncrement;
  75725. }
  75726. }
  75727. }
  75728. destPath.lineTo (x3, y3);
  75729. }
  75730. }
  75731. }
  75732. }
  75733. void addLineEnd (Path& destPath,
  75734. const PathStrokeType::EndCapStyle style,
  75735. const float x1, const float y1,
  75736. const float x2, const float y2,
  75737. const float width)
  75738. {
  75739. if (style == PathStrokeType::butt)
  75740. {
  75741. destPath.lineTo (x2, y2);
  75742. }
  75743. else
  75744. {
  75745. float offx1, offy1, offx2, offy2;
  75746. float dx = x2 - x1;
  75747. float dy = y2 - y1;
  75748. const float len = juce_hypot (dx, dy);
  75749. if (len == 0)
  75750. {
  75751. offx1 = offx2 = x1;
  75752. offy1 = offy2 = y1;
  75753. }
  75754. else
  75755. {
  75756. const float offset = width / len;
  75757. dx *= offset;
  75758. dy *= offset;
  75759. offx1 = x1 + dy;
  75760. offy1 = y1 - dx;
  75761. offx2 = x2 + dy;
  75762. offy2 = y2 - dx;
  75763. }
  75764. if (style == PathStrokeType::square)
  75765. {
  75766. // sqaure ends
  75767. destPath.lineTo (offx1, offy1);
  75768. destPath.lineTo (offx2, offy2);
  75769. destPath.lineTo (x2, y2);
  75770. }
  75771. else
  75772. {
  75773. // rounded ends
  75774. const float midx = (offx1 + offx2) * 0.5f;
  75775. const float midy = (offy1 + offy2) * 0.5f;
  75776. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75777. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75778. midx, midy);
  75779. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75780. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75781. x2, y2);
  75782. }
  75783. }
  75784. }
  75785. struct Arrowhead
  75786. {
  75787. float startWidth, startLength;
  75788. float endWidth, endLength;
  75789. };
  75790. void addArrowhead (Path& destPath,
  75791. const float x1, const float y1,
  75792. const float x2, const float y2,
  75793. const float tipX, const float tipY,
  75794. const float width,
  75795. const float arrowheadWidth)
  75796. {
  75797. Line<float> line (x1, y1, x2, y2);
  75798. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75799. destPath.lineTo (tipX, tipY);
  75800. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75801. destPath.lineTo (x2, y2);
  75802. }
  75803. struct LineSection
  75804. {
  75805. float x1, y1, x2, y2; // original line
  75806. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75807. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75808. };
  75809. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75810. {
  75811. while (amountAtEnd > 0 && subPath.size() > 0)
  75812. {
  75813. LineSection& l = subPath.getReference (subPath.size() - 1);
  75814. float dx = l.rx2 - l.rx1;
  75815. float dy = l.ry2 - l.ry1;
  75816. const float len = juce_hypot (dx, dy);
  75817. if (len <= amountAtEnd && subPath.size() > 1)
  75818. {
  75819. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75820. prev.x2 = l.x2;
  75821. prev.y2 = l.y2;
  75822. subPath.removeLast();
  75823. amountAtEnd -= len;
  75824. }
  75825. else
  75826. {
  75827. const float prop = jmin (0.9999f, amountAtEnd / len);
  75828. dx *= prop;
  75829. dy *= prop;
  75830. l.rx1 += dx;
  75831. l.ry1 += dy;
  75832. l.lx2 += dx;
  75833. l.ly2 += dy;
  75834. break;
  75835. }
  75836. }
  75837. while (amountAtStart > 0 && subPath.size() > 0)
  75838. {
  75839. LineSection& l = subPath.getReference (0);
  75840. float dx = l.rx2 - l.rx1;
  75841. float dy = l.ry2 - l.ry1;
  75842. const float len = juce_hypot (dx, dy);
  75843. if (len <= amountAtStart && subPath.size() > 1)
  75844. {
  75845. LineSection& next = subPath.getReference (1);
  75846. next.x1 = l.x1;
  75847. next.y1 = l.y1;
  75848. subPath.remove (0);
  75849. amountAtStart -= len;
  75850. }
  75851. else
  75852. {
  75853. const float prop = jmin (0.9999f, amountAtStart / len);
  75854. dx *= prop;
  75855. dy *= prop;
  75856. l.rx2 -= dx;
  75857. l.ry2 -= dy;
  75858. l.lx1 -= dx;
  75859. l.ly1 -= dy;
  75860. break;
  75861. }
  75862. }
  75863. }
  75864. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75865. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75866. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75867. const Arrowhead* const arrowhead)
  75868. {
  75869. jassert (subPath.size() > 0);
  75870. if (arrowhead != 0)
  75871. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75872. const LineSection& firstLine = subPath.getReference (0);
  75873. float lastX1 = firstLine.lx1;
  75874. float lastY1 = firstLine.ly1;
  75875. float lastX2 = firstLine.lx2;
  75876. float lastY2 = firstLine.ly2;
  75877. if (isClosed)
  75878. {
  75879. destPath.startNewSubPath (lastX1, lastY1);
  75880. }
  75881. else
  75882. {
  75883. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75884. if (arrowhead != 0)
  75885. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75886. width, arrowhead->startWidth);
  75887. else
  75888. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75889. }
  75890. int i;
  75891. for (i = 1; i < subPath.size(); ++i)
  75892. {
  75893. const LineSection& l = subPath.getReference (i);
  75894. addEdgeAndJoint (destPath, jointStyle,
  75895. maxMiterExtensionSquared, width,
  75896. lastX1, lastY1, lastX2, lastY2,
  75897. l.lx1, l.ly1, l.lx2, l.ly2,
  75898. l.x1, l.y1);
  75899. lastX1 = l.lx1;
  75900. lastY1 = l.ly1;
  75901. lastX2 = l.lx2;
  75902. lastY2 = l.ly2;
  75903. }
  75904. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75905. if (isClosed)
  75906. {
  75907. const LineSection& l = subPath.getReference (0);
  75908. addEdgeAndJoint (destPath, jointStyle,
  75909. maxMiterExtensionSquared, width,
  75910. lastX1, lastY1, lastX2, lastY2,
  75911. l.lx1, l.ly1, l.lx2, l.ly2,
  75912. l.x1, l.y1);
  75913. destPath.closeSubPath();
  75914. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75915. }
  75916. else
  75917. {
  75918. destPath.lineTo (lastX2, lastY2);
  75919. if (arrowhead != 0)
  75920. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75921. width, arrowhead->endWidth);
  75922. else
  75923. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75924. }
  75925. lastX1 = lastLine.rx1;
  75926. lastY1 = lastLine.ry1;
  75927. lastX2 = lastLine.rx2;
  75928. lastY2 = lastLine.ry2;
  75929. for (i = subPath.size() - 1; --i >= 0;)
  75930. {
  75931. const LineSection& l = subPath.getReference (i);
  75932. addEdgeAndJoint (destPath, jointStyle,
  75933. maxMiterExtensionSquared, width,
  75934. lastX1, lastY1, lastX2, lastY2,
  75935. l.rx1, l.ry1, l.rx2, l.ry2,
  75936. l.x2, l.y2);
  75937. lastX1 = l.rx1;
  75938. lastY1 = l.ry1;
  75939. lastX2 = l.rx2;
  75940. lastY2 = l.ry2;
  75941. }
  75942. if (isClosed)
  75943. {
  75944. addEdgeAndJoint (destPath, jointStyle,
  75945. maxMiterExtensionSquared, width,
  75946. lastX1, lastY1, lastX2, lastY2,
  75947. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75948. lastLine.x2, lastLine.y2);
  75949. }
  75950. else
  75951. {
  75952. // do the last line
  75953. destPath.lineTo (lastX2, lastY2);
  75954. }
  75955. destPath.closeSubPath();
  75956. }
  75957. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75958. const PathStrokeType::EndCapStyle endStyle,
  75959. Path& destPath, const Path& source,
  75960. const AffineTransform& transform,
  75961. const float extraAccuracy, const Arrowhead* const arrowhead)
  75962. {
  75963. jassert (extraAccuracy > 0);
  75964. if (thickness <= 0)
  75965. {
  75966. destPath.clear();
  75967. return;
  75968. }
  75969. const Path* sourcePath = &source;
  75970. Path temp;
  75971. if (sourcePath == &destPath)
  75972. {
  75973. destPath.swapWithPath (temp);
  75974. sourcePath = &temp;
  75975. }
  75976. else
  75977. {
  75978. destPath.clear();
  75979. }
  75980. destPath.setUsingNonZeroWinding (true);
  75981. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75982. const float width = 0.5f * thickness;
  75983. // Iterate the path, creating a list of the
  75984. // left/right-hand lines along either side of it...
  75985. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  75986. Array <LineSection> subPath;
  75987. subPath.ensureStorageAllocated (512);
  75988. LineSection l;
  75989. l.x1 = 0;
  75990. l.y1 = 0;
  75991. const float minSegmentLength = 0.0001f;
  75992. while (it.next())
  75993. {
  75994. if (it.subPathIndex == 0)
  75995. {
  75996. if (subPath.size() > 0)
  75997. {
  75998. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75999. subPath.clearQuick();
  76000. }
  76001. l.x1 = it.x1;
  76002. l.y1 = it.y1;
  76003. }
  76004. l.x2 = it.x2;
  76005. l.y2 = it.y2;
  76006. float dx = l.x2 - l.x1;
  76007. float dy = l.y2 - l.y1;
  76008. const float hypotSquared = dx*dx + dy*dy;
  76009. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76010. {
  76011. const float len = std::sqrt (hypotSquared);
  76012. if (len == 0)
  76013. {
  76014. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76015. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76016. }
  76017. else
  76018. {
  76019. const float offset = width / len;
  76020. dx *= offset;
  76021. dy *= offset;
  76022. l.rx2 = l.x1 - dy;
  76023. l.ry2 = l.y1 + dx;
  76024. l.lx1 = l.x1 + dy;
  76025. l.ly1 = l.y1 - dx;
  76026. l.lx2 = l.x2 + dy;
  76027. l.ly2 = l.y2 - dx;
  76028. l.rx1 = l.x2 - dy;
  76029. l.ry1 = l.y2 + dx;
  76030. }
  76031. subPath.add (l);
  76032. if (it.closesSubPath)
  76033. {
  76034. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76035. subPath.clearQuick();
  76036. }
  76037. else
  76038. {
  76039. l.x1 = it.x2;
  76040. l.y1 = it.y2;
  76041. }
  76042. }
  76043. }
  76044. if (subPath.size() > 0)
  76045. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76046. }
  76047. }
  76048. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76049. const AffineTransform& transform, const float extraAccuracy) const
  76050. {
  76051. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76052. transform, extraAccuracy, 0);
  76053. }
  76054. void PathStrokeType::createDashedStroke (Path& destPath,
  76055. const Path& sourcePath,
  76056. const float* dashLengths,
  76057. int numDashLengths,
  76058. const AffineTransform& transform,
  76059. const float extraAccuracy) const
  76060. {
  76061. jassert (extraAccuracy > 0);
  76062. if (thickness <= 0)
  76063. return;
  76064. // this should really be an even number..
  76065. jassert ((numDashLengths & 1) == 0);
  76066. Path newDestPath;
  76067. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76068. bool first = true;
  76069. int dashNum = 0;
  76070. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76071. float dx = 0.0f, dy = 0.0f;
  76072. for (;;)
  76073. {
  76074. const bool isSolid = ((dashNum & 1) == 0);
  76075. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76076. jassert (dashLen > 0); // must be a positive increment!
  76077. if (dashLen <= 0)
  76078. break;
  76079. pos += dashLen;
  76080. while (pos > lineEndPos)
  76081. {
  76082. if (! it.next())
  76083. {
  76084. if (isSolid && ! first)
  76085. newDestPath.lineTo (it.x2, it.y2);
  76086. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76087. return;
  76088. }
  76089. if (isSolid && ! first)
  76090. newDestPath.lineTo (it.x1, it.y1);
  76091. else
  76092. newDestPath.startNewSubPath (it.x1, it.y1);
  76093. dx = it.x2 - it.x1;
  76094. dy = it.y2 - it.y1;
  76095. lineLen = juce_hypot (dx, dy);
  76096. lineEndPos += lineLen;
  76097. first = it.closesSubPath;
  76098. }
  76099. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76100. if (isSolid)
  76101. newDestPath.lineTo (it.x1 + dx * alpha,
  76102. it.y1 + dy * alpha);
  76103. else
  76104. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76105. it.y1 + dy * alpha);
  76106. }
  76107. }
  76108. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76109. const Path& sourcePath,
  76110. const float arrowheadStartWidth, const float arrowheadStartLength,
  76111. const float arrowheadEndWidth, const float arrowheadEndLength,
  76112. const AffineTransform& transform,
  76113. const float extraAccuracy) const
  76114. {
  76115. PathStrokeHelpers::Arrowhead head;
  76116. head.startWidth = arrowheadStartWidth;
  76117. head.startLength = arrowheadStartLength;
  76118. head.endWidth = arrowheadEndWidth;
  76119. head.endLength = arrowheadEndLength;
  76120. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76121. destPath, sourcePath, transform, extraAccuracy, &head);
  76122. }
  76123. END_JUCE_NAMESPACE
  76124. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76125. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76126. BEGIN_JUCE_NAMESPACE
  76127. PositionedRectangle::PositionedRectangle() throw()
  76128. : x (0.0),
  76129. y (0.0),
  76130. w (0.0),
  76131. h (0.0),
  76132. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76133. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76134. wMode (absoluteSize),
  76135. hMode (absoluteSize)
  76136. {
  76137. }
  76138. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76139. : x (other.x),
  76140. y (other.y),
  76141. w (other.w),
  76142. h (other.h),
  76143. xMode (other.xMode),
  76144. yMode (other.yMode),
  76145. wMode (other.wMode),
  76146. hMode (other.hMode)
  76147. {
  76148. }
  76149. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76150. {
  76151. x = other.x;
  76152. y = other.y;
  76153. w = other.w;
  76154. h = other.h;
  76155. xMode = other.xMode;
  76156. yMode = other.yMode;
  76157. wMode = other.wMode;
  76158. hMode = other.hMode;
  76159. return *this;
  76160. }
  76161. PositionedRectangle::~PositionedRectangle() throw()
  76162. {
  76163. }
  76164. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76165. {
  76166. return x == other.x
  76167. && y == other.y
  76168. && w == other.w
  76169. && h == other.h
  76170. && xMode == other.xMode
  76171. && yMode == other.yMode
  76172. && wMode == other.wMode
  76173. && hMode == other.hMode;
  76174. }
  76175. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76176. {
  76177. return ! operator== (other);
  76178. }
  76179. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76180. {
  76181. StringArray tokens;
  76182. tokens.addTokens (stringVersion, false);
  76183. decodePosString (tokens [0], xMode, x);
  76184. decodePosString (tokens [1], yMode, y);
  76185. decodeSizeString (tokens [2], wMode, w);
  76186. decodeSizeString (tokens [3], hMode, h);
  76187. }
  76188. const String PositionedRectangle::toString() const throw()
  76189. {
  76190. String s;
  76191. s.preallocateStorage (12);
  76192. addPosDescription (s, xMode, x);
  76193. s << ' ';
  76194. addPosDescription (s, yMode, y);
  76195. s << ' ';
  76196. addSizeDescription (s, wMode, w);
  76197. s << ' ';
  76198. addSizeDescription (s, hMode, h);
  76199. return s;
  76200. }
  76201. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76202. {
  76203. jassert (! target.isEmpty());
  76204. double x_, y_, w_, h_;
  76205. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76206. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76207. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76208. roundToInt (w_), roundToInt (h_));
  76209. }
  76210. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76211. double& x_, double& y_,
  76212. double& w_, double& h_) const throw()
  76213. {
  76214. jassert (! target.isEmpty());
  76215. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76216. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76217. }
  76218. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76219. {
  76220. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76221. }
  76222. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76223. const Rectangle<int>& target) throw()
  76224. {
  76225. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76226. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76227. }
  76228. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76229. const double newW, const double newH,
  76230. const Rectangle<int>& target) throw()
  76231. {
  76232. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76233. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76234. }
  76235. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76236. {
  76237. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76238. updateFrom (comp.getBounds(), Rectangle<int>());
  76239. else
  76240. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76241. }
  76242. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76243. {
  76244. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76245. }
  76246. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76247. {
  76248. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76249. | absoluteFromParentBottomRight
  76250. | absoluteFromParentCentre
  76251. | proportionOfParentSize));
  76252. }
  76253. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76254. {
  76255. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76256. }
  76257. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76258. {
  76259. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76260. | absoluteFromParentBottomRight
  76261. | absoluteFromParentCentre
  76262. | proportionOfParentSize));
  76263. }
  76264. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76265. {
  76266. return (SizeMode) wMode;
  76267. }
  76268. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76269. {
  76270. return (SizeMode) hMode;
  76271. }
  76272. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76273. const PositionMode xMode_,
  76274. const AnchorPoint yAnchor,
  76275. const PositionMode yMode_,
  76276. const SizeMode widthMode,
  76277. const SizeMode heightMode,
  76278. const Rectangle<int>& target) throw()
  76279. {
  76280. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76281. {
  76282. double tx, tw;
  76283. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76284. xMode = (uint8) (xAnchor | xMode_);
  76285. wMode = (uint8) widthMode;
  76286. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76287. }
  76288. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76289. {
  76290. double ty, th;
  76291. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76292. yMode = (uint8) (yAnchor | yMode_);
  76293. hMode = (uint8) heightMode;
  76294. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76295. }
  76296. }
  76297. bool PositionedRectangle::isPositionAbsolute() const throw()
  76298. {
  76299. return xMode == absoluteFromParentTopLeft
  76300. && yMode == absoluteFromParentTopLeft
  76301. && wMode == absoluteSize
  76302. && hMode == absoluteSize;
  76303. }
  76304. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76305. {
  76306. if ((mode & proportionOfParentSize) != 0)
  76307. {
  76308. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76309. }
  76310. else
  76311. {
  76312. s << (roundToInt (value * 100.0) / 100.0);
  76313. if ((mode & absoluteFromParentBottomRight) != 0)
  76314. s << 'R';
  76315. else if ((mode & absoluteFromParentCentre) != 0)
  76316. s << 'C';
  76317. }
  76318. if ((mode & anchorAtRightOrBottom) != 0)
  76319. s << 'r';
  76320. else if ((mode & anchorAtCentre) != 0)
  76321. s << 'c';
  76322. }
  76323. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76324. {
  76325. if (mode == proportionalSize)
  76326. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76327. else if (mode == parentSizeMinusAbsolute)
  76328. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76329. else
  76330. s << (roundToInt (value * 100.0) / 100.0);
  76331. }
  76332. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76333. {
  76334. if (s.containsChar ('r'))
  76335. mode = anchorAtRightOrBottom;
  76336. else if (s.containsChar ('c'))
  76337. mode = anchorAtCentre;
  76338. else
  76339. mode = anchorAtLeftOrTop;
  76340. if (s.containsChar ('%'))
  76341. {
  76342. mode |= proportionOfParentSize;
  76343. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76344. }
  76345. else
  76346. {
  76347. if (s.containsChar ('R'))
  76348. mode |= absoluteFromParentBottomRight;
  76349. else if (s.containsChar ('C'))
  76350. mode |= absoluteFromParentCentre;
  76351. else
  76352. mode |= absoluteFromParentTopLeft;
  76353. value = s.removeCharacters ("rcRC").getDoubleValue();
  76354. }
  76355. }
  76356. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76357. {
  76358. if (s.containsChar ('%'))
  76359. {
  76360. mode = proportionalSize;
  76361. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76362. }
  76363. else if (s.containsChar ('M'))
  76364. {
  76365. mode = parentSizeMinusAbsolute;
  76366. value = s.getDoubleValue();
  76367. }
  76368. else
  76369. {
  76370. mode = absoluteSize;
  76371. value = s.getDoubleValue();
  76372. }
  76373. }
  76374. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76375. const double x_, const double w_,
  76376. const uint8 xMode_, const uint8 wMode_,
  76377. const int parentPos,
  76378. const int parentSize) const throw()
  76379. {
  76380. if (wMode_ == proportionalSize)
  76381. wOut = roundToInt (w_ * parentSize);
  76382. else if (wMode_ == parentSizeMinusAbsolute)
  76383. wOut = jmax (0, parentSize - roundToInt (w_));
  76384. else
  76385. wOut = roundToInt (w_);
  76386. if ((xMode_ & proportionOfParentSize) != 0)
  76387. xOut = parentPos + x_ * parentSize;
  76388. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76389. xOut = (parentPos + parentSize) - x_;
  76390. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76391. xOut = x_ + (parentPos + parentSize / 2);
  76392. else
  76393. xOut = x_ + parentPos;
  76394. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76395. xOut -= wOut;
  76396. else if ((xMode_ & anchorAtCentre) != 0)
  76397. xOut -= wOut / 2;
  76398. }
  76399. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76400. double x_, const double w_,
  76401. const uint8 xMode_, const uint8 wMode_,
  76402. const int parentPos,
  76403. const int parentSize) const throw()
  76404. {
  76405. if (wMode_ == proportionalSize)
  76406. {
  76407. if (parentSize > 0)
  76408. wOut = w_ / parentSize;
  76409. }
  76410. else if (wMode_ == parentSizeMinusAbsolute)
  76411. wOut = parentSize - w_;
  76412. else
  76413. wOut = w_;
  76414. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76415. x_ += w_;
  76416. else if ((xMode_ & anchorAtCentre) != 0)
  76417. x_ += w_ / 2;
  76418. if ((xMode_ & proportionOfParentSize) != 0)
  76419. {
  76420. if (parentSize > 0)
  76421. xOut = (x_ - parentPos) / parentSize;
  76422. }
  76423. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76424. xOut = (parentPos + parentSize) - x_;
  76425. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76426. xOut = x_ - (parentPos + parentSize / 2);
  76427. else
  76428. xOut = x_ - parentPos;
  76429. }
  76430. END_JUCE_NAMESPACE
  76431. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76432. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76433. BEGIN_JUCE_NAMESPACE
  76434. RectangleList::RectangleList() throw()
  76435. {
  76436. }
  76437. RectangleList::RectangleList (const Rectangle<int>& rect)
  76438. {
  76439. if (! rect.isEmpty())
  76440. rects.add (rect);
  76441. }
  76442. RectangleList::RectangleList (const RectangleList& other)
  76443. : rects (other.rects)
  76444. {
  76445. }
  76446. RectangleList& RectangleList::operator= (const RectangleList& other)
  76447. {
  76448. rects = other.rects;
  76449. return *this;
  76450. }
  76451. RectangleList::~RectangleList()
  76452. {
  76453. }
  76454. void RectangleList::clear()
  76455. {
  76456. rects.clearQuick();
  76457. }
  76458. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76459. {
  76460. if (isPositiveAndBelow (index, rects.size()))
  76461. return rects.getReference (index);
  76462. return Rectangle<int>();
  76463. }
  76464. bool RectangleList::isEmpty() const throw()
  76465. {
  76466. return rects.size() == 0;
  76467. }
  76468. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76469. : current (0),
  76470. owner (list),
  76471. index (list.rects.size())
  76472. {
  76473. }
  76474. RectangleList::Iterator::~Iterator()
  76475. {
  76476. }
  76477. bool RectangleList::Iterator::next() throw()
  76478. {
  76479. if (--index >= 0)
  76480. {
  76481. current = & (owner.rects.getReference (index));
  76482. return true;
  76483. }
  76484. return false;
  76485. }
  76486. void RectangleList::add (const Rectangle<int>& rect)
  76487. {
  76488. if (! rect.isEmpty())
  76489. {
  76490. if (rects.size() == 0)
  76491. {
  76492. rects.add (rect);
  76493. }
  76494. else
  76495. {
  76496. bool anyOverlaps = false;
  76497. int i;
  76498. for (i = rects.size(); --i >= 0;)
  76499. {
  76500. Rectangle<int>& ourRect = rects.getReference (i);
  76501. if (rect.intersects (ourRect))
  76502. {
  76503. if (rect.contains (ourRect))
  76504. rects.remove (i);
  76505. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76506. anyOverlaps = true;
  76507. }
  76508. }
  76509. if (anyOverlaps && rects.size() > 0)
  76510. {
  76511. RectangleList r (rect);
  76512. for (i = rects.size(); --i >= 0;)
  76513. {
  76514. const Rectangle<int>& ourRect = rects.getReference (i);
  76515. if (rect.intersects (ourRect))
  76516. {
  76517. r.subtract (ourRect);
  76518. if (r.rects.size() == 0)
  76519. return;
  76520. }
  76521. }
  76522. for (i = r.getNumRectangles(); --i >= 0;)
  76523. rects.add (r.rects.getReference (i));
  76524. }
  76525. else
  76526. {
  76527. rects.add (rect);
  76528. }
  76529. }
  76530. }
  76531. }
  76532. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76533. {
  76534. if (! rect.isEmpty())
  76535. rects.add (rect);
  76536. }
  76537. void RectangleList::add (const int x, const int y, const int w, const int h)
  76538. {
  76539. if (rects.size() == 0)
  76540. {
  76541. if (w > 0 && h > 0)
  76542. rects.add (Rectangle<int> (x, y, w, h));
  76543. }
  76544. else
  76545. {
  76546. add (Rectangle<int> (x, y, w, h));
  76547. }
  76548. }
  76549. void RectangleList::add (const RectangleList& other)
  76550. {
  76551. for (int i = 0; i < other.rects.size(); ++i)
  76552. add (other.rects.getReference (i));
  76553. }
  76554. void RectangleList::subtract (const Rectangle<int>& rect)
  76555. {
  76556. const int originalNumRects = rects.size();
  76557. if (originalNumRects > 0)
  76558. {
  76559. const int x1 = rect.x;
  76560. const int y1 = rect.y;
  76561. const int x2 = x1 + rect.w;
  76562. const int y2 = y1 + rect.h;
  76563. for (int i = getNumRectangles(); --i >= 0;)
  76564. {
  76565. Rectangle<int>& r = rects.getReference (i);
  76566. const int rx1 = r.x;
  76567. const int ry1 = r.y;
  76568. const int rx2 = rx1 + r.w;
  76569. const int ry2 = ry1 + r.h;
  76570. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76571. {
  76572. if (x1 > rx1 && x1 < rx2)
  76573. {
  76574. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76575. {
  76576. r.w = x1 - rx1;
  76577. }
  76578. else
  76579. {
  76580. r.x = x1;
  76581. r.w = rx2 - x1;
  76582. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76583. i += 2;
  76584. }
  76585. }
  76586. else if (x2 > rx1 && x2 < rx2)
  76587. {
  76588. r.x = x2;
  76589. r.w = rx2 - x2;
  76590. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76591. {
  76592. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76593. i += 2;
  76594. }
  76595. }
  76596. else if (y1 > ry1 && y1 < ry2)
  76597. {
  76598. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76599. {
  76600. r.h = y1 - ry1;
  76601. }
  76602. else
  76603. {
  76604. r.y = y1;
  76605. r.h = ry2 - y1;
  76606. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76607. i += 2;
  76608. }
  76609. }
  76610. else if (y2 > ry1 && y2 < ry2)
  76611. {
  76612. r.y = y2;
  76613. r.h = ry2 - y2;
  76614. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76615. {
  76616. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76617. i += 2;
  76618. }
  76619. }
  76620. else
  76621. {
  76622. rects.remove (i);
  76623. }
  76624. }
  76625. }
  76626. }
  76627. }
  76628. bool RectangleList::subtract (const RectangleList& otherList)
  76629. {
  76630. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76631. subtract (otherList.rects.getReference (i));
  76632. return rects.size() > 0;
  76633. }
  76634. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76635. {
  76636. bool notEmpty = false;
  76637. if (rect.isEmpty())
  76638. {
  76639. clear();
  76640. }
  76641. else
  76642. {
  76643. for (int i = rects.size(); --i >= 0;)
  76644. {
  76645. Rectangle<int>& r = rects.getReference (i);
  76646. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76647. rects.remove (i);
  76648. else
  76649. notEmpty = true;
  76650. }
  76651. }
  76652. return notEmpty;
  76653. }
  76654. bool RectangleList::clipTo (const RectangleList& other)
  76655. {
  76656. if (rects.size() == 0)
  76657. return false;
  76658. RectangleList result;
  76659. for (int j = 0; j < rects.size(); ++j)
  76660. {
  76661. const Rectangle<int>& rect = rects.getReference (j);
  76662. for (int i = other.rects.size(); --i >= 0;)
  76663. {
  76664. Rectangle<int> r (other.rects.getReference (i));
  76665. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76666. result.rects.add (r);
  76667. }
  76668. }
  76669. swapWith (result);
  76670. return ! isEmpty();
  76671. }
  76672. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76673. {
  76674. destRegion.clear();
  76675. if (! rect.isEmpty())
  76676. {
  76677. for (int i = rects.size(); --i >= 0;)
  76678. {
  76679. Rectangle<int> r (rects.getReference (i));
  76680. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76681. destRegion.rects.add (r);
  76682. }
  76683. }
  76684. return destRegion.rects.size() > 0;
  76685. }
  76686. void RectangleList::swapWith (RectangleList& otherList) throw()
  76687. {
  76688. rects.swapWithArray (otherList.rects);
  76689. }
  76690. void RectangleList::consolidate()
  76691. {
  76692. int i;
  76693. for (i = 0; i < getNumRectangles() - 1; ++i)
  76694. {
  76695. Rectangle<int>& r = rects.getReference (i);
  76696. const int rx1 = r.x;
  76697. const int ry1 = r.y;
  76698. const int rx2 = rx1 + r.w;
  76699. const int ry2 = ry1 + r.h;
  76700. for (int j = rects.size(); --j > i;)
  76701. {
  76702. Rectangle<int>& r2 = rects.getReference (j);
  76703. const int jrx1 = r2.x;
  76704. const int jry1 = r2.y;
  76705. const int jrx2 = jrx1 + r2.w;
  76706. const int jry2 = jry1 + r2.h;
  76707. // if the vertical edges of any blocks are touching and their horizontals don't
  76708. // line up, split them horizontally..
  76709. if (jrx1 == rx2 || jrx2 == rx1)
  76710. {
  76711. if (jry1 > ry1 && jry1 < ry2)
  76712. {
  76713. r.h = jry1 - ry1;
  76714. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76715. i = -1;
  76716. break;
  76717. }
  76718. if (jry2 > ry1 && jry2 < ry2)
  76719. {
  76720. r.h = jry2 - ry1;
  76721. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76722. i = -1;
  76723. break;
  76724. }
  76725. else if (ry1 > jry1 && ry1 < jry2)
  76726. {
  76727. r2.h = ry1 - jry1;
  76728. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76729. i = -1;
  76730. break;
  76731. }
  76732. else if (ry2 > jry1 && ry2 < jry2)
  76733. {
  76734. r2.h = ry2 - jry1;
  76735. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76736. i = -1;
  76737. break;
  76738. }
  76739. }
  76740. }
  76741. }
  76742. for (i = 0; i < rects.size() - 1; ++i)
  76743. {
  76744. Rectangle<int>& r = rects.getReference (i);
  76745. for (int j = rects.size(); --j > i;)
  76746. {
  76747. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76748. {
  76749. rects.remove (j);
  76750. i = -1;
  76751. break;
  76752. }
  76753. }
  76754. }
  76755. }
  76756. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76757. {
  76758. for (int i = getNumRectangles(); --i >= 0;)
  76759. if (rects.getReference (i).contains (x, y))
  76760. return true;
  76761. return false;
  76762. }
  76763. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76764. {
  76765. if (rects.size() > 1)
  76766. {
  76767. RectangleList r (rectangleToCheck);
  76768. for (int i = rects.size(); --i >= 0;)
  76769. {
  76770. r.subtract (rects.getReference (i));
  76771. if (r.rects.size() == 0)
  76772. return true;
  76773. }
  76774. }
  76775. else if (rects.size() > 0)
  76776. {
  76777. return rects.getReference (0).contains (rectangleToCheck);
  76778. }
  76779. return false;
  76780. }
  76781. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76782. {
  76783. for (int i = rects.size(); --i >= 0;)
  76784. if (rects.getReference (i).intersects (rectangleToCheck))
  76785. return true;
  76786. return false;
  76787. }
  76788. bool RectangleList::intersects (const RectangleList& other) const throw()
  76789. {
  76790. for (int i = rects.size(); --i >= 0;)
  76791. if (other.intersectsRectangle (rects.getReference (i)))
  76792. return true;
  76793. return false;
  76794. }
  76795. const Rectangle<int> RectangleList::getBounds() const throw()
  76796. {
  76797. if (rects.size() <= 1)
  76798. {
  76799. if (rects.size() == 0)
  76800. return Rectangle<int>();
  76801. else
  76802. return rects.getReference (0);
  76803. }
  76804. else
  76805. {
  76806. const Rectangle<int>& r = rects.getReference (0);
  76807. int minX = r.x;
  76808. int minY = r.y;
  76809. int maxX = minX + r.w;
  76810. int maxY = minY + r.h;
  76811. for (int i = rects.size(); --i > 0;)
  76812. {
  76813. const Rectangle<int>& r2 = rects.getReference (i);
  76814. minX = jmin (minX, r2.x);
  76815. minY = jmin (minY, r2.y);
  76816. maxX = jmax (maxX, r2.getRight());
  76817. maxY = jmax (maxY, r2.getBottom());
  76818. }
  76819. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76820. }
  76821. }
  76822. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76823. {
  76824. for (int i = rects.size(); --i >= 0;)
  76825. {
  76826. Rectangle<int>& r = rects.getReference (i);
  76827. r.x += dx;
  76828. r.y += dy;
  76829. }
  76830. }
  76831. const Path RectangleList::toPath() const
  76832. {
  76833. Path p;
  76834. for (int i = rects.size(); --i >= 0;)
  76835. {
  76836. const Rectangle<int>& r = rects.getReference (i);
  76837. p.addRectangle ((float) r.x,
  76838. (float) r.y,
  76839. (float) r.w,
  76840. (float) r.h);
  76841. }
  76842. return p;
  76843. }
  76844. END_JUCE_NAMESPACE
  76845. /*** End of inlined file: juce_RectangleList.cpp ***/
  76846. /*** Start of inlined file: juce_Image.cpp ***/
  76847. BEGIN_JUCE_NAMESPACE
  76848. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76849. : format (format_), width (width_), height (height_)
  76850. {
  76851. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76852. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76853. }
  76854. Image::SharedImage::~SharedImage()
  76855. {
  76856. }
  76857. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76858. {
  76859. return imageData + lineStride * y + pixelStride * x;
  76860. }
  76861. class SoftwareSharedImage : public Image::SharedImage
  76862. {
  76863. public:
  76864. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76865. : Image::SharedImage (format_, width_, height_)
  76866. {
  76867. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76868. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76869. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76870. imageData = imageDataAllocated;
  76871. }
  76872. Image::ImageType getType() const
  76873. {
  76874. return Image::SoftwareImage;
  76875. }
  76876. LowLevelGraphicsContext* createLowLevelContext()
  76877. {
  76878. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76879. }
  76880. Image::SharedImage* clone()
  76881. {
  76882. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76883. memcpy (s->imageData, imageData, lineStride * height);
  76884. return s;
  76885. }
  76886. private:
  76887. HeapBlock<uint8> imageDataAllocated;
  76888. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76889. };
  76890. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76891. {
  76892. return new SoftwareSharedImage (format, width, height, clearImage);
  76893. }
  76894. class SubsectionSharedImage : public Image::SharedImage
  76895. {
  76896. public:
  76897. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76898. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76899. image (image_), area (area_)
  76900. {
  76901. pixelStride = image_->getPixelStride();
  76902. lineStride = image_->getLineStride();
  76903. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76904. }
  76905. Image::ImageType getType() const
  76906. {
  76907. return Image::SoftwareImage;
  76908. }
  76909. LowLevelGraphicsContext* createLowLevelContext()
  76910. {
  76911. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76912. g->clipToRectangle (area);
  76913. g->setOrigin (area.getX(), area.getY());
  76914. return g;
  76915. }
  76916. Image::SharedImage* clone()
  76917. {
  76918. return new SubsectionSharedImage (image->clone(), area);
  76919. }
  76920. private:
  76921. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76922. const Rectangle<int> area;
  76923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76924. };
  76925. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76926. {
  76927. if (area.contains (getBounds()))
  76928. return *this;
  76929. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76930. if (validArea.isEmpty())
  76931. return Image::null;
  76932. return Image (new SubsectionSharedImage (image, validArea));
  76933. }
  76934. Image::Image()
  76935. {
  76936. }
  76937. Image::Image (SharedImage* const instance)
  76938. : image (instance)
  76939. {
  76940. }
  76941. Image::Image (const PixelFormat format,
  76942. const int width, const int height,
  76943. const bool clearImage, const ImageType type)
  76944. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76945. : new SoftwareSharedImage (format, width, height, clearImage))
  76946. {
  76947. }
  76948. Image::Image (const Image& other)
  76949. : image (other.image)
  76950. {
  76951. }
  76952. Image& Image::operator= (const Image& other)
  76953. {
  76954. image = other.image;
  76955. return *this;
  76956. }
  76957. Image::~Image()
  76958. {
  76959. }
  76960. const Image Image::null;
  76961. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76962. {
  76963. return image == 0 ? 0 : image->createLowLevelContext();
  76964. }
  76965. void Image::duplicateIfShared()
  76966. {
  76967. if (image != 0 && image->getReferenceCount() > 1)
  76968. image = image->clone();
  76969. }
  76970. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76971. {
  76972. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76973. return *this;
  76974. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76975. Graphics g (newImage);
  76976. g.setImageResamplingQuality (quality);
  76977. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76978. return newImage;
  76979. }
  76980. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76981. {
  76982. if (image == 0 || newFormat == image->format)
  76983. return *this;
  76984. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76985. if (newFormat == SingleChannel)
  76986. {
  76987. if (! hasAlphaChannel())
  76988. {
  76989. newImage.clear (getBounds(), Colours::black);
  76990. }
  76991. else
  76992. {
  76993. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76994. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76995. for (int y = 0; y < image->height; ++y)
  76996. {
  76997. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76998. uint8* dst = destData.getLinePointer (y);
  76999. for (int x = image->width; --x >= 0;)
  77000. {
  77001. *dst++ = src->getAlpha();
  77002. ++src;
  77003. }
  77004. }
  77005. }
  77006. }
  77007. else
  77008. {
  77009. if (hasAlphaChannel())
  77010. newImage.clear (getBounds());
  77011. Graphics g (newImage);
  77012. g.drawImageAt (*this, 0, 0);
  77013. }
  77014. return newImage;
  77015. }
  77016. NamedValueSet* Image::getProperties() const
  77017. {
  77018. return image == 0 ? 0 : &(image->userData);
  77019. }
  77020. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77021. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77022. pixelFormat (image.getFormat()),
  77023. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77024. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77025. width (w),
  77026. height (h)
  77027. {
  77028. jassert (data != 0);
  77029. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77030. }
  77031. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77032. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77033. pixelFormat (image.getFormat()),
  77034. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77035. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77036. width (w),
  77037. height (h)
  77038. {
  77039. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77040. }
  77041. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77042. : data (image.image == 0 ? 0 : image.image->imageData),
  77043. pixelFormat (image.getFormat()),
  77044. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77045. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77046. width (image.getWidth()),
  77047. height (image.getHeight())
  77048. {
  77049. }
  77050. Image::BitmapData::~BitmapData()
  77051. {
  77052. }
  77053. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77054. {
  77055. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77056. const uint8* const pixel = getPixelPointer (x, y);
  77057. switch (pixelFormat)
  77058. {
  77059. case Image::ARGB:
  77060. {
  77061. PixelARGB p (*(const PixelARGB*) pixel);
  77062. p.unpremultiply();
  77063. return Colour (p.getARGB());
  77064. }
  77065. case Image::RGB:
  77066. return Colour (((const PixelRGB*) pixel)->getARGB());
  77067. case Image::SingleChannel:
  77068. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77069. default:
  77070. jassertfalse;
  77071. break;
  77072. }
  77073. return Colour();
  77074. }
  77075. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77076. {
  77077. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77078. uint8* const pixel = getPixelPointer (x, y);
  77079. const PixelARGB col (colour.getPixelARGB());
  77080. switch (pixelFormat)
  77081. {
  77082. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77083. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77084. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77085. default: jassertfalse; break;
  77086. }
  77087. }
  77088. void Image::setPixelData (int x, int y, int w, int h,
  77089. const uint8* const sourcePixelData, const int sourceLineStride)
  77090. {
  77091. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77092. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77093. {
  77094. const BitmapData dest (*this, x, y, w, h, true);
  77095. for (int i = 0; i < h; ++i)
  77096. {
  77097. memcpy (dest.getLinePointer(i),
  77098. sourcePixelData + sourceLineStride * i,
  77099. w * dest.pixelStride);
  77100. }
  77101. }
  77102. }
  77103. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77104. {
  77105. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77106. if (! clipped.isEmpty())
  77107. {
  77108. const PixelARGB col (colourToClearTo.getPixelARGB());
  77109. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77110. uint8* dest = destData.data;
  77111. int dh = clipped.getHeight();
  77112. while (--dh >= 0)
  77113. {
  77114. uint8* line = dest;
  77115. dest += destData.lineStride;
  77116. if (isARGB())
  77117. {
  77118. for (int x = clipped.getWidth(); --x >= 0;)
  77119. {
  77120. ((PixelARGB*) line)->set (col);
  77121. line += destData.pixelStride;
  77122. }
  77123. }
  77124. else if (isRGB())
  77125. {
  77126. for (int x = clipped.getWidth(); --x >= 0;)
  77127. {
  77128. ((PixelRGB*) line)->set (col);
  77129. line += destData.pixelStride;
  77130. }
  77131. }
  77132. else
  77133. {
  77134. for (int x = clipped.getWidth(); --x >= 0;)
  77135. {
  77136. *line = col.getAlpha();
  77137. line += destData.pixelStride;
  77138. }
  77139. }
  77140. }
  77141. }
  77142. }
  77143. const Colour Image::getPixelAt (const int x, const int y) const
  77144. {
  77145. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77146. {
  77147. const BitmapData srcData (*this, x, y, 1, 1);
  77148. return srcData.getPixelColour (0, 0);
  77149. }
  77150. return Colour();
  77151. }
  77152. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77153. {
  77154. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77155. {
  77156. const BitmapData destData (*this, x, y, 1, 1, true);
  77157. destData.setPixelColour (0, 0, colour);
  77158. }
  77159. }
  77160. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77161. {
  77162. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77163. && hasAlphaChannel())
  77164. {
  77165. const BitmapData destData (*this, x, y, 1, 1, true);
  77166. if (isARGB())
  77167. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77168. else
  77169. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77170. }
  77171. }
  77172. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77173. {
  77174. if (hasAlphaChannel())
  77175. {
  77176. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77177. if (isARGB())
  77178. {
  77179. for (int y = 0; y < destData.height; ++y)
  77180. {
  77181. uint8* p = destData.getLinePointer (y);
  77182. for (int x = 0; x < destData.width; ++x)
  77183. {
  77184. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77185. p += destData.pixelStride;
  77186. }
  77187. }
  77188. }
  77189. else
  77190. {
  77191. for (int y = 0; y < destData.height; ++y)
  77192. {
  77193. uint8* p = destData.getLinePointer (y);
  77194. for (int x = 0; x < destData.width; ++x)
  77195. {
  77196. *p = (uint8) (*p * amountToMultiplyBy);
  77197. p += destData.pixelStride;
  77198. }
  77199. }
  77200. }
  77201. }
  77202. else
  77203. {
  77204. jassertfalse; // can't do this without an alpha-channel!
  77205. }
  77206. }
  77207. void Image::desaturate()
  77208. {
  77209. if (isARGB() || isRGB())
  77210. {
  77211. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77212. if (isARGB())
  77213. {
  77214. for (int y = 0; y < destData.height; ++y)
  77215. {
  77216. uint8* p = destData.getLinePointer (y);
  77217. for (int x = 0; x < destData.width; ++x)
  77218. {
  77219. ((PixelARGB*) p)->desaturate();
  77220. p += destData.pixelStride;
  77221. }
  77222. }
  77223. }
  77224. else
  77225. {
  77226. for (int y = 0; y < destData.height; ++y)
  77227. {
  77228. uint8* p = destData.getLinePointer (y);
  77229. for (int x = 0; x < destData.width; ++x)
  77230. {
  77231. ((PixelRGB*) p)->desaturate();
  77232. p += destData.pixelStride;
  77233. }
  77234. }
  77235. }
  77236. }
  77237. }
  77238. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77239. {
  77240. if (hasAlphaChannel())
  77241. {
  77242. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77243. SparseSet<int> pixelsOnRow;
  77244. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77245. for (int y = 0; y < srcData.height; ++y)
  77246. {
  77247. pixelsOnRow.clear();
  77248. const uint8* lineData = srcData.getLinePointer (y);
  77249. if (isARGB())
  77250. {
  77251. for (int x = 0; x < srcData.width; ++x)
  77252. {
  77253. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77254. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77255. lineData += srcData.pixelStride;
  77256. }
  77257. }
  77258. else
  77259. {
  77260. for (int x = 0; x < srcData.width; ++x)
  77261. {
  77262. if (*lineData >= threshold)
  77263. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77264. lineData += srcData.pixelStride;
  77265. }
  77266. }
  77267. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77268. {
  77269. const Range<int> range (pixelsOnRow.getRange (i));
  77270. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77271. }
  77272. result.consolidate();
  77273. }
  77274. }
  77275. else
  77276. {
  77277. result.add (0, 0, getWidth(), getHeight());
  77278. }
  77279. }
  77280. void Image::moveImageSection (int dx, int dy,
  77281. int sx, int sy,
  77282. int w, int h)
  77283. {
  77284. if (dx < 0)
  77285. {
  77286. w += dx;
  77287. sx -= dx;
  77288. dx = 0;
  77289. }
  77290. if (dy < 0)
  77291. {
  77292. h += dy;
  77293. sy -= dy;
  77294. dy = 0;
  77295. }
  77296. if (sx < 0)
  77297. {
  77298. w += sx;
  77299. dx -= sx;
  77300. sx = 0;
  77301. }
  77302. if (sy < 0)
  77303. {
  77304. h += sy;
  77305. dy -= sy;
  77306. sy = 0;
  77307. }
  77308. const int minX = jmin (dx, sx);
  77309. const int minY = jmin (dy, sy);
  77310. w = jmin (w, getWidth() - jmax (sx, dx));
  77311. h = jmin (h, getHeight() - jmax (sy, dy));
  77312. if (w > 0 && h > 0)
  77313. {
  77314. const int maxX = jmax (dx, sx) + w;
  77315. const int maxY = jmax (dy, sy) + h;
  77316. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77317. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77318. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77319. const int lineSize = destData.pixelStride * w;
  77320. if (dy > sy)
  77321. {
  77322. while (--h >= 0)
  77323. {
  77324. const int offset = h * destData.lineStride;
  77325. memmove (dst + offset, src + offset, lineSize);
  77326. }
  77327. }
  77328. else if (dst != src)
  77329. {
  77330. while (--h >= 0)
  77331. {
  77332. memmove (dst, src, lineSize);
  77333. dst += destData.lineStride;
  77334. src += destData.lineStride;
  77335. }
  77336. }
  77337. }
  77338. }
  77339. END_JUCE_NAMESPACE
  77340. /*** End of inlined file: juce_Image.cpp ***/
  77341. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77342. BEGIN_JUCE_NAMESPACE
  77343. class ImageCache::Pimpl : public Timer,
  77344. public DeletedAtShutdown
  77345. {
  77346. public:
  77347. Pimpl()
  77348. : cacheTimeout (5000)
  77349. {
  77350. }
  77351. ~Pimpl()
  77352. {
  77353. clearSingletonInstance();
  77354. }
  77355. const Image getFromHashCode (const int64 hashCode)
  77356. {
  77357. const ScopedLock sl (lock);
  77358. for (int i = images.size(); --i >= 0;)
  77359. {
  77360. Item* const item = images.getUnchecked(i);
  77361. if (item->hashCode == hashCode)
  77362. return item->image;
  77363. }
  77364. return Image::null;
  77365. }
  77366. void addImageToCache (const Image& image, const int64 hashCode)
  77367. {
  77368. if (image.isValid())
  77369. {
  77370. if (! isTimerRunning())
  77371. startTimer (2000);
  77372. Item* const item = new Item();
  77373. item->hashCode = hashCode;
  77374. item->image = image;
  77375. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77376. const ScopedLock sl (lock);
  77377. images.add (item);
  77378. }
  77379. }
  77380. void timerCallback()
  77381. {
  77382. const uint32 now = Time::getApproximateMillisecondCounter();
  77383. const ScopedLock sl (lock);
  77384. for (int i = images.size(); --i >= 0;)
  77385. {
  77386. Item* const item = images.getUnchecked(i);
  77387. if (item->image.getReferenceCount() <= 1)
  77388. {
  77389. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77390. images.remove (i);
  77391. }
  77392. else
  77393. {
  77394. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77395. }
  77396. }
  77397. if (images.size() == 0)
  77398. stopTimer();
  77399. }
  77400. struct Item
  77401. {
  77402. Image image;
  77403. int64 hashCode;
  77404. uint32 lastUseTime;
  77405. };
  77406. int cacheTimeout;
  77407. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77408. private:
  77409. OwnedArray<Item> images;
  77410. CriticalSection lock;
  77411. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77412. };
  77413. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77414. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77415. {
  77416. if (Pimpl::getInstanceWithoutCreating() != 0)
  77417. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77418. return Image::null;
  77419. }
  77420. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77421. {
  77422. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77423. }
  77424. const Image ImageCache::getFromFile (const File& file)
  77425. {
  77426. const int64 hashCode = file.hashCode64();
  77427. Image image (getFromHashCode (hashCode));
  77428. if (image.isNull())
  77429. {
  77430. image = ImageFileFormat::loadFrom (file);
  77431. addImageToCache (image, hashCode);
  77432. }
  77433. return image;
  77434. }
  77435. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77436. {
  77437. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77438. Image image (getFromHashCode (hashCode));
  77439. if (image.isNull())
  77440. {
  77441. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77442. addImageToCache (image, hashCode);
  77443. }
  77444. return image;
  77445. }
  77446. void ImageCache::setCacheTimeout (const int millisecs)
  77447. {
  77448. Pimpl::getInstance()->cacheTimeout = millisecs;
  77449. }
  77450. END_JUCE_NAMESPACE
  77451. /*** End of inlined file: juce_ImageCache.cpp ***/
  77452. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77453. BEGIN_JUCE_NAMESPACE
  77454. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77455. : values (size_ * size_),
  77456. size (size_)
  77457. {
  77458. clear();
  77459. }
  77460. ImageConvolutionKernel::~ImageConvolutionKernel()
  77461. {
  77462. }
  77463. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77464. {
  77465. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77466. return values [x + y * size];
  77467. jassertfalse;
  77468. return 0;
  77469. }
  77470. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77471. {
  77472. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77473. {
  77474. values [x + y * size] = value;
  77475. }
  77476. else
  77477. {
  77478. jassertfalse;
  77479. }
  77480. }
  77481. void ImageConvolutionKernel::clear()
  77482. {
  77483. for (int i = size * size; --i >= 0;)
  77484. values[i] = 0;
  77485. }
  77486. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77487. {
  77488. double currentTotal = 0.0;
  77489. for (int i = size * size; --i >= 0;)
  77490. currentTotal += values[i];
  77491. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77492. }
  77493. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77494. {
  77495. for (int i = size * size; --i >= 0;)
  77496. values[i] *= multiplier;
  77497. }
  77498. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77499. {
  77500. const double radiusFactor = -1.0 / (radius * radius * 2);
  77501. const int centre = size >> 1;
  77502. for (int y = size; --y >= 0;)
  77503. {
  77504. for (int x = size; --x >= 0;)
  77505. {
  77506. const int cx = x - centre;
  77507. const int cy = y - centre;
  77508. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77509. }
  77510. }
  77511. setOverallSum (1.0f);
  77512. }
  77513. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77514. const Image& sourceImage,
  77515. const Rectangle<int>& destinationArea) const
  77516. {
  77517. if (sourceImage == destImage)
  77518. {
  77519. destImage.duplicateIfShared();
  77520. }
  77521. else
  77522. {
  77523. if (sourceImage.getWidth() != destImage.getWidth()
  77524. || sourceImage.getHeight() != destImage.getHeight()
  77525. || sourceImage.getFormat() != destImage.getFormat())
  77526. {
  77527. jassertfalse;
  77528. return;
  77529. }
  77530. }
  77531. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77532. if (area.isEmpty())
  77533. return;
  77534. const int right = area.getRight();
  77535. const int bottom = area.getBottom();
  77536. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77537. uint8* line = destData.data;
  77538. const Image::BitmapData srcData (sourceImage, false);
  77539. if (destData.pixelStride == 4)
  77540. {
  77541. for (int y = area.getY(); y < bottom; ++y)
  77542. {
  77543. uint8* dest = line;
  77544. line += destData.lineStride;
  77545. for (int x = area.getX(); x < right; ++x)
  77546. {
  77547. float c1 = 0;
  77548. float c2 = 0;
  77549. float c3 = 0;
  77550. float c4 = 0;
  77551. for (int yy = 0; yy < size; ++yy)
  77552. {
  77553. const int sy = y + yy - (size >> 1);
  77554. if (sy >= srcData.height)
  77555. break;
  77556. if (sy >= 0)
  77557. {
  77558. int sx = x - (size >> 1);
  77559. const uint8* src = srcData.getPixelPointer (sx, sy);
  77560. for (int xx = 0; xx < size; ++xx)
  77561. {
  77562. if (sx >= srcData.width)
  77563. break;
  77564. if (sx >= 0)
  77565. {
  77566. const float kernelMult = values [xx + yy * size];
  77567. c1 += kernelMult * *src++;
  77568. c2 += kernelMult * *src++;
  77569. c3 += kernelMult * *src++;
  77570. c4 += kernelMult * *src++;
  77571. }
  77572. else
  77573. {
  77574. src += 4;
  77575. }
  77576. ++sx;
  77577. }
  77578. }
  77579. }
  77580. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77581. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77582. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77583. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77584. }
  77585. }
  77586. }
  77587. else if (destData.pixelStride == 3)
  77588. {
  77589. for (int y = area.getY(); y < bottom; ++y)
  77590. {
  77591. uint8* dest = line;
  77592. line += destData.lineStride;
  77593. for (int x = area.getX(); x < right; ++x)
  77594. {
  77595. float c1 = 0;
  77596. float c2 = 0;
  77597. float c3 = 0;
  77598. for (int yy = 0; yy < size; ++yy)
  77599. {
  77600. const int sy = y + yy - (size >> 1);
  77601. if (sy >= srcData.height)
  77602. break;
  77603. if (sy >= 0)
  77604. {
  77605. int sx = x - (size >> 1);
  77606. const uint8* src = srcData.getPixelPointer (sx, sy);
  77607. for (int xx = 0; xx < size; ++xx)
  77608. {
  77609. if (sx >= srcData.width)
  77610. break;
  77611. if (sx >= 0)
  77612. {
  77613. const float kernelMult = values [xx + yy * size];
  77614. c1 += kernelMult * *src++;
  77615. c2 += kernelMult * *src++;
  77616. c3 += kernelMult * *src++;
  77617. }
  77618. else
  77619. {
  77620. src += 3;
  77621. }
  77622. ++sx;
  77623. }
  77624. }
  77625. }
  77626. *dest++ = (uint8) roundToInt (c1);
  77627. *dest++ = (uint8) roundToInt (c2);
  77628. *dest++ = (uint8) roundToInt (c3);
  77629. }
  77630. }
  77631. }
  77632. }
  77633. END_JUCE_NAMESPACE
  77634. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77635. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77636. BEGIN_JUCE_NAMESPACE
  77637. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77638. {
  77639. static PNGImageFormat png;
  77640. static JPEGImageFormat jpg;
  77641. static GIFImageFormat gif;
  77642. ImageFileFormat* formats[4];
  77643. int numFormats = 0;
  77644. formats [numFormats++] = &png;
  77645. formats [numFormats++] = &jpg;
  77646. formats [numFormats++] = &gif;
  77647. const int64 streamPos = input.getPosition();
  77648. for (int i = 0; i < numFormats; ++i)
  77649. {
  77650. const bool found = formats[i]->canUnderstand (input);
  77651. input.setPosition (streamPos);
  77652. if (found)
  77653. return formats[i];
  77654. }
  77655. return 0;
  77656. }
  77657. const Image ImageFileFormat::loadFrom (InputStream& input)
  77658. {
  77659. ImageFileFormat* const format = findImageFormatForStream (input);
  77660. if (format != 0)
  77661. return format->decodeImage (input);
  77662. return Image::null;
  77663. }
  77664. const Image ImageFileFormat::loadFrom (const File& file)
  77665. {
  77666. InputStream* const in = file.createInputStream();
  77667. if (in != 0)
  77668. {
  77669. BufferedInputStream b (in, 8192, true);
  77670. return loadFrom (b);
  77671. }
  77672. return Image::null;
  77673. }
  77674. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77675. {
  77676. if (rawData != 0 && numBytes > 4)
  77677. {
  77678. MemoryInputStream stream (rawData, numBytes, false);
  77679. return loadFrom (stream);
  77680. }
  77681. return Image::null;
  77682. }
  77683. END_JUCE_NAMESPACE
  77684. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77685. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77686. BEGIN_JUCE_NAMESPACE
  77687. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77688. const Image juce_loadWithCoreImage (InputStream& input);
  77689. #else
  77690. class GIFLoader
  77691. {
  77692. public:
  77693. GIFLoader (InputStream& in)
  77694. : input (in),
  77695. dataBlockIsZero (false),
  77696. fresh (false),
  77697. finished (false)
  77698. {
  77699. currentBit = lastBit = lastByteIndex = 0;
  77700. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77701. firstcode = oldcode = 0;
  77702. clearCode = end_code = 0;
  77703. int imageWidth, imageHeight;
  77704. int transparent = -1;
  77705. if (! getSizeFromHeader (imageWidth, imageHeight))
  77706. return;
  77707. if ((imageWidth <= 0) || (imageHeight <= 0))
  77708. return;
  77709. unsigned char buf [16];
  77710. if (in.read (buf, 3) != 3)
  77711. return;
  77712. int numColours = 2 << (buf[0] & 7);
  77713. if ((buf[0] & 0x80) != 0)
  77714. readPalette (numColours);
  77715. for (;;)
  77716. {
  77717. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77718. break;
  77719. if (buf[0] == '!')
  77720. {
  77721. if (input.read (buf, 1) != 1)
  77722. break;
  77723. if (processExtension (buf[0], transparent) < 0)
  77724. break;
  77725. continue;
  77726. }
  77727. if (buf[0] != ',')
  77728. continue;
  77729. if (input.read (buf, 9) != 9)
  77730. break;
  77731. imageWidth = makeWord (buf[4], buf[5]);
  77732. imageHeight = makeWord (buf[6], buf[7]);
  77733. numColours = 2 << (buf[8] & 7);
  77734. if ((buf[8] & 0x80) != 0)
  77735. if (! readPalette (numColours))
  77736. break;
  77737. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77738. imageWidth, imageHeight, (transparent >= 0));
  77739. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77740. readImage ((buf[8] & 0x40) != 0, transparent);
  77741. break;
  77742. }
  77743. }
  77744. ~GIFLoader() {}
  77745. Image image;
  77746. private:
  77747. InputStream& input;
  77748. uint8 buffer [300];
  77749. uint8 palette [256][4];
  77750. bool dataBlockIsZero, fresh, finished;
  77751. int currentBit, lastBit, lastByteIndex;
  77752. int codeSize, setCodeSize;
  77753. int maxCode, maxCodeSize;
  77754. int firstcode, oldcode;
  77755. int clearCode, end_code;
  77756. enum { maxGifCode = 1 << 12 };
  77757. int table [2] [maxGifCode];
  77758. int stack [2 * maxGifCode];
  77759. int *sp;
  77760. bool getSizeFromHeader (int& w, int& h)
  77761. {
  77762. char b[8];
  77763. if (input.read (b, 6) == 6)
  77764. {
  77765. if ((strncmp ("GIF87a", b, 6) == 0)
  77766. || (strncmp ("GIF89a", b, 6) == 0))
  77767. {
  77768. if (input.read (b, 4) == 4)
  77769. {
  77770. w = makeWord (b[0], b[1]);
  77771. h = makeWord (b[2], b[3]);
  77772. return true;
  77773. }
  77774. }
  77775. }
  77776. return false;
  77777. }
  77778. bool readPalette (const int numCols)
  77779. {
  77780. unsigned char rgb[4];
  77781. for (int i = 0; i < numCols; ++i)
  77782. {
  77783. input.read (rgb, 3);
  77784. palette [i][0] = rgb[0];
  77785. palette [i][1] = rgb[1];
  77786. palette [i][2] = rgb[2];
  77787. palette [i][3] = 0xff;
  77788. }
  77789. return true;
  77790. }
  77791. int readDataBlock (unsigned char* dest)
  77792. {
  77793. unsigned char n;
  77794. if (input.read (&n, 1) == 1)
  77795. {
  77796. dataBlockIsZero = (n == 0);
  77797. if (dataBlockIsZero || (input.read (dest, n) == n))
  77798. return n;
  77799. }
  77800. return -1;
  77801. }
  77802. int processExtension (const int type, int& transparent)
  77803. {
  77804. unsigned char b [300];
  77805. int n = 0;
  77806. if (type == 0xf9)
  77807. {
  77808. n = readDataBlock (b);
  77809. if (n < 0)
  77810. return 1;
  77811. if ((b[0] & 0x1) != 0)
  77812. transparent = b[3];
  77813. }
  77814. do
  77815. {
  77816. n = readDataBlock (b);
  77817. }
  77818. while (n > 0);
  77819. return n;
  77820. }
  77821. int readLZWByte (const bool initialise, const int inputCodeSize)
  77822. {
  77823. int code, incode, i;
  77824. if (initialise)
  77825. {
  77826. setCodeSize = inputCodeSize;
  77827. codeSize = setCodeSize + 1;
  77828. clearCode = 1 << setCodeSize;
  77829. end_code = clearCode + 1;
  77830. maxCodeSize = 2 * clearCode;
  77831. maxCode = clearCode + 2;
  77832. getCode (0, true);
  77833. fresh = true;
  77834. for (i = 0; i < clearCode; ++i)
  77835. {
  77836. table[0][i] = 0;
  77837. table[1][i] = i;
  77838. }
  77839. for (; i < maxGifCode; ++i)
  77840. {
  77841. table[0][i] = 0;
  77842. table[1][i] = 0;
  77843. }
  77844. sp = stack;
  77845. return 0;
  77846. }
  77847. else if (fresh)
  77848. {
  77849. fresh = false;
  77850. do
  77851. {
  77852. firstcode = oldcode
  77853. = getCode (codeSize, false);
  77854. }
  77855. while (firstcode == clearCode);
  77856. return firstcode;
  77857. }
  77858. if (sp > stack)
  77859. return *--sp;
  77860. while ((code = getCode (codeSize, false)) >= 0)
  77861. {
  77862. if (code == clearCode)
  77863. {
  77864. for (i = 0; i < clearCode; ++i)
  77865. {
  77866. table[0][i] = 0;
  77867. table[1][i] = i;
  77868. }
  77869. for (; i < maxGifCode; ++i)
  77870. {
  77871. table[0][i] = 0;
  77872. table[1][i] = 0;
  77873. }
  77874. codeSize = setCodeSize + 1;
  77875. maxCodeSize = 2 * clearCode;
  77876. maxCode = clearCode + 2;
  77877. sp = stack;
  77878. firstcode = oldcode = getCode (codeSize, false);
  77879. return firstcode;
  77880. }
  77881. else if (code == end_code)
  77882. {
  77883. if (dataBlockIsZero)
  77884. return -2;
  77885. unsigned char buf [260];
  77886. int n;
  77887. while ((n = readDataBlock (buf)) > 0)
  77888. {}
  77889. if (n != 0)
  77890. return -2;
  77891. }
  77892. incode = code;
  77893. if (code >= maxCode)
  77894. {
  77895. *sp++ = firstcode;
  77896. code = oldcode;
  77897. }
  77898. while (code >= clearCode)
  77899. {
  77900. *sp++ = table[1][code];
  77901. if (code == table[0][code])
  77902. return -2;
  77903. code = table[0][code];
  77904. }
  77905. *sp++ = firstcode = table[1][code];
  77906. if ((code = maxCode) < maxGifCode)
  77907. {
  77908. table[0][code] = oldcode;
  77909. table[1][code] = firstcode;
  77910. ++maxCode;
  77911. if ((maxCode >= maxCodeSize)
  77912. && (maxCodeSize < maxGifCode))
  77913. {
  77914. maxCodeSize <<= 1;
  77915. ++codeSize;
  77916. }
  77917. }
  77918. oldcode = incode;
  77919. if (sp > stack)
  77920. return *--sp;
  77921. }
  77922. return code;
  77923. }
  77924. int getCode (const int codeSize_, const bool initialise)
  77925. {
  77926. if (initialise)
  77927. {
  77928. currentBit = 0;
  77929. lastBit = 0;
  77930. finished = false;
  77931. return 0;
  77932. }
  77933. if ((currentBit + codeSize_) >= lastBit)
  77934. {
  77935. if (finished)
  77936. return -1;
  77937. buffer[0] = buffer [lastByteIndex - 2];
  77938. buffer[1] = buffer [lastByteIndex - 1];
  77939. const int n = readDataBlock (&buffer[2]);
  77940. if (n == 0)
  77941. finished = true;
  77942. lastByteIndex = 2 + n;
  77943. currentBit = (currentBit - lastBit) + 16;
  77944. lastBit = (2 + n) * 8 ;
  77945. }
  77946. int result = 0;
  77947. int i = currentBit;
  77948. for (int j = 0; j < codeSize_; ++j)
  77949. {
  77950. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77951. ++i;
  77952. }
  77953. currentBit += codeSize_;
  77954. return result;
  77955. }
  77956. bool readImage (const int interlace, const int transparent)
  77957. {
  77958. unsigned char c;
  77959. if (input.read (&c, 1) != 1
  77960. || readLZWByte (true, c) < 0)
  77961. return false;
  77962. if (transparent >= 0)
  77963. {
  77964. palette [transparent][0] = 0;
  77965. palette [transparent][1] = 0;
  77966. palette [transparent][2] = 0;
  77967. palette [transparent][3] = 0;
  77968. }
  77969. int index;
  77970. int xpos = 0, ypos = 0, pass = 0;
  77971. const Image::BitmapData destData (image, true);
  77972. uint8* p = destData.data;
  77973. const bool hasAlpha = image.hasAlphaChannel();
  77974. while ((index = readLZWByte (false, c)) >= 0)
  77975. {
  77976. const uint8* const paletteEntry = palette [index];
  77977. if (hasAlpha)
  77978. {
  77979. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77980. paletteEntry[0],
  77981. paletteEntry[1],
  77982. paletteEntry[2]);
  77983. ((PixelARGB*) p)->premultiply();
  77984. }
  77985. else
  77986. {
  77987. ((PixelRGB*) p)->setARGB (0,
  77988. paletteEntry[0],
  77989. paletteEntry[1],
  77990. paletteEntry[2]);
  77991. }
  77992. p += destData.pixelStride;
  77993. ++xpos;
  77994. if (xpos == destData.width)
  77995. {
  77996. xpos = 0;
  77997. if (interlace)
  77998. {
  77999. switch (pass)
  78000. {
  78001. case 0:
  78002. case 1: ypos += 8; break;
  78003. case 2: ypos += 4; break;
  78004. case 3: ypos += 2; break;
  78005. }
  78006. while (ypos >= destData.height)
  78007. {
  78008. ++pass;
  78009. switch (pass)
  78010. {
  78011. case 1: ypos = 4; break;
  78012. case 2: ypos = 2; break;
  78013. case 3: ypos = 1; break;
  78014. default: return true;
  78015. }
  78016. }
  78017. }
  78018. else
  78019. {
  78020. ++ypos;
  78021. }
  78022. p = destData.getPixelPointer (xpos, ypos);
  78023. }
  78024. if (ypos >= destData.height)
  78025. break;
  78026. }
  78027. return true;
  78028. }
  78029. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78030. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  78031. };
  78032. #endif
  78033. GIFImageFormat::GIFImageFormat() {}
  78034. GIFImageFormat::~GIFImageFormat() {}
  78035. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78036. bool GIFImageFormat::canUnderstand (InputStream& in)
  78037. {
  78038. char header [4];
  78039. return (in.read (header, sizeof (header)) == sizeof (header))
  78040. && header[0] == 'G'
  78041. && header[1] == 'I'
  78042. && header[2] == 'F';
  78043. }
  78044. const Image GIFImageFormat::decodeImage (InputStream& in)
  78045. {
  78046. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78047. return juce_loadWithCoreImage (in);
  78048. #else
  78049. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78050. return loader->image;
  78051. #endif
  78052. }
  78053. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78054. {
  78055. jassertfalse; // writing isn't implemented for GIFs!
  78056. return false;
  78057. }
  78058. END_JUCE_NAMESPACE
  78059. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78060. #endif
  78061. //==============================================================================
  78062. // some files include lots of library code, so leave them to the end to avoid cluttering
  78063. // up the build for the clean files.
  78064. #if JUCE_BUILD_CORE
  78065. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78066. namespace zlibNamespace
  78067. {
  78068. #if JUCE_INCLUDE_ZLIB_CODE
  78069. #undef OS_CODE
  78070. #undef fdopen
  78071. /*** Start of inlined file: zlib.h ***/
  78072. #ifndef ZLIB_H
  78073. #define ZLIB_H
  78074. /*** Start of inlined file: zconf.h ***/
  78075. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78076. #ifndef ZCONF_H
  78077. #define ZCONF_H
  78078. // *** Just a few hacks here to make it compile nicely with Juce..
  78079. #define Z_PREFIX 1
  78080. #undef __MACTYPES__
  78081. #ifdef _MSC_VER
  78082. #pragma warning (disable : 4131 4127 4244 4267)
  78083. #endif
  78084. /*
  78085. * If you *really* need a unique prefix for all types and library functions,
  78086. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78087. */
  78088. #ifdef Z_PREFIX
  78089. # define deflateInit_ z_deflateInit_
  78090. # define deflate z_deflate
  78091. # define deflateEnd z_deflateEnd
  78092. # define inflateInit_ z_inflateInit_
  78093. # define inflate z_inflate
  78094. # define inflateEnd z_inflateEnd
  78095. # define inflatePrime z_inflatePrime
  78096. # define inflateGetHeader z_inflateGetHeader
  78097. # define adler32_combine z_adler32_combine
  78098. # define crc32_combine z_crc32_combine
  78099. # define deflateInit2_ z_deflateInit2_
  78100. # define deflateSetDictionary z_deflateSetDictionary
  78101. # define deflateCopy z_deflateCopy
  78102. # define deflateReset z_deflateReset
  78103. # define deflateParams z_deflateParams
  78104. # define deflateBound z_deflateBound
  78105. # define deflatePrime z_deflatePrime
  78106. # define inflateInit2_ z_inflateInit2_
  78107. # define inflateSetDictionary z_inflateSetDictionary
  78108. # define inflateSync z_inflateSync
  78109. # define inflateSyncPoint z_inflateSyncPoint
  78110. # define inflateCopy z_inflateCopy
  78111. # define inflateReset z_inflateReset
  78112. # define inflateBack z_inflateBack
  78113. # define inflateBackEnd z_inflateBackEnd
  78114. # define compress z_compress
  78115. # define compress2 z_compress2
  78116. # define compressBound z_compressBound
  78117. # define uncompress z_uncompress
  78118. # define adler32 z_adler32
  78119. # define crc32 z_crc32
  78120. # define get_crc_table z_get_crc_table
  78121. # define zError z_zError
  78122. # define alloc_func z_alloc_func
  78123. # define free_func z_free_func
  78124. # define in_func z_in_func
  78125. # define out_func z_out_func
  78126. # define Byte z_Byte
  78127. # define uInt z_uInt
  78128. # define uLong z_uLong
  78129. # define Bytef z_Bytef
  78130. # define charf z_charf
  78131. # define intf z_intf
  78132. # define uIntf z_uIntf
  78133. # define uLongf z_uLongf
  78134. # define voidpf z_voidpf
  78135. # define voidp z_voidp
  78136. #endif
  78137. #if defined(__MSDOS__) && !defined(MSDOS)
  78138. # define MSDOS
  78139. #endif
  78140. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78141. # define OS2
  78142. #endif
  78143. #if defined(_WINDOWS) && !defined(WINDOWS)
  78144. # define WINDOWS
  78145. #endif
  78146. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78147. # ifndef WIN32
  78148. # define WIN32
  78149. # endif
  78150. #endif
  78151. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78152. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78153. # ifndef SYS16BIT
  78154. # define SYS16BIT
  78155. # endif
  78156. # endif
  78157. #endif
  78158. /*
  78159. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78160. * than 64k bytes at a time (needed on systems with 16-bit int).
  78161. */
  78162. #ifdef SYS16BIT
  78163. # define MAXSEG_64K
  78164. #endif
  78165. #ifdef MSDOS
  78166. # define UNALIGNED_OK
  78167. #endif
  78168. #ifdef __STDC_VERSION__
  78169. # ifndef STDC
  78170. # define STDC
  78171. # endif
  78172. # if __STDC_VERSION__ >= 199901L
  78173. # ifndef STDC99
  78174. # define STDC99
  78175. # endif
  78176. # endif
  78177. #endif
  78178. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78179. # define STDC
  78180. #endif
  78181. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78182. # define STDC
  78183. #endif
  78184. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78185. # define STDC
  78186. #endif
  78187. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78188. # define STDC
  78189. #endif
  78190. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78191. # define STDC
  78192. #endif
  78193. #ifndef STDC
  78194. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78195. # define const /* note: need a more gentle solution here */
  78196. # endif
  78197. #endif
  78198. /* Some Mac compilers merge all .h files incorrectly: */
  78199. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78200. # define NO_DUMMY_DECL
  78201. #endif
  78202. /* Maximum value for memLevel in deflateInit2 */
  78203. #ifndef MAX_MEM_LEVEL
  78204. # ifdef MAXSEG_64K
  78205. # define MAX_MEM_LEVEL 8
  78206. # else
  78207. # define MAX_MEM_LEVEL 9
  78208. # endif
  78209. #endif
  78210. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78211. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78212. * created by gzip. (Files created by minigzip can still be extracted by
  78213. * gzip.)
  78214. */
  78215. #ifndef MAX_WBITS
  78216. # define MAX_WBITS 15 /* 32K LZ77 window */
  78217. #endif
  78218. /* The memory requirements for deflate are (in bytes):
  78219. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78220. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78221. plus a few kilobytes for small objects. For example, if you want to reduce
  78222. the default memory requirements from 256K to 128K, compile with
  78223. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78224. Of course this will generally degrade compression (there's no free lunch).
  78225. The memory requirements for inflate are (in bytes) 1 << windowBits
  78226. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78227. for small objects.
  78228. */
  78229. /* Type declarations */
  78230. #ifndef OF /* function prototypes */
  78231. # ifdef STDC
  78232. # define OF(args) args
  78233. # else
  78234. # define OF(args) ()
  78235. # endif
  78236. #endif
  78237. /* The following definitions for FAR are needed only for MSDOS mixed
  78238. * model programming (small or medium model with some far allocations).
  78239. * This was tested only with MSC; for other MSDOS compilers you may have
  78240. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78241. * just define FAR to be empty.
  78242. */
  78243. #ifdef SYS16BIT
  78244. # if defined(M_I86SM) || defined(M_I86MM)
  78245. /* MSC small or medium model */
  78246. # define SMALL_MEDIUM
  78247. # ifdef _MSC_VER
  78248. # define FAR _far
  78249. # else
  78250. # define FAR far
  78251. # endif
  78252. # endif
  78253. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78254. /* Turbo C small or medium model */
  78255. # define SMALL_MEDIUM
  78256. # ifdef __BORLANDC__
  78257. # define FAR _far
  78258. # else
  78259. # define FAR far
  78260. # endif
  78261. # endif
  78262. #endif
  78263. #if defined(WINDOWS) || defined(WIN32)
  78264. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78265. * This is not mandatory, but it offers a little performance increase.
  78266. */
  78267. # ifdef ZLIB_DLL
  78268. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78269. # ifdef ZLIB_INTERNAL
  78270. # define ZEXTERN extern __declspec(dllexport)
  78271. # else
  78272. # define ZEXTERN extern __declspec(dllimport)
  78273. # endif
  78274. # endif
  78275. # endif /* ZLIB_DLL */
  78276. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78277. * define ZLIB_WINAPI.
  78278. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78279. */
  78280. # ifdef ZLIB_WINAPI
  78281. # ifdef FAR
  78282. # undef FAR
  78283. # endif
  78284. # include <windows.h>
  78285. /* No need for _export, use ZLIB.DEF instead. */
  78286. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78287. # define ZEXPORT WINAPI
  78288. # ifdef WIN32
  78289. # define ZEXPORTVA WINAPIV
  78290. # else
  78291. # define ZEXPORTVA FAR CDECL
  78292. # endif
  78293. # endif
  78294. #endif
  78295. #if defined (__BEOS__)
  78296. # ifdef ZLIB_DLL
  78297. # ifdef ZLIB_INTERNAL
  78298. # define ZEXPORT __declspec(dllexport)
  78299. # define ZEXPORTVA __declspec(dllexport)
  78300. # else
  78301. # define ZEXPORT __declspec(dllimport)
  78302. # define ZEXPORTVA __declspec(dllimport)
  78303. # endif
  78304. # endif
  78305. #endif
  78306. #ifndef ZEXTERN
  78307. # define ZEXTERN extern
  78308. #endif
  78309. #ifndef ZEXPORT
  78310. # define ZEXPORT
  78311. #endif
  78312. #ifndef ZEXPORTVA
  78313. # define ZEXPORTVA
  78314. #endif
  78315. #ifndef FAR
  78316. # define FAR
  78317. #endif
  78318. #if !defined(__MACTYPES__)
  78319. typedef unsigned char Byte; /* 8 bits */
  78320. #endif
  78321. typedef unsigned int uInt; /* 16 bits or more */
  78322. typedef unsigned long uLong; /* 32 bits or more */
  78323. #ifdef SMALL_MEDIUM
  78324. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78325. # define Bytef Byte FAR
  78326. #else
  78327. typedef Byte FAR Bytef;
  78328. #endif
  78329. typedef char FAR charf;
  78330. typedef int FAR intf;
  78331. typedef uInt FAR uIntf;
  78332. typedef uLong FAR uLongf;
  78333. #ifdef STDC
  78334. typedef void const *voidpc;
  78335. typedef void FAR *voidpf;
  78336. typedef void *voidp;
  78337. #else
  78338. typedef Byte const *voidpc;
  78339. typedef Byte FAR *voidpf;
  78340. typedef Byte *voidp;
  78341. #endif
  78342. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78343. # include <sys/types.h> /* for off_t */
  78344. # include <unistd.h> /* for SEEK_* and off_t */
  78345. # ifdef VMS
  78346. # include <unixio.h> /* for off_t */
  78347. # endif
  78348. # define z_off_t off_t
  78349. #endif
  78350. #ifndef SEEK_SET
  78351. # define SEEK_SET 0 /* Seek from beginning of file. */
  78352. # define SEEK_CUR 1 /* Seek from current position. */
  78353. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78354. #endif
  78355. #ifndef z_off_t
  78356. # define z_off_t long
  78357. #endif
  78358. #if defined(__OS400__)
  78359. # define NO_vsnprintf
  78360. #endif
  78361. #if defined(__MVS__)
  78362. # define NO_vsnprintf
  78363. # ifdef FAR
  78364. # undef FAR
  78365. # endif
  78366. #endif
  78367. /* MVS linker does not support external names larger than 8 bytes */
  78368. #if defined(__MVS__)
  78369. # pragma map(deflateInit_,"DEIN")
  78370. # pragma map(deflateInit2_,"DEIN2")
  78371. # pragma map(deflateEnd,"DEEND")
  78372. # pragma map(deflateBound,"DEBND")
  78373. # pragma map(inflateInit_,"ININ")
  78374. # pragma map(inflateInit2_,"ININ2")
  78375. # pragma map(inflateEnd,"INEND")
  78376. # pragma map(inflateSync,"INSY")
  78377. # pragma map(inflateSetDictionary,"INSEDI")
  78378. # pragma map(compressBound,"CMBND")
  78379. # pragma map(inflate_table,"INTABL")
  78380. # pragma map(inflate_fast,"INFA")
  78381. # pragma map(inflate_copyright,"INCOPY")
  78382. #endif
  78383. #endif /* ZCONF_H */
  78384. /*** End of inlined file: zconf.h ***/
  78385. #ifdef __cplusplus
  78386. //extern "C" {
  78387. #endif
  78388. #define ZLIB_VERSION "1.2.3"
  78389. #define ZLIB_VERNUM 0x1230
  78390. /*
  78391. The 'zlib' compression library provides in-memory compression and
  78392. decompression functions, including integrity checks of the uncompressed
  78393. data. This version of the library supports only one compression method
  78394. (deflation) but other algorithms will be added later and will have the same
  78395. stream interface.
  78396. Compression can be done in a single step if the buffers are large
  78397. enough (for example if an input file is mmap'ed), or can be done by
  78398. repeated calls of the compression function. In the latter case, the
  78399. application must provide more input and/or consume the output
  78400. (providing more output space) before each call.
  78401. The compressed data format used by default by the in-memory functions is
  78402. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78403. around a deflate stream, which is itself documented in RFC 1951.
  78404. The library also supports reading and writing files in gzip (.gz) format
  78405. with an interface similar to that of stdio using the functions that start
  78406. with "gz". The gzip format is different from the zlib format. gzip is a
  78407. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78408. This library can optionally read and write gzip streams in memory as well.
  78409. The zlib format was designed to be compact and fast for use in memory
  78410. and on communications channels. The gzip format was designed for single-
  78411. file compression on file systems, has a larger header than zlib to maintain
  78412. directory information, and uses a different, slower check method than zlib.
  78413. The library does not install any signal handler. The decoder checks
  78414. the consistency of the compressed data, so the library should never
  78415. crash even in case of corrupted input.
  78416. */
  78417. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78418. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78419. struct internal_state;
  78420. typedef struct z_stream_s {
  78421. Bytef *next_in; /* next input byte */
  78422. uInt avail_in; /* number of bytes available at next_in */
  78423. uLong total_in; /* total nb of input bytes read so far */
  78424. Bytef *next_out; /* next output byte should be put there */
  78425. uInt avail_out; /* remaining free space at next_out */
  78426. uLong total_out; /* total nb of bytes output so far */
  78427. char *msg; /* last error message, NULL if no error */
  78428. struct internal_state FAR *state; /* not visible by applications */
  78429. alloc_func zalloc; /* used to allocate the internal state */
  78430. free_func zfree; /* used to free the internal state */
  78431. voidpf opaque; /* private data object passed to zalloc and zfree */
  78432. int data_type; /* best guess about the data type: binary or text */
  78433. uLong adler; /* adler32 value of the uncompressed data */
  78434. uLong reserved; /* reserved for future use */
  78435. } z_stream;
  78436. typedef z_stream FAR *z_streamp;
  78437. /*
  78438. gzip header information passed to and from zlib routines. See RFC 1952
  78439. for more details on the meanings of these fields.
  78440. */
  78441. typedef struct gz_header_s {
  78442. int text; /* true if compressed data believed to be text */
  78443. uLong time; /* modification time */
  78444. int xflags; /* extra flags (not used when writing a gzip file) */
  78445. int os; /* operating system */
  78446. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78447. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78448. uInt extra_max; /* space at extra (only when reading header) */
  78449. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78450. uInt name_max; /* space at name (only when reading header) */
  78451. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78452. uInt comm_max; /* space at comment (only when reading header) */
  78453. int hcrc; /* true if there was or will be a header crc */
  78454. int done; /* true when done reading gzip header (not used
  78455. when writing a gzip file) */
  78456. } gz_header;
  78457. typedef gz_header FAR *gz_headerp;
  78458. /*
  78459. The application must update next_in and avail_in when avail_in has
  78460. dropped to zero. It must update next_out and avail_out when avail_out
  78461. has dropped to zero. The application must initialize zalloc, zfree and
  78462. opaque before calling the init function. All other fields are set by the
  78463. compression library and must not be updated by the application.
  78464. The opaque value provided by the application will be passed as the first
  78465. parameter for calls of zalloc and zfree. This can be useful for custom
  78466. memory management. The compression library attaches no meaning to the
  78467. opaque value.
  78468. zalloc must return Z_NULL if there is not enough memory for the object.
  78469. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78470. thread safe.
  78471. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78472. exactly 65536 bytes, but will not be required to allocate more than this
  78473. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78474. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78475. have their offset normalized to zero. The default allocation function
  78476. provided by this library ensures this (see zutil.c). To reduce memory
  78477. requirements and avoid any allocation of 64K objects, at the expense of
  78478. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78479. The fields total_in and total_out can be used for statistics or
  78480. progress reports. After compression, total_in holds the total size of
  78481. the uncompressed data and may be saved for use in the decompressor
  78482. (particularly if the decompressor wants to decompress everything in
  78483. a single step).
  78484. */
  78485. /* constants */
  78486. #define Z_NO_FLUSH 0
  78487. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78488. #define Z_SYNC_FLUSH 2
  78489. #define Z_FULL_FLUSH 3
  78490. #define Z_FINISH 4
  78491. #define Z_BLOCK 5
  78492. /* Allowed flush values; see deflate() and inflate() below for details */
  78493. #define Z_OK 0
  78494. #define Z_STREAM_END 1
  78495. #define Z_NEED_DICT 2
  78496. #define Z_ERRNO (-1)
  78497. #define Z_STREAM_ERROR (-2)
  78498. #define Z_DATA_ERROR (-3)
  78499. #define Z_MEM_ERROR (-4)
  78500. #define Z_BUF_ERROR (-5)
  78501. #define Z_VERSION_ERROR (-6)
  78502. /* Return codes for the compression/decompression functions. Negative
  78503. * values are errors, positive values are used for special but normal events.
  78504. */
  78505. #define Z_NO_COMPRESSION 0
  78506. #define Z_BEST_SPEED 1
  78507. #define Z_BEST_COMPRESSION 9
  78508. #define Z_DEFAULT_COMPRESSION (-1)
  78509. /* compression levels */
  78510. #define Z_FILTERED 1
  78511. #define Z_HUFFMAN_ONLY 2
  78512. #define Z_RLE 3
  78513. #define Z_FIXED 4
  78514. #define Z_DEFAULT_STRATEGY 0
  78515. /* compression strategy; see deflateInit2() below for details */
  78516. #define Z_BINARY 0
  78517. #define Z_TEXT 1
  78518. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78519. #define Z_UNKNOWN 2
  78520. /* Possible values of the data_type field (though see inflate()) */
  78521. #define Z_DEFLATED 8
  78522. /* The deflate compression method (the only one supported in this version) */
  78523. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78524. #define zlib_version zlibVersion()
  78525. /* for compatibility with versions < 1.0.2 */
  78526. /* basic functions */
  78527. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78528. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78529. If the first character differs, the library code actually used is
  78530. not compatible with the zlib.h header file used by the application.
  78531. This check is automatically made by deflateInit and inflateInit.
  78532. */
  78533. /*
  78534. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78535. Initializes the internal stream state for compression. The fields
  78536. zalloc, zfree and opaque must be initialized before by the caller.
  78537. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78538. use default allocation functions.
  78539. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78540. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78541. all (the input data is simply copied a block at a time).
  78542. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78543. compression (currently equivalent to level 6).
  78544. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78545. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78546. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78547. with the version assumed by the caller (ZLIB_VERSION).
  78548. msg is set to null if there is no error message. deflateInit does not
  78549. perform any compression: this will be done by deflate().
  78550. */
  78551. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78552. /*
  78553. deflate compresses as much data as possible, and stops when the input
  78554. buffer becomes empty or the output buffer becomes full. It may introduce some
  78555. output latency (reading input without producing any output) except when
  78556. forced to flush.
  78557. The detailed semantics are as follows. deflate performs one or both of the
  78558. following actions:
  78559. - Compress more input starting at next_in and update next_in and avail_in
  78560. accordingly. If not all input can be processed (because there is not
  78561. enough room in the output buffer), next_in and avail_in are updated and
  78562. processing will resume at this point for the next call of deflate().
  78563. - Provide more output starting at next_out and update next_out and avail_out
  78564. accordingly. This action is forced if the parameter flush is non zero.
  78565. Forcing flush frequently degrades the compression ratio, so this parameter
  78566. should be set only when necessary (in interactive applications).
  78567. Some output may be provided even if flush is not set.
  78568. Before the call of deflate(), the application should ensure that at least
  78569. one of the actions is possible, by providing more input and/or consuming
  78570. more output, and updating avail_in or avail_out accordingly; avail_out
  78571. should never be zero before the call. The application can consume the
  78572. compressed output when it wants, for example when the output buffer is full
  78573. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78574. and with zero avail_out, it must be called again after making room in the
  78575. output buffer because there might be more output pending.
  78576. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78577. decide how much data to accumualte before producing output, in order to
  78578. maximize compression.
  78579. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78580. flushed to the output buffer and the output is aligned on a byte boundary, so
  78581. that the decompressor can get all input data available so far. (In particular
  78582. avail_in is zero after the call if enough output space has been provided
  78583. before the call.) Flushing may degrade compression for some compression
  78584. algorithms and so it should be used only when necessary.
  78585. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78586. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78587. restart from this point if previous compressed data has been damaged or if
  78588. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78589. compression.
  78590. If deflate returns with avail_out == 0, this function must be called again
  78591. with the same value of the flush parameter and more output space (updated
  78592. avail_out), until the flush is complete (deflate returns with non-zero
  78593. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78594. avail_out is greater than six to avoid repeated flush markers due to
  78595. avail_out == 0 on return.
  78596. If the parameter flush is set to Z_FINISH, pending input is processed,
  78597. pending output is flushed and deflate returns with Z_STREAM_END if there
  78598. was enough output space; if deflate returns with Z_OK, this function must be
  78599. called again with Z_FINISH and more output space (updated avail_out) but no
  78600. more input data, until it returns with Z_STREAM_END or an error. After
  78601. deflate has returned Z_STREAM_END, the only possible operations on the
  78602. stream are deflateReset or deflateEnd.
  78603. Z_FINISH can be used immediately after deflateInit if all the compression
  78604. is to be done in a single step. In this case, avail_out must be at least
  78605. the value returned by deflateBound (see below). If deflate does not return
  78606. Z_STREAM_END, then it must be called again as described above.
  78607. deflate() sets strm->adler to the adler32 checksum of all input read
  78608. so far (that is, total_in bytes).
  78609. deflate() may update strm->data_type if it can make a good guess about
  78610. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78611. binary. This field is only for information purposes and does not affect
  78612. the compression algorithm in any manner.
  78613. deflate() returns Z_OK if some progress has been made (more input
  78614. processed or more output produced), Z_STREAM_END if all input has been
  78615. consumed and all output has been produced (only when flush is set to
  78616. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78617. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78618. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78619. fatal, and deflate() can be called again with more input and more output
  78620. space to continue compressing.
  78621. */
  78622. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78623. /*
  78624. All dynamically allocated data structures for this stream are freed.
  78625. This function discards any unprocessed input and does not flush any
  78626. pending output.
  78627. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78628. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78629. prematurely (some input or output was discarded). In the error case,
  78630. msg may be set but then points to a static string (which must not be
  78631. deallocated).
  78632. */
  78633. /*
  78634. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78635. Initializes the internal stream state for decompression. The fields
  78636. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78637. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78638. value depends on the compression method), inflateInit determines the
  78639. compression method from the zlib header and allocates all data structures
  78640. accordingly; otherwise the allocation will be deferred to the first call of
  78641. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78642. use default allocation functions.
  78643. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78644. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78645. version assumed by the caller. msg is set to null if there is no error
  78646. message. inflateInit does not perform any decompression apart from reading
  78647. the zlib header if present: this will be done by inflate(). (So next_in and
  78648. avail_in may be modified, but next_out and avail_out are unchanged.)
  78649. */
  78650. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78651. /*
  78652. inflate decompresses as much data as possible, and stops when the input
  78653. buffer becomes empty or the output buffer becomes full. It may introduce
  78654. some output latency (reading input without producing any output) except when
  78655. forced to flush.
  78656. The detailed semantics are as follows. inflate performs one or both of the
  78657. following actions:
  78658. - Decompress more input starting at next_in and update next_in and avail_in
  78659. accordingly. If not all input can be processed (because there is not
  78660. enough room in the output buffer), next_in is updated and processing
  78661. will resume at this point for the next call of inflate().
  78662. - Provide more output starting at next_out and update next_out and avail_out
  78663. accordingly. inflate() provides as much output as possible, until there
  78664. is no more input data or no more space in the output buffer (see below
  78665. about the flush parameter).
  78666. Before the call of inflate(), the application should ensure that at least
  78667. one of the actions is possible, by providing more input and/or consuming
  78668. more output, and updating the next_* and avail_* values accordingly.
  78669. The application can consume the uncompressed output when it wants, for
  78670. example when the output buffer is full (avail_out == 0), or after each
  78671. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78672. must be called again after making room in the output buffer because there
  78673. might be more output pending.
  78674. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78675. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78676. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78677. if and when it gets to the next deflate block boundary. When decoding the
  78678. zlib or gzip format, this will cause inflate() to return immediately after
  78679. the header and before the first block. When doing a raw inflate, inflate()
  78680. will go ahead and process the first block, and will return when it gets to
  78681. the end of that block, or when it runs out of data.
  78682. The Z_BLOCK option assists in appending to or combining deflate streams.
  78683. Also to assist in this, on return inflate() will set strm->data_type to the
  78684. number of unused bits in the last byte taken from strm->next_in, plus 64
  78685. if inflate() is currently decoding the last block in the deflate stream,
  78686. plus 128 if inflate() returned immediately after decoding an end-of-block
  78687. code or decoding the complete header up to just before the first byte of the
  78688. deflate stream. The end-of-block will not be indicated until all of the
  78689. uncompressed data from that block has been written to strm->next_out. The
  78690. number of unused bits may in general be greater than seven, except when
  78691. bit 7 of data_type is set, in which case the number of unused bits will be
  78692. less than eight.
  78693. inflate() should normally be called until it returns Z_STREAM_END or an
  78694. error. However if all decompression is to be performed in a single step
  78695. (a single call of inflate), the parameter flush should be set to
  78696. Z_FINISH. In this case all pending input is processed and all pending
  78697. output is flushed; avail_out must be large enough to hold all the
  78698. uncompressed data. (The size of the uncompressed data may have been saved
  78699. by the compressor for this purpose.) The next operation on this stream must
  78700. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78701. is never required, but can be used to inform inflate that a faster approach
  78702. may be used for the single inflate() call.
  78703. In this implementation, inflate() always flushes as much output as
  78704. possible to the output buffer, and always uses the faster approach on the
  78705. first call. So the only effect of the flush parameter in this implementation
  78706. is on the return value of inflate(), as noted below, or when it returns early
  78707. because Z_BLOCK is used.
  78708. If a preset dictionary is needed after this call (see inflateSetDictionary
  78709. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78710. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78711. strm->adler to the adler32 checksum of all output produced so far (that is,
  78712. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78713. below. At the end of the stream, inflate() checks that its computed adler32
  78714. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78715. only if the checksum is correct.
  78716. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78717. deflate data. The header type is detected automatically. Any information
  78718. contained in the gzip header is not retained, so applications that need that
  78719. information should instead use raw inflate, see inflateInit2() below, or
  78720. inflateBack() and perform their own processing of the gzip header and
  78721. trailer.
  78722. inflate() returns Z_OK if some progress has been made (more input processed
  78723. or more output produced), Z_STREAM_END if the end of the compressed data has
  78724. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78725. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78726. corrupted (input stream not conforming to the zlib format or incorrect check
  78727. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78728. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78729. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78730. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78731. inflate() can be called again with more input and more output space to
  78732. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78733. call inflateSync() to look for a good compression block if a partial recovery
  78734. of the data is desired.
  78735. */
  78736. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78737. /*
  78738. All dynamically allocated data structures for this stream are freed.
  78739. This function discards any unprocessed input and does not flush any
  78740. pending output.
  78741. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78742. was inconsistent. In the error case, msg may be set but then points to a
  78743. static string (which must not be deallocated).
  78744. */
  78745. /* Advanced functions */
  78746. /*
  78747. The following functions are needed only in some special applications.
  78748. */
  78749. /*
  78750. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78751. int level,
  78752. int method,
  78753. int windowBits,
  78754. int memLevel,
  78755. int strategy));
  78756. This is another version of deflateInit with more compression options. The
  78757. fields next_in, zalloc, zfree and opaque must be initialized before by
  78758. the caller.
  78759. The method parameter is the compression method. It must be Z_DEFLATED in
  78760. this version of the library.
  78761. The windowBits parameter is the base two logarithm of the window size
  78762. (the size of the history buffer). It should be in the range 8..15 for this
  78763. version of the library. Larger values of this parameter result in better
  78764. compression at the expense of memory usage. The default value is 15 if
  78765. deflateInit is used instead.
  78766. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78767. determines the window size. deflate() will then generate raw deflate data
  78768. with no zlib header or trailer, and will not compute an adler32 check value.
  78769. windowBits can also be greater than 15 for optional gzip encoding. Add
  78770. 16 to windowBits to write a simple gzip header and trailer around the
  78771. compressed data instead of a zlib wrapper. The gzip header will have no
  78772. file name, no extra data, no comment, no modification time (set to zero),
  78773. no header crc, and the operating system will be set to 255 (unknown). If a
  78774. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78775. The memLevel parameter specifies how much memory should be allocated
  78776. for the internal compression state. memLevel=1 uses minimum memory but
  78777. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78778. for optimal speed. The default value is 8. See zconf.h for total memory
  78779. usage as a function of windowBits and memLevel.
  78780. The strategy parameter is used to tune the compression algorithm. Use the
  78781. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78782. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78783. string match), or Z_RLE to limit match distances to one (run-length
  78784. encoding). Filtered data consists mostly of small values with a somewhat
  78785. random distribution. In this case, the compression algorithm is tuned to
  78786. compress them better. The effect of Z_FILTERED is to force more Huffman
  78787. coding and less string matching; it is somewhat intermediate between
  78788. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78789. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78790. parameter only affects the compression ratio but not the correctness of the
  78791. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78792. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78793. applications.
  78794. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78795. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78796. method). msg is set to null if there is no error message. deflateInit2 does
  78797. not perform any compression: this will be done by deflate().
  78798. */
  78799. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78800. const Bytef *dictionary,
  78801. uInt dictLength));
  78802. /*
  78803. Initializes the compression dictionary from the given byte sequence
  78804. without producing any compressed output. This function must be called
  78805. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78806. call of deflate. The compressor and decompressor must use exactly the same
  78807. dictionary (see inflateSetDictionary).
  78808. The dictionary should consist of strings (byte sequences) that are likely
  78809. to be encountered later in the data to be compressed, with the most commonly
  78810. used strings preferably put towards the end of the dictionary. Using a
  78811. dictionary is most useful when the data to be compressed is short and can be
  78812. predicted with good accuracy; the data can then be compressed better than
  78813. with the default empty dictionary.
  78814. Depending on the size of the compression data structures selected by
  78815. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78816. discarded, for example if the dictionary is larger than the window size in
  78817. deflate or deflate2. Thus the strings most likely to be useful should be
  78818. put at the end of the dictionary, not at the front. In addition, the
  78819. current implementation of deflate will use at most the window size minus
  78820. 262 bytes of the provided dictionary.
  78821. Upon return of this function, strm->adler is set to the adler32 value
  78822. of the dictionary; the decompressor may later use this value to determine
  78823. which dictionary has been used by the compressor. (The adler32 value
  78824. applies to the whole dictionary even if only a subset of the dictionary is
  78825. actually used by the compressor.) If a raw deflate was requested, then the
  78826. adler32 value is not computed and strm->adler is not set.
  78827. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78828. parameter is invalid (such as NULL dictionary) or the stream state is
  78829. inconsistent (for example if deflate has already been called for this stream
  78830. or if the compression method is bsort). deflateSetDictionary does not
  78831. perform any compression: this will be done by deflate().
  78832. */
  78833. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78834. z_streamp source));
  78835. /*
  78836. Sets the destination stream as a complete copy of the source stream.
  78837. This function can be useful when several compression strategies will be
  78838. tried, for example when there are several ways of pre-processing the input
  78839. data with a filter. The streams that will be discarded should then be freed
  78840. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78841. compression state which can be quite large, so this strategy is slow and
  78842. can consume lots of memory.
  78843. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78844. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78845. (such as zalloc being NULL). msg is left unchanged in both source and
  78846. destination.
  78847. */
  78848. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78849. /*
  78850. This function is equivalent to deflateEnd followed by deflateInit,
  78851. but does not free and reallocate all the internal compression state.
  78852. The stream will keep the same compression level and any other attributes
  78853. that may have been set by deflateInit2.
  78854. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78855. stream state was inconsistent (such as zalloc or state being NULL).
  78856. */
  78857. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78858. int level,
  78859. int strategy));
  78860. /*
  78861. Dynamically update the compression level and compression strategy. The
  78862. interpretation of level and strategy is as in deflateInit2. This can be
  78863. used to switch between compression and straight copy of the input data, or
  78864. to switch to a different kind of input data requiring a different
  78865. strategy. If the compression level is changed, the input available so far
  78866. is compressed with the old level (and may be flushed); the new level will
  78867. take effect only at the next call of deflate().
  78868. Before the call of deflateParams, the stream state must be set as for
  78869. a call of deflate(), since the currently available input may have to
  78870. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78871. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78872. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78873. if strm->avail_out was zero.
  78874. */
  78875. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78876. int good_length,
  78877. int max_lazy,
  78878. int nice_length,
  78879. int max_chain));
  78880. /*
  78881. Fine tune deflate's internal compression parameters. This should only be
  78882. used by someone who understands the algorithm used by zlib's deflate for
  78883. searching for the best matching string, and even then only by the most
  78884. fanatic optimizer trying to squeeze out the last compressed bit for their
  78885. specific input data. Read the deflate.c source code for the meaning of the
  78886. max_lazy, good_length, nice_length, and max_chain parameters.
  78887. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78888. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78889. */
  78890. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78891. uLong sourceLen));
  78892. /*
  78893. deflateBound() returns an upper bound on the compressed size after
  78894. deflation of sourceLen bytes. It must be called after deflateInit()
  78895. or deflateInit2(). This would be used to allocate an output buffer
  78896. for deflation in a single pass, and so would be called before deflate().
  78897. */
  78898. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78899. int bits,
  78900. int value));
  78901. /*
  78902. deflatePrime() inserts bits in the deflate output stream. The intent
  78903. is that this function is used to start off the deflate output with the
  78904. bits leftover from a previous deflate stream when appending to it. As such,
  78905. this function can only be used for raw deflate, and must be used before the
  78906. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78907. less than or equal to 16, and that many of the least significant bits of
  78908. value will be inserted in the output.
  78909. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78910. stream state was inconsistent.
  78911. */
  78912. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78913. gz_headerp head));
  78914. /*
  78915. deflateSetHeader() provides gzip header information for when a gzip
  78916. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78917. after deflateInit2() or deflateReset() and before the first call of
  78918. deflate(). The text, time, os, extra field, name, and comment information
  78919. in the provided gz_header structure are written to the gzip header (xflag is
  78920. ignored -- the extra flags are set according to the compression level). The
  78921. caller must assure that, if not Z_NULL, name and comment are terminated with
  78922. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78923. available there. If hcrc is true, a gzip header crc is included. Note that
  78924. the current versions of the command-line version of gzip (up through version
  78925. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78926. gzip file" and give up.
  78927. If deflateSetHeader is not used, the default gzip header has text false,
  78928. the time set to zero, and os set to 255, with no extra, name, or comment
  78929. fields. The gzip header is returned to the default state by deflateReset().
  78930. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78931. stream state was inconsistent.
  78932. */
  78933. /*
  78934. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78935. int windowBits));
  78936. This is another version of inflateInit with an extra parameter. The
  78937. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78938. before by the caller.
  78939. The windowBits parameter is the base two logarithm of the maximum window
  78940. size (the size of the history buffer). It should be in the range 8..15 for
  78941. this version of the library. The default value is 15 if inflateInit is used
  78942. instead. windowBits must be greater than or equal to the windowBits value
  78943. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78944. deflateInit2() was not used. If a compressed stream with a larger window
  78945. size is given as input, inflate() will return with the error code
  78946. Z_DATA_ERROR instead of trying to allocate a larger window.
  78947. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78948. determines the window size. inflate() will then process raw deflate data,
  78949. not looking for a zlib or gzip header, not generating a check value, and not
  78950. looking for any check values for comparison at the end of the stream. This
  78951. is for use with other formats that use the deflate compressed data format
  78952. such as zip. Those formats provide their own check values. If a custom
  78953. format is developed using the raw deflate format for compressed data, it is
  78954. recommended that a check value such as an adler32 or a crc32 be applied to
  78955. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78956. most applications, the zlib format should be used as is. Note that comments
  78957. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78958. windowBits can also be greater than 15 for optional gzip decoding. Add
  78959. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78960. detection, or add 16 to decode only the gzip format (the zlib format will
  78961. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78962. a crc32 instead of an adler32.
  78963. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78964. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78965. is set to null if there is no error message. inflateInit2 does not perform
  78966. any decompression apart from reading the zlib header if present: this will
  78967. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78968. and avail_out are unchanged.)
  78969. */
  78970. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78971. const Bytef *dictionary,
  78972. uInt dictLength));
  78973. /*
  78974. Initializes the decompression dictionary from the given uncompressed byte
  78975. sequence. This function must be called immediately after a call of inflate,
  78976. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78977. can be determined from the adler32 value returned by that call of inflate.
  78978. The compressor and decompressor must use exactly the same dictionary (see
  78979. deflateSetDictionary). For raw inflate, this function can be called
  78980. immediately after inflateInit2() or inflateReset() and before any call of
  78981. inflate() to set the dictionary. The application must insure that the
  78982. dictionary that was used for compression is provided.
  78983. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78984. parameter is invalid (such as NULL dictionary) or the stream state is
  78985. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78986. expected one (incorrect adler32 value). inflateSetDictionary does not
  78987. perform any decompression: this will be done by subsequent calls of
  78988. inflate().
  78989. */
  78990. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78991. /*
  78992. Skips invalid compressed data until a full flush point (see above the
  78993. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78994. available input is skipped. No output is provided.
  78995. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78996. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78997. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78998. case, the application may save the current current value of total_in which
  78999. indicates where valid compressed data was found. In the error case, the
  79000. application may repeatedly call inflateSync, providing more input each time,
  79001. until success or end of the input data.
  79002. */
  79003. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79004. z_streamp source));
  79005. /*
  79006. Sets the destination stream as a complete copy of the source stream.
  79007. This function can be useful when randomly accessing a large stream. The
  79008. first pass through the stream can periodically record the inflate state,
  79009. allowing restarting inflate at those points when randomly accessing the
  79010. stream.
  79011. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79012. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79013. (such as zalloc being NULL). msg is left unchanged in both source and
  79014. destination.
  79015. */
  79016. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79017. /*
  79018. This function is equivalent to inflateEnd followed by inflateInit,
  79019. but does not free and reallocate all the internal decompression state.
  79020. The stream will keep attributes that may have been set by inflateInit2.
  79021. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79022. stream state was inconsistent (such as zalloc or state being NULL).
  79023. */
  79024. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79025. int bits,
  79026. int value));
  79027. /*
  79028. This function inserts bits in the inflate input stream. The intent is
  79029. that this function is used to start inflating at a bit position in the
  79030. middle of a byte. The provided bits will be used before any bytes are used
  79031. from next_in. This function should only be used with raw inflate, and
  79032. should be used before the first inflate() call after inflateInit2() or
  79033. inflateReset(). bits must be less than or equal to 16, and that many of the
  79034. least significant bits of value will be inserted in the input.
  79035. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79036. stream state was inconsistent.
  79037. */
  79038. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79039. gz_headerp head));
  79040. /*
  79041. inflateGetHeader() requests that gzip header information be stored in the
  79042. provided gz_header structure. inflateGetHeader() may be called after
  79043. inflateInit2() or inflateReset(), and before the first call of inflate().
  79044. As inflate() processes the gzip stream, head->done is zero until the header
  79045. is completed, at which time head->done is set to one. If a zlib stream is
  79046. being decoded, then head->done is set to -1 to indicate that there will be
  79047. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79048. force inflate() to return immediately after header processing is complete
  79049. and before any actual data is decompressed.
  79050. The text, time, xflags, and os fields are filled in with the gzip header
  79051. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79052. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79053. contains the maximum number of bytes to write to extra. Once done is true,
  79054. extra_len contains the actual extra field length, and extra contains the
  79055. extra field, or that field truncated if extra_max is less than extra_len.
  79056. If name is not Z_NULL, then up to name_max characters are written there,
  79057. terminated with a zero unless the length is greater than name_max. If
  79058. comment is not Z_NULL, then up to comm_max characters are written there,
  79059. terminated with a zero unless the length is greater than comm_max. When
  79060. any of extra, name, or comment are not Z_NULL and the respective field is
  79061. not present in the header, then that field is set to Z_NULL to signal its
  79062. absence. This allows the use of deflateSetHeader() with the returned
  79063. structure to duplicate the header. However if those fields are set to
  79064. allocated memory, then the application will need to save those pointers
  79065. elsewhere so that they can be eventually freed.
  79066. If inflateGetHeader is not used, then the header information is simply
  79067. discarded. The header is always checked for validity, including the header
  79068. CRC if present. inflateReset() will reset the process to discard the header
  79069. information. The application would need to call inflateGetHeader() again to
  79070. retrieve the header from the next gzip stream.
  79071. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79072. stream state was inconsistent.
  79073. */
  79074. /*
  79075. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79076. unsigned char FAR *window));
  79077. Initialize the internal stream state for decompression using inflateBack()
  79078. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79079. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79080. derived memory allocation routines are used. windowBits is the base two
  79081. logarithm of the window size, in the range 8..15. window is a caller
  79082. supplied buffer of that size. Except for special applications where it is
  79083. assured that deflate was used with small window sizes, windowBits must be 15
  79084. and a 32K byte window must be supplied to be able to decompress general
  79085. deflate streams.
  79086. See inflateBack() for the usage of these routines.
  79087. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79088. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79089. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79090. match the version of the header file.
  79091. */
  79092. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79093. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79094. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79095. in_func in, void FAR *in_desc,
  79096. out_func out, void FAR *out_desc));
  79097. /*
  79098. inflateBack() does a raw inflate with a single call using a call-back
  79099. interface for input and output. This is more efficient than inflate() for
  79100. file i/o applications in that it avoids copying between the output and the
  79101. sliding window by simply making the window itself the output buffer. This
  79102. function trusts the application to not change the output buffer passed by
  79103. the output function, at least until inflateBack() returns.
  79104. inflateBackInit() must be called first to allocate the internal state
  79105. and to initialize the state with the user-provided window buffer.
  79106. inflateBack() may then be used multiple times to inflate a complete, raw
  79107. deflate stream with each call. inflateBackEnd() is then called to free
  79108. the allocated state.
  79109. A raw deflate stream is one with no zlib or gzip header or trailer.
  79110. This routine would normally be used in a utility that reads zip or gzip
  79111. files and writes out uncompressed files. The utility would decode the
  79112. header and process the trailer on its own, hence this routine expects
  79113. only the raw deflate stream to decompress. This is different from the
  79114. normal behavior of inflate(), which expects either a zlib or gzip header and
  79115. trailer around the deflate stream.
  79116. inflateBack() uses two subroutines supplied by the caller that are then
  79117. called by inflateBack() for input and output. inflateBack() calls those
  79118. routines until it reads a complete deflate stream and writes out all of the
  79119. uncompressed data, or until it encounters an error. The function's
  79120. parameters and return types are defined above in the in_func and out_func
  79121. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79122. number of bytes of provided input, and a pointer to that input in buf. If
  79123. there is no input available, in() must return zero--buf is ignored in that
  79124. case--and inflateBack() will return a buffer error. inflateBack() will call
  79125. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79126. should return zero on success, or non-zero on failure. If out() returns
  79127. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79128. are permitted to change the contents of the window provided to
  79129. inflateBackInit(), which is also the buffer that out() uses to write from.
  79130. The length written by out() will be at most the window size. Any non-zero
  79131. amount of input may be provided by in().
  79132. For convenience, inflateBack() can be provided input on the first call by
  79133. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79134. in() will be called. Therefore strm->next_in must be initialized before
  79135. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79136. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79137. must also be initialized, and then if strm->avail_in is not zero, input will
  79138. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79139. The in_desc and out_desc parameters of inflateBack() is passed as the
  79140. first parameter of in() and out() respectively when they are called. These
  79141. descriptors can be optionally used to pass any information that the caller-
  79142. supplied in() and out() functions need to do their job.
  79143. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79144. pass back any unused input that was provided by the last in() call. The
  79145. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79146. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79147. error in the deflate stream (in which case strm->msg is set to indicate the
  79148. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79149. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79150. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79151. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79152. out() returning non-zero. (in() will always be called before out(), so
  79153. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79154. that inflateBack() cannot return Z_OK.
  79155. */
  79156. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79157. /*
  79158. All memory allocated by inflateBackInit() is freed.
  79159. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79160. state was inconsistent.
  79161. */
  79162. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79163. /* Return flags indicating compile-time options.
  79164. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79165. 1.0: size of uInt
  79166. 3.2: size of uLong
  79167. 5.4: size of voidpf (pointer)
  79168. 7.6: size of z_off_t
  79169. Compiler, assembler, and debug options:
  79170. 8: DEBUG
  79171. 9: ASMV or ASMINF -- use ASM code
  79172. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79173. 11: 0 (reserved)
  79174. One-time table building (smaller code, but not thread-safe if true):
  79175. 12: BUILDFIXED -- build static block decoding tables when needed
  79176. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79177. 14,15: 0 (reserved)
  79178. Library content (indicates missing functionality):
  79179. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79180. deflate code when not needed)
  79181. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79182. and decode gzip streams (to avoid linking crc code)
  79183. 18-19: 0 (reserved)
  79184. Operation variations (changes in library functionality):
  79185. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79186. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79187. 22,23: 0 (reserved)
  79188. The sprintf variant used by gzprintf (zero is best):
  79189. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79190. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79191. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79192. Remainder:
  79193. 27-31: 0 (reserved)
  79194. */
  79195. /* utility functions */
  79196. /*
  79197. The following utility functions are implemented on top of the
  79198. basic stream-oriented functions. To simplify the interface, some
  79199. default options are assumed (compression level and memory usage,
  79200. standard memory allocation functions). The source code of these
  79201. utility functions can easily be modified if you need special options.
  79202. */
  79203. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79204. const Bytef *source, uLong sourceLen));
  79205. /*
  79206. Compresses the source buffer into the destination buffer. sourceLen is
  79207. the byte length of the source buffer. Upon entry, destLen is the total
  79208. size of the destination buffer, which must be at least the value returned
  79209. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79210. compressed buffer.
  79211. This function can be used to compress a whole file at once if the
  79212. input file is mmap'ed.
  79213. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79214. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79215. buffer.
  79216. */
  79217. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79218. const Bytef *source, uLong sourceLen,
  79219. int level));
  79220. /*
  79221. Compresses the source buffer into the destination buffer. The level
  79222. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79223. length of the source buffer. Upon entry, destLen is the total size of the
  79224. destination buffer, which must be at least the value returned by
  79225. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79226. compressed buffer.
  79227. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79228. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79229. Z_STREAM_ERROR if the level parameter is invalid.
  79230. */
  79231. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79232. /*
  79233. compressBound() returns an upper bound on the compressed size after
  79234. compress() or compress2() on sourceLen bytes. It would be used before
  79235. a compress() or compress2() call to allocate the destination buffer.
  79236. */
  79237. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79238. const Bytef *source, uLong sourceLen));
  79239. /*
  79240. Decompresses the source buffer into the destination buffer. sourceLen is
  79241. the byte length of the source buffer. Upon entry, destLen is the total
  79242. size of the destination buffer, which must be large enough to hold the
  79243. entire uncompressed data. (The size of the uncompressed data must have
  79244. been saved previously by the compressor and transmitted to the decompressor
  79245. by some mechanism outside the scope of this compression library.)
  79246. Upon exit, destLen is the actual size of the compressed buffer.
  79247. This function can be used to decompress a whole file at once if the
  79248. input file is mmap'ed.
  79249. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79250. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79251. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79252. */
  79253. typedef voidp gzFile;
  79254. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79255. /*
  79256. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79257. is as in fopen ("rb" or "wb") but can also include a compression level
  79258. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79259. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79260. as in "wb1R". (See the description of deflateInit2 for more information
  79261. about the strategy parameter.)
  79262. gzopen can be used to read a file which is not in gzip format; in this
  79263. case gzread will directly read from the file without decompression.
  79264. gzopen returns NULL if the file could not be opened or if there was
  79265. insufficient memory to allocate the (de)compression state; errno
  79266. can be checked to distinguish the two cases (if errno is zero, the
  79267. zlib error is Z_MEM_ERROR). */
  79268. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79269. /*
  79270. gzdopen() associates a gzFile with the file descriptor fd. File
  79271. descriptors are obtained from calls like open, dup, creat, pipe or
  79272. fileno (in the file has been previously opened with fopen).
  79273. The mode parameter is as in gzopen.
  79274. The next call of gzclose on the returned gzFile will also close the
  79275. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79276. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79277. gzdopen returns NULL if there was insufficient memory to allocate
  79278. the (de)compression state.
  79279. */
  79280. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79281. /*
  79282. Dynamically update the compression level or strategy. See the description
  79283. of deflateInit2 for the meaning of these parameters.
  79284. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79285. opened for writing.
  79286. */
  79287. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79288. /*
  79289. Reads the given number of uncompressed bytes from the compressed file.
  79290. If the input file was not in gzip format, gzread copies the given number
  79291. of bytes into the buffer.
  79292. gzread returns the number of uncompressed bytes actually read (0 for
  79293. end of file, -1 for error). */
  79294. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79295. voidpc buf, unsigned len));
  79296. /*
  79297. Writes the given number of uncompressed bytes into the compressed file.
  79298. gzwrite returns the number of uncompressed bytes actually written
  79299. (0 in case of error).
  79300. */
  79301. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79302. /*
  79303. Converts, formats, and writes the args to the compressed file under
  79304. control of the format string, as in fprintf. gzprintf returns the number of
  79305. uncompressed bytes actually written (0 in case of error). The number of
  79306. uncompressed bytes written is limited to 4095. The caller should assure that
  79307. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79308. return an error (0) with nothing written. In this case, there may also be a
  79309. buffer overflow with unpredictable consequences, which is possible only if
  79310. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79311. because the secure snprintf() or vsnprintf() functions were not available.
  79312. */
  79313. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79314. /*
  79315. Writes the given null-terminated string to the compressed file, excluding
  79316. the terminating null character.
  79317. gzputs returns the number of characters written, or -1 in case of error.
  79318. */
  79319. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79320. /*
  79321. Reads bytes from the compressed file until len-1 characters are read, or
  79322. a newline character is read and transferred to buf, or an end-of-file
  79323. condition is encountered. The string is then terminated with a null
  79324. character.
  79325. gzgets returns buf, or Z_NULL in case of error.
  79326. */
  79327. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79328. /*
  79329. Writes c, converted to an unsigned char, into the compressed file.
  79330. gzputc returns the value that was written, or -1 in case of error.
  79331. */
  79332. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79333. /*
  79334. Reads one byte from the compressed file. gzgetc returns this byte
  79335. or -1 in case of end of file or error.
  79336. */
  79337. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79338. /*
  79339. Push one character back onto the stream to be read again later.
  79340. Only one character of push-back is allowed. gzungetc() returns the
  79341. character pushed, or -1 on failure. gzungetc() will fail if a
  79342. character has been pushed but not read yet, or if c is -1. The pushed
  79343. character will be discarded if the stream is repositioned with gzseek()
  79344. or gzrewind().
  79345. */
  79346. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79347. /*
  79348. Flushes all pending output into the compressed file. The parameter
  79349. flush is as in the deflate() function. The return value is the zlib
  79350. error number (see function gzerror below). gzflush returns Z_OK if
  79351. the flush parameter is Z_FINISH and all output could be flushed.
  79352. gzflush should be called only when strictly necessary because it can
  79353. degrade compression.
  79354. */
  79355. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79356. z_off_t offset, int whence));
  79357. /*
  79358. Sets the starting position for the next gzread or gzwrite on the
  79359. given compressed file. The offset represents a number of bytes in the
  79360. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79361. the value SEEK_END is not supported.
  79362. If the file is opened for reading, this function is emulated but can be
  79363. extremely slow. If the file is opened for writing, only forward seeks are
  79364. supported; gzseek then compresses a sequence of zeroes up to the new
  79365. starting position.
  79366. gzseek returns the resulting offset location as measured in bytes from
  79367. the beginning of the uncompressed stream, or -1 in case of error, in
  79368. particular if the file is opened for writing and the new starting position
  79369. would be before the current position.
  79370. */
  79371. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79372. /*
  79373. Rewinds the given file. This function is supported only for reading.
  79374. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79375. */
  79376. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79377. /*
  79378. Returns the starting position for the next gzread or gzwrite on the
  79379. given compressed file. This position represents a number of bytes in the
  79380. uncompressed data stream.
  79381. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79382. */
  79383. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79384. /*
  79385. Returns 1 when EOF has previously been detected reading the given
  79386. input stream, otherwise zero.
  79387. */
  79388. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79389. /*
  79390. Returns 1 if file is being read directly without decompression, otherwise
  79391. zero.
  79392. */
  79393. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79394. /*
  79395. Flushes all pending output if necessary, closes the compressed file
  79396. and deallocates all the (de)compression state. The return value is the zlib
  79397. error number (see function gzerror below).
  79398. */
  79399. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79400. /*
  79401. Returns the error message for the last error which occurred on the
  79402. given compressed file. errnum is set to zlib error number. If an
  79403. error occurred in the file system and not in the compression library,
  79404. errnum is set to Z_ERRNO and the application may consult errno
  79405. to get the exact error code.
  79406. */
  79407. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79408. /*
  79409. Clears the error and end-of-file flags for file. This is analogous to the
  79410. clearerr() function in stdio. This is useful for continuing to read a gzip
  79411. file that is being written concurrently.
  79412. */
  79413. /* checksum functions */
  79414. /*
  79415. These functions are not related to compression but are exported
  79416. anyway because they might be useful in applications using the
  79417. compression library.
  79418. */
  79419. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79420. /*
  79421. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79422. return the updated checksum. If buf is NULL, this function returns
  79423. the required initial value for the checksum.
  79424. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79425. much faster. Usage example:
  79426. uLong adler = adler32(0L, Z_NULL, 0);
  79427. while (read_buffer(buffer, length) != EOF) {
  79428. adler = adler32(adler, buffer, length);
  79429. }
  79430. if (adler != original_adler) error();
  79431. */
  79432. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79433. z_off_t len2));
  79434. /*
  79435. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79436. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79437. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79438. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79439. */
  79440. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79441. /*
  79442. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79443. updated CRC-32. If buf is NULL, this function returns the required initial
  79444. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79445. performed within this function so it shouldn't be done by the application.
  79446. Usage example:
  79447. uLong crc = crc32(0L, Z_NULL, 0);
  79448. while (read_buffer(buffer, length) != EOF) {
  79449. crc = crc32(crc, buffer, length);
  79450. }
  79451. if (crc != original_crc) error();
  79452. */
  79453. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79454. /*
  79455. Combine two CRC-32 check values into one. For two sequences of bytes,
  79456. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79457. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79458. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79459. len2.
  79460. */
  79461. /* various hacks, don't look :) */
  79462. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79463. * and the compiler's view of z_stream:
  79464. */
  79465. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79466. const char *version, int stream_size));
  79467. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79468. const char *version, int stream_size));
  79469. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79470. int windowBits, int memLevel,
  79471. int strategy, const char *version,
  79472. int stream_size));
  79473. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79474. const char *version, int stream_size));
  79475. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79476. unsigned char FAR *window,
  79477. const char *version,
  79478. int stream_size));
  79479. #define deflateInit(strm, level) \
  79480. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79481. #define inflateInit(strm) \
  79482. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79483. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79484. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79485. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79486. #define inflateInit2(strm, windowBits) \
  79487. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79488. #define inflateBackInit(strm, windowBits, window) \
  79489. inflateBackInit_((strm), (windowBits), (window), \
  79490. ZLIB_VERSION, sizeof(z_stream))
  79491. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79492. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79493. #endif
  79494. ZEXTERN const char * ZEXPORT zError OF((int));
  79495. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79496. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79497. #ifdef __cplusplus
  79498. //}
  79499. #endif
  79500. #endif /* ZLIB_H */
  79501. /*** End of inlined file: zlib.h ***/
  79502. #undef OS_CODE
  79503. #else
  79504. #include <zlib.h>
  79505. #endif
  79506. }
  79507. BEGIN_JUCE_NAMESPACE
  79508. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79509. {
  79510. public:
  79511. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79512. : data (0),
  79513. dataSize (0),
  79514. compLevel (compressionLevel),
  79515. strategy (0),
  79516. setParams (true),
  79517. streamIsValid (false),
  79518. finished (false),
  79519. shouldFinish (false)
  79520. {
  79521. using namespace zlibNamespace;
  79522. zerostruct (stream);
  79523. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79524. windowBits != 0 ? windowBits : MAX_WBITS,
  79525. 8, strategy) == Z_OK);
  79526. }
  79527. ~GZIPCompressorHelper()
  79528. {
  79529. using namespace zlibNamespace;
  79530. if (streamIsValid)
  79531. deflateEnd (&stream);
  79532. }
  79533. bool needsInput() const throw()
  79534. {
  79535. return dataSize <= 0;
  79536. }
  79537. void setInput (const uint8* const newData, const int size) throw()
  79538. {
  79539. data = newData;
  79540. dataSize = size;
  79541. }
  79542. int doNextBlock (uint8* const dest, const int destSize) throw()
  79543. {
  79544. using namespace zlibNamespace;
  79545. if (streamIsValid)
  79546. {
  79547. stream.next_in = const_cast <uint8*> (data);
  79548. stream.next_out = dest;
  79549. stream.avail_in = dataSize;
  79550. stream.avail_out = destSize;
  79551. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79552. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79553. setParams = false;
  79554. switch (result)
  79555. {
  79556. case Z_STREAM_END:
  79557. finished = true;
  79558. // Deliberate fall-through..
  79559. case Z_OK:
  79560. data += dataSize - stream.avail_in;
  79561. dataSize = stream.avail_in;
  79562. return destSize - stream.avail_out;
  79563. default:
  79564. break;
  79565. }
  79566. }
  79567. return 0;
  79568. }
  79569. enum { gzipCompBufferSize = 32768 };
  79570. private:
  79571. zlibNamespace::z_stream stream;
  79572. const uint8* data;
  79573. int dataSize, compLevel, strategy;
  79574. bool setParams, streamIsValid;
  79575. public:
  79576. bool finished, shouldFinish;
  79577. };
  79578. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79579. int compressionLevel,
  79580. const bool deleteDestStream,
  79581. const int windowBits)
  79582. : destStream (destStream_),
  79583. streamToDelete (deleteDestStream ? destStream_ : 0),
  79584. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79585. {
  79586. if (compressionLevel < 1 || compressionLevel > 9)
  79587. compressionLevel = -1;
  79588. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79589. }
  79590. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79591. {
  79592. flush();
  79593. }
  79594. void GZIPCompressorOutputStream::flush()
  79595. {
  79596. if (! helper->finished)
  79597. {
  79598. helper->shouldFinish = true;
  79599. while (! helper->finished)
  79600. doNextBlock();
  79601. }
  79602. destStream->flush();
  79603. }
  79604. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79605. {
  79606. if (! helper->finished)
  79607. {
  79608. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79609. while (! helper->needsInput())
  79610. {
  79611. if (! doNextBlock())
  79612. return false;
  79613. }
  79614. }
  79615. return true;
  79616. }
  79617. bool GZIPCompressorOutputStream::doNextBlock()
  79618. {
  79619. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79620. return len <= 0 || destStream->write (buffer, len);
  79621. }
  79622. int64 GZIPCompressorOutputStream::getPosition()
  79623. {
  79624. return destStream->getPosition();
  79625. }
  79626. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79627. {
  79628. jassertfalse; // can't do it!
  79629. return false;
  79630. }
  79631. END_JUCE_NAMESPACE
  79632. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79633. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79634. #if JUCE_MSVC
  79635. #pragma warning (push)
  79636. #pragma warning (disable: 4309 4305)
  79637. #endif
  79638. namespace zlibNamespace
  79639. {
  79640. #if JUCE_INCLUDE_ZLIB_CODE
  79641. #undef OS_CODE
  79642. #undef fdopen
  79643. #define ZLIB_INTERNAL
  79644. #define NO_DUMMY_DECL
  79645. /*** Start of inlined file: adler32.c ***/
  79646. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79647. #define ZLIB_INTERNAL
  79648. #define BASE 65521UL /* largest prime smaller than 65536 */
  79649. #define NMAX 5552
  79650. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79651. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79652. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79653. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79654. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79655. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79656. /* use NO_DIVIDE if your processor does not do division in hardware */
  79657. #ifdef NO_DIVIDE
  79658. # define MOD(a) \
  79659. do { \
  79660. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79661. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79662. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79663. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79664. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79665. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79666. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79667. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79668. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79669. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79670. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79671. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79672. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79673. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79674. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79675. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79676. if (a >= BASE) a -= BASE; \
  79677. } while (0)
  79678. # define MOD4(a) \
  79679. do { \
  79680. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79681. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79682. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79683. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79684. if (a >= BASE) a -= BASE; \
  79685. } while (0)
  79686. #else
  79687. # define MOD(a) a %= BASE
  79688. # define MOD4(a) a %= BASE
  79689. #endif
  79690. /* ========================================================================= */
  79691. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79692. {
  79693. unsigned long sum2;
  79694. unsigned n;
  79695. /* split Adler-32 into component sums */
  79696. sum2 = (adler >> 16) & 0xffff;
  79697. adler &= 0xffff;
  79698. /* in case user likes doing a byte at a time, keep it fast */
  79699. if (len == 1) {
  79700. adler += buf[0];
  79701. if (adler >= BASE)
  79702. adler -= BASE;
  79703. sum2 += adler;
  79704. if (sum2 >= BASE)
  79705. sum2 -= BASE;
  79706. return adler | (sum2 << 16);
  79707. }
  79708. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79709. if (buf == Z_NULL)
  79710. return 1L;
  79711. /* in case short lengths are provided, keep it somewhat fast */
  79712. if (len < 16) {
  79713. while (len--) {
  79714. adler += *buf++;
  79715. sum2 += adler;
  79716. }
  79717. if (adler >= BASE)
  79718. adler -= BASE;
  79719. MOD4(sum2); /* only added so many BASE's */
  79720. return adler | (sum2 << 16);
  79721. }
  79722. /* do length NMAX blocks -- requires just one modulo operation */
  79723. while (len >= NMAX) {
  79724. len -= NMAX;
  79725. n = NMAX / 16; /* NMAX is divisible by 16 */
  79726. do {
  79727. DO16(buf); /* 16 sums unrolled */
  79728. buf += 16;
  79729. } while (--n);
  79730. MOD(adler);
  79731. MOD(sum2);
  79732. }
  79733. /* do remaining bytes (less than NMAX, still just one modulo) */
  79734. if (len) { /* avoid modulos if none remaining */
  79735. while (len >= 16) {
  79736. len -= 16;
  79737. DO16(buf);
  79738. buf += 16;
  79739. }
  79740. while (len--) {
  79741. adler += *buf++;
  79742. sum2 += adler;
  79743. }
  79744. MOD(adler);
  79745. MOD(sum2);
  79746. }
  79747. /* return recombined sums */
  79748. return adler | (sum2 << 16);
  79749. }
  79750. /* ========================================================================= */
  79751. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79752. {
  79753. unsigned long sum1;
  79754. unsigned long sum2;
  79755. unsigned rem;
  79756. /* the derivation of this formula is left as an exercise for the reader */
  79757. rem = (unsigned)(len2 % BASE);
  79758. sum1 = adler1 & 0xffff;
  79759. sum2 = rem * sum1;
  79760. MOD(sum2);
  79761. sum1 += (adler2 & 0xffff) + BASE - 1;
  79762. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79763. if (sum1 > BASE) sum1 -= BASE;
  79764. if (sum1 > BASE) sum1 -= BASE;
  79765. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79766. if (sum2 > BASE) sum2 -= BASE;
  79767. return sum1 | (sum2 << 16);
  79768. }
  79769. /*** End of inlined file: adler32.c ***/
  79770. /*** Start of inlined file: compress.c ***/
  79771. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79772. #define ZLIB_INTERNAL
  79773. /* ===========================================================================
  79774. Compresses the source buffer into the destination buffer. The level
  79775. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79776. length of the source buffer. Upon entry, destLen is the total size of the
  79777. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79778. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79779. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79780. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79781. Z_STREAM_ERROR if the level parameter is invalid.
  79782. */
  79783. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79784. uLong sourceLen, int level)
  79785. {
  79786. z_stream stream;
  79787. int err;
  79788. stream.next_in = (Bytef*)source;
  79789. stream.avail_in = (uInt)sourceLen;
  79790. #ifdef MAXSEG_64K
  79791. /* Check for source > 64K on 16-bit machine: */
  79792. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79793. #endif
  79794. stream.next_out = dest;
  79795. stream.avail_out = (uInt)*destLen;
  79796. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79797. stream.zalloc = (alloc_func)0;
  79798. stream.zfree = (free_func)0;
  79799. stream.opaque = (voidpf)0;
  79800. err = deflateInit(&stream, level);
  79801. if (err != Z_OK) return err;
  79802. err = deflate(&stream, Z_FINISH);
  79803. if (err != Z_STREAM_END) {
  79804. deflateEnd(&stream);
  79805. return err == Z_OK ? Z_BUF_ERROR : err;
  79806. }
  79807. *destLen = stream.total_out;
  79808. err = deflateEnd(&stream);
  79809. return err;
  79810. }
  79811. /* ===========================================================================
  79812. */
  79813. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79814. {
  79815. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79816. }
  79817. /* ===========================================================================
  79818. If the default memLevel or windowBits for deflateInit() is changed, then
  79819. this function needs to be updated.
  79820. */
  79821. uLong ZEXPORT compressBound (uLong sourceLen)
  79822. {
  79823. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79824. }
  79825. /*** End of inlined file: compress.c ***/
  79826. #undef DO1
  79827. #undef DO8
  79828. /*** Start of inlined file: crc32.c ***/
  79829. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79830. /*
  79831. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79832. protection on the static variables used to control the first-use generation
  79833. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79834. first call get_crc_table() to initialize the tables before allowing more than
  79835. one thread to use crc32().
  79836. */
  79837. #ifdef MAKECRCH
  79838. # include <stdio.h>
  79839. # ifndef DYNAMIC_CRC_TABLE
  79840. # define DYNAMIC_CRC_TABLE
  79841. # endif /* !DYNAMIC_CRC_TABLE */
  79842. #endif /* MAKECRCH */
  79843. /*** Start of inlined file: zutil.h ***/
  79844. /* WARNING: this file should *not* be used by applications. It is
  79845. part of the implementation of the compression library and is
  79846. subject to change. Applications should only use zlib.h.
  79847. */
  79848. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79849. #ifndef ZUTIL_H
  79850. #define ZUTIL_H
  79851. #define ZLIB_INTERNAL
  79852. #ifdef STDC
  79853. # ifndef _WIN32_WCE
  79854. # include <stddef.h>
  79855. # endif
  79856. # include <string.h>
  79857. # include <stdlib.h>
  79858. #endif
  79859. #ifdef NO_ERRNO_H
  79860. # ifdef _WIN32_WCE
  79861. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79862. * errno. We define it as a global variable to simplify porting.
  79863. * Its value is always 0 and should not be used. We rename it to
  79864. * avoid conflict with other libraries that use the same workaround.
  79865. */
  79866. # define errno z_errno
  79867. # endif
  79868. extern int errno;
  79869. #else
  79870. # ifndef _WIN32_WCE
  79871. # include <errno.h>
  79872. # endif
  79873. #endif
  79874. #ifndef local
  79875. # define local static
  79876. #endif
  79877. /* compile with -Dlocal if your debugger can't find static symbols */
  79878. typedef unsigned char uch;
  79879. typedef uch FAR uchf;
  79880. typedef unsigned short ush;
  79881. typedef ush FAR ushf;
  79882. typedef unsigned long ulg;
  79883. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79884. /* (size given to avoid silly warnings with Visual C++) */
  79885. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79886. #define ERR_RETURN(strm,err) \
  79887. return (strm->msg = (char*)ERR_MSG(err), (err))
  79888. /* To be used only when the state is known to be valid */
  79889. /* common constants */
  79890. #ifndef DEF_WBITS
  79891. # define DEF_WBITS MAX_WBITS
  79892. #endif
  79893. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79894. #if MAX_MEM_LEVEL >= 8
  79895. # define DEF_MEM_LEVEL 8
  79896. #else
  79897. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79898. #endif
  79899. /* default memLevel */
  79900. #define STORED_BLOCK 0
  79901. #define STATIC_TREES 1
  79902. #define DYN_TREES 2
  79903. /* The three kinds of block type */
  79904. #define MIN_MATCH 3
  79905. #define MAX_MATCH 258
  79906. /* The minimum and maximum match lengths */
  79907. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79908. /* target dependencies */
  79909. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79910. # define OS_CODE 0x00
  79911. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79912. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79913. /* Allow compilation with ANSI keywords only enabled */
  79914. void _Cdecl farfree( void *block );
  79915. void *_Cdecl farmalloc( unsigned long nbytes );
  79916. # else
  79917. # include <alloc.h>
  79918. # endif
  79919. # else /* MSC or DJGPP */
  79920. # include <malloc.h>
  79921. # endif
  79922. #endif
  79923. #ifdef AMIGA
  79924. # define OS_CODE 0x01
  79925. #endif
  79926. #if defined(VAXC) || defined(VMS)
  79927. # define OS_CODE 0x02
  79928. # define F_OPEN(name, mode) \
  79929. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79930. #endif
  79931. #if defined(ATARI) || defined(atarist)
  79932. # define OS_CODE 0x05
  79933. #endif
  79934. #ifdef OS2
  79935. # define OS_CODE 0x06
  79936. # ifdef M_I86
  79937. #include <malloc.h>
  79938. # endif
  79939. #endif
  79940. #if defined(MACOS) || TARGET_OS_MAC
  79941. # define OS_CODE 0x07
  79942. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79943. # include <unix.h> /* for fdopen */
  79944. # else
  79945. # ifndef fdopen
  79946. # define fdopen(fd,mode) NULL /* No fdopen() */
  79947. # endif
  79948. # endif
  79949. #endif
  79950. #ifdef TOPS20
  79951. # define OS_CODE 0x0a
  79952. #endif
  79953. #ifdef WIN32
  79954. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79955. # define OS_CODE 0x0b
  79956. # endif
  79957. #endif
  79958. #ifdef __50SERIES /* Prime/PRIMOS */
  79959. # define OS_CODE 0x0f
  79960. #endif
  79961. #if defined(_BEOS_) || defined(RISCOS)
  79962. # define fdopen(fd,mode) NULL /* No fdopen() */
  79963. #endif
  79964. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79965. # if defined(_WIN32_WCE)
  79966. # define fdopen(fd,mode) NULL /* No fdopen() */
  79967. # ifndef _PTRDIFF_T_DEFINED
  79968. typedef int ptrdiff_t;
  79969. # define _PTRDIFF_T_DEFINED
  79970. # endif
  79971. # else
  79972. # define fdopen(fd,type) _fdopen(fd,type)
  79973. # endif
  79974. #endif
  79975. /* common defaults */
  79976. #ifndef OS_CODE
  79977. # define OS_CODE 0x03 /* assume Unix */
  79978. #endif
  79979. #ifndef F_OPEN
  79980. # define F_OPEN(name, mode) fopen((name), (mode))
  79981. #endif
  79982. /* functions */
  79983. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79984. # ifndef HAVE_VSNPRINTF
  79985. # define HAVE_VSNPRINTF
  79986. # endif
  79987. #endif
  79988. #if defined(__CYGWIN__)
  79989. # ifndef HAVE_VSNPRINTF
  79990. # define HAVE_VSNPRINTF
  79991. # endif
  79992. #endif
  79993. #ifndef HAVE_VSNPRINTF
  79994. # ifdef MSDOS
  79995. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79996. but for now we just assume it doesn't. */
  79997. # define NO_vsnprintf
  79998. # endif
  79999. # ifdef __TURBOC__
  80000. # define NO_vsnprintf
  80001. # endif
  80002. # ifdef WIN32
  80003. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80004. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80005. # define vsnprintf _vsnprintf
  80006. # endif
  80007. # endif
  80008. # ifdef __SASC
  80009. # define NO_vsnprintf
  80010. # endif
  80011. #endif
  80012. #ifdef VMS
  80013. # define NO_vsnprintf
  80014. #endif
  80015. #if defined(pyr)
  80016. # define NO_MEMCPY
  80017. #endif
  80018. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80019. /* Use our own functions for small and medium model with MSC <= 5.0.
  80020. * You may have to use the same strategy for Borland C (untested).
  80021. * The __SC__ check is for Symantec.
  80022. */
  80023. # define NO_MEMCPY
  80024. #endif
  80025. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80026. # define HAVE_MEMCPY
  80027. #endif
  80028. #ifdef HAVE_MEMCPY
  80029. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80030. # define zmemcpy _fmemcpy
  80031. # define zmemcmp _fmemcmp
  80032. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80033. # else
  80034. # define zmemcpy memcpy
  80035. # define zmemcmp memcmp
  80036. # define zmemzero(dest, len) memset(dest, 0, len)
  80037. # endif
  80038. #else
  80039. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80040. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80041. extern void zmemzero OF((Bytef* dest, uInt len));
  80042. #endif
  80043. /* Diagnostic functions */
  80044. #ifdef DEBUG
  80045. # include <stdio.h>
  80046. extern int z_verbose;
  80047. extern void z_error OF((const char *m));
  80048. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80049. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80050. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80051. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80052. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80053. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80054. #else
  80055. # define Assert(cond,msg)
  80056. # define Trace(x)
  80057. # define Tracev(x)
  80058. # define Tracevv(x)
  80059. # define Tracec(c,x)
  80060. # define Tracecv(c,x)
  80061. #endif
  80062. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80063. void zcfree OF((voidpf opaque, voidpf ptr));
  80064. #define ZALLOC(strm, items, size) \
  80065. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80066. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80067. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80068. #endif /* ZUTIL_H */
  80069. /*** End of inlined file: zutil.h ***/
  80070. /* for STDC and FAR definitions */
  80071. #define local static
  80072. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80073. #ifndef NOBYFOUR
  80074. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80075. # include <limits.h>
  80076. # define BYFOUR
  80077. # if (UINT_MAX == 0xffffffffUL)
  80078. typedef unsigned int u4;
  80079. # else
  80080. # if (ULONG_MAX == 0xffffffffUL)
  80081. typedef unsigned long u4;
  80082. # else
  80083. # if (USHRT_MAX == 0xffffffffUL)
  80084. typedef unsigned short u4;
  80085. # else
  80086. # undef BYFOUR /* can't find a four-byte integer type! */
  80087. # endif
  80088. # endif
  80089. # endif
  80090. # endif /* STDC */
  80091. #endif /* !NOBYFOUR */
  80092. /* Definitions for doing the crc four data bytes at a time. */
  80093. #ifdef BYFOUR
  80094. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80095. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80096. local unsigned long crc32_little OF((unsigned long,
  80097. const unsigned char FAR *, unsigned));
  80098. local unsigned long crc32_big OF((unsigned long,
  80099. const unsigned char FAR *, unsigned));
  80100. # define TBLS 8
  80101. #else
  80102. # define TBLS 1
  80103. #endif /* BYFOUR */
  80104. /* Local functions for crc concatenation */
  80105. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80106. unsigned long vec));
  80107. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80108. #ifdef DYNAMIC_CRC_TABLE
  80109. local volatile int crc_table_empty = 1;
  80110. local unsigned long FAR crc_table[TBLS][256];
  80111. local void make_crc_table OF((void));
  80112. #ifdef MAKECRCH
  80113. local void write_table OF((FILE *, const unsigned long FAR *));
  80114. #endif /* MAKECRCH */
  80115. /*
  80116. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80117. 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.
  80118. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80119. with the lowest powers in the most significant bit. Then adding polynomials
  80120. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80121. one. If we call the above polynomial p, and represent a byte as the
  80122. polynomial q, also with the lowest power in the most significant bit (so the
  80123. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80124. where a mod b means the remainder after dividing a by b.
  80125. This calculation is done using the shift-register method of multiplying and
  80126. taking the remainder. The register is initialized to zero, and for each
  80127. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80128. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80129. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80130. out is a one). We start with the highest power (least significant bit) of
  80131. q and repeat for all eight bits of q.
  80132. The first table is simply the CRC of all possible eight bit values. This is
  80133. all the information needed to generate CRCs on data a byte at a time for all
  80134. combinations of CRC register values and incoming bytes. The remaining tables
  80135. allow for word-at-a-time CRC calculation for both big-endian and little-
  80136. endian machines, where a word is four bytes.
  80137. */
  80138. local void make_crc_table()
  80139. {
  80140. unsigned long c;
  80141. int n, k;
  80142. unsigned long poly; /* polynomial exclusive-or pattern */
  80143. /* terms of polynomial defining this crc (except x^32): */
  80144. static volatile int first = 1; /* flag to limit concurrent making */
  80145. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80146. /* See if another task is already doing this (not thread-safe, but better
  80147. than nothing -- significantly reduces duration of vulnerability in
  80148. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80149. if (first) {
  80150. first = 0;
  80151. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80152. poly = 0UL;
  80153. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80154. poly |= 1UL << (31 - p[n]);
  80155. /* generate a crc for every 8-bit value */
  80156. for (n = 0; n < 256; n++) {
  80157. c = (unsigned long)n;
  80158. for (k = 0; k < 8; k++)
  80159. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80160. crc_table[0][n] = c;
  80161. }
  80162. #ifdef BYFOUR
  80163. /* generate crc for each value followed by one, two, and three zeros,
  80164. and then the byte reversal of those as well as the first table */
  80165. for (n = 0; n < 256; n++) {
  80166. c = crc_table[0][n];
  80167. crc_table[4][n] = REV(c);
  80168. for (k = 1; k < 4; k++) {
  80169. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80170. crc_table[k][n] = c;
  80171. crc_table[k + 4][n] = REV(c);
  80172. }
  80173. }
  80174. #endif /* BYFOUR */
  80175. crc_table_empty = 0;
  80176. }
  80177. else { /* not first */
  80178. /* wait for the other guy to finish (not efficient, but rare) */
  80179. while (crc_table_empty)
  80180. ;
  80181. }
  80182. #ifdef MAKECRCH
  80183. /* write out CRC tables to crc32.h */
  80184. {
  80185. FILE *out;
  80186. out = fopen("crc32.h", "w");
  80187. if (out == NULL) return;
  80188. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80189. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80190. fprintf(out, "local const unsigned long FAR ");
  80191. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80192. write_table(out, crc_table[0]);
  80193. # ifdef BYFOUR
  80194. fprintf(out, "#ifdef BYFOUR\n");
  80195. for (k = 1; k < 8; k++) {
  80196. fprintf(out, " },\n {\n");
  80197. write_table(out, crc_table[k]);
  80198. }
  80199. fprintf(out, "#endif\n");
  80200. # endif /* BYFOUR */
  80201. fprintf(out, " }\n};\n");
  80202. fclose(out);
  80203. }
  80204. #endif /* MAKECRCH */
  80205. }
  80206. #ifdef MAKECRCH
  80207. local void write_table(out, table)
  80208. FILE *out;
  80209. const unsigned long FAR *table;
  80210. {
  80211. int n;
  80212. for (n = 0; n < 256; n++)
  80213. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80214. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80215. }
  80216. #endif /* MAKECRCH */
  80217. #else /* !DYNAMIC_CRC_TABLE */
  80218. /* ========================================================================
  80219. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80220. */
  80221. /*** Start of inlined file: crc32.h ***/
  80222. local const unsigned long FAR crc_table[TBLS][256] =
  80223. {
  80224. {
  80225. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80226. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80227. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80228. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80229. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80230. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80231. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80232. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80233. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80234. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80235. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80236. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80237. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80238. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80239. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80240. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80241. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80242. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80243. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80244. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80245. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80246. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80247. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80248. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80249. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80250. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80251. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80252. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80253. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80254. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80255. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80256. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80257. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80258. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80259. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80260. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80261. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80262. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80263. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80264. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80265. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80266. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80267. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80268. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80269. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80270. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80271. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80272. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80273. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80274. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80275. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80276. 0x2d02ef8dUL
  80277. #ifdef BYFOUR
  80278. },
  80279. {
  80280. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80281. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80282. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80283. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80284. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80285. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80286. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80287. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80288. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80289. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80290. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80291. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80292. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80293. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80294. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80295. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80296. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80297. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80298. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80299. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80300. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80301. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80302. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80303. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80304. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80305. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80306. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80307. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80308. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80309. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80310. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80311. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80312. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80313. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80314. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80315. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80316. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80317. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80318. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80319. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80320. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80321. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80322. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80323. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80324. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80325. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80326. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80327. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80328. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80329. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80330. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80331. 0x9324fd72UL
  80332. },
  80333. {
  80334. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80335. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80336. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80337. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80338. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80339. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80340. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80341. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80342. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80343. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80344. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80345. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80346. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80347. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80348. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80349. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80350. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80351. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80352. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80353. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80354. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80355. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80356. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80357. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80358. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80359. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80360. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80361. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80362. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80363. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80364. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80365. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80366. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80367. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80368. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80369. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80370. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80371. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80372. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80373. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80374. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80375. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80376. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80377. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80378. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80379. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80380. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80381. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80382. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80383. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80384. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80385. 0xbe9834edUL
  80386. },
  80387. {
  80388. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80389. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80390. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80391. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80392. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80393. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80394. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80395. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80396. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80397. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80398. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80399. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80400. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80401. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80402. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80403. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80404. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80405. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80406. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80407. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80408. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80409. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80410. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80411. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80412. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80413. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80414. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80415. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80416. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80417. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80418. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80419. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80420. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80421. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80422. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80423. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80424. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80425. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80426. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80427. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80428. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80429. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80430. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80431. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80432. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80433. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80434. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80435. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80436. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80437. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80438. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80439. 0xde0506f1UL
  80440. },
  80441. {
  80442. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80443. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80444. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80445. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80446. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80447. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80448. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80449. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80450. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80451. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80452. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80453. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80454. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80455. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80456. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80457. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80458. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80459. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80460. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80461. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80462. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80463. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80464. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80465. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80466. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80467. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80468. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80469. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80470. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80471. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80472. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80473. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80474. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80475. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80476. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80477. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80478. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80479. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80480. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80481. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80482. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80483. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80484. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80485. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80486. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80487. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80488. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80489. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80490. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80491. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80492. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80493. 0x8def022dUL
  80494. },
  80495. {
  80496. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80497. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80498. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80499. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80500. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80501. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80502. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80503. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80504. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80505. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80506. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80507. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80508. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80509. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80510. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80511. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80512. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80513. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80514. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80515. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80516. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80517. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80518. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80519. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80520. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80521. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80522. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80523. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80524. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80525. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80526. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80527. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80528. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80529. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80530. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80531. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80532. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80533. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80534. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80535. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80536. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80537. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80538. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80539. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80540. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80541. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80542. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80543. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80544. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80545. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80546. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80547. 0x72fd2493UL
  80548. },
  80549. {
  80550. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80551. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80552. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80553. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80554. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80555. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80556. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80557. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80558. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80559. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80560. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80561. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80562. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80563. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80564. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80565. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80566. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80567. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80568. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80569. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80570. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80571. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80572. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80573. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80574. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80575. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80576. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80577. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80578. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80579. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80580. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80581. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80582. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80583. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80584. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80585. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80586. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80587. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80588. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80589. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80590. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80591. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80592. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80593. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80594. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80595. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80596. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80597. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80598. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80599. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80600. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80601. 0xed3498beUL
  80602. },
  80603. {
  80604. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80605. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80606. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80607. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80608. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80609. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80610. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80611. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80612. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80613. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80614. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80615. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80616. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80617. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80618. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80619. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80620. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80621. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80622. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80623. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80624. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80625. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80626. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80627. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80628. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80629. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80630. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80631. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80632. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80633. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80634. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80635. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80636. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80637. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80638. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80639. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80640. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80641. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80642. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80643. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80644. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80645. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80646. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80647. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80648. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80649. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80650. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80651. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80652. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80653. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80654. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80655. 0xf10605deUL
  80656. #endif
  80657. }
  80658. };
  80659. /*** End of inlined file: crc32.h ***/
  80660. #endif /* DYNAMIC_CRC_TABLE */
  80661. /* =========================================================================
  80662. * This function can be used by asm versions of crc32()
  80663. */
  80664. const unsigned long FAR * ZEXPORT get_crc_table()
  80665. {
  80666. #ifdef DYNAMIC_CRC_TABLE
  80667. if (crc_table_empty)
  80668. make_crc_table();
  80669. #endif /* DYNAMIC_CRC_TABLE */
  80670. return (const unsigned long FAR *)crc_table;
  80671. }
  80672. /* ========================================================================= */
  80673. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80674. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80675. /* ========================================================================= */
  80676. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80677. {
  80678. if (buf == Z_NULL) return 0UL;
  80679. #ifdef DYNAMIC_CRC_TABLE
  80680. if (crc_table_empty)
  80681. make_crc_table();
  80682. #endif /* DYNAMIC_CRC_TABLE */
  80683. #ifdef BYFOUR
  80684. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80685. u4 endian;
  80686. endian = 1;
  80687. if (*((unsigned char *)(&endian)))
  80688. return crc32_little(crc, buf, len);
  80689. else
  80690. return crc32_big(crc, buf, len);
  80691. }
  80692. #endif /* BYFOUR */
  80693. crc = crc ^ 0xffffffffUL;
  80694. while (len >= 8) {
  80695. DO8;
  80696. len -= 8;
  80697. }
  80698. if (len) do {
  80699. DO1;
  80700. } while (--len);
  80701. return crc ^ 0xffffffffUL;
  80702. }
  80703. #ifdef BYFOUR
  80704. /* ========================================================================= */
  80705. #define DOLIT4 c ^= *buf4++; \
  80706. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80707. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80708. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80709. /* ========================================================================= */
  80710. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80711. {
  80712. register u4 c;
  80713. register const u4 FAR *buf4;
  80714. c = (u4)crc;
  80715. c = ~c;
  80716. while (len && ((ptrdiff_t)buf & 3)) {
  80717. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80718. len--;
  80719. }
  80720. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80721. while (len >= 32) {
  80722. DOLIT32;
  80723. len -= 32;
  80724. }
  80725. while (len >= 4) {
  80726. DOLIT4;
  80727. len -= 4;
  80728. }
  80729. buf = (const unsigned char FAR *)buf4;
  80730. if (len) do {
  80731. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80732. } while (--len);
  80733. c = ~c;
  80734. return (unsigned long)c;
  80735. }
  80736. /* ========================================================================= */
  80737. #define DOBIG4 c ^= *++buf4; \
  80738. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80739. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80740. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80741. /* ========================================================================= */
  80742. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80743. {
  80744. register u4 c;
  80745. register const u4 FAR *buf4;
  80746. c = REV((u4)crc);
  80747. c = ~c;
  80748. while (len && ((ptrdiff_t)buf & 3)) {
  80749. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80750. len--;
  80751. }
  80752. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80753. buf4--;
  80754. while (len >= 32) {
  80755. DOBIG32;
  80756. len -= 32;
  80757. }
  80758. while (len >= 4) {
  80759. DOBIG4;
  80760. len -= 4;
  80761. }
  80762. buf4++;
  80763. buf = (const unsigned char FAR *)buf4;
  80764. if (len) do {
  80765. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80766. } while (--len);
  80767. c = ~c;
  80768. return (unsigned long)(REV(c));
  80769. }
  80770. #endif /* BYFOUR */
  80771. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80772. /* ========================================================================= */
  80773. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80774. {
  80775. unsigned long sum;
  80776. sum = 0;
  80777. while (vec) {
  80778. if (vec & 1)
  80779. sum ^= *mat;
  80780. vec >>= 1;
  80781. mat++;
  80782. }
  80783. return sum;
  80784. }
  80785. /* ========================================================================= */
  80786. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80787. {
  80788. int n;
  80789. for (n = 0; n < GF2_DIM; n++)
  80790. square[n] = gf2_matrix_times(mat, mat[n]);
  80791. }
  80792. /* ========================================================================= */
  80793. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80794. {
  80795. int n;
  80796. unsigned long row;
  80797. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80798. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80799. /* degenerate case */
  80800. if (len2 == 0)
  80801. return crc1;
  80802. /* put operator for one zero bit in odd */
  80803. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80804. row = 1;
  80805. for (n = 1; n < GF2_DIM; n++) {
  80806. odd[n] = row;
  80807. row <<= 1;
  80808. }
  80809. /* put operator for two zero bits in even */
  80810. gf2_matrix_square(even, odd);
  80811. /* put operator for four zero bits in odd */
  80812. gf2_matrix_square(odd, even);
  80813. /* apply len2 zeros to crc1 (first square will put the operator for one
  80814. zero byte, eight zero bits, in even) */
  80815. do {
  80816. /* apply zeros operator for this bit of len2 */
  80817. gf2_matrix_square(even, odd);
  80818. if (len2 & 1)
  80819. crc1 = gf2_matrix_times(even, crc1);
  80820. len2 >>= 1;
  80821. /* if no more bits set, then done */
  80822. if (len2 == 0)
  80823. break;
  80824. /* another iteration of the loop with odd and even swapped */
  80825. gf2_matrix_square(odd, even);
  80826. if (len2 & 1)
  80827. crc1 = gf2_matrix_times(odd, crc1);
  80828. len2 >>= 1;
  80829. /* if no more bits set, then done */
  80830. } while (len2 != 0);
  80831. /* return combined crc */
  80832. crc1 ^= crc2;
  80833. return crc1;
  80834. }
  80835. /*** End of inlined file: crc32.c ***/
  80836. /*** Start of inlined file: deflate.c ***/
  80837. /*
  80838. * ALGORITHM
  80839. *
  80840. * The "deflation" process depends on being able to identify portions
  80841. * of the input text which are identical to earlier input (within a
  80842. * sliding window trailing behind the input currently being processed).
  80843. *
  80844. * The most straightforward technique turns out to be the fastest for
  80845. * most input files: try all possible matches and select the longest.
  80846. * The key feature of this algorithm is that insertions into the string
  80847. * dictionary are very simple and thus fast, and deletions are avoided
  80848. * completely. Insertions are performed at each input character, whereas
  80849. * string matches are performed only when the previous match ends. So it
  80850. * is preferable to spend more time in matches to allow very fast string
  80851. * insertions and avoid deletions. The matching algorithm for small
  80852. * strings is inspired from that of Rabin & Karp. A brute force approach
  80853. * is used to find longer strings when a small match has been found.
  80854. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80855. * (by Leonid Broukhis).
  80856. * A previous version of this file used a more sophisticated algorithm
  80857. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80858. * time, but has a larger average cost, uses more memory and is patented.
  80859. * However the F&G algorithm may be faster for some highly redundant
  80860. * files if the parameter max_chain_length (described below) is too large.
  80861. *
  80862. * ACKNOWLEDGEMENTS
  80863. *
  80864. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80865. * I found it in 'freeze' written by Leonid Broukhis.
  80866. * Thanks to many people for bug reports and testing.
  80867. *
  80868. * REFERENCES
  80869. *
  80870. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80871. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80872. *
  80873. * A description of the Rabin and Karp algorithm is given in the book
  80874. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80875. *
  80876. * Fiala,E.R., and Greene,D.H.
  80877. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80878. *
  80879. */
  80880. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80881. /*** Start of inlined file: deflate.h ***/
  80882. /* WARNING: this file should *not* be used by applications. It is
  80883. part of the implementation of the compression library and is
  80884. subject to change. Applications should only use zlib.h.
  80885. */
  80886. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80887. #ifndef DEFLATE_H
  80888. #define DEFLATE_H
  80889. /* define NO_GZIP when compiling if you want to disable gzip header and
  80890. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80891. the crc code when it is not needed. For shared libraries, gzip encoding
  80892. should be left enabled. */
  80893. #ifndef NO_GZIP
  80894. # define GZIP
  80895. #endif
  80896. #define NO_DUMMY_DECL
  80897. /* ===========================================================================
  80898. * Internal compression state.
  80899. */
  80900. #define LENGTH_CODES 29
  80901. /* number of length codes, not counting the special END_BLOCK code */
  80902. #define LITERALS 256
  80903. /* number of literal bytes 0..255 */
  80904. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80905. /* number of Literal or Length codes, including the END_BLOCK code */
  80906. #define D_CODES 30
  80907. /* number of distance codes */
  80908. #define BL_CODES 19
  80909. /* number of codes used to transfer the bit lengths */
  80910. #define HEAP_SIZE (2*L_CODES+1)
  80911. /* maximum heap size */
  80912. #define MAX_BITS 15
  80913. /* All codes must not exceed MAX_BITS bits */
  80914. #define INIT_STATE 42
  80915. #define EXTRA_STATE 69
  80916. #define NAME_STATE 73
  80917. #define COMMENT_STATE 91
  80918. #define HCRC_STATE 103
  80919. #define BUSY_STATE 113
  80920. #define FINISH_STATE 666
  80921. /* Stream status */
  80922. /* Data structure describing a single value and its code string. */
  80923. typedef struct ct_data_s {
  80924. union {
  80925. ush freq; /* frequency count */
  80926. ush code; /* bit string */
  80927. } fc;
  80928. union {
  80929. ush dad; /* father node in Huffman tree */
  80930. ush len; /* length of bit string */
  80931. } dl;
  80932. } FAR ct_data;
  80933. #define Freq fc.freq
  80934. #define Code fc.code
  80935. #define Dad dl.dad
  80936. #define Len dl.len
  80937. typedef struct static_tree_desc_s static_tree_desc;
  80938. typedef struct tree_desc_s {
  80939. ct_data *dyn_tree; /* the dynamic tree */
  80940. int max_code; /* largest code with non zero frequency */
  80941. static_tree_desc *stat_desc; /* the corresponding static tree */
  80942. } FAR tree_desc;
  80943. typedef ush Pos;
  80944. typedef Pos FAR Posf;
  80945. typedef unsigned IPos;
  80946. /* A Pos is an index in the character window. We use short instead of int to
  80947. * save space in the various tables. IPos is used only for parameter passing.
  80948. */
  80949. typedef struct internal_state {
  80950. z_streamp strm; /* pointer back to this zlib stream */
  80951. int status; /* as the name implies */
  80952. Bytef *pending_buf; /* output still pending */
  80953. ulg pending_buf_size; /* size of pending_buf */
  80954. Bytef *pending_out; /* next pending byte to output to the stream */
  80955. uInt pending; /* nb of bytes in the pending buffer */
  80956. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80957. gz_headerp gzhead; /* gzip header information to write */
  80958. uInt gzindex; /* where in extra, name, or comment */
  80959. Byte method; /* STORED (for zip only) or DEFLATED */
  80960. int last_flush; /* value of flush param for previous deflate call */
  80961. /* used by deflate.c: */
  80962. uInt w_size; /* LZ77 window size (32K by default) */
  80963. uInt w_bits; /* log2(w_size) (8..16) */
  80964. uInt w_mask; /* w_size - 1 */
  80965. Bytef *window;
  80966. /* Sliding window. Input bytes are read into the second half of the window,
  80967. * and move to the first half later to keep a dictionary of at least wSize
  80968. * bytes. With this organization, matches are limited to a distance of
  80969. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80970. * performed with a length multiple of the block size. Also, it limits
  80971. * the window size to 64K, which is quite useful on MSDOS.
  80972. * To do: use the user input buffer as sliding window.
  80973. */
  80974. ulg window_size;
  80975. /* Actual size of window: 2*wSize, except when the user input buffer
  80976. * is directly used as sliding window.
  80977. */
  80978. Posf *prev;
  80979. /* Link to older string with same hash index. To limit the size of this
  80980. * array to 64K, this link is maintained only for the last 32K strings.
  80981. * An index in this array is thus a window index modulo 32K.
  80982. */
  80983. Posf *head; /* Heads of the hash chains or NIL. */
  80984. uInt ins_h; /* hash index of string to be inserted */
  80985. uInt hash_size; /* number of elements in hash table */
  80986. uInt hash_bits; /* log2(hash_size) */
  80987. uInt hash_mask; /* hash_size-1 */
  80988. uInt hash_shift;
  80989. /* Number of bits by which ins_h must be shifted at each input
  80990. * step. It must be such that after MIN_MATCH steps, the oldest
  80991. * byte no longer takes part in the hash key, that is:
  80992. * hash_shift * MIN_MATCH >= hash_bits
  80993. */
  80994. long block_start;
  80995. /* Window position at the beginning of the current output block. Gets
  80996. * negative when the window is moved backwards.
  80997. */
  80998. uInt match_length; /* length of best match */
  80999. IPos prev_match; /* previous match */
  81000. int match_available; /* set if previous match exists */
  81001. uInt strstart; /* start of string to insert */
  81002. uInt match_start; /* start of matching string */
  81003. uInt lookahead; /* number of valid bytes ahead in window */
  81004. uInt prev_length;
  81005. /* Length of the best match at previous step. Matches not greater than this
  81006. * are discarded. This is used in the lazy match evaluation.
  81007. */
  81008. uInt max_chain_length;
  81009. /* To speed up deflation, hash chains are never searched beyond this
  81010. * length. A higher limit improves compression ratio but degrades the
  81011. * speed.
  81012. */
  81013. uInt max_lazy_match;
  81014. /* Attempt to find a better match only when the current match is strictly
  81015. * smaller than this value. This mechanism is used only for compression
  81016. * levels >= 4.
  81017. */
  81018. # define max_insert_length max_lazy_match
  81019. /* Insert new strings in the hash table only if the match length is not
  81020. * greater than this length. This saves time but degrades compression.
  81021. * max_insert_length is used only for compression levels <= 3.
  81022. */
  81023. int level; /* compression level (1..9) */
  81024. int strategy; /* favor or force Huffman coding*/
  81025. uInt good_match;
  81026. /* Use a faster search when the previous match is longer than this */
  81027. int nice_match; /* Stop searching when current match exceeds this */
  81028. /* used by trees.c: */
  81029. /* Didn't use ct_data typedef below to supress compiler warning */
  81030. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81031. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81032. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81033. struct tree_desc_s l_desc; /* desc. for literal tree */
  81034. struct tree_desc_s d_desc; /* desc. for distance tree */
  81035. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81036. ush bl_count[MAX_BITS+1];
  81037. /* number of codes at each bit length for an optimal tree */
  81038. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81039. int heap_len; /* number of elements in the heap */
  81040. int heap_max; /* element of largest frequency */
  81041. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81042. * The same heap array is used to build all trees.
  81043. */
  81044. uch depth[2*L_CODES+1];
  81045. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81046. */
  81047. uchf *l_buf; /* buffer for literals or lengths */
  81048. uInt lit_bufsize;
  81049. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81050. * limiting lit_bufsize to 64K:
  81051. * - frequencies can be kept in 16 bit counters
  81052. * - if compression is not successful for the first block, all input
  81053. * data is still in the window so we can still emit a stored block even
  81054. * when input comes from standard input. (This can also be done for
  81055. * all blocks if lit_bufsize is not greater than 32K.)
  81056. * - if compression is not successful for a file smaller than 64K, we can
  81057. * even emit a stored file instead of a stored block (saving 5 bytes).
  81058. * This is applicable only for zip (not gzip or zlib).
  81059. * - creating new Huffman trees less frequently may not provide fast
  81060. * adaptation to changes in the input data statistics. (Take for
  81061. * example a binary file with poorly compressible code followed by
  81062. * a highly compressible string table.) Smaller buffer sizes give
  81063. * fast adaptation but have of course the overhead of transmitting
  81064. * trees more frequently.
  81065. * - I can't count above 4
  81066. */
  81067. uInt last_lit; /* running index in l_buf */
  81068. ushf *d_buf;
  81069. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81070. * the same number of elements. To use different lengths, an extra flag
  81071. * array would be necessary.
  81072. */
  81073. ulg opt_len; /* bit length of current block with optimal trees */
  81074. ulg static_len; /* bit length of current block with static trees */
  81075. uInt matches; /* number of string matches in current block */
  81076. int last_eob_len; /* bit length of EOB code for last block */
  81077. #ifdef DEBUG
  81078. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81079. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81080. #endif
  81081. ush bi_buf;
  81082. /* Output buffer. bits are inserted starting at the bottom (least
  81083. * significant bits).
  81084. */
  81085. int bi_valid;
  81086. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81087. * are always zero.
  81088. */
  81089. } FAR deflate_state;
  81090. /* Output a byte on the stream.
  81091. * IN assertion: there is enough room in pending_buf.
  81092. */
  81093. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81094. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81095. /* Minimum amount of lookahead, except at the end of the input file.
  81096. * See deflate.c for comments about the MIN_MATCH+1.
  81097. */
  81098. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81099. /* In order to simplify the code, particularly on 16 bit machines, match
  81100. * distances are limited to MAX_DIST instead of WSIZE.
  81101. */
  81102. /* in trees.c */
  81103. void _tr_init OF((deflate_state *s));
  81104. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81105. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81106. int eof));
  81107. void _tr_align OF((deflate_state *s));
  81108. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81109. int eof));
  81110. #define d_code(dist) \
  81111. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81112. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81113. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81114. * used.
  81115. */
  81116. #ifndef DEBUG
  81117. /* Inline versions of _tr_tally for speed: */
  81118. #if defined(GEN_TREES_H) || !defined(STDC)
  81119. extern uch _length_code[];
  81120. extern uch _dist_code[];
  81121. #else
  81122. extern const uch _length_code[];
  81123. extern const uch _dist_code[];
  81124. #endif
  81125. # define _tr_tally_lit(s, c, flush) \
  81126. { uch cc = (c); \
  81127. s->d_buf[s->last_lit] = 0; \
  81128. s->l_buf[s->last_lit++] = cc; \
  81129. s->dyn_ltree[cc].Freq++; \
  81130. flush = (s->last_lit == s->lit_bufsize-1); \
  81131. }
  81132. # define _tr_tally_dist(s, distance, length, flush) \
  81133. { uch len = (length); \
  81134. ush dist = (distance); \
  81135. s->d_buf[s->last_lit] = dist; \
  81136. s->l_buf[s->last_lit++] = len; \
  81137. dist--; \
  81138. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81139. s->dyn_dtree[d_code(dist)].Freq++; \
  81140. flush = (s->last_lit == s->lit_bufsize-1); \
  81141. }
  81142. #else
  81143. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81144. # define _tr_tally_dist(s, distance, length, flush) \
  81145. flush = _tr_tally(s, distance, length)
  81146. #endif
  81147. #endif /* DEFLATE_H */
  81148. /*** End of inlined file: deflate.h ***/
  81149. const char deflate_copyright[] =
  81150. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81151. /*
  81152. If you use the zlib library in a product, an acknowledgment is welcome
  81153. in the documentation of your product. If for some reason you cannot
  81154. include such an acknowledgment, I would appreciate that you keep this
  81155. copyright string in the executable of your product.
  81156. */
  81157. /* ===========================================================================
  81158. * Function prototypes.
  81159. */
  81160. typedef enum {
  81161. need_more, /* block not completed, need more input or more output */
  81162. block_done, /* block flush performed */
  81163. finish_started, /* finish started, need only more output at next deflate */
  81164. finish_done /* finish done, accept no more input or output */
  81165. } block_state;
  81166. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81167. /* Compression function. Returns the block state after the call. */
  81168. local void fill_window OF((deflate_state *s));
  81169. local block_state deflate_stored OF((deflate_state *s, int flush));
  81170. local block_state deflate_fast OF((deflate_state *s, int flush));
  81171. #ifndef FASTEST
  81172. local block_state deflate_slow OF((deflate_state *s, int flush));
  81173. #endif
  81174. local void lm_init OF((deflate_state *s));
  81175. local void putShortMSB OF((deflate_state *s, uInt b));
  81176. local void flush_pending OF((z_streamp strm));
  81177. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81178. #ifndef FASTEST
  81179. #ifdef ASMV
  81180. void match_init OF((void)); /* asm code initialization */
  81181. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81182. #else
  81183. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81184. #endif
  81185. #endif
  81186. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81187. #ifdef DEBUG
  81188. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81189. int length));
  81190. #endif
  81191. /* ===========================================================================
  81192. * Local data
  81193. */
  81194. #define NIL 0
  81195. /* Tail of hash chains */
  81196. #ifndef TOO_FAR
  81197. # define TOO_FAR 4096
  81198. #endif
  81199. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81200. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81201. /* Minimum amount of lookahead, except at the end of the input file.
  81202. * See deflate.c for comments about the MIN_MATCH+1.
  81203. */
  81204. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81205. * the desired pack level (0..9). The values given below have been tuned to
  81206. * exclude worst case performance for pathological files. Better values may be
  81207. * found for specific files.
  81208. */
  81209. typedef struct config_s {
  81210. ush good_length; /* reduce lazy search above this match length */
  81211. ush max_lazy; /* do not perform lazy search above this match length */
  81212. ush nice_length; /* quit search above this match length */
  81213. ush max_chain;
  81214. compress_func func;
  81215. } config;
  81216. #ifdef FASTEST
  81217. local const config configuration_table[2] = {
  81218. /* good lazy nice chain */
  81219. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81220. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81221. #else
  81222. local const config configuration_table[10] = {
  81223. /* good lazy nice chain */
  81224. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81225. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81226. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81227. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81228. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81229. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81230. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81231. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81232. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81233. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81234. #endif
  81235. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81236. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81237. * meaning.
  81238. */
  81239. #define EQUAL 0
  81240. /* result of memcmp for equal strings */
  81241. #ifndef NO_DUMMY_DECL
  81242. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81243. #endif
  81244. /* ===========================================================================
  81245. * Update a hash value with the given input byte
  81246. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81247. * input characters, so that a running hash key can be computed from the
  81248. * previous key instead of complete recalculation each time.
  81249. */
  81250. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81251. /* ===========================================================================
  81252. * Insert string str in the dictionary and set match_head to the previous head
  81253. * of the hash chain (the most recent string with same hash key). Return
  81254. * the previous length of the hash chain.
  81255. * If this file is compiled with -DFASTEST, the compression level is forced
  81256. * to 1, and no hash chains are maintained.
  81257. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81258. * input characters and the first MIN_MATCH bytes of str are valid
  81259. * (except for the last MIN_MATCH-1 bytes of the input file).
  81260. */
  81261. #ifdef FASTEST
  81262. #define INSERT_STRING(s, str, match_head) \
  81263. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81264. match_head = s->head[s->ins_h], \
  81265. s->head[s->ins_h] = (Pos)(str))
  81266. #else
  81267. #define INSERT_STRING(s, str, match_head) \
  81268. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81269. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81270. s->head[s->ins_h] = (Pos)(str))
  81271. #endif
  81272. /* ===========================================================================
  81273. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81274. * prev[] will be initialized on the fly.
  81275. */
  81276. #define CLEAR_HASH(s) \
  81277. s->head[s->hash_size-1] = NIL; \
  81278. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81279. /* ========================================================================= */
  81280. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81281. {
  81282. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81283. Z_DEFAULT_STRATEGY, version, stream_size);
  81284. /* To do: ignore strm->next_in if we use it as window */
  81285. }
  81286. /* ========================================================================= */
  81287. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81288. {
  81289. deflate_state *s;
  81290. int wrap = 1;
  81291. static const char my_version[] = ZLIB_VERSION;
  81292. ushf *overlay;
  81293. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81294. * output size for (length,distance) codes is <= 24 bits.
  81295. */
  81296. if (version == Z_NULL || version[0] != my_version[0] ||
  81297. stream_size != sizeof(z_stream)) {
  81298. return Z_VERSION_ERROR;
  81299. }
  81300. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81301. strm->msg = Z_NULL;
  81302. if (strm->zalloc == (alloc_func)0) {
  81303. strm->zalloc = zcalloc;
  81304. strm->opaque = (voidpf)0;
  81305. }
  81306. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81307. #ifdef FASTEST
  81308. if (level != 0) level = 1;
  81309. #else
  81310. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81311. #endif
  81312. if (windowBits < 0) { /* suppress zlib wrapper */
  81313. wrap = 0;
  81314. windowBits = -windowBits;
  81315. }
  81316. #ifdef GZIP
  81317. else if (windowBits > 15) {
  81318. wrap = 2; /* write gzip wrapper instead */
  81319. windowBits -= 16;
  81320. }
  81321. #endif
  81322. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81323. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81324. strategy < 0 || strategy > Z_FIXED) {
  81325. return Z_STREAM_ERROR;
  81326. }
  81327. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81328. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81329. if (s == Z_NULL) return Z_MEM_ERROR;
  81330. strm->state = (struct internal_state FAR *)s;
  81331. s->strm = strm;
  81332. s->wrap = wrap;
  81333. s->gzhead = Z_NULL;
  81334. s->w_bits = windowBits;
  81335. s->w_size = 1 << s->w_bits;
  81336. s->w_mask = s->w_size - 1;
  81337. s->hash_bits = memLevel + 7;
  81338. s->hash_size = 1 << s->hash_bits;
  81339. s->hash_mask = s->hash_size - 1;
  81340. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81341. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81342. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81343. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81344. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81345. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81346. s->pending_buf = (uchf *) overlay;
  81347. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81348. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81349. s->pending_buf == Z_NULL) {
  81350. s->status = FINISH_STATE;
  81351. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81352. deflateEnd (strm);
  81353. return Z_MEM_ERROR;
  81354. }
  81355. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81356. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81357. s->level = level;
  81358. s->strategy = strategy;
  81359. s->method = (Byte)method;
  81360. return deflateReset(strm);
  81361. }
  81362. /* ========================================================================= */
  81363. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81364. {
  81365. deflate_state *s;
  81366. uInt length = dictLength;
  81367. uInt n;
  81368. IPos hash_head = 0;
  81369. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81370. strm->state->wrap == 2 ||
  81371. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81372. return Z_STREAM_ERROR;
  81373. s = strm->state;
  81374. if (s->wrap)
  81375. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81376. if (length < MIN_MATCH) return Z_OK;
  81377. if (length > MAX_DIST(s)) {
  81378. length = MAX_DIST(s);
  81379. dictionary += dictLength - length; /* use the tail of the dictionary */
  81380. }
  81381. zmemcpy(s->window, dictionary, length);
  81382. s->strstart = length;
  81383. s->block_start = (long)length;
  81384. /* Insert all strings in the hash table (except for the last two bytes).
  81385. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81386. * call of fill_window.
  81387. */
  81388. s->ins_h = s->window[0];
  81389. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81390. for (n = 0; n <= length - MIN_MATCH; n++) {
  81391. INSERT_STRING(s, n, hash_head);
  81392. }
  81393. if (hash_head) hash_head = 0; /* to make compiler happy */
  81394. return Z_OK;
  81395. }
  81396. /* ========================================================================= */
  81397. int ZEXPORT deflateReset (z_streamp strm)
  81398. {
  81399. deflate_state *s;
  81400. if (strm == Z_NULL || strm->state == Z_NULL ||
  81401. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81402. return Z_STREAM_ERROR;
  81403. }
  81404. strm->total_in = strm->total_out = 0;
  81405. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81406. strm->data_type = Z_UNKNOWN;
  81407. s = (deflate_state *)strm->state;
  81408. s->pending = 0;
  81409. s->pending_out = s->pending_buf;
  81410. if (s->wrap < 0) {
  81411. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81412. }
  81413. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81414. strm->adler =
  81415. #ifdef GZIP
  81416. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81417. #endif
  81418. adler32(0L, Z_NULL, 0);
  81419. s->last_flush = Z_NO_FLUSH;
  81420. _tr_init(s);
  81421. lm_init(s);
  81422. return Z_OK;
  81423. }
  81424. /* ========================================================================= */
  81425. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81426. {
  81427. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81428. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81429. strm->state->gzhead = head;
  81430. return Z_OK;
  81431. }
  81432. /* ========================================================================= */
  81433. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81434. {
  81435. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81436. strm->state->bi_valid = bits;
  81437. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81438. return Z_OK;
  81439. }
  81440. /* ========================================================================= */
  81441. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81442. {
  81443. deflate_state *s;
  81444. compress_func func;
  81445. int err = Z_OK;
  81446. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81447. s = strm->state;
  81448. #ifdef FASTEST
  81449. if (level != 0) level = 1;
  81450. #else
  81451. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81452. #endif
  81453. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81454. return Z_STREAM_ERROR;
  81455. }
  81456. func = configuration_table[s->level].func;
  81457. if (func != configuration_table[level].func && strm->total_in != 0) {
  81458. /* Flush the last buffer: */
  81459. err = deflate(strm, Z_PARTIAL_FLUSH);
  81460. }
  81461. if (s->level != level) {
  81462. s->level = level;
  81463. s->max_lazy_match = configuration_table[level].max_lazy;
  81464. s->good_match = configuration_table[level].good_length;
  81465. s->nice_match = configuration_table[level].nice_length;
  81466. s->max_chain_length = configuration_table[level].max_chain;
  81467. }
  81468. s->strategy = strategy;
  81469. return err;
  81470. }
  81471. /* ========================================================================= */
  81472. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81473. {
  81474. deflate_state *s;
  81475. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81476. s = strm->state;
  81477. s->good_match = good_length;
  81478. s->max_lazy_match = max_lazy;
  81479. s->nice_match = nice_length;
  81480. s->max_chain_length = max_chain;
  81481. return Z_OK;
  81482. }
  81483. /* =========================================================================
  81484. * For the default windowBits of 15 and memLevel of 8, this function returns
  81485. * a close to exact, as well as small, upper bound on the compressed size.
  81486. * They are coded as constants here for a reason--if the #define's are
  81487. * changed, then this function needs to be changed as well. The return
  81488. * value for 15 and 8 only works for those exact settings.
  81489. *
  81490. * For any setting other than those defaults for windowBits and memLevel,
  81491. * the value returned is a conservative worst case for the maximum expansion
  81492. * resulting from using fixed blocks instead of stored blocks, which deflate
  81493. * can emit on compressed data for some combinations of the parameters.
  81494. *
  81495. * This function could be more sophisticated to provide closer upper bounds
  81496. * for every combination of windowBits and memLevel, as well as wrap.
  81497. * But even the conservative upper bound of about 14% expansion does not
  81498. * seem onerous for output buffer allocation.
  81499. */
  81500. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81501. {
  81502. deflate_state *s;
  81503. uLong destLen;
  81504. /* conservative upper bound */
  81505. destLen = sourceLen +
  81506. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81507. /* if can't get parameters, return conservative bound */
  81508. if (strm == Z_NULL || strm->state == Z_NULL)
  81509. return destLen;
  81510. /* if not default parameters, return conservative bound */
  81511. s = strm->state;
  81512. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81513. return destLen;
  81514. /* default settings: return tight bound for that case */
  81515. return compressBound(sourceLen);
  81516. }
  81517. /* =========================================================================
  81518. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81519. * IN assertion: the stream state is correct and there is enough room in
  81520. * pending_buf.
  81521. */
  81522. local void putShortMSB (deflate_state *s, uInt b)
  81523. {
  81524. put_byte(s, (Byte)(b >> 8));
  81525. put_byte(s, (Byte)(b & 0xff));
  81526. }
  81527. /* =========================================================================
  81528. * Flush as much pending output as possible. All deflate() output goes
  81529. * through this function so some applications may wish to modify it
  81530. * to avoid allocating a large strm->next_out buffer and copying into it.
  81531. * (See also read_buf()).
  81532. */
  81533. local void flush_pending (z_streamp strm)
  81534. {
  81535. unsigned len = strm->state->pending;
  81536. if (len > strm->avail_out) len = strm->avail_out;
  81537. if (len == 0) return;
  81538. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81539. strm->next_out += len;
  81540. strm->state->pending_out += len;
  81541. strm->total_out += len;
  81542. strm->avail_out -= len;
  81543. strm->state->pending -= len;
  81544. if (strm->state->pending == 0) {
  81545. strm->state->pending_out = strm->state->pending_buf;
  81546. }
  81547. }
  81548. /* ========================================================================= */
  81549. int ZEXPORT deflate (z_streamp strm, int flush)
  81550. {
  81551. int old_flush; /* value of flush param for previous deflate call */
  81552. deflate_state *s;
  81553. if (strm == Z_NULL || strm->state == Z_NULL ||
  81554. flush > Z_FINISH || flush < 0) {
  81555. return Z_STREAM_ERROR;
  81556. }
  81557. s = strm->state;
  81558. if (strm->next_out == Z_NULL ||
  81559. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81560. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81561. ERR_RETURN(strm, Z_STREAM_ERROR);
  81562. }
  81563. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81564. s->strm = strm; /* just in case */
  81565. old_flush = s->last_flush;
  81566. s->last_flush = flush;
  81567. /* Write the header */
  81568. if (s->status == INIT_STATE) {
  81569. #ifdef GZIP
  81570. if (s->wrap == 2) {
  81571. strm->adler = crc32(0L, Z_NULL, 0);
  81572. put_byte(s, 31);
  81573. put_byte(s, 139);
  81574. put_byte(s, 8);
  81575. if (s->gzhead == NULL) {
  81576. put_byte(s, 0);
  81577. put_byte(s, 0);
  81578. put_byte(s, 0);
  81579. put_byte(s, 0);
  81580. put_byte(s, 0);
  81581. put_byte(s, s->level == 9 ? 2 :
  81582. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81583. 4 : 0));
  81584. put_byte(s, OS_CODE);
  81585. s->status = BUSY_STATE;
  81586. }
  81587. else {
  81588. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81589. (s->gzhead->hcrc ? 2 : 0) +
  81590. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81591. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81592. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81593. );
  81594. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81595. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81596. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81597. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81598. put_byte(s, s->level == 9 ? 2 :
  81599. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81600. 4 : 0));
  81601. put_byte(s, s->gzhead->os & 0xff);
  81602. if (s->gzhead->extra != NULL) {
  81603. put_byte(s, s->gzhead->extra_len & 0xff);
  81604. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81605. }
  81606. if (s->gzhead->hcrc)
  81607. strm->adler = crc32(strm->adler, s->pending_buf,
  81608. s->pending);
  81609. s->gzindex = 0;
  81610. s->status = EXTRA_STATE;
  81611. }
  81612. }
  81613. else
  81614. #endif
  81615. {
  81616. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81617. uInt level_flags;
  81618. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81619. level_flags = 0;
  81620. else if (s->level < 6)
  81621. level_flags = 1;
  81622. else if (s->level == 6)
  81623. level_flags = 2;
  81624. else
  81625. level_flags = 3;
  81626. header |= (level_flags << 6);
  81627. if (s->strstart != 0) header |= PRESET_DICT;
  81628. header += 31 - (header % 31);
  81629. s->status = BUSY_STATE;
  81630. putShortMSB(s, header);
  81631. /* Save the adler32 of the preset dictionary: */
  81632. if (s->strstart != 0) {
  81633. putShortMSB(s, (uInt)(strm->adler >> 16));
  81634. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81635. }
  81636. strm->adler = adler32(0L, Z_NULL, 0);
  81637. }
  81638. }
  81639. #ifdef GZIP
  81640. if (s->status == EXTRA_STATE) {
  81641. if (s->gzhead->extra != NULL) {
  81642. uInt beg = s->pending; /* start of bytes to update crc */
  81643. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81644. if (s->pending == s->pending_buf_size) {
  81645. if (s->gzhead->hcrc && s->pending > beg)
  81646. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81647. s->pending - beg);
  81648. flush_pending(strm);
  81649. beg = s->pending;
  81650. if (s->pending == s->pending_buf_size)
  81651. break;
  81652. }
  81653. put_byte(s, s->gzhead->extra[s->gzindex]);
  81654. s->gzindex++;
  81655. }
  81656. if (s->gzhead->hcrc && s->pending > beg)
  81657. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81658. s->pending - beg);
  81659. if (s->gzindex == s->gzhead->extra_len) {
  81660. s->gzindex = 0;
  81661. s->status = NAME_STATE;
  81662. }
  81663. }
  81664. else
  81665. s->status = NAME_STATE;
  81666. }
  81667. if (s->status == NAME_STATE) {
  81668. if (s->gzhead->name != NULL) {
  81669. uInt beg = s->pending; /* start of bytes to update crc */
  81670. int val;
  81671. do {
  81672. if (s->pending == s->pending_buf_size) {
  81673. if (s->gzhead->hcrc && s->pending > beg)
  81674. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81675. s->pending - beg);
  81676. flush_pending(strm);
  81677. beg = s->pending;
  81678. if (s->pending == s->pending_buf_size) {
  81679. val = 1;
  81680. break;
  81681. }
  81682. }
  81683. val = s->gzhead->name[s->gzindex++];
  81684. put_byte(s, val);
  81685. } while (val != 0);
  81686. if (s->gzhead->hcrc && s->pending > beg)
  81687. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81688. s->pending - beg);
  81689. if (val == 0) {
  81690. s->gzindex = 0;
  81691. s->status = COMMENT_STATE;
  81692. }
  81693. }
  81694. else
  81695. s->status = COMMENT_STATE;
  81696. }
  81697. if (s->status == COMMENT_STATE) {
  81698. if (s->gzhead->comment != NULL) {
  81699. uInt beg = s->pending; /* start of bytes to update crc */
  81700. int val;
  81701. do {
  81702. if (s->pending == s->pending_buf_size) {
  81703. if (s->gzhead->hcrc && s->pending > beg)
  81704. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81705. s->pending - beg);
  81706. flush_pending(strm);
  81707. beg = s->pending;
  81708. if (s->pending == s->pending_buf_size) {
  81709. val = 1;
  81710. break;
  81711. }
  81712. }
  81713. val = s->gzhead->comment[s->gzindex++];
  81714. put_byte(s, val);
  81715. } while (val != 0);
  81716. if (s->gzhead->hcrc && s->pending > beg)
  81717. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81718. s->pending - beg);
  81719. if (val == 0)
  81720. s->status = HCRC_STATE;
  81721. }
  81722. else
  81723. s->status = HCRC_STATE;
  81724. }
  81725. if (s->status == HCRC_STATE) {
  81726. if (s->gzhead->hcrc) {
  81727. if (s->pending + 2 > s->pending_buf_size)
  81728. flush_pending(strm);
  81729. if (s->pending + 2 <= s->pending_buf_size) {
  81730. put_byte(s, (Byte)(strm->adler & 0xff));
  81731. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81732. strm->adler = crc32(0L, Z_NULL, 0);
  81733. s->status = BUSY_STATE;
  81734. }
  81735. }
  81736. else
  81737. s->status = BUSY_STATE;
  81738. }
  81739. #endif
  81740. /* Flush as much pending output as possible */
  81741. if (s->pending != 0) {
  81742. flush_pending(strm);
  81743. if (strm->avail_out == 0) {
  81744. /* Since avail_out is 0, deflate will be called again with
  81745. * more output space, but possibly with both pending and
  81746. * avail_in equal to zero. There won't be anything to do,
  81747. * but this is not an error situation so make sure we
  81748. * return OK instead of BUF_ERROR at next call of deflate:
  81749. */
  81750. s->last_flush = -1;
  81751. return Z_OK;
  81752. }
  81753. /* Make sure there is something to do and avoid duplicate consecutive
  81754. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81755. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81756. */
  81757. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81758. flush != Z_FINISH) {
  81759. ERR_RETURN(strm, Z_BUF_ERROR);
  81760. }
  81761. /* User must not provide more input after the first FINISH: */
  81762. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81763. ERR_RETURN(strm, Z_BUF_ERROR);
  81764. }
  81765. /* Start a new block or continue the current one.
  81766. */
  81767. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81768. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81769. block_state bstate;
  81770. bstate = (*(configuration_table[s->level].func))(s, flush);
  81771. if (bstate == finish_started || bstate == finish_done) {
  81772. s->status = FINISH_STATE;
  81773. }
  81774. if (bstate == need_more || bstate == finish_started) {
  81775. if (strm->avail_out == 0) {
  81776. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81777. }
  81778. return Z_OK;
  81779. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81780. * of deflate should use the same flush parameter to make sure
  81781. * that the flush is complete. So we don't have to output an
  81782. * empty block here, this will be done at next call. This also
  81783. * ensures that for a very small output buffer, we emit at most
  81784. * one empty block.
  81785. */
  81786. }
  81787. if (bstate == block_done) {
  81788. if (flush == Z_PARTIAL_FLUSH) {
  81789. _tr_align(s);
  81790. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81791. _tr_stored_block(s, (char*)0, 0L, 0);
  81792. /* For a full flush, this empty block will be recognized
  81793. * as a special marker by inflate_sync().
  81794. */
  81795. if (flush == Z_FULL_FLUSH) {
  81796. CLEAR_HASH(s); /* forget history */
  81797. }
  81798. }
  81799. flush_pending(strm);
  81800. if (strm->avail_out == 0) {
  81801. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81802. return Z_OK;
  81803. }
  81804. }
  81805. }
  81806. Assert(strm->avail_out > 0, "bug2");
  81807. if (flush != Z_FINISH) return Z_OK;
  81808. if (s->wrap <= 0) return Z_STREAM_END;
  81809. /* Write the trailer */
  81810. #ifdef GZIP
  81811. if (s->wrap == 2) {
  81812. put_byte(s, (Byte)(strm->adler & 0xff));
  81813. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81814. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81815. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81816. put_byte(s, (Byte)(strm->total_in & 0xff));
  81817. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81818. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81819. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81820. }
  81821. else
  81822. #endif
  81823. {
  81824. putShortMSB(s, (uInt)(strm->adler >> 16));
  81825. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81826. }
  81827. flush_pending(strm);
  81828. /* If avail_out is zero, the application will call deflate again
  81829. * to flush the rest.
  81830. */
  81831. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81832. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81833. }
  81834. /* ========================================================================= */
  81835. int ZEXPORT deflateEnd (z_streamp strm)
  81836. {
  81837. int status;
  81838. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81839. status = strm->state->status;
  81840. if (status != INIT_STATE &&
  81841. status != EXTRA_STATE &&
  81842. status != NAME_STATE &&
  81843. status != COMMENT_STATE &&
  81844. status != HCRC_STATE &&
  81845. status != BUSY_STATE &&
  81846. status != FINISH_STATE) {
  81847. return Z_STREAM_ERROR;
  81848. }
  81849. /* Deallocate in reverse order of allocations: */
  81850. TRY_FREE(strm, strm->state->pending_buf);
  81851. TRY_FREE(strm, strm->state->head);
  81852. TRY_FREE(strm, strm->state->prev);
  81853. TRY_FREE(strm, strm->state->window);
  81854. ZFREE(strm, strm->state);
  81855. strm->state = Z_NULL;
  81856. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81857. }
  81858. /* =========================================================================
  81859. * Copy the source state to the destination state.
  81860. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81861. * doesn't have enough memory anyway to duplicate compression states).
  81862. */
  81863. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81864. {
  81865. #ifdef MAXSEG_64K
  81866. return Z_STREAM_ERROR;
  81867. #else
  81868. deflate_state *ds;
  81869. deflate_state *ss;
  81870. ushf *overlay;
  81871. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81872. return Z_STREAM_ERROR;
  81873. }
  81874. ss = source->state;
  81875. zmemcpy(dest, source, sizeof(z_stream));
  81876. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81877. if (ds == Z_NULL) return Z_MEM_ERROR;
  81878. dest->state = (struct internal_state FAR *) ds;
  81879. zmemcpy(ds, ss, sizeof(deflate_state));
  81880. ds->strm = dest;
  81881. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81882. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81883. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81884. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81885. ds->pending_buf = (uchf *) overlay;
  81886. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81887. ds->pending_buf == Z_NULL) {
  81888. deflateEnd (dest);
  81889. return Z_MEM_ERROR;
  81890. }
  81891. /* following zmemcpy do not work for 16-bit MSDOS */
  81892. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81893. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81894. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81895. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81896. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81897. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81898. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81899. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81900. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81901. ds->bl_desc.dyn_tree = ds->bl_tree;
  81902. return Z_OK;
  81903. #endif /* MAXSEG_64K */
  81904. }
  81905. /* ===========================================================================
  81906. * Read a new buffer from the current input stream, update the adler32
  81907. * and total number of bytes read. All deflate() input goes through
  81908. * this function so some applications may wish to modify it to avoid
  81909. * allocating a large strm->next_in buffer and copying from it.
  81910. * (See also flush_pending()).
  81911. */
  81912. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81913. {
  81914. unsigned len = strm->avail_in;
  81915. if (len > size) len = size;
  81916. if (len == 0) return 0;
  81917. strm->avail_in -= len;
  81918. if (strm->state->wrap == 1) {
  81919. strm->adler = adler32(strm->adler, strm->next_in, len);
  81920. }
  81921. #ifdef GZIP
  81922. else if (strm->state->wrap == 2) {
  81923. strm->adler = crc32(strm->adler, strm->next_in, len);
  81924. }
  81925. #endif
  81926. zmemcpy(buf, strm->next_in, len);
  81927. strm->next_in += len;
  81928. strm->total_in += len;
  81929. return (int)len;
  81930. }
  81931. /* ===========================================================================
  81932. * Initialize the "longest match" routines for a new zlib stream
  81933. */
  81934. local void lm_init (deflate_state *s)
  81935. {
  81936. s->window_size = (ulg)2L*s->w_size;
  81937. CLEAR_HASH(s);
  81938. /* Set the default configuration parameters:
  81939. */
  81940. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81941. s->good_match = configuration_table[s->level].good_length;
  81942. s->nice_match = configuration_table[s->level].nice_length;
  81943. s->max_chain_length = configuration_table[s->level].max_chain;
  81944. s->strstart = 0;
  81945. s->block_start = 0L;
  81946. s->lookahead = 0;
  81947. s->match_length = s->prev_length = MIN_MATCH-1;
  81948. s->match_available = 0;
  81949. s->ins_h = 0;
  81950. #ifndef FASTEST
  81951. #ifdef ASMV
  81952. match_init(); /* initialize the asm code */
  81953. #endif
  81954. #endif
  81955. }
  81956. #ifndef FASTEST
  81957. /* ===========================================================================
  81958. * Set match_start to the longest match starting at the given string and
  81959. * return its length. Matches shorter or equal to prev_length are discarded,
  81960. * in which case the result is equal to prev_length and match_start is
  81961. * garbage.
  81962. * IN assertions: cur_match is the head of the hash chain for the current
  81963. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81964. * OUT assertion: the match length is not greater than s->lookahead.
  81965. */
  81966. #ifndef ASMV
  81967. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81968. * match.S. The code will be functionally equivalent.
  81969. */
  81970. local uInt longest_match(deflate_state *s, IPos cur_match)
  81971. {
  81972. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81973. register Bytef *scan = s->window + s->strstart; /* current string */
  81974. register Bytef *match; /* matched string */
  81975. register int len; /* length of current match */
  81976. int best_len = s->prev_length; /* best match length so far */
  81977. int nice_match = s->nice_match; /* stop if match long enough */
  81978. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81979. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81980. /* Stop when cur_match becomes <= limit. To simplify the code,
  81981. * we prevent matches with the string of window index 0.
  81982. */
  81983. Posf *prev = s->prev;
  81984. uInt wmask = s->w_mask;
  81985. #ifdef UNALIGNED_OK
  81986. /* Compare two bytes at a time. Note: this is not always beneficial.
  81987. * Try with and without -DUNALIGNED_OK to check.
  81988. */
  81989. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81990. register ush scan_start = *(ushf*)scan;
  81991. register ush scan_end = *(ushf*)(scan+best_len-1);
  81992. #else
  81993. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81994. register Byte scan_end1 = scan[best_len-1];
  81995. register Byte scan_end = scan[best_len];
  81996. #endif
  81997. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81998. * It is easy to get rid of this optimization if necessary.
  81999. */
  82000. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82001. /* Do not waste too much time if we already have a good match: */
  82002. if (s->prev_length >= s->good_match) {
  82003. chain_length >>= 2;
  82004. }
  82005. /* Do not look for matches beyond the end of the input. This is necessary
  82006. * to make deflate deterministic.
  82007. */
  82008. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82009. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82010. do {
  82011. Assert(cur_match < s->strstart, "no future");
  82012. match = s->window + cur_match;
  82013. /* Skip to next match if the match length cannot increase
  82014. * or if the match length is less than 2. Note that the checks below
  82015. * for insufficient lookahead only occur occasionally for performance
  82016. * reasons. Therefore uninitialized memory will be accessed, and
  82017. * conditional jumps will be made that depend on those values.
  82018. * However the length of the match is limited to the lookahead, so
  82019. * the output of deflate is not affected by the uninitialized values.
  82020. */
  82021. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82022. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82023. * UNALIGNED_OK if your compiler uses a different size.
  82024. */
  82025. if (*(ushf*)(match+best_len-1) != scan_end ||
  82026. *(ushf*)match != scan_start) continue;
  82027. /* It is not necessary to compare scan[2] and match[2] since they are
  82028. * always equal when the other bytes match, given that the hash keys
  82029. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82030. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82031. * lookahead only every 4th comparison; the 128th check will be made
  82032. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82033. * necessary to put more guard bytes at the end of the window, or
  82034. * to check more often for insufficient lookahead.
  82035. */
  82036. Assert(scan[2] == match[2], "scan[2]?");
  82037. scan++, match++;
  82038. do {
  82039. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82040. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82041. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82042. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82043. scan < strend);
  82044. /* The funny "do {}" generates better code on most compilers */
  82045. /* Here, scan <= window+strstart+257 */
  82046. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82047. if (*scan == *match) scan++;
  82048. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82049. scan = strend - (MAX_MATCH-1);
  82050. #else /* UNALIGNED_OK */
  82051. if (match[best_len] != scan_end ||
  82052. match[best_len-1] != scan_end1 ||
  82053. *match != *scan ||
  82054. *++match != scan[1]) continue;
  82055. /* The check at best_len-1 can be removed because it will be made
  82056. * again later. (This heuristic is not always a win.)
  82057. * It is not necessary to compare scan[2] and match[2] since they
  82058. * are always equal when the other bytes match, given that
  82059. * the hash keys are equal and that HASH_BITS >= 8.
  82060. */
  82061. scan += 2, match++;
  82062. Assert(*scan == *match, "match[2]?");
  82063. /* We check for insufficient lookahead only every 8th comparison;
  82064. * the 256th check will be made at strstart+258.
  82065. */
  82066. do {
  82067. } while (*++scan == *++match && *++scan == *++match &&
  82068. *++scan == *++match && *++scan == *++match &&
  82069. *++scan == *++match && *++scan == *++match &&
  82070. *++scan == *++match && *++scan == *++match &&
  82071. scan < strend);
  82072. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82073. len = MAX_MATCH - (int)(strend - scan);
  82074. scan = strend - MAX_MATCH;
  82075. #endif /* UNALIGNED_OK */
  82076. if (len > best_len) {
  82077. s->match_start = cur_match;
  82078. best_len = len;
  82079. if (len >= nice_match) break;
  82080. #ifdef UNALIGNED_OK
  82081. scan_end = *(ushf*)(scan+best_len-1);
  82082. #else
  82083. scan_end1 = scan[best_len-1];
  82084. scan_end = scan[best_len];
  82085. #endif
  82086. }
  82087. } while ((cur_match = prev[cur_match & wmask]) > limit
  82088. && --chain_length != 0);
  82089. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82090. return s->lookahead;
  82091. }
  82092. #endif /* ASMV */
  82093. #endif /* FASTEST */
  82094. /* ---------------------------------------------------------------------------
  82095. * Optimized version for level == 1 or strategy == Z_RLE only
  82096. */
  82097. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82098. {
  82099. register Bytef *scan = s->window + s->strstart; /* current string */
  82100. register Bytef *match; /* matched string */
  82101. register int len; /* length of current match */
  82102. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82103. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82104. * It is easy to get rid of this optimization if necessary.
  82105. */
  82106. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82107. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82108. Assert(cur_match < s->strstart, "no future");
  82109. match = s->window + cur_match;
  82110. /* Return failure if the match length is less than 2:
  82111. */
  82112. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82113. /* The check at best_len-1 can be removed because it will be made
  82114. * again later. (This heuristic is not always a win.)
  82115. * It is not necessary to compare scan[2] and match[2] since they
  82116. * are always equal when the other bytes match, given that
  82117. * the hash keys are equal and that HASH_BITS >= 8.
  82118. */
  82119. scan += 2, match += 2;
  82120. Assert(*scan == *match, "match[2]?");
  82121. /* We check for insufficient lookahead only every 8th comparison;
  82122. * the 256th check will be made at strstart+258.
  82123. */
  82124. do {
  82125. } while (*++scan == *++match && *++scan == *++match &&
  82126. *++scan == *++match && *++scan == *++match &&
  82127. *++scan == *++match && *++scan == *++match &&
  82128. *++scan == *++match && *++scan == *++match &&
  82129. scan < strend);
  82130. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82131. len = MAX_MATCH - (int)(strend - scan);
  82132. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82133. s->match_start = cur_match;
  82134. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82135. }
  82136. #ifdef DEBUG
  82137. /* ===========================================================================
  82138. * Check that the match at match_start is indeed a match.
  82139. */
  82140. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82141. {
  82142. /* check that the match is indeed a match */
  82143. if (zmemcmp(s->window + match,
  82144. s->window + start, length) != EQUAL) {
  82145. fprintf(stderr, " start %u, match %u, length %d\n",
  82146. start, match, length);
  82147. do {
  82148. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82149. } while (--length != 0);
  82150. z_error("invalid match");
  82151. }
  82152. if (z_verbose > 1) {
  82153. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82154. do { putc(s->window[start++], stderr); } while (--length != 0);
  82155. }
  82156. }
  82157. #else
  82158. # define check_match(s, start, match, length)
  82159. #endif /* DEBUG */
  82160. /* ===========================================================================
  82161. * Fill the window when the lookahead becomes insufficient.
  82162. * Updates strstart and lookahead.
  82163. *
  82164. * IN assertion: lookahead < MIN_LOOKAHEAD
  82165. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82166. * At least one byte has been read, or avail_in == 0; reads are
  82167. * performed for at least two bytes (required for the zip translate_eol
  82168. * option -- not supported here).
  82169. */
  82170. local void fill_window (deflate_state *s)
  82171. {
  82172. register unsigned n, m;
  82173. register Posf *p;
  82174. unsigned more; /* Amount of free space at the end of the window. */
  82175. uInt wsize = s->w_size;
  82176. do {
  82177. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82178. /* Deal with !@#$% 64K limit: */
  82179. if (sizeof(int) <= 2) {
  82180. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82181. more = wsize;
  82182. } else if (more == (unsigned)(-1)) {
  82183. /* Very unlikely, but possible on 16 bit machine if
  82184. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82185. */
  82186. more--;
  82187. }
  82188. }
  82189. /* If the window is almost full and there is insufficient lookahead,
  82190. * move the upper half to the lower one to make room in the upper half.
  82191. */
  82192. if (s->strstart >= wsize+MAX_DIST(s)) {
  82193. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82194. s->match_start -= wsize;
  82195. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82196. s->block_start -= (long) wsize;
  82197. /* Slide the hash table (could be avoided with 32 bit values
  82198. at the expense of memory usage). We slide even when level == 0
  82199. to keep the hash table consistent if we switch back to level > 0
  82200. later. (Using level 0 permanently is not an optimal usage of
  82201. zlib, so we don't care about this pathological case.)
  82202. */
  82203. /* %%% avoid this when Z_RLE */
  82204. n = s->hash_size;
  82205. p = &s->head[n];
  82206. do {
  82207. m = *--p;
  82208. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82209. } while (--n);
  82210. n = wsize;
  82211. #ifndef FASTEST
  82212. p = &s->prev[n];
  82213. do {
  82214. m = *--p;
  82215. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82216. /* If n is not on any hash chain, prev[n] is garbage but
  82217. * its value will never be used.
  82218. */
  82219. } while (--n);
  82220. #endif
  82221. more += wsize;
  82222. }
  82223. if (s->strm->avail_in == 0) return;
  82224. /* If there was no sliding:
  82225. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82226. * more == window_size - lookahead - strstart
  82227. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82228. * => more >= window_size - 2*WSIZE + 2
  82229. * In the BIG_MEM or MMAP case (not yet supported),
  82230. * window_size == input_size + MIN_LOOKAHEAD &&
  82231. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82232. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82233. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82234. */
  82235. Assert(more >= 2, "more < 2");
  82236. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82237. s->lookahead += n;
  82238. /* Initialize the hash value now that we have some input: */
  82239. if (s->lookahead >= MIN_MATCH) {
  82240. s->ins_h = s->window[s->strstart];
  82241. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82242. #if MIN_MATCH != 3
  82243. Call UPDATE_HASH() MIN_MATCH-3 more times
  82244. #endif
  82245. }
  82246. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82247. * but this is not important since only literal bytes will be emitted.
  82248. */
  82249. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82250. }
  82251. /* ===========================================================================
  82252. * Flush the current block, with given end-of-file flag.
  82253. * IN assertion: strstart is set to the end of the current match.
  82254. */
  82255. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82256. _tr_flush_block(s, (s->block_start >= 0L ? \
  82257. (charf *)&s->window[(unsigned)s->block_start] : \
  82258. (charf *)Z_NULL), \
  82259. (ulg)((long)s->strstart - s->block_start), \
  82260. (eof)); \
  82261. s->block_start = s->strstart; \
  82262. flush_pending(s->strm); \
  82263. Tracev((stderr,"[FLUSH]")); \
  82264. }
  82265. /* Same but force premature exit if necessary. */
  82266. #define FLUSH_BLOCK(s, eof) { \
  82267. FLUSH_BLOCK_ONLY(s, eof); \
  82268. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82269. }
  82270. /* ===========================================================================
  82271. * Copy without compression as much as possible from the input stream, return
  82272. * the current block state.
  82273. * This function does not insert new strings in the dictionary since
  82274. * uncompressible data is probably not useful. This function is used
  82275. * only for the level=0 compression option.
  82276. * NOTE: this function should be optimized to avoid extra copying from
  82277. * window to pending_buf.
  82278. */
  82279. local block_state deflate_stored(deflate_state *s, int flush)
  82280. {
  82281. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82282. * to pending_buf_size, and each stored block has a 5 byte header:
  82283. */
  82284. ulg max_block_size = 0xffff;
  82285. ulg max_start;
  82286. if (max_block_size > s->pending_buf_size - 5) {
  82287. max_block_size = s->pending_buf_size - 5;
  82288. }
  82289. /* Copy as much as possible from input to output: */
  82290. for (;;) {
  82291. /* Fill the window as much as possible: */
  82292. if (s->lookahead <= 1) {
  82293. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82294. s->block_start >= (long)s->w_size, "slide too late");
  82295. fill_window(s);
  82296. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82297. if (s->lookahead == 0) break; /* flush the current block */
  82298. }
  82299. Assert(s->block_start >= 0L, "block gone");
  82300. s->strstart += s->lookahead;
  82301. s->lookahead = 0;
  82302. /* Emit a stored block if pending_buf will be full: */
  82303. max_start = s->block_start + max_block_size;
  82304. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82305. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82306. s->lookahead = (uInt)(s->strstart - max_start);
  82307. s->strstart = (uInt)max_start;
  82308. FLUSH_BLOCK(s, 0);
  82309. }
  82310. /* Flush if we may have to slide, otherwise block_start may become
  82311. * negative and the data will be gone:
  82312. */
  82313. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82314. FLUSH_BLOCK(s, 0);
  82315. }
  82316. }
  82317. FLUSH_BLOCK(s, flush == Z_FINISH);
  82318. return flush == Z_FINISH ? finish_done : block_done;
  82319. }
  82320. /* ===========================================================================
  82321. * Compress as much as possible from the input stream, return the current
  82322. * block state.
  82323. * This function does not perform lazy evaluation of matches and inserts
  82324. * new strings in the dictionary only for unmatched strings or for short
  82325. * matches. It is used only for the fast compression options.
  82326. */
  82327. local block_state deflate_fast(deflate_state *s, int flush)
  82328. {
  82329. IPos hash_head = NIL; /* head of the hash chain */
  82330. int bflush; /* set if current block must be flushed */
  82331. for (;;) {
  82332. /* Make sure that we always have enough lookahead, except
  82333. * at the end of the input file. We need MAX_MATCH bytes
  82334. * for the next match, plus MIN_MATCH bytes to insert the
  82335. * string following the next match.
  82336. */
  82337. if (s->lookahead < MIN_LOOKAHEAD) {
  82338. fill_window(s);
  82339. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82340. return need_more;
  82341. }
  82342. if (s->lookahead == 0) break; /* flush the current block */
  82343. }
  82344. /* Insert the string window[strstart .. strstart+2] in the
  82345. * dictionary, and set hash_head to the head of the hash chain:
  82346. */
  82347. if (s->lookahead >= MIN_MATCH) {
  82348. INSERT_STRING(s, s->strstart, hash_head);
  82349. }
  82350. /* Find the longest match, discarding those <= prev_length.
  82351. * At this point we have always match_length < MIN_MATCH
  82352. */
  82353. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82354. /* To simplify the code, we prevent matches with the string
  82355. * of window index 0 (in particular we have to avoid a match
  82356. * of the string with itself at the start of the input file).
  82357. */
  82358. #ifdef FASTEST
  82359. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82360. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82361. s->match_length = longest_match_fast (s, hash_head);
  82362. }
  82363. #else
  82364. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82365. s->match_length = longest_match (s, hash_head);
  82366. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82367. s->match_length = longest_match_fast (s, hash_head);
  82368. }
  82369. #endif
  82370. /* longest_match() or longest_match_fast() sets match_start */
  82371. }
  82372. if (s->match_length >= MIN_MATCH) {
  82373. check_match(s, s->strstart, s->match_start, s->match_length);
  82374. _tr_tally_dist(s, s->strstart - s->match_start,
  82375. s->match_length - MIN_MATCH, bflush);
  82376. s->lookahead -= s->match_length;
  82377. /* Insert new strings in the hash table only if the match length
  82378. * is not too large. This saves time but degrades compression.
  82379. */
  82380. #ifndef FASTEST
  82381. if (s->match_length <= s->max_insert_length &&
  82382. s->lookahead >= MIN_MATCH) {
  82383. s->match_length--; /* string at strstart already in table */
  82384. do {
  82385. s->strstart++;
  82386. INSERT_STRING(s, s->strstart, hash_head);
  82387. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82388. * always MIN_MATCH bytes ahead.
  82389. */
  82390. } while (--s->match_length != 0);
  82391. s->strstart++;
  82392. } else
  82393. #endif
  82394. {
  82395. s->strstart += s->match_length;
  82396. s->match_length = 0;
  82397. s->ins_h = s->window[s->strstart];
  82398. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82399. #if MIN_MATCH != 3
  82400. Call UPDATE_HASH() MIN_MATCH-3 more times
  82401. #endif
  82402. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82403. * matter since it will be recomputed at next deflate call.
  82404. */
  82405. }
  82406. } else {
  82407. /* No match, output a literal byte */
  82408. Tracevv((stderr,"%c", s->window[s->strstart]));
  82409. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82410. s->lookahead--;
  82411. s->strstart++;
  82412. }
  82413. if (bflush) FLUSH_BLOCK(s, 0);
  82414. }
  82415. FLUSH_BLOCK(s, flush == Z_FINISH);
  82416. return flush == Z_FINISH ? finish_done : block_done;
  82417. }
  82418. #ifndef FASTEST
  82419. /* ===========================================================================
  82420. * Same as above, but achieves better compression. We use a lazy
  82421. * evaluation for matches: a match is finally adopted only if there is
  82422. * no better match at the next window position.
  82423. */
  82424. local block_state deflate_slow(deflate_state *s, int flush)
  82425. {
  82426. IPos hash_head = NIL; /* head of hash chain */
  82427. int bflush; /* set if current block must be flushed */
  82428. /* Process the input block. */
  82429. for (;;) {
  82430. /* Make sure that we always have enough lookahead, except
  82431. * at the end of the input file. We need MAX_MATCH bytes
  82432. * for the next match, plus MIN_MATCH bytes to insert the
  82433. * string following the next match.
  82434. */
  82435. if (s->lookahead < MIN_LOOKAHEAD) {
  82436. fill_window(s);
  82437. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82438. return need_more;
  82439. }
  82440. if (s->lookahead == 0) break; /* flush the current block */
  82441. }
  82442. /* Insert the string window[strstart .. strstart+2] in the
  82443. * dictionary, and set hash_head to the head of the hash chain:
  82444. */
  82445. if (s->lookahead >= MIN_MATCH) {
  82446. INSERT_STRING(s, s->strstart, hash_head);
  82447. }
  82448. /* Find the longest match, discarding those <= prev_length.
  82449. */
  82450. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82451. s->match_length = MIN_MATCH-1;
  82452. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82453. s->strstart - hash_head <= MAX_DIST(s)) {
  82454. /* To simplify the code, we prevent matches with the string
  82455. * of window index 0 (in particular we have to avoid a match
  82456. * of the string with itself at the start of the input file).
  82457. */
  82458. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82459. s->match_length = longest_match (s, hash_head);
  82460. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82461. s->match_length = longest_match_fast (s, hash_head);
  82462. }
  82463. /* longest_match() or longest_match_fast() sets match_start */
  82464. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82465. #if TOO_FAR <= 32767
  82466. || (s->match_length == MIN_MATCH &&
  82467. s->strstart - s->match_start > TOO_FAR)
  82468. #endif
  82469. )) {
  82470. /* If prev_match is also MIN_MATCH, match_start is garbage
  82471. * but we will ignore the current match anyway.
  82472. */
  82473. s->match_length = MIN_MATCH-1;
  82474. }
  82475. }
  82476. /* If there was a match at the previous step and the current
  82477. * match is not better, output the previous match:
  82478. */
  82479. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82480. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82481. /* Do not insert strings in hash table beyond this. */
  82482. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82483. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82484. s->prev_length - MIN_MATCH, bflush);
  82485. /* Insert in hash table all strings up to the end of the match.
  82486. * strstart-1 and strstart are already inserted. If there is not
  82487. * enough lookahead, the last two strings are not inserted in
  82488. * the hash table.
  82489. */
  82490. s->lookahead -= s->prev_length-1;
  82491. s->prev_length -= 2;
  82492. do {
  82493. if (++s->strstart <= max_insert) {
  82494. INSERT_STRING(s, s->strstart, hash_head);
  82495. }
  82496. } while (--s->prev_length != 0);
  82497. s->match_available = 0;
  82498. s->match_length = MIN_MATCH-1;
  82499. s->strstart++;
  82500. if (bflush) FLUSH_BLOCK(s, 0);
  82501. } else if (s->match_available) {
  82502. /* If there was no match at the previous position, output a
  82503. * single literal. If there was a match but the current match
  82504. * is longer, truncate the previous match to a single literal.
  82505. */
  82506. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82507. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82508. if (bflush) {
  82509. FLUSH_BLOCK_ONLY(s, 0);
  82510. }
  82511. s->strstart++;
  82512. s->lookahead--;
  82513. if (s->strm->avail_out == 0) return need_more;
  82514. } else {
  82515. /* There is no previous match to compare with, wait for
  82516. * the next step to decide.
  82517. */
  82518. s->match_available = 1;
  82519. s->strstart++;
  82520. s->lookahead--;
  82521. }
  82522. }
  82523. Assert (flush != Z_NO_FLUSH, "no flush?");
  82524. if (s->match_available) {
  82525. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82526. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82527. s->match_available = 0;
  82528. }
  82529. FLUSH_BLOCK(s, flush == Z_FINISH);
  82530. return flush == Z_FINISH ? finish_done : block_done;
  82531. }
  82532. #endif /* FASTEST */
  82533. #if 0
  82534. /* ===========================================================================
  82535. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82536. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82537. * deflate switches away from Z_RLE.)
  82538. */
  82539. local block_state deflate_rle(s, flush)
  82540. deflate_state *s;
  82541. int flush;
  82542. {
  82543. int bflush; /* set if current block must be flushed */
  82544. uInt run; /* length of run */
  82545. uInt max; /* maximum length of run */
  82546. uInt prev; /* byte at distance one to match */
  82547. Bytef *scan; /* scan for end of run */
  82548. for (;;) {
  82549. /* Make sure that we always have enough lookahead, except
  82550. * at the end of the input file. We need MAX_MATCH bytes
  82551. * for the longest encodable run.
  82552. */
  82553. if (s->lookahead < MAX_MATCH) {
  82554. fill_window(s);
  82555. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82556. return need_more;
  82557. }
  82558. if (s->lookahead == 0) break; /* flush the current block */
  82559. }
  82560. /* See how many times the previous byte repeats */
  82561. run = 0;
  82562. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82563. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82564. scan = s->window + s->strstart - 1;
  82565. prev = *scan++;
  82566. do {
  82567. if (*scan++ != prev)
  82568. break;
  82569. } while (++run < max);
  82570. }
  82571. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82572. if (run >= MIN_MATCH) {
  82573. check_match(s, s->strstart, s->strstart - 1, run);
  82574. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82575. s->lookahead -= run;
  82576. s->strstart += run;
  82577. } else {
  82578. /* No match, output a literal byte */
  82579. Tracevv((stderr,"%c", s->window[s->strstart]));
  82580. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82581. s->lookahead--;
  82582. s->strstart++;
  82583. }
  82584. if (bflush) FLUSH_BLOCK(s, 0);
  82585. }
  82586. FLUSH_BLOCK(s, flush == Z_FINISH);
  82587. return flush == Z_FINISH ? finish_done : block_done;
  82588. }
  82589. #endif
  82590. /*** End of inlined file: deflate.c ***/
  82591. /*** Start of inlined file: inffast.c ***/
  82592. /*** Start of inlined file: inftrees.h ***/
  82593. /* WARNING: this file should *not* be used by applications. It is
  82594. part of the implementation of the compression library and is
  82595. subject to change. Applications should only use zlib.h.
  82596. */
  82597. #ifndef _INFTREES_H_
  82598. #define _INFTREES_H_
  82599. /* Structure for decoding tables. Each entry provides either the
  82600. information needed to do the operation requested by the code that
  82601. indexed that table entry, or it provides a pointer to another
  82602. table that indexes more bits of the code. op indicates whether
  82603. the entry is a pointer to another table, a literal, a length or
  82604. distance, an end-of-block, or an invalid code. For a table
  82605. pointer, the low four bits of op is the number of index bits of
  82606. that table. For a length or distance, the low four bits of op
  82607. is the number of extra bits to get after the code. bits is
  82608. the number of bits in this code or part of the code to drop off
  82609. of the bit buffer. val is the actual byte to output in the case
  82610. of a literal, the base length or distance, or the offset from
  82611. the current table to the next table. Each entry is four bytes. */
  82612. typedef struct {
  82613. unsigned char op; /* operation, extra bits, table bits */
  82614. unsigned char bits; /* bits in this part of the code */
  82615. unsigned short val; /* offset in table or code value */
  82616. } code;
  82617. /* op values as set by inflate_table():
  82618. 00000000 - literal
  82619. 0000tttt - table link, tttt != 0 is the number of table index bits
  82620. 0001eeee - length or distance, eeee is the number of extra bits
  82621. 01100000 - end of block
  82622. 01000000 - invalid code
  82623. */
  82624. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82625. exhaustive search was 1444 code structures (852 for length/literals
  82626. and 592 for distances, the latter actually the result of an
  82627. exhaustive search). The true maximum is not known, but the value
  82628. below is more than safe. */
  82629. #define ENOUGH 2048
  82630. #define MAXD 592
  82631. /* Type of code to build for inftable() */
  82632. typedef enum {
  82633. CODES,
  82634. LENS,
  82635. DISTS
  82636. } codetype;
  82637. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82638. unsigned codes, code FAR * FAR *table,
  82639. unsigned FAR *bits, unsigned short FAR *work));
  82640. #endif
  82641. /*** End of inlined file: inftrees.h ***/
  82642. /*** Start of inlined file: inflate.h ***/
  82643. /* WARNING: this file should *not* be used by applications. It is
  82644. part of the implementation of the compression library and is
  82645. subject to change. Applications should only use zlib.h.
  82646. */
  82647. #ifndef _INFLATE_H_
  82648. #define _INFLATE_H_
  82649. /* define NO_GZIP when compiling if you want to disable gzip header and
  82650. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82651. the crc code when it is not needed. For shared libraries, gzip decoding
  82652. should be left enabled. */
  82653. #ifndef NO_GZIP
  82654. # define GUNZIP
  82655. #endif
  82656. /* Possible inflate modes between inflate() calls */
  82657. typedef enum {
  82658. HEAD, /* i: waiting for magic header */
  82659. FLAGS, /* i: waiting for method and flags (gzip) */
  82660. TIME, /* i: waiting for modification time (gzip) */
  82661. OS, /* i: waiting for extra flags and operating system (gzip) */
  82662. EXLEN, /* i: waiting for extra length (gzip) */
  82663. EXTRA, /* i: waiting for extra bytes (gzip) */
  82664. NAME, /* i: waiting for end of file name (gzip) */
  82665. COMMENT, /* i: waiting for end of comment (gzip) */
  82666. HCRC, /* i: waiting for header crc (gzip) */
  82667. DICTID, /* i: waiting for dictionary check value */
  82668. DICT, /* waiting for inflateSetDictionary() call */
  82669. TYPE, /* i: waiting for type bits, including last-flag bit */
  82670. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82671. STORED, /* i: waiting for stored size (length and complement) */
  82672. COPY, /* i/o: waiting for input or output to copy stored block */
  82673. TABLE, /* i: waiting for dynamic block table lengths */
  82674. LENLENS, /* i: waiting for code length code lengths */
  82675. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82676. LEN, /* i: waiting for length/lit code */
  82677. LENEXT, /* i: waiting for length extra bits */
  82678. DIST, /* i: waiting for distance code */
  82679. DISTEXT, /* i: waiting for distance extra bits */
  82680. MATCH, /* o: waiting for output space to copy string */
  82681. LIT, /* o: waiting for output space to write literal */
  82682. CHECK, /* i: waiting for 32-bit check value */
  82683. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82684. DONE, /* finished check, done -- remain here until reset */
  82685. BAD, /* got a data error -- remain here until reset */
  82686. MEM, /* got an inflate() memory error -- remain here until reset */
  82687. SYNC /* looking for synchronization bytes to restart inflate() */
  82688. } inflate_mode;
  82689. /*
  82690. State transitions between above modes -
  82691. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82692. Process header:
  82693. HEAD -> (gzip) or (zlib)
  82694. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82695. NAME -> COMMENT -> HCRC -> TYPE
  82696. (zlib) -> DICTID or TYPE
  82697. DICTID -> DICT -> TYPE
  82698. Read deflate blocks:
  82699. TYPE -> STORED or TABLE or LEN or CHECK
  82700. STORED -> COPY -> TYPE
  82701. TABLE -> LENLENS -> CODELENS -> LEN
  82702. Read deflate codes:
  82703. LEN -> LENEXT or LIT or TYPE
  82704. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82705. LIT -> LEN
  82706. Process trailer:
  82707. CHECK -> LENGTH -> DONE
  82708. */
  82709. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82710. struct inflate_state {
  82711. inflate_mode mode; /* current inflate mode */
  82712. int last; /* true if processing last block */
  82713. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82714. int havedict; /* true if dictionary provided */
  82715. int flags; /* gzip header method and flags (0 if zlib) */
  82716. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82717. unsigned long check; /* protected copy of check value */
  82718. unsigned long total; /* protected copy of output count */
  82719. gz_headerp head; /* where to save gzip header information */
  82720. /* sliding window */
  82721. unsigned wbits; /* log base 2 of requested window size */
  82722. unsigned wsize; /* window size or zero if not using window */
  82723. unsigned whave; /* valid bytes in the window */
  82724. unsigned write; /* window write index */
  82725. unsigned char FAR *window; /* allocated sliding window, if needed */
  82726. /* bit accumulator */
  82727. unsigned long hold; /* input bit accumulator */
  82728. unsigned bits; /* number of bits in "in" */
  82729. /* for string and stored block copying */
  82730. unsigned length; /* literal or length of data to copy */
  82731. unsigned offset; /* distance back to copy string from */
  82732. /* for table and code decoding */
  82733. unsigned extra; /* extra bits needed */
  82734. /* fixed and dynamic code tables */
  82735. code const FAR *lencode; /* starting table for length/literal codes */
  82736. code const FAR *distcode; /* starting table for distance codes */
  82737. unsigned lenbits; /* index bits for lencode */
  82738. unsigned distbits; /* index bits for distcode */
  82739. /* dynamic table building */
  82740. unsigned ncode; /* number of code length code lengths */
  82741. unsigned nlen; /* number of length code lengths */
  82742. unsigned ndist; /* number of distance code lengths */
  82743. unsigned have; /* number of code lengths in lens[] */
  82744. code FAR *next; /* next available space in codes[] */
  82745. unsigned short lens[320]; /* temporary storage for code lengths */
  82746. unsigned short work[288]; /* work area for code table building */
  82747. code codes[ENOUGH]; /* space for code tables */
  82748. };
  82749. #endif
  82750. /*** End of inlined file: inflate.h ***/
  82751. /*** Start of inlined file: inffast.h ***/
  82752. /* WARNING: this file should *not* be used by applications. It is
  82753. part of the implementation of the compression library and is
  82754. subject to change. Applications should only use zlib.h.
  82755. */
  82756. void inflate_fast OF((z_streamp strm, unsigned start));
  82757. /*** End of inlined file: inffast.h ***/
  82758. #ifndef ASMINF
  82759. /* Allow machine dependent optimization for post-increment or pre-increment.
  82760. Based on testing to date,
  82761. Pre-increment preferred for:
  82762. - PowerPC G3 (Adler)
  82763. - MIPS R5000 (Randers-Pehrson)
  82764. Post-increment preferred for:
  82765. - none
  82766. No measurable difference:
  82767. - Pentium III (Anderson)
  82768. - M68060 (Nikl)
  82769. */
  82770. #ifdef POSTINC
  82771. # define OFF 0
  82772. # define PUP(a) *(a)++
  82773. #else
  82774. # define OFF 1
  82775. # define PUP(a) *++(a)
  82776. #endif
  82777. /*
  82778. Decode literal, length, and distance codes and write out the resulting
  82779. literal and match bytes until either not enough input or output is
  82780. available, an end-of-block is encountered, or a data error is encountered.
  82781. When large enough input and output buffers are supplied to inflate(), for
  82782. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82783. inflate execution time is spent in this routine.
  82784. Entry assumptions:
  82785. state->mode == LEN
  82786. strm->avail_in >= 6
  82787. strm->avail_out >= 258
  82788. start >= strm->avail_out
  82789. state->bits < 8
  82790. On return, state->mode is one of:
  82791. LEN -- ran out of enough output space or enough available input
  82792. TYPE -- reached end of block code, inflate() to interpret next block
  82793. BAD -- error in block data
  82794. Notes:
  82795. - The maximum input bits used by a length/distance pair is 15 bits for the
  82796. length code, 5 bits for the length extra, 15 bits for the distance code,
  82797. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82798. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82799. checking for available input while decoding.
  82800. - The maximum bytes that a single length/distance pair can output is 258
  82801. bytes, which is the maximum length that can be coded. inflate_fast()
  82802. requires strm->avail_out >= 258 for each loop to avoid checking for
  82803. output space.
  82804. */
  82805. void inflate_fast (z_streamp strm, unsigned start)
  82806. {
  82807. struct inflate_state FAR *state;
  82808. unsigned char FAR *in; /* local strm->next_in */
  82809. unsigned char FAR *last; /* while in < last, enough input available */
  82810. unsigned char FAR *out; /* local strm->next_out */
  82811. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82812. unsigned char FAR *end; /* while out < end, enough space available */
  82813. #ifdef INFLATE_STRICT
  82814. unsigned dmax; /* maximum distance from zlib header */
  82815. #endif
  82816. unsigned wsize; /* window size or zero if not using window */
  82817. unsigned whave; /* valid bytes in the window */
  82818. unsigned write; /* window write index */
  82819. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82820. unsigned long hold; /* local strm->hold */
  82821. unsigned bits; /* local strm->bits */
  82822. code const FAR *lcode; /* local strm->lencode */
  82823. code const FAR *dcode; /* local strm->distcode */
  82824. unsigned lmask; /* mask for first level of length codes */
  82825. unsigned dmask; /* mask for first level of distance codes */
  82826. code thisx; /* retrieved table entry */
  82827. unsigned op; /* code bits, operation, extra bits, or */
  82828. /* window position, window bytes to copy */
  82829. unsigned len; /* match length, unused bytes */
  82830. unsigned dist; /* match distance */
  82831. unsigned char FAR *from; /* where to copy match from */
  82832. /* copy state to local variables */
  82833. state = (struct inflate_state FAR *)strm->state;
  82834. in = strm->next_in - OFF;
  82835. last = in + (strm->avail_in - 5);
  82836. out = strm->next_out - OFF;
  82837. beg = out - (start - strm->avail_out);
  82838. end = out + (strm->avail_out - 257);
  82839. #ifdef INFLATE_STRICT
  82840. dmax = state->dmax;
  82841. #endif
  82842. wsize = state->wsize;
  82843. whave = state->whave;
  82844. write = state->write;
  82845. window = state->window;
  82846. hold = state->hold;
  82847. bits = state->bits;
  82848. lcode = state->lencode;
  82849. dcode = state->distcode;
  82850. lmask = (1U << state->lenbits) - 1;
  82851. dmask = (1U << state->distbits) - 1;
  82852. /* decode literals and length/distances until end-of-block or not enough
  82853. input data or output space */
  82854. do {
  82855. if (bits < 15) {
  82856. hold += (unsigned long)(PUP(in)) << bits;
  82857. bits += 8;
  82858. hold += (unsigned long)(PUP(in)) << bits;
  82859. bits += 8;
  82860. }
  82861. thisx = lcode[hold & lmask];
  82862. dolen:
  82863. op = (unsigned)(thisx.bits);
  82864. hold >>= op;
  82865. bits -= op;
  82866. op = (unsigned)(thisx.op);
  82867. if (op == 0) { /* literal */
  82868. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82869. "inflate: literal '%c'\n" :
  82870. "inflate: literal 0x%02x\n", thisx.val));
  82871. PUP(out) = (unsigned char)(thisx.val);
  82872. }
  82873. else if (op & 16) { /* length base */
  82874. len = (unsigned)(thisx.val);
  82875. op &= 15; /* number of extra bits */
  82876. if (op) {
  82877. if (bits < op) {
  82878. hold += (unsigned long)(PUP(in)) << bits;
  82879. bits += 8;
  82880. }
  82881. len += (unsigned)hold & ((1U << op) - 1);
  82882. hold >>= op;
  82883. bits -= op;
  82884. }
  82885. Tracevv((stderr, "inflate: length %u\n", len));
  82886. if (bits < 15) {
  82887. hold += (unsigned long)(PUP(in)) << bits;
  82888. bits += 8;
  82889. hold += (unsigned long)(PUP(in)) << bits;
  82890. bits += 8;
  82891. }
  82892. thisx = dcode[hold & dmask];
  82893. dodist:
  82894. op = (unsigned)(thisx.bits);
  82895. hold >>= op;
  82896. bits -= op;
  82897. op = (unsigned)(thisx.op);
  82898. if (op & 16) { /* distance base */
  82899. dist = (unsigned)(thisx.val);
  82900. op &= 15; /* number of extra bits */
  82901. if (bits < op) {
  82902. hold += (unsigned long)(PUP(in)) << bits;
  82903. bits += 8;
  82904. if (bits < op) {
  82905. hold += (unsigned long)(PUP(in)) << bits;
  82906. bits += 8;
  82907. }
  82908. }
  82909. dist += (unsigned)hold & ((1U << op) - 1);
  82910. #ifdef INFLATE_STRICT
  82911. if (dist > dmax) {
  82912. strm->msg = (char *)"invalid distance too far back";
  82913. state->mode = BAD;
  82914. break;
  82915. }
  82916. #endif
  82917. hold >>= op;
  82918. bits -= op;
  82919. Tracevv((stderr, "inflate: distance %u\n", dist));
  82920. op = (unsigned)(out - beg); /* max distance in output */
  82921. if (dist > op) { /* see if copy from window */
  82922. op = dist - op; /* distance back in window */
  82923. if (op > whave) {
  82924. strm->msg = (char *)"invalid distance too far back";
  82925. state->mode = BAD;
  82926. break;
  82927. }
  82928. from = window - OFF;
  82929. if (write == 0) { /* very common case */
  82930. from += wsize - op;
  82931. if (op < len) { /* some from window */
  82932. len -= op;
  82933. do {
  82934. PUP(out) = PUP(from);
  82935. } while (--op);
  82936. from = out - dist; /* rest from output */
  82937. }
  82938. }
  82939. else if (write < op) { /* wrap around window */
  82940. from += wsize + write - op;
  82941. op -= write;
  82942. if (op < len) { /* some from end of window */
  82943. len -= op;
  82944. do {
  82945. PUP(out) = PUP(from);
  82946. } while (--op);
  82947. from = window - OFF;
  82948. if (write < len) { /* some from start of window */
  82949. op = write;
  82950. len -= op;
  82951. do {
  82952. PUP(out) = PUP(from);
  82953. } while (--op);
  82954. from = out - dist; /* rest from output */
  82955. }
  82956. }
  82957. }
  82958. else { /* contiguous in window */
  82959. from += write - op;
  82960. if (op < len) { /* some from window */
  82961. len -= op;
  82962. do {
  82963. PUP(out) = PUP(from);
  82964. } while (--op);
  82965. from = out - dist; /* rest from output */
  82966. }
  82967. }
  82968. while (len > 2) {
  82969. PUP(out) = PUP(from);
  82970. PUP(out) = PUP(from);
  82971. PUP(out) = PUP(from);
  82972. len -= 3;
  82973. }
  82974. if (len) {
  82975. PUP(out) = PUP(from);
  82976. if (len > 1)
  82977. PUP(out) = PUP(from);
  82978. }
  82979. }
  82980. else {
  82981. from = out - dist; /* copy direct from output */
  82982. do { /* minimum length is three */
  82983. PUP(out) = PUP(from);
  82984. PUP(out) = PUP(from);
  82985. PUP(out) = PUP(from);
  82986. len -= 3;
  82987. } while (len > 2);
  82988. if (len) {
  82989. PUP(out) = PUP(from);
  82990. if (len > 1)
  82991. PUP(out) = PUP(from);
  82992. }
  82993. }
  82994. }
  82995. else if ((op & 64) == 0) { /* 2nd level distance code */
  82996. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82997. goto dodist;
  82998. }
  82999. else {
  83000. strm->msg = (char *)"invalid distance code";
  83001. state->mode = BAD;
  83002. break;
  83003. }
  83004. }
  83005. else if ((op & 64) == 0) { /* 2nd level length code */
  83006. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83007. goto dolen;
  83008. }
  83009. else if (op & 32) { /* end-of-block */
  83010. Tracevv((stderr, "inflate: end of block\n"));
  83011. state->mode = TYPE;
  83012. break;
  83013. }
  83014. else {
  83015. strm->msg = (char *)"invalid literal/length code";
  83016. state->mode = BAD;
  83017. break;
  83018. }
  83019. } while (in < last && out < end);
  83020. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83021. len = bits >> 3;
  83022. in -= len;
  83023. bits -= len << 3;
  83024. hold &= (1U << bits) - 1;
  83025. /* update state and return */
  83026. strm->next_in = in + OFF;
  83027. strm->next_out = out + OFF;
  83028. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83029. strm->avail_out = (unsigned)(out < end ?
  83030. 257 + (end - out) : 257 - (out - end));
  83031. state->hold = hold;
  83032. state->bits = bits;
  83033. return;
  83034. }
  83035. /*
  83036. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83037. - Using bit fields for code structure
  83038. - Different op definition to avoid & for extra bits (do & for table bits)
  83039. - Three separate decoding do-loops for direct, window, and write == 0
  83040. - Special case for distance > 1 copies to do overlapped load and store copy
  83041. - Explicit branch predictions (based on measured branch probabilities)
  83042. - Deferring match copy and interspersed it with decoding subsequent codes
  83043. - Swapping literal/length else
  83044. - Swapping window/direct else
  83045. - Larger unrolled copy loops (three is about right)
  83046. - Moving len -= 3 statement into middle of loop
  83047. */
  83048. #endif /* !ASMINF */
  83049. /*** End of inlined file: inffast.c ***/
  83050. #undef PULLBYTE
  83051. #undef LOAD
  83052. #undef RESTORE
  83053. #undef INITBITS
  83054. #undef NEEDBITS
  83055. #undef DROPBITS
  83056. #undef BYTEBITS
  83057. /*** Start of inlined file: inflate.c ***/
  83058. /*
  83059. * Change history:
  83060. *
  83061. * 1.2.beta0 24 Nov 2002
  83062. * - First version -- complete rewrite of inflate to simplify code, avoid
  83063. * creation of window when not needed, minimize use of window when it is
  83064. * needed, make inffast.c even faster, implement gzip decoding, and to
  83065. * improve code readability and style over the previous zlib inflate code
  83066. *
  83067. * 1.2.beta1 25 Nov 2002
  83068. * - Use pointers for available input and output checking in inffast.c
  83069. * - Remove input and output counters in inffast.c
  83070. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83071. * - Remove unnecessary second byte pull from length extra in inffast.c
  83072. * - Unroll direct copy to three copies per loop in inffast.c
  83073. *
  83074. * 1.2.beta2 4 Dec 2002
  83075. * - Change external routine names to reduce potential conflicts
  83076. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83077. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83078. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83079. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83080. *
  83081. * 1.2.beta3 22 Dec 2002
  83082. * - Add comments on state->bits assertion in inffast.c
  83083. * - Add comments on op field in inftrees.h
  83084. * - Fix bug in reuse of allocated window after inflateReset()
  83085. * - Remove bit fields--back to byte structure for speed
  83086. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83087. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83088. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83089. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83090. * - Use local copies of stream next and avail values, as well as local bit
  83091. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83092. *
  83093. * 1.2.beta4 1 Jan 2003
  83094. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83095. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83096. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83097. * - Rearrange window copies in inflate_fast() for speed and simplification
  83098. * - Unroll last copy for window match in inflate_fast()
  83099. * - Use local copies of window variables in inflate_fast() for speed
  83100. * - Pull out common write == 0 case for speed in inflate_fast()
  83101. * - Make op and len in inflate_fast() unsigned for consistency
  83102. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83103. * - Simplified bad distance check in inflate_fast()
  83104. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83105. * source file infback.c to provide a call-back interface to inflate for
  83106. * programs like gzip and unzip -- uses window as output buffer to avoid
  83107. * window copying
  83108. *
  83109. * 1.2.beta5 1 Jan 2003
  83110. * - Improved inflateBack() interface to allow the caller to provide initial
  83111. * input in strm.
  83112. * - Fixed stored blocks bug in inflateBack()
  83113. *
  83114. * 1.2.beta6 4 Jan 2003
  83115. * - Added comments in inffast.c on effectiveness of POSTINC
  83116. * - Typecasting all around to reduce compiler warnings
  83117. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83118. * make compilers happy
  83119. * - Changed type of window in inflateBackInit() to unsigned char *
  83120. *
  83121. * 1.2.beta7 27 Jan 2003
  83122. * - Changed many types to unsigned or unsigned short to avoid warnings
  83123. * - Added inflateCopy() function
  83124. *
  83125. * 1.2.0 9 Mar 2003
  83126. * - Changed inflateBack() interface to provide separate opaque descriptors
  83127. * for the in() and out() functions
  83128. * - Changed inflateBack() argument and in_func typedef to swap the length
  83129. * and buffer address return values for the input function
  83130. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83131. *
  83132. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83133. */
  83134. /*** Start of inlined file: inffast.h ***/
  83135. /* WARNING: this file should *not* be used by applications. It is
  83136. part of the implementation of the compression library and is
  83137. subject to change. Applications should only use zlib.h.
  83138. */
  83139. void inflate_fast OF((z_streamp strm, unsigned start));
  83140. /*** End of inlined file: inffast.h ***/
  83141. #ifdef MAKEFIXED
  83142. # ifndef BUILDFIXED
  83143. # define BUILDFIXED
  83144. # endif
  83145. #endif
  83146. /* function prototypes */
  83147. local void fixedtables OF((struct inflate_state FAR *state));
  83148. local int updatewindow OF((z_streamp strm, unsigned out));
  83149. #ifdef BUILDFIXED
  83150. void makefixed OF((void));
  83151. #endif
  83152. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83153. unsigned len));
  83154. int ZEXPORT inflateReset (z_streamp strm)
  83155. {
  83156. struct inflate_state FAR *state;
  83157. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83158. state = (struct inflate_state FAR *)strm->state;
  83159. strm->total_in = strm->total_out = state->total = 0;
  83160. strm->msg = Z_NULL;
  83161. strm->adler = 1; /* to support ill-conceived Java test suite */
  83162. state->mode = HEAD;
  83163. state->last = 0;
  83164. state->havedict = 0;
  83165. state->dmax = 32768U;
  83166. state->head = Z_NULL;
  83167. state->wsize = 0;
  83168. state->whave = 0;
  83169. state->write = 0;
  83170. state->hold = 0;
  83171. state->bits = 0;
  83172. state->lencode = state->distcode = state->next = state->codes;
  83173. Tracev((stderr, "inflate: reset\n"));
  83174. return Z_OK;
  83175. }
  83176. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83177. {
  83178. struct inflate_state FAR *state;
  83179. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83180. state = (struct inflate_state FAR *)strm->state;
  83181. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83182. value &= (1L << bits) - 1;
  83183. state->hold += value << state->bits;
  83184. state->bits += bits;
  83185. return Z_OK;
  83186. }
  83187. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83188. {
  83189. struct inflate_state FAR *state;
  83190. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83191. stream_size != (int)(sizeof(z_stream)))
  83192. return Z_VERSION_ERROR;
  83193. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83194. strm->msg = Z_NULL; /* in case we return an error */
  83195. if (strm->zalloc == (alloc_func)0) {
  83196. strm->zalloc = zcalloc;
  83197. strm->opaque = (voidpf)0;
  83198. }
  83199. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83200. state = (struct inflate_state FAR *)
  83201. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83202. if (state == Z_NULL) return Z_MEM_ERROR;
  83203. Tracev((stderr, "inflate: allocated\n"));
  83204. strm->state = (struct internal_state FAR *)state;
  83205. if (windowBits < 0) {
  83206. state->wrap = 0;
  83207. windowBits = -windowBits;
  83208. }
  83209. else {
  83210. state->wrap = (windowBits >> 4) + 1;
  83211. #ifdef GUNZIP
  83212. if (windowBits < 48) windowBits &= 15;
  83213. #endif
  83214. }
  83215. if (windowBits < 8 || windowBits > 15) {
  83216. ZFREE(strm, state);
  83217. strm->state = Z_NULL;
  83218. return Z_STREAM_ERROR;
  83219. }
  83220. state->wbits = (unsigned)windowBits;
  83221. state->window = Z_NULL;
  83222. return inflateReset(strm);
  83223. }
  83224. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83225. {
  83226. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83227. }
  83228. /*
  83229. Return state with length and distance decoding tables and index sizes set to
  83230. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83231. If BUILDFIXED is defined, then instead this routine builds the tables the
  83232. first time it's called, and returns those tables the first time and
  83233. thereafter. This reduces the size of the code by about 2K bytes, in
  83234. exchange for a little execution time. However, BUILDFIXED should not be
  83235. used for threaded applications, since the rewriting of the tables and virgin
  83236. may not be thread-safe.
  83237. */
  83238. local void fixedtables (struct inflate_state FAR *state)
  83239. {
  83240. #ifdef BUILDFIXED
  83241. static int virgin = 1;
  83242. static code *lenfix, *distfix;
  83243. static code fixed[544];
  83244. /* build fixed huffman tables if first call (may not be thread safe) */
  83245. if (virgin) {
  83246. unsigned sym, bits;
  83247. static code *next;
  83248. /* literal/length table */
  83249. sym = 0;
  83250. while (sym < 144) state->lens[sym++] = 8;
  83251. while (sym < 256) state->lens[sym++] = 9;
  83252. while (sym < 280) state->lens[sym++] = 7;
  83253. while (sym < 288) state->lens[sym++] = 8;
  83254. next = fixed;
  83255. lenfix = next;
  83256. bits = 9;
  83257. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83258. /* distance table */
  83259. sym = 0;
  83260. while (sym < 32) state->lens[sym++] = 5;
  83261. distfix = next;
  83262. bits = 5;
  83263. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83264. /* do this just once */
  83265. virgin = 0;
  83266. }
  83267. #else /* !BUILDFIXED */
  83268. /*** Start of inlined file: inffixed.h ***/
  83269. /* WARNING: this file should *not* be used by applications. It
  83270. is part of the implementation of the compression library and
  83271. is subject to change. Applications should only use zlib.h.
  83272. */
  83273. static const code lenfix[512] = {
  83274. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83275. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83276. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83277. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83278. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83279. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83280. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83281. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83282. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83283. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83284. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83285. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83286. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83287. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83288. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83289. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83290. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83291. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83292. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83293. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83294. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83295. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83296. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83297. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83298. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83299. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83300. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83301. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83302. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83303. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83304. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83305. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83306. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83307. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83308. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83309. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83310. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83311. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83312. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83313. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83314. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83315. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83316. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83317. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83318. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83319. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83320. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83321. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83322. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83323. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83324. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83325. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83326. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83327. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83328. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83329. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83330. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83331. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83332. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83333. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83334. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83335. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83336. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83337. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83338. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83339. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83340. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83341. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83342. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83343. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83344. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83345. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83346. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83347. {0,9,255}
  83348. };
  83349. static const code distfix[32] = {
  83350. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83351. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83352. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83353. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83354. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83355. {22,5,193},{64,5,0}
  83356. };
  83357. /*** End of inlined file: inffixed.h ***/
  83358. #endif /* BUILDFIXED */
  83359. state->lencode = lenfix;
  83360. state->lenbits = 9;
  83361. state->distcode = distfix;
  83362. state->distbits = 5;
  83363. }
  83364. #ifdef MAKEFIXED
  83365. #include <stdio.h>
  83366. /*
  83367. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83368. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83369. those tables to stdout, which would be piped to inffixed.h. A small program
  83370. can simply call makefixed to do this:
  83371. void makefixed(void);
  83372. int main(void)
  83373. {
  83374. makefixed();
  83375. return 0;
  83376. }
  83377. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83378. a.out > inffixed.h
  83379. */
  83380. void makefixed()
  83381. {
  83382. unsigned low, size;
  83383. struct inflate_state state;
  83384. fixedtables(&state);
  83385. puts(" /* inffixed.h -- table for decoding fixed codes");
  83386. puts(" * Generated automatically by makefixed().");
  83387. puts(" */");
  83388. puts("");
  83389. puts(" /* WARNING: this file should *not* be used by applications.");
  83390. puts(" It is part of the implementation of this library and is");
  83391. puts(" subject to change. Applications should only use zlib.h.");
  83392. puts(" */");
  83393. puts("");
  83394. size = 1U << 9;
  83395. printf(" static const code lenfix[%u] = {", size);
  83396. low = 0;
  83397. for (;;) {
  83398. if ((low % 7) == 0) printf("\n ");
  83399. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83400. state.lencode[low].val);
  83401. if (++low == size) break;
  83402. putchar(',');
  83403. }
  83404. puts("\n };");
  83405. size = 1U << 5;
  83406. printf("\n static const code distfix[%u] = {", size);
  83407. low = 0;
  83408. for (;;) {
  83409. if ((low % 6) == 0) printf("\n ");
  83410. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83411. state.distcode[low].val);
  83412. if (++low == size) break;
  83413. putchar(',');
  83414. }
  83415. puts("\n };");
  83416. }
  83417. #endif /* MAKEFIXED */
  83418. /*
  83419. Update the window with the last wsize (normally 32K) bytes written before
  83420. returning. If window does not exist yet, create it. This is only called
  83421. when a window is already in use, or when output has been written during this
  83422. inflate call, but the end of the deflate stream has not been reached yet.
  83423. It is also called to create a window for dictionary data when a dictionary
  83424. is loaded.
  83425. Providing output buffers larger than 32K to inflate() should provide a speed
  83426. advantage, since only the last 32K of output is copied to the sliding window
  83427. upon return from inflate(), and since all distances after the first 32K of
  83428. output will fall in the output data, making match copies simpler and faster.
  83429. The advantage may be dependent on the size of the processor's data caches.
  83430. */
  83431. local int updatewindow (z_streamp strm, unsigned out)
  83432. {
  83433. struct inflate_state FAR *state;
  83434. unsigned copy, dist;
  83435. state = (struct inflate_state FAR *)strm->state;
  83436. /* if it hasn't been done already, allocate space for the window */
  83437. if (state->window == Z_NULL) {
  83438. state->window = (unsigned char FAR *)
  83439. ZALLOC(strm, 1U << state->wbits,
  83440. sizeof(unsigned char));
  83441. if (state->window == Z_NULL) return 1;
  83442. }
  83443. /* if window not in use yet, initialize */
  83444. if (state->wsize == 0) {
  83445. state->wsize = 1U << state->wbits;
  83446. state->write = 0;
  83447. state->whave = 0;
  83448. }
  83449. /* copy state->wsize or less output bytes into the circular window */
  83450. copy = out - strm->avail_out;
  83451. if (copy >= state->wsize) {
  83452. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83453. state->write = 0;
  83454. state->whave = state->wsize;
  83455. }
  83456. else {
  83457. dist = state->wsize - state->write;
  83458. if (dist > copy) dist = copy;
  83459. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83460. copy -= dist;
  83461. if (copy) {
  83462. zmemcpy(state->window, strm->next_out - copy, copy);
  83463. state->write = copy;
  83464. state->whave = state->wsize;
  83465. }
  83466. else {
  83467. state->write += dist;
  83468. if (state->write == state->wsize) state->write = 0;
  83469. if (state->whave < state->wsize) state->whave += dist;
  83470. }
  83471. }
  83472. return 0;
  83473. }
  83474. /* Macros for inflate(): */
  83475. /* check function to use adler32() for zlib or crc32() for gzip */
  83476. #ifdef GUNZIP
  83477. # define UPDATE(check, buf, len) \
  83478. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83479. #else
  83480. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83481. #endif
  83482. /* check macros for header crc */
  83483. #ifdef GUNZIP
  83484. # define CRC2(check, word) \
  83485. do { \
  83486. hbuf[0] = (unsigned char)(word); \
  83487. hbuf[1] = (unsigned char)((word) >> 8); \
  83488. check = crc32(check, hbuf, 2); \
  83489. } while (0)
  83490. # define CRC4(check, word) \
  83491. do { \
  83492. hbuf[0] = (unsigned char)(word); \
  83493. hbuf[1] = (unsigned char)((word) >> 8); \
  83494. hbuf[2] = (unsigned char)((word) >> 16); \
  83495. hbuf[3] = (unsigned char)((word) >> 24); \
  83496. check = crc32(check, hbuf, 4); \
  83497. } while (0)
  83498. #endif
  83499. /* Load registers with state in inflate() for speed */
  83500. #define LOAD() \
  83501. do { \
  83502. put = strm->next_out; \
  83503. left = strm->avail_out; \
  83504. next = strm->next_in; \
  83505. have = strm->avail_in; \
  83506. hold = state->hold; \
  83507. bits = state->bits; \
  83508. } while (0)
  83509. /* Restore state from registers in inflate() */
  83510. #define RESTORE() \
  83511. do { \
  83512. strm->next_out = put; \
  83513. strm->avail_out = left; \
  83514. strm->next_in = next; \
  83515. strm->avail_in = have; \
  83516. state->hold = hold; \
  83517. state->bits = bits; \
  83518. } while (0)
  83519. /* Clear the input bit accumulator */
  83520. #define INITBITS() \
  83521. do { \
  83522. hold = 0; \
  83523. bits = 0; \
  83524. } while (0)
  83525. /* Get a byte of input into the bit accumulator, or return from inflate()
  83526. if there is no input available. */
  83527. #define PULLBYTE() \
  83528. do { \
  83529. if (have == 0) goto inf_leave; \
  83530. have--; \
  83531. hold += (unsigned long)(*next++) << bits; \
  83532. bits += 8; \
  83533. } while (0)
  83534. /* Assure that there are at least n bits in the bit accumulator. If there is
  83535. not enough available input to do that, then return from inflate(). */
  83536. #define NEEDBITS(n) \
  83537. do { \
  83538. while (bits < (unsigned)(n)) \
  83539. PULLBYTE(); \
  83540. } while (0)
  83541. /* Return the low n bits of the bit accumulator (n < 16) */
  83542. #define BITS(n) \
  83543. ((unsigned)hold & ((1U << (n)) - 1))
  83544. /* Remove n bits from the bit accumulator */
  83545. #define DROPBITS(n) \
  83546. do { \
  83547. hold >>= (n); \
  83548. bits -= (unsigned)(n); \
  83549. } while (0)
  83550. /* Remove zero to seven bits as needed to go to a byte boundary */
  83551. #define BYTEBITS() \
  83552. do { \
  83553. hold >>= bits & 7; \
  83554. bits -= bits & 7; \
  83555. } while (0)
  83556. /* Reverse the bytes in a 32-bit value */
  83557. #define REVERSE(q) \
  83558. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83559. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83560. /*
  83561. inflate() uses a state machine to process as much input data and generate as
  83562. much output data as possible before returning. The state machine is
  83563. structured roughly as follows:
  83564. for (;;) switch (state) {
  83565. ...
  83566. case STATEn:
  83567. if (not enough input data or output space to make progress)
  83568. return;
  83569. ... make progress ...
  83570. state = STATEm;
  83571. break;
  83572. ...
  83573. }
  83574. so when inflate() is called again, the same case is attempted again, and
  83575. if the appropriate resources are provided, the machine proceeds to the
  83576. next state. The NEEDBITS() macro is usually the way the state evaluates
  83577. whether it can proceed or should return. NEEDBITS() does the return if
  83578. the requested bits are not available. The typical use of the BITS macros
  83579. is:
  83580. NEEDBITS(n);
  83581. ... do something with BITS(n) ...
  83582. DROPBITS(n);
  83583. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83584. input left to load n bits into the accumulator, or it continues. BITS(n)
  83585. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83586. the low n bits off the accumulator. INITBITS() clears the accumulator
  83587. and sets the number of available bits to zero. BYTEBITS() discards just
  83588. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83589. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83590. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83591. if there is no input available. The decoding of variable length codes uses
  83592. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83593. code, and no more.
  83594. Some states loop until they get enough input, making sure that enough
  83595. state information is maintained to continue the loop where it left off
  83596. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83597. would all have to actually be part of the saved state in case NEEDBITS()
  83598. returns:
  83599. case STATEw:
  83600. while (want < need) {
  83601. NEEDBITS(n);
  83602. keep[want++] = BITS(n);
  83603. DROPBITS(n);
  83604. }
  83605. state = STATEx;
  83606. case STATEx:
  83607. As shown above, if the next state is also the next case, then the break
  83608. is omitted.
  83609. A state may also return if there is not enough output space available to
  83610. complete that state. Those states are copying stored data, writing a
  83611. literal byte, and copying a matching string.
  83612. When returning, a "goto inf_leave" is used to update the total counters,
  83613. update the check value, and determine whether any progress has been made
  83614. during that inflate() call in order to return the proper return code.
  83615. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83616. When there is a window, goto inf_leave will update the window with the last
  83617. output written. If a goto inf_leave occurs in the middle of decompression
  83618. and there is no window currently, goto inf_leave will create one and copy
  83619. output to the window for the next call of inflate().
  83620. In this implementation, the flush parameter of inflate() only affects the
  83621. return code (per zlib.h). inflate() always writes as much as possible to
  83622. strm->next_out, given the space available and the provided input--the effect
  83623. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83624. the allocation of and copying into a sliding window until necessary, which
  83625. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83626. stream available. So the only thing the flush parameter actually does is:
  83627. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83628. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83629. */
  83630. int ZEXPORT inflate (z_streamp strm, int flush)
  83631. {
  83632. struct inflate_state FAR *state;
  83633. unsigned char FAR *next; /* next input */
  83634. unsigned char FAR *put; /* next output */
  83635. unsigned have, left; /* available input and output */
  83636. unsigned long hold; /* bit buffer */
  83637. unsigned bits; /* bits in bit buffer */
  83638. unsigned in, out; /* save starting available input and output */
  83639. unsigned copy; /* number of stored or match bytes to copy */
  83640. unsigned char FAR *from; /* where to copy match bytes from */
  83641. code thisx; /* current decoding table entry */
  83642. code last; /* parent table entry */
  83643. unsigned len; /* length to copy for repeats, bits to drop */
  83644. int ret; /* return code */
  83645. #ifdef GUNZIP
  83646. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83647. #endif
  83648. static const unsigned short order[19] = /* permutation of code lengths */
  83649. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83650. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83651. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83652. return Z_STREAM_ERROR;
  83653. state = (struct inflate_state FAR *)strm->state;
  83654. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83655. LOAD();
  83656. in = have;
  83657. out = left;
  83658. ret = Z_OK;
  83659. for (;;)
  83660. switch (state->mode) {
  83661. case HEAD:
  83662. if (state->wrap == 0) {
  83663. state->mode = TYPEDO;
  83664. break;
  83665. }
  83666. NEEDBITS(16);
  83667. #ifdef GUNZIP
  83668. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83669. state->check = crc32(0L, Z_NULL, 0);
  83670. CRC2(state->check, hold);
  83671. INITBITS();
  83672. state->mode = FLAGS;
  83673. break;
  83674. }
  83675. state->flags = 0; /* expect zlib header */
  83676. if (state->head != Z_NULL)
  83677. state->head->done = -1;
  83678. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83679. #else
  83680. if (
  83681. #endif
  83682. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83683. strm->msg = (char *)"incorrect header check";
  83684. state->mode = BAD;
  83685. break;
  83686. }
  83687. if (BITS(4) != Z_DEFLATED) {
  83688. strm->msg = (char *)"unknown compression method";
  83689. state->mode = BAD;
  83690. break;
  83691. }
  83692. DROPBITS(4);
  83693. len = BITS(4) + 8;
  83694. if (len > state->wbits) {
  83695. strm->msg = (char *)"invalid window size";
  83696. state->mode = BAD;
  83697. break;
  83698. }
  83699. state->dmax = 1U << len;
  83700. Tracev((stderr, "inflate: zlib header ok\n"));
  83701. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83702. state->mode = hold & 0x200 ? DICTID : TYPE;
  83703. INITBITS();
  83704. break;
  83705. #ifdef GUNZIP
  83706. case FLAGS:
  83707. NEEDBITS(16);
  83708. state->flags = (int)(hold);
  83709. if ((state->flags & 0xff) != Z_DEFLATED) {
  83710. strm->msg = (char *)"unknown compression method";
  83711. state->mode = BAD;
  83712. break;
  83713. }
  83714. if (state->flags & 0xe000) {
  83715. strm->msg = (char *)"unknown header flags set";
  83716. state->mode = BAD;
  83717. break;
  83718. }
  83719. if (state->head != Z_NULL)
  83720. state->head->text = (int)((hold >> 8) & 1);
  83721. if (state->flags & 0x0200) CRC2(state->check, hold);
  83722. INITBITS();
  83723. state->mode = TIME;
  83724. case TIME:
  83725. NEEDBITS(32);
  83726. if (state->head != Z_NULL)
  83727. state->head->time = hold;
  83728. if (state->flags & 0x0200) CRC4(state->check, hold);
  83729. INITBITS();
  83730. state->mode = OS;
  83731. case OS:
  83732. NEEDBITS(16);
  83733. if (state->head != Z_NULL) {
  83734. state->head->xflags = (int)(hold & 0xff);
  83735. state->head->os = (int)(hold >> 8);
  83736. }
  83737. if (state->flags & 0x0200) CRC2(state->check, hold);
  83738. INITBITS();
  83739. state->mode = EXLEN;
  83740. case EXLEN:
  83741. if (state->flags & 0x0400) {
  83742. NEEDBITS(16);
  83743. state->length = (unsigned)(hold);
  83744. if (state->head != Z_NULL)
  83745. state->head->extra_len = (unsigned)hold;
  83746. if (state->flags & 0x0200) CRC2(state->check, hold);
  83747. INITBITS();
  83748. }
  83749. else if (state->head != Z_NULL)
  83750. state->head->extra = Z_NULL;
  83751. state->mode = EXTRA;
  83752. case EXTRA:
  83753. if (state->flags & 0x0400) {
  83754. copy = state->length;
  83755. if (copy > have) copy = have;
  83756. if (copy) {
  83757. if (state->head != Z_NULL &&
  83758. state->head->extra != Z_NULL) {
  83759. len = state->head->extra_len - state->length;
  83760. zmemcpy(state->head->extra + len, next,
  83761. len + copy > state->head->extra_max ?
  83762. state->head->extra_max - len : copy);
  83763. }
  83764. if (state->flags & 0x0200)
  83765. state->check = crc32(state->check, next, copy);
  83766. have -= copy;
  83767. next += copy;
  83768. state->length -= copy;
  83769. }
  83770. if (state->length) goto inf_leave;
  83771. }
  83772. state->length = 0;
  83773. state->mode = NAME;
  83774. case NAME:
  83775. if (state->flags & 0x0800) {
  83776. if (have == 0) goto inf_leave;
  83777. copy = 0;
  83778. do {
  83779. len = (unsigned)(next[copy++]);
  83780. if (state->head != Z_NULL &&
  83781. state->head->name != Z_NULL &&
  83782. state->length < state->head->name_max)
  83783. state->head->name[state->length++] = len;
  83784. } while (len && copy < have);
  83785. if (state->flags & 0x0200)
  83786. state->check = crc32(state->check, next, copy);
  83787. have -= copy;
  83788. next += copy;
  83789. if (len) goto inf_leave;
  83790. }
  83791. else if (state->head != Z_NULL)
  83792. state->head->name = Z_NULL;
  83793. state->length = 0;
  83794. state->mode = COMMENT;
  83795. case COMMENT:
  83796. if (state->flags & 0x1000) {
  83797. if (have == 0) goto inf_leave;
  83798. copy = 0;
  83799. do {
  83800. len = (unsigned)(next[copy++]);
  83801. if (state->head != Z_NULL &&
  83802. state->head->comment != Z_NULL &&
  83803. state->length < state->head->comm_max)
  83804. state->head->comment[state->length++] = len;
  83805. } while (len && copy < have);
  83806. if (state->flags & 0x0200)
  83807. state->check = crc32(state->check, next, copy);
  83808. have -= copy;
  83809. next += copy;
  83810. if (len) goto inf_leave;
  83811. }
  83812. else if (state->head != Z_NULL)
  83813. state->head->comment = Z_NULL;
  83814. state->mode = HCRC;
  83815. case HCRC:
  83816. if (state->flags & 0x0200) {
  83817. NEEDBITS(16);
  83818. if (hold != (state->check & 0xffff)) {
  83819. strm->msg = (char *)"header crc mismatch";
  83820. state->mode = BAD;
  83821. break;
  83822. }
  83823. INITBITS();
  83824. }
  83825. if (state->head != Z_NULL) {
  83826. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83827. state->head->done = 1;
  83828. }
  83829. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83830. state->mode = TYPE;
  83831. break;
  83832. #endif
  83833. case DICTID:
  83834. NEEDBITS(32);
  83835. strm->adler = state->check = REVERSE(hold);
  83836. INITBITS();
  83837. state->mode = DICT;
  83838. case DICT:
  83839. if (state->havedict == 0) {
  83840. RESTORE();
  83841. return Z_NEED_DICT;
  83842. }
  83843. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83844. state->mode = TYPE;
  83845. case TYPE:
  83846. if (flush == Z_BLOCK) goto inf_leave;
  83847. case TYPEDO:
  83848. if (state->last) {
  83849. BYTEBITS();
  83850. state->mode = CHECK;
  83851. break;
  83852. }
  83853. NEEDBITS(3);
  83854. state->last = BITS(1);
  83855. DROPBITS(1);
  83856. switch (BITS(2)) {
  83857. case 0: /* stored block */
  83858. Tracev((stderr, "inflate: stored block%s\n",
  83859. state->last ? " (last)" : ""));
  83860. state->mode = STORED;
  83861. break;
  83862. case 1: /* fixed block */
  83863. fixedtables(state);
  83864. Tracev((stderr, "inflate: fixed codes block%s\n",
  83865. state->last ? " (last)" : ""));
  83866. state->mode = LEN; /* decode codes */
  83867. break;
  83868. case 2: /* dynamic block */
  83869. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83870. state->last ? " (last)" : ""));
  83871. state->mode = TABLE;
  83872. break;
  83873. case 3:
  83874. strm->msg = (char *)"invalid block type";
  83875. state->mode = BAD;
  83876. }
  83877. DROPBITS(2);
  83878. break;
  83879. case STORED:
  83880. BYTEBITS(); /* go to byte boundary */
  83881. NEEDBITS(32);
  83882. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83883. strm->msg = (char *)"invalid stored block lengths";
  83884. state->mode = BAD;
  83885. break;
  83886. }
  83887. state->length = (unsigned)hold & 0xffff;
  83888. Tracev((stderr, "inflate: stored length %u\n",
  83889. state->length));
  83890. INITBITS();
  83891. state->mode = COPY;
  83892. case COPY:
  83893. copy = state->length;
  83894. if (copy) {
  83895. if (copy > have) copy = have;
  83896. if (copy > left) copy = left;
  83897. if (copy == 0) goto inf_leave;
  83898. zmemcpy(put, next, copy);
  83899. have -= copy;
  83900. next += copy;
  83901. left -= copy;
  83902. put += copy;
  83903. state->length -= copy;
  83904. break;
  83905. }
  83906. Tracev((stderr, "inflate: stored end\n"));
  83907. state->mode = TYPE;
  83908. break;
  83909. case TABLE:
  83910. NEEDBITS(14);
  83911. state->nlen = BITS(5) + 257;
  83912. DROPBITS(5);
  83913. state->ndist = BITS(5) + 1;
  83914. DROPBITS(5);
  83915. state->ncode = BITS(4) + 4;
  83916. DROPBITS(4);
  83917. #ifndef PKZIP_BUG_WORKAROUND
  83918. if (state->nlen > 286 || state->ndist > 30) {
  83919. strm->msg = (char *)"too many length or distance symbols";
  83920. state->mode = BAD;
  83921. break;
  83922. }
  83923. #endif
  83924. Tracev((stderr, "inflate: table sizes ok\n"));
  83925. state->have = 0;
  83926. state->mode = LENLENS;
  83927. case LENLENS:
  83928. while (state->have < state->ncode) {
  83929. NEEDBITS(3);
  83930. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83931. DROPBITS(3);
  83932. }
  83933. while (state->have < 19)
  83934. state->lens[order[state->have++]] = 0;
  83935. state->next = state->codes;
  83936. state->lencode = (code const FAR *)(state->next);
  83937. state->lenbits = 7;
  83938. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83939. &(state->lenbits), state->work);
  83940. if (ret) {
  83941. strm->msg = (char *)"invalid code lengths set";
  83942. state->mode = BAD;
  83943. break;
  83944. }
  83945. Tracev((stderr, "inflate: code lengths ok\n"));
  83946. state->have = 0;
  83947. state->mode = CODELENS;
  83948. case CODELENS:
  83949. while (state->have < state->nlen + state->ndist) {
  83950. for (;;) {
  83951. thisx = state->lencode[BITS(state->lenbits)];
  83952. if ((unsigned)(thisx.bits) <= bits) break;
  83953. PULLBYTE();
  83954. }
  83955. if (thisx.val < 16) {
  83956. NEEDBITS(thisx.bits);
  83957. DROPBITS(thisx.bits);
  83958. state->lens[state->have++] = thisx.val;
  83959. }
  83960. else {
  83961. if (thisx.val == 16) {
  83962. NEEDBITS(thisx.bits + 2);
  83963. DROPBITS(thisx.bits);
  83964. if (state->have == 0) {
  83965. strm->msg = (char *)"invalid bit length repeat";
  83966. state->mode = BAD;
  83967. break;
  83968. }
  83969. len = state->lens[state->have - 1];
  83970. copy = 3 + BITS(2);
  83971. DROPBITS(2);
  83972. }
  83973. else if (thisx.val == 17) {
  83974. NEEDBITS(thisx.bits + 3);
  83975. DROPBITS(thisx.bits);
  83976. len = 0;
  83977. copy = 3 + BITS(3);
  83978. DROPBITS(3);
  83979. }
  83980. else {
  83981. NEEDBITS(thisx.bits + 7);
  83982. DROPBITS(thisx.bits);
  83983. len = 0;
  83984. copy = 11 + BITS(7);
  83985. DROPBITS(7);
  83986. }
  83987. if (state->have + copy > state->nlen + state->ndist) {
  83988. strm->msg = (char *)"invalid bit length repeat";
  83989. state->mode = BAD;
  83990. break;
  83991. }
  83992. while (copy--)
  83993. state->lens[state->have++] = (unsigned short)len;
  83994. }
  83995. }
  83996. /* handle error breaks in while */
  83997. if (state->mode == BAD) break;
  83998. /* build code tables */
  83999. state->next = state->codes;
  84000. state->lencode = (code const FAR *)(state->next);
  84001. state->lenbits = 9;
  84002. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84003. &(state->lenbits), state->work);
  84004. if (ret) {
  84005. strm->msg = (char *)"invalid literal/lengths set";
  84006. state->mode = BAD;
  84007. break;
  84008. }
  84009. state->distcode = (code const FAR *)(state->next);
  84010. state->distbits = 6;
  84011. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84012. &(state->next), &(state->distbits), state->work);
  84013. if (ret) {
  84014. strm->msg = (char *)"invalid distances set";
  84015. state->mode = BAD;
  84016. break;
  84017. }
  84018. Tracev((stderr, "inflate: codes ok\n"));
  84019. state->mode = LEN;
  84020. case LEN:
  84021. if (have >= 6 && left >= 258) {
  84022. RESTORE();
  84023. inflate_fast(strm, out);
  84024. LOAD();
  84025. break;
  84026. }
  84027. for (;;) {
  84028. thisx = state->lencode[BITS(state->lenbits)];
  84029. if ((unsigned)(thisx.bits) <= bits) break;
  84030. PULLBYTE();
  84031. }
  84032. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84033. last = thisx;
  84034. for (;;) {
  84035. thisx = state->lencode[last.val +
  84036. (BITS(last.bits + last.op) >> last.bits)];
  84037. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84038. PULLBYTE();
  84039. }
  84040. DROPBITS(last.bits);
  84041. }
  84042. DROPBITS(thisx.bits);
  84043. state->length = (unsigned)thisx.val;
  84044. if ((int)(thisx.op) == 0) {
  84045. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84046. "inflate: literal '%c'\n" :
  84047. "inflate: literal 0x%02x\n", thisx.val));
  84048. state->mode = LIT;
  84049. break;
  84050. }
  84051. if (thisx.op & 32) {
  84052. Tracevv((stderr, "inflate: end of block\n"));
  84053. state->mode = TYPE;
  84054. break;
  84055. }
  84056. if (thisx.op & 64) {
  84057. strm->msg = (char *)"invalid literal/length code";
  84058. state->mode = BAD;
  84059. break;
  84060. }
  84061. state->extra = (unsigned)(thisx.op) & 15;
  84062. state->mode = LENEXT;
  84063. case LENEXT:
  84064. if (state->extra) {
  84065. NEEDBITS(state->extra);
  84066. state->length += BITS(state->extra);
  84067. DROPBITS(state->extra);
  84068. }
  84069. Tracevv((stderr, "inflate: length %u\n", state->length));
  84070. state->mode = DIST;
  84071. case DIST:
  84072. for (;;) {
  84073. thisx = state->distcode[BITS(state->distbits)];
  84074. if ((unsigned)(thisx.bits) <= bits) break;
  84075. PULLBYTE();
  84076. }
  84077. if ((thisx.op & 0xf0) == 0) {
  84078. last = thisx;
  84079. for (;;) {
  84080. thisx = state->distcode[last.val +
  84081. (BITS(last.bits + last.op) >> last.bits)];
  84082. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84083. PULLBYTE();
  84084. }
  84085. DROPBITS(last.bits);
  84086. }
  84087. DROPBITS(thisx.bits);
  84088. if (thisx.op & 64) {
  84089. strm->msg = (char *)"invalid distance code";
  84090. state->mode = BAD;
  84091. break;
  84092. }
  84093. state->offset = (unsigned)thisx.val;
  84094. state->extra = (unsigned)(thisx.op) & 15;
  84095. state->mode = DISTEXT;
  84096. case DISTEXT:
  84097. if (state->extra) {
  84098. NEEDBITS(state->extra);
  84099. state->offset += BITS(state->extra);
  84100. DROPBITS(state->extra);
  84101. }
  84102. #ifdef INFLATE_STRICT
  84103. if (state->offset > state->dmax) {
  84104. strm->msg = (char *)"invalid distance too far back";
  84105. state->mode = BAD;
  84106. break;
  84107. }
  84108. #endif
  84109. if (state->offset > state->whave + out - left) {
  84110. strm->msg = (char *)"invalid distance too far back";
  84111. state->mode = BAD;
  84112. break;
  84113. }
  84114. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84115. state->mode = MATCH;
  84116. case MATCH:
  84117. if (left == 0) goto inf_leave;
  84118. copy = out - left;
  84119. if (state->offset > copy) { /* copy from window */
  84120. copy = state->offset - copy;
  84121. if (copy > state->write) {
  84122. copy -= state->write;
  84123. from = state->window + (state->wsize - copy);
  84124. }
  84125. else
  84126. from = state->window + (state->write - copy);
  84127. if (copy > state->length) copy = state->length;
  84128. }
  84129. else { /* copy from output */
  84130. from = put - state->offset;
  84131. copy = state->length;
  84132. }
  84133. if (copy > left) copy = left;
  84134. left -= copy;
  84135. state->length -= copy;
  84136. do {
  84137. *put++ = *from++;
  84138. } while (--copy);
  84139. if (state->length == 0) state->mode = LEN;
  84140. break;
  84141. case LIT:
  84142. if (left == 0) goto inf_leave;
  84143. *put++ = (unsigned char)(state->length);
  84144. left--;
  84145. state->mode = LEN;
  84146. break;
  84147. case CHECK:
  84148. if (state->wrap) {
  84149. NEEDBITS(32);
  84150. out -= left;
  84151. strm->total_out += out;
  84152. state->total += out;
  84153. if (out)
  84154. strm->adler = state->check =
  84155. UPDATE(state->check, put - out, out);
  84156. out = left;
  84157. if ((
  84158. #ifdef GUNZIP
  84159. state->flags ? hold :
  84160. #endif
  84161. REVERSE(hold)) != state->check) {
  84162. strm->msg = (char *)"incorrect data check";
  84163. state->mode = BAD;
  84164. break;
  84165. }
  84166. INITBITS();
  84167. Tracev((stderr, "inflate: check matches trailer\n"));
  84168. }
  84169. #ifdef GUNZIP
  84170. state->mode = LENGTH;
  84171. case LENGTH:
  84172. if (state->wrap && state->flags) {
  84173. NEEDBITS(32);
  84174. if (hold != (state->total & 0xffffffffUL)) {
  84175. strm->msg = (char *)"incorrect length check";
  84176. state->mode = BAD;
  84177. break;
  84178. }
  84179. INITBITS();
  84180. Tracev((stderr, "inflate: length matches trailer\n"));
  84181. }
  84182. #endif
  84183. state->mode = DONE;
  84184. case DONE:
  84185. ret = Z_STREAM_END;
  84186. goto inf_leave;
  84187. case BAD:
  84188. ret = Z_DATA_ERROR;
  84189. goto inf_leave;
  84190. case MEM:
  84191. return Z_MEM_ERROR;
  84192. case SYNC:
  84193. default:
  84194. return Z_STREAM_ERROR;
  84195. }
  84196. /*
  84197. Return from inflate(), updating the total counts and the check value.
  84198. If there was no progress during the inflate() call, return a buffer
  84199. error. Call updatewindow() to create and/or update the window state.
  84200. Note: a memory error from inflate() is non-recoverable.
  84201. */
  84202. inf_leave:
  84203. RESTORE();
  84204. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84205. if (updatewindow(strm, out)) {
  84206. state->mode = MEM;
  84207. return Z_MEM_ERROR;
  84208. }
  84209. in -= strm->avail_in;
  84210. out -= strm->avail_out;
  84211. strm->total_in += in;
  84212. strm->total_out += out;
  84213. state->total += out;
  84214. if (state->wrap && out)
  84215. strm->adler = state->check =
  84216. UPDATE(state->check, strm->next_out - out, out);
  84217. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84218. (state->mode == TYPE ? 128 : 0);
  84219. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84220. ret = Z_BUF_ERROR;
  84221. return ret;
  84222. }
  84223. int ZEXPORT inflateEnd (z_streamp strm)
  84224. {
  84225. struct inflate_state FAR *state;
  84226. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84227. return Z_STREAM_ERROR;
  84228. state = (struct inflate_state FAR *)strm->state;
  84229. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84230. ZFREE(strm, strm->state);
  84231. strm->state = Z_NULL;
  84232. Tracev((stderr, "inflate: end\n"));
  84233. return Z_OK;
  84234. }
  84235. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84236. {
  84237. struct inflate_state FAR *state;
  84238. unsigned long id_;
  84239. /* check state */
  84240. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84241. state = (struct inflate_state FAR *)strm->state;
  84242. if (state->wrap != 0 && state->mode != DICT)
  84243. return Z_STREAM_ERROR;
  84244. /* check for correct dictionary id */
  84245. if (state->mode == DICT) {
  84246. id_ = adler32(0L, Z_NULL, 0);
  84247. id_ = adler32(id_, dictionary, dictLength);
  84248. if (id_ != state->check)
  84249. return Z_DATA_ERROR;
  84250. }
  84251. /* copy dictionary to window */
  84252. if (updatewindow(strm, strm->avail_out)) {
  84253. state->mode = MEM;
  84254. return Z_MEM_ERROR;
  84255. }
  84256. if (dictLength > state->wsize) {
  84257. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84258. state->wsize);
  84259. state->whave = state->wsize;
  84260. }
  84261. else {
  84262. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84263. dictLength);
  84264. state->whave = dictLength;
  84265. }
  84266. state->havedict = 1;
  84267. Tracev((stderr, "inflate: dictionary set\n"));
  84268. return Z_OK;
  84269. }
  84270. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84271. {
  84272. struct inflate_state FAR *state;
  84273. /* check state */
  84274. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84275. state = (struct inflate_state FAR *)strm->state;
  84276. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84277. /* save header structure */
  84278. state->head = head;
  84279. head->done = 0;
  84280. return Z_OK;
  84281. }
  84282. /*
  84283. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84284. or when out of input. When called, *have is the number of pattern bytes
  84285. found in order so far, in 0..3. On return *have is updated to the new
  84286. state. If on return *have equals four, then the pattern was found and the
  84287. return value is how many bytes were read including the last byte of the
  84288. pattern. If *have is less than four, then the pattern has not been found
  84289. yet and the return value is len. In the latter case, syncsearch() can be
  84290. called again with more data and the *have state. *have is initialized to
  84291. zero for the first call.
  84292. */
  84293. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84294. {
  84295. unsigned got;
  84296. unsigned next;
  84297. got = *have;
  84298. next = 0;
  84299. while (next < len && got < 4) {
  84300. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84301. got++;
  84302. else if (buf[next])
  84303. got = 0;
  84304. else
  84305. got = 4 - got;
  84306. next++;
  84307. }
  84308. *have = got;
  84309. return next;
  84310. }
  84311. int ZEXPORT inflateSync (z_streamp strm)
  84312. {
  84313. unsigned len; /* number of bytes to look at or looked at */
  84314. unsigned long in, out; /* temporary to save total_in and total_out */
  84315. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84316. struct inflate_state FAR *state;
  84317. /* check parameters */
  84318. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84319. state = (struct inflate_state FAR *)strm->state;
  84320. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84321. /* if first time, start search in bit buffer */
  84322. if (state->mode != SYNC) {
  84323. state->mode = SYNC;
  84324. state->hold <<= state->bits & 7;
  84325. state->bits -= state->bits & 7;
  84326. len = 0;
  84327. while (state->bits >= 8) {
  84328. buf[len++] = (unsigned char)(state->hold);
  84329. state->hold >>= 8;
  84330. state->bits -= 8;
  84331. }
  84332. state->have = 0;
  84333. syncsearch(&(state->have), buf, len);
  84334. }
  84335. /* search available input */
  84336. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84337. strm->avail_in -= len;
  84338. strm->next_in += len;
  84339. strm->total_in += len;
  84340. /* return no joy or set up to restart inflate() on a new block */
  84341. if (state->have != 4) return Z_DATA_ERROR;
  84342. in = strm->total_in; out = strm->total_out;
  84343. inflateReset(strm);
  84344. strm->total_in = in; strm->total_out = out;
  84345. state->mode = TYPE;
  84346. return Z_OK;
  84347. }
  84348. /*
  84349. Returns true if inflate is currently at the end of a block generated by
  84350. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84351. implementation to provide an additional safety check. PPP uses
  84352. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84353. block. When decompressing, PPP checks that at the end of input packet,
  84354. inflate is waiting for these length bytes.
  84355. */
  84356. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84357. {
  84358. struct inflate_state FAR *state;
  84359. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84360. state = (struct inflate_state FAR *)strm->state;
  84361. return state->mode == STORED && state->bits == 0;
  84362. }
  84363. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84364. {
  84365. struct inflate_state FAR *state;
  84366. struct inflate_state FAR *copy;
  84367. unsigned char FAR *window;
  84368. unsigned wsize;
  84369. /* check input */
  84370. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84371. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84372. return Z_STREAM_ERROR;
  84373. state = (struct inflate_state FAR *)source->state;
  84374. /* allocate space */
  84375. copy = (struct inflate_state FAR *)
  84376. ZALLOC(source, 1, sizeof(struct inflate_state));
  84377. if (copy == Z_NULL) return Z_MEM_ERROR;
  84378. window = Z_NULL;
  84379. if (state->window != Z_NULL) {
  84380. window = (unsigned char FAR *)
  84381. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84382. if (window == Z_NULL) {
  84383. ZFREE(source, copy);
  84384. return Z_MEM_ERROR;
  84385. }
  84386. }
  84387. /* copy state */
  84388. zmemcpy(dest, source, sizeof(z_stream));
  84389. zmemcpy(copy, state, sizeof(struct inflate_state));
  84390. if (state->lencode >= state->codes &&
  84391. state->lencode <= state->codes + ENOUGH - 1) {
  84392. copy->lencode = copy->codes + (state->lencode - state->codes);
  84393. copy->distcode = copy->codes + (state->distcode - state->codes);
  84394. }
  84395. copy->next = copy->codes + (state->next - state->codes);
  84396. if (window != Z_NULL) {
  84397. wsize = 1U << state->wbits;
  84398. zmemcpy(window, state->window, wsize);
  84399. }
  84400. copy->window = window;
  84401. dest->state = (struct internal_state FAR *)copy;
  84402. return Z_OK;
  84403. }
  84404. /*** End of inlined file: inflate.c ***/
  84405. /*** Start of inlined file: inftrees.c ***/
  84406. #define MAXBITS 15
  84407. const char inflate_copyright[] =
  84408. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84409. /*
  84410. If you use the zlib library in a product, an acknowledgment is welcome
  84411. in the documentation of your product. If for some reason you cannot
  84412. include such an acknowledgment, I would appreciate that you keep this
  84413. copyright string in the executable of your product.
  84414. */
  84415. /*
  84416. Build a set of tables to decode the provided canonical Huffman code.
  84417. The code lengths are lens[0..codes-1]. The result starts at *table,
  84418. whose indices are 0..2^bits-1. work is a writable array of at least
  84419. lens shorts, which is used as a work area. type is the type of code
  84420. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84421. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84422. on return points to the next available entry's address. bits is the
  84423. requested root table index bits, and on return it is the actual root
  84424. table index bits. It will differ if the request is greater than the
  84425. longest code or if it is less than the shortest code.
  84426. */
  84427. int inflate_table (codetype type,
  84428. unsigned short FAR *lens,
  84429. unsigned codes,
  84430. code FAR * FAR *table,
  84431. unsigned FAR *bits,
  84432. unsigned short FAR *work)
  84433. {
  84434. unsigned len; /* a code's length in bits */
  84435. unsigned sym; /* index of code symbols */
  84436. unsigned min, max; /* minimum and maximum code lengths */
  84437. unsigned root; /* number of index bits for root table */
  84438. unsigned curr; /* number of index bits for current table */
  84439. unsigned drop; /* code bits to drop for sub-table */
  84440. int left; /* number of prefix codes available */
  84441. unsigned used; /* code entries in table used */
  84442. unsigned huff; /* Huffman code */
  84443. unsigned incr; /* for incrementing code, index */
  84444. unsigned fill; /* index for replicating entries */
  84445. unsigned low; /* low bits for current root entry */
  84446. unsigned mask; /* mask for low root bits */
  84447. code thisx; /* table entry for duplication */
  84448. code FAR *next; /* next available space in table */
  84449. const unsigned short FAR *base; /* base value table to use */
  84450. const unsigned short FAR *extra; /* extra bits table to use */
  84451. int end; /* use base and extra for symbol > end */
  84452. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84453. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84454. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84455. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84456. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84457. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84458. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84459. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84460. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84461. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84462. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84463. 8193, 12289, 16385, 24577, 0, 0};
  84464. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84465. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84466. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84467. 28, 28, 29, 29, 64, 64};
  84468. /*
  84469. Process a set of code lengths to create a canonical Huffman code. The
  84470. code lengths are lens[0..codes-1]. Each length corresponds to the
  84471. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84472. symbols by length from short to long, and retaining the symbol order
  84473. for codes with equal lengths. Then the code starts with all zero bits
  84474. for the first code of the shortest length, and the codes are integer
  84475. increments for the same length, and zeros are appended as the length
  84476. increases. For the deflate format, these bits are stored backwards
  84477. from their more natural integer increment ordering, and so when the
  84478. decoding tables are built in the large loop below, the integer codes
  84479. are incremented backwards.
  84480. This routine assumes, but does not check, that all of the entries in
  84481. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84482. 1..MAXBITS is interpreted as that code length. zero means that that
  84483. symbol does not occur in this code.
  84484. The codes are sorted by computing a count of codes for each length,
  84485. creating from that a table of starting indices for each length in the
  84486. sorted table, and then entering the symbols in order in the sorted
  84487. table. The sorted table is work[], with that space being provided by
  84488. the caller.
  84489. The length counts are used for other purposes as well, i.e. finding
  84490. the minimum and maximum length codes, determining if there are any
  84491. codes at all, checking for a valid set of lengths, and looking ahead
  84492. at length counts to determine sub-table sizes when building the
  84493. decoding tables.
  84494. */
  84495. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84496. for (len = 0; len <= MAXBITS; len++)
  84497. count[len] = 0;
  84498. for (sym = 0; sym < codes; sym++)
  84499. count[lens[sym]]++;
  84500. /* bound code lengths, force root to be within code lengths */
  84501. root = *bits;
  84502. for (max = MAXBITS; max >= 1; max--)
  84503. if (count[max] != 0) break;
  84504. if (root > max) root = max;
  84505. if (max == 0) { /* no symbols to code at all */
  84506. thisx.op = (unsigned char)64; /* invalid code marker */
  84507. thisx.bits = (unsigned char)1;
  84508. thisx.val = (unsigned short)0;
  84509. *(*table)++ = thisx; /* make a table to force an error */
  84510. *(*table)++ = thisx;
  84511. *bits = 1;
  84512. return 0; /* no symbols, but wait for decoding to report error */
  84513. }
  84514. for (min = 1; min <= MAXBITS; min++)
  84515. if (count[min] != 0) break;
  84516. if (root < min) root = min;
  84517. /* check for an over-subscribed or incomplete set of lengths */
  84518. left = 1;
  84519. for (len = 1; len <= MAXBITS; len++) {
  84520. left <<= 1;
  84521. left -= count[len];
  84522. if (left < 0) return -1; /* over-subscribed */
  84523. }
  84524. if (left > 0 && (type == CODES || max != 1))
  84525. return -1; /* incomplete set */
  84526. /* generate offsets into symbol table for each length for sorting */
  84527. offs[1] = 0;
  84528. for (len = 1; len < MAXBITS; len++)
  84529. offs[len + 1] = offs[len] + count[len];
  84530. /* sort symbols by length, by symbol order within each length */
  84531. for (sym = 0; sym < codes; sym++)
  84532. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84533. /*
  84534. Create and fill in decoding tables. In this loop, the table being
  84535. filled is at next and has curr index bits. The code being used is huff
  84536. with length len. That code is converted to an index by dropping drop
  84537. bits off of the bottom. For codes where len is less than drop + curr,
  84538. those top drop + curr - len bits are incremented through all values to
  84539. fill the table with replicated entries.
  84540. root is the number of index bits for the root table. When len exceeds
  84541. root, sub-tables are created pointed to by the root entry with an index
  84542. of the low root bits of huff. This is saved in low to check for when a
  84543. new sub-table should be started. drop is zero when the root table is
  84544. being filled, and drop is root when sub-tables are being filled.
  84545. When a new sub-table is needed, it is necessary to look ahead in the
  84546. code lengths to determine what size sub-table is needed. The length
  84547. counts are used for this, and so count[] is decremented as codes are
  84548. entered in the tables.
  84549. used keeps track of how many table entries have been allocated from the
  84550. provided *table space. It is checked when a LENS table is being made
  84551. against the space in *table, ENOUGH, minus the maximum space needed by
  84552. the worst case distance code, MAXD. This should never happen, but the
  84553. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84554. This assumes that when type == LENS, bits == 9.
  84555. sym increments through all symbols, and the loop terminates when
  84556. all codes of length max, i.e. all codes, have been processed. This
  84557. routine permits incomplete codes, so another loop after this one fills
  84558. in the rest of the decoding tables with invalid code markers.
  84559. */
  84560. /* set up for code type */
  84561. switch (type) {
  84562. case CODES:
  84563. base = extra = work; /* dummy value--not used */
  84564. end = 19;
  84565. break;
  84566. case LENS:
  84567. base = lbase;
  84568. base -= 257;
  84569. extra = lext;
  84570. extra -= 257;
  84571. end = 256;
  84572. break;
  84573. default: /* DISTS */
  84574. base = dbase;
  84575. extra = dext;
  84576. end = -1;
  84577. }
  84578. /* initialize state for loop */
  84579. huff = 0; /* starting code */
  84580. sym = 0; /* starting code symbol */
  84581. len = min; /* starting code length */
  84582. next = *table; /* current table to fill in */
  84583. curr = root; /* current table index bits */
  84584. drop = 0; /* current bits to drop from code for index */
  84585. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84586. used = 1U << root; /* use root table entries */
  84587. mask = used - 1; /* mask for comparing low */
  84588. /* check available table space */
  84589. if (type == LENS && used >= ENOUGH - MAXD)
  84590. return 1;
  84591. /* process all codes and make table entries */
  84592. for (;;) {
  84593. /* create table entry */
  84594. thisx.bits = (unsigned char)(len - drop);
  84595. if ((int)(work[sym]) < end) {
  84596. thisx.op = (unsigned char)0;
  84597. thisx.val = work[sym];
  84598. }
  84599. else if ((int)(work[sym]) > end) {
  84600. thisx.op = (unsigned char)(extra[work[sym]]);
  84601. thisx.val = base[work[sym]];
  84602. }
  84603. else {
  84604. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84605. thisx.val = 0;
  84606. }
  84607. /* replicate for those indices with low len bits equal to huff */
  84608. incr = 1U << (len - drop);
  84609. fill = 1U << curr;
  84610. min = fill; /* save offset to next table */
  84611. do {
  84612. fill -= incr;
  84613. next[(huff >> drop) + fill] = thisx;
  84614. } while (fill != 0);
  84615. /* backwards increment the len-bit code huff */
  84616. incr = 1U << (len - 1);
  84617. while (huff & incr)
  84618. incr >>= 1;
  84619. if (incr != 0) {
  84620. huff &= incr - 1;
  84621. huff += incr;
  84622. }
  84623. else
  84624. huff = 0;
  84625. /* go to next symbol, update count, len */
  84626. sym++;
  84627. if (--(count[len]) == 0) {
  84628. if (len == max) break;
  84629. len = lens[work[sym]];
  84630. }
  84631. /* create new sub-table if needed */
  84632. if (len > root && (huff & mask) != low) {
  84633. /* if first time, transition to sub-tables */
  84634. if (drop == 0)
  84635. drop = root;
  84636. /* increment past last table */
  84637. next += min; /* here min is 1 << curr */
  84638. /* determine length of next table */
  84639. curr = len - drop;
  84640. left = (int)(1 << curr);
  84641. while (curr + drop < max) {
  84642. left -= count[curr + drop];
  84643. if (left <= 0) break;
  84644. curr++;
  84645. left <<= 1;
  84646. }
  84647. /* check for enough space */
  84648. used += 1U << curr;
  84649. if (type == LENS && used >= ENOUGH - MAXD)
  84650. return 1;
  84651. /* point entry in root table to sub-table */
  84652. low = huff & mask;
  84653. (*table)[low].op = (unsigned char)curr;
  84654. (*table)[low].bits = (unsigned char)root;
  84655. (*table)[low].val = (unsigned short)(next - *table);
  84656. }
  84657. }
  84658. /*
  84659. Fill in rest of table for incomplete codes. This loop is similar to the
  84660. loop above in incrementing huff for table indices. It is assumed that
  84661. len is equal to curr + drop, so there is no loop needed to increment
  84662. through high index bits. When the current sub-table is filled, the loop
  84663. drops back to the root table to fill in any remaining entries there.
  84664. */
  84665. thisx.op = (unsigned char)64; /* invalid code marker */
  84666. thisx.bits = (unsigned char)(len - drop);
  84667. thisx.val = (unsigned short)0;
  84668. while (huff != 0) {
  84669. /* when done with sub-table, drop back to root table */
  84670. if (drop != 0 && (huff & mask) != low) {
  84671. drop = 0;
  84672. len = root;
  84673. next = *table;
  84674. thisx.bits = (unsigned char)len;
  84675. }
  84676. /* put invalid code marker in table */
  84677. next[huff >> drop] = thisx;
  84678. /* backwards increment the len-bit code huff */
  84679. incr = 1U << (len - 1);
  84680. while (huff & incr)
  84681. incr >>= 1;
  84682. if (incr != 0) {
  84683. huff &= incr - 1;
  84684. huff += incr;
  84685. }
  84686. else
  84687. huff = 0;
  84688. }
  84689. /* set return parameters */
  84690. *table += used;
  84691. *bits = root;
  84692. return 0;
  84693. }
  84694. /*** End of inlined file: inftrees.c ***/
  84695. /*** Start of inlined file: trees.c ***/
  84696. /*
  84697. * ALGORITHM
  84698. *
  84699. * The "deflation" process uses several Huffman trees. The more
  84700. * common source values are represented by shorter bit sequences.
  84701. *
  84702. * Each code tree is stored in a compressed form which is itself
  84703. * a Huffman encoding of the lengths of all the code strings (in
  84704. * ascending order by source values). The actual code strings are
  84705. * reconstructed from the lengths in the inflate process, as described
  84706. * in the deflate specification.
  84707. *
  84708. * REFERENCES
  84709. *
  84710. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84711. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84712. *
  84713. * Storer, James A.
  84714. * Data Compression: Methods and Theory, pp. 49-50.
  84715. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84716. *
  84717. * Sedgewick, R.
  84718. * Algorithms, p290.
  84719. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84720. */
  84721. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84722. /* #define GEN_TREES_H */
  84723. #ifdef DEBUG
  84724. # include <ctype.h>
  84725. #endif
  84726. /* ===========================================================================
  84727. * Constants
  84728. */
  84729. #define MAX_BL_BITS 7
  84730. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84731. #define END_BLOCK 256
  84732. /* end of block literal code */
  84733. #define REP_3_6 16
  84734. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84735. #define REPZ_3_10 17
  84736. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84737. #define REPZ_11_138 18
  84738. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84739. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84740. = {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};
  84741. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84742. = {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};
  84743. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84744. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84745. local const uch bl_order[BL_CODES]
  84746. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84747. /* The lengths of the bit length codes are sent in order of decreasing
  84748. * probability, to avoid transmitting the lengths for unused bit length codes.
  84749. */
  84750. #define Buf_size (8 * 2*sizeof(char))
  84751. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84752. * more than 16 bits on some systems.)
  84753. */
  84754. /* ===========================================================================
  84755. * Local data. These are initialized only once.
  84756. */
  84757. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84758. #if defined(GEN_TREES_H) || !defined(STDC)
  84759. /* non ANSI compilers may not accept trees.h */
  84760. local ct_data static_ltree[L_CODES+2];
  84761. /* The static literal tree. Since the bit lengths are imposed, there is no
  84762. * need for the L_CODES extra codes used during heap construction. However
  84763. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84764. * below).
  84765. */
  84766. local ct_data static_dtree[D_CODES];
  84767. /* The static distance tree. (Actually a trivial tree since all codes use
  84768. * 5 bits.)
  84769. */
  84770. uch _dist_code[DIST_CODE_LEN];
  84771. /* Distance codes. The first 256 values correspond to the distances
  84772. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84773. * the 15 bit distances.
  84774. */
  84775. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84776. /* length code for each normalized match length (0 == MIN_MATCH) */
  84777. local int base_length[LENGTH_CODES];
  84778. /* First normalized length for each code (0 = MIN_MATCH) */
  84779. local int base_dist[D_CODES];
  84780. /* First normalized distance for each code (0 = distance of 1) */
  84781. #else
  84782. /*** Start of inlined file: trees.h ***/
  84783. local const ct_data static_ltree[L_CODES+2] = {
  84784. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84785. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84786. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84787. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84788. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84789. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84790. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84791. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84792. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84793. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84794. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84795. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84796. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84797. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84798. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84799. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84800. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84801. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84802. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84803. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84804. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84805. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84806. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84807. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84808. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84809. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84810. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84811. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84812. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84813. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84814. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84815. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84816. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84817. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84818. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84819. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84820. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84821. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84822. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84823. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84824. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84825. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84826. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84827. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84828. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84829. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84830. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84831. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84832. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84833. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84834. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84835. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84836. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84837. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84838. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84839. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84840. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84841. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84842. };
  84843. local const ct_data static_dtree[D_CODES] = {
  84844. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84845. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84846. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84847. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84848. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84849. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84850. };
  84851. const uch _dist_code[DIST_CODE_LEN] = {
  84852. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84853. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84854. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84855. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84856. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84857. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84858. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84859. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84860. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84861. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84862. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84863. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84864. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84865. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84866. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84867. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84868. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84869. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84870. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84871. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84872. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84873. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84874. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84875. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84876. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84877. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84878. };
  84879. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84880. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84881. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84882. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84883. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84884. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84885. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84886. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84887. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84888. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84889. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84890. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84891. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84892. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84893. };
  84894. local const int base_length[LENGTH_CODES] = {
  84895. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84896. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84897. };
  84898. local const int base_dist[D_CODES] = {
  84899. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84900. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84901. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84902. };
  84903. /*** End of inlined file: trees.h ***/
  84904. #endif /* GEN_TREES_H */
  84905. struct static_tree_desc_s {
  84906. const ct_data *static_tree; /* static tree or NULL */
  84907. const intf *extra_bits; /* extra bits for each code or NULL */
  84908. int extra_base; /* base index for extra_bits */
  84909. int elems; /* max number of elements in the tree */
  84910. int max_length; /* max bit length for the codes */
  84911. };
  84912. local static_tree_desc static_l_desc =
  84913. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84914. local static_tree_desc static_d_desc =
  84915. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84916. local static_tree_desc static_bl_desc =
  84917. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84918. /* ===========================================================================
  84919. * Local (static) routines in this file.
  84920. */
  84921. local void tr_static_init OF((void));
  84922. local void init_block OF((deflate_state *s));
  84923. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84924. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84925. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84926. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84927. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84928. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84929. local int build_bl_tree OF((deflate_state *s));
  84930. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84931. int blcodes));
  84932. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84933. ct_data *dtree));
  84934. local void set_data_type OF((deflate_state *s));
  84935. local unsigned bi_reverse OF((unsigned value, int length));
  84936. local void bi_windup OF((deflate_state *s));
  84937. local void bi_flush OF((deflate_state *s));
  84938. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84939. int header));
  84940. #ifdef GEN_TREES_H
  84941. local void gen_trees_header OF((void));
  84942. #endif
  84943. #ifndef DEBUG
  84944. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84945. /* Send a code of the given tree. c and tree must not have side effects */
  84946. #else /* DEBUG */
  84947. # define send_code(s, c, tree) \
  84948. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84949. send_bits(s, tree[c].Code, tree[c].Len); }
  84950. #endif
  84951. /* ===========================================================================
  84952. * Output a short LSB first on the stream.
  84953. * IN assertion: there is enough room in pendingBuf.
  84954. */
  84955. #define put_short(s, w) { \
  84956. put_byte(s, (uch)((w) & 0xff)); \
  84957. put_byte(s, (uch)((ush)(w) >> 8)); \
  84958. }
  84959. /* ===========================================================================
  84960. * Send a value on a given number of bits.
  84961. * IN assertion: length <= 16 and value fits in length bits.
  84962. */
  84963. #ifdef DEBUG
  84964. local void send_bits OF((deflate_state *s, int value, int length));
  84965. local void send_bits (deflate_state *s, int value, int length)
  84966. {
  84967. Tracevv((stderr," l %2d v %4x ", length, value));
  84968. Assert(length > 0 && length <= 15, "invalid length");
  84969. s->bits_sent += (ulg)length;
  84970. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84971. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84972. * unused bits in value.
  84973. */
  84974. if (s->bi_valid > (int)Buf_size - length) {
  84975. s->bi_buf |= (value << s->bi_valid);
  84976. put_short(s, s->bi_buf);
  84977. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84978. s->bi_valid += length - Buf_size;
  84979. } else {
  84980. s->bi_buf |= value << s->bi_valid;
  84981. s->bi_valid += length;
  84982. }
  84983. }
  84984. #else /* !DEBUG */
  84985. #define send_bits(s, value, length) \
  84986. { int len = length;\
  84987. if (s->bi_valid > (int)Buf_size - len) {\
  84988. int val = value;\
  84989. s->bi_buf |= (val << s->bi_valid);\
  84990. put_short(s, s->bi_buf);\
  84991. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84992. s->bi_valid += len - Buf_size;\
  84993. } else {\
  84994. s->bi_buf |= (value) << s->bi_valid;\
  84995. s->bi_valid += len;\
  84996. }\
  84997. }
  84998. #endif /* DEBUG */
  84999. /* the arguments must not have side effects */
  85000. /* ===========================================================================
  85001. * Initialize the various 'constant' tables.
  85002. */
  85003. local void tr_static_init()
  85004. {
  85005. #if defined(GEN_TREES_H) || !defined(STDC)
  85006. static int static_init_done = 0;
  85007. int n; /* iterates over tree elements */
  85008. int bits; /* bit counter */
  85009. int length; /* length value */
  85010. int code; /* code value */
  85011. int dist; /* distance index */
  85012. ush bl_count[MAX_BITS+1];
  85013. /* number of codes at each bit length for an optimal tree */
  85014. if (static_init_done) return;
  85015. /* For some embedded targets, global variables are not initialized: */
  85016. static_l_desc.static_tree = static_ltree;
  85017. static_l_desc.extra_bits = extra_lbits;
  85018. static_d_desc.static_tree = static_dtree;
  85019. static_d_desc.extra_bits = extra_dbits;
  85020. static_bl_desc.extra_bits = extra_blbits;
  85021. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85022. length = 0;
  85023. for (code = 0; code < LENGTH_CODES-1; code++) {
  85024. base_length[code] = length;
  85025. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85026. _length_code[length++] = (uch)code;
  85027. }
  85028. }
  85029. Assert (length == 256, "tr_static_init: length != 256");
  85030. /* Note that the length 255 (match length 258) can be represented
  85031. * in two different ways: code 284 + 5 bits or code 285, so we
  85032. * overwrite length_code[255] to use the best encoding:
  85033. */
  85034. _length_code[length-1] = (uch)code;
  85035. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85036. dist = 0;
  85037. for (code = 0 ; code < 16; code++) {
  85038. base_dist[code] = dist;
  85039. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85040. _dist_code[dist++] = (uch)code;
  85041. }
  85042. }
  85043. Assert (dist == 256, "tr_static_init: dist != 256");
  85044. dist >>= 7; /* from now on, all distances are divided by 128 */
  85045. for ( ; code < D_CODES; code++) {
  85046. base_dist[code] = dist << 7;
  85047. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85048. _dist_code[256 + dist++] = (uch)code;
  85049. }
  85050. }
  85051. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85052. /* Construct the codes of the static literal tree */
  85053. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85054. n = 0;
  85055. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85056. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85057. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85058. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85059. /* Codes 286 and 287 do not exist, but we must include them in the
  85060. * tree construction to get a canonical Huffman tree (longest code
  85061. * all ones)
  85062. */
  85063. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85064. /* The static distance tree is trivial: */
  85065. for (n = 0; n < D_CODES; n++) {
  85066. static_dtree[n].Len = 5;
  85067. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85068. }
  85069. static_init_done = 1;
  85070. # ifdef GEN_TREES_H
  85071. gen_trees_header();
  85072. # endif
  85073. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85074. }
  85075. /* ===========================================================================
  85076. * Genererate the file trees.h describing the static trees.
  85077. */
  85078. #ifdef GEN_TREES_H
  85079. # ifndef DEBUG
  85080. # include <stdio.h>
  85081. # endif
  85082. # define SEPARATOR(i, last, width) \
  85083. ((i) == (last)? "\n};\n\n" : \
  85084. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85085. void gen_trees_header()
  85086. {
  85087. FILE *header = fopen("trees.h", "w");
  85088. int i;
  85089. Assert (header != NULL, "Can't open trees.h");
  85090. fprintf(header,
  85091. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85092. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85093. for (i = 0; i < L_CODES+2; i++) {
  85094. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85095. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85096. }
  85097. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85098. for (i = 0; i < D_CODES; i++) {
  85099. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85100. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85101. }
  85102. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85103. for (i = 0; i < DIST_CODE_LEN; i++) {
  85104. fprintf(header, "%2u%s", _dist_code[i],
  85105. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85106. }
  85107. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85108. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85109. fprintf(header, "%2u%s", _length_code[i],
  85110. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85111. }
  85112. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85113. for (i = 0; i < LENGTH_CODES; i++) {
  85114. fprintf(header, "%1u%s", base_length[i],
  85115. SEPARATOR(i, LENGTH_CODES-1, 20));
  85116. }
  85117. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85118. for (i = 0; i < D_CODES; i++) {
  85119. fprintf(header, "%5u%s", base_dist[i],
  85120. SEPARATOR(i, D_CODES-1, 10));
  85121. }
  85122. fclose(header);
  85123. }
  85124. #endif /* GEN_TREES_H */
  85125. /* ===========================================================================
  85126. * Initialize the tree data structures for a new zlib stream.
  85127. */
  85128. void _tr_init(deflate_state *s)
  85129. {
  85130. tr_static_init();
  85131. s->l_desc.dyn_tree = s->dyn_ltree;
  85132. s->l_desc.stat_desc = &static_l_desc;
  85133. s->d_desc.dyn_tree = s->dyn_dtree;
  85134. s->d_desc.stat_desc = &static_d_desc;
  85135. s->bl_desc.dyn_tree = s->bl_tree;
  85136. s->bl_desc.stat_desc = &static_bl_desc;
  85137. s->bi_buf = 0;
  85138. s->bi_valid = 0;
  85139. s->last_eob_len = 8; /* enough lookahead for inflate */
  85140. #ifdef DEBUG
  85141. s->compressed_len = 0L;
  85142. s->bits_sent = 0L;
  85143. #endif
  85144. /* Initialize the first block of the first file: */
  85145. init_block(s);
  85146. }
  85147. /* ===========================================================================
  85148. * Initialize a new block.
  85149. */
  85150. local void init_block (deflate_state *s)
  85151. {
  85152. int n; /* iterates over tree elements */
  85153. /* Initialize the trees. */
  85154. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85155. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85156. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85157. s->dyn_ltree[END_BLOCK].Freq = 1;
  85158. s->opt_len = s->static_len = 0L;
  85159. s->last_lit = s->matches = 0;
  85160. }
  85161. #define SMALLEST 1
  85162. /* Index within the heap array of least frequent node in the Huffman tree */
  85163. /* ===========================================================================
  85164. * Remove the smallest element from the heap and recreate the heap with
  85165. * one less element. Updates heap and heap_len.
  85166. */
  85167. #define pqremove(s, tree, top) \
  85168. {\
  85169. top = s->heap[SMALLEST]; \
  85170. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85171. pqdownheap(s, tree, SMALLEST); \
  85172. }
  85173. /* ===========================================================================
  85174. * Compares to subtrees, using the tree depth as tie breaker when
  85175. * the subtrees have equal frequency. This minimizes the worst case length.
  85176. */
  85177. #define smaller(tree, n, m, depth) \
  85178. (tree[n].Freq < tree[m].Freq || \
  85179. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85180. /* ===========================================================================
  85181. * Restore the heap property by moving down the tree starting at node k,
  85182. * exchanging a node with the smallest of its two sons if necessary, stopping
  85183. * when the heap property is re-established (each father smaller than its
  85184. * two sons).
  85185. */
  85186. local void pqdownheap (deflate_state *s,
  85187. ct_data *tree, /* the tree to restore */
  85188. int k) /* node to move down */
  85189. {
  85190. int v = s->heap[k];
  85191. int j = k << 1; /* left son of k */
  85192. while (j <= s->heap_len) {
  85193. /* Set j to the smallest of the two sons: */
  85194. if (j < s->heap_len &&
  85195. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85196. j++;
  85197. }
  85198. /* Exit if v is smaller than both sons */
  85199. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85200. /* Exchange v with the smallest son */
  85201. s->heap[k] = s->heap[j]; k = j;
  85202. /* And continue down the tree, setting j to the left son of k */
  85203. j <<= 1;
  85204. }
  85205. s->heap[k] = v;
  85206. }
  85207. /* ===========================================================================
  85208. * Compute the optimal bit lengths for a tree and update the total bit length
  85209. * for the current block.
  85210. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85211. * above are the tree nodes sorted by increasing frequency.
  85212. * OUT assertions: the field len is set to the optimal bit length, the
  85213. * array bl_count contains the frequencies for each bit length.
  85214. * The length opt_len is updated; static_len is also updated if stree is
  85215. * not null.
  85216. */
  85217. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85218. {
  85219. ct_data *tree = desc->dyn_tree;
  85220. int max_code = desc->max_code;
  85221. const ct_data *stree = desc->stat_desc->static_tree;
  85222. const intf *extra = desc->stat_desc->extra_bits;
  85223. int base = desc->stat_desc->extra_base;
  85224. int max_length = desc->stat_desc->max_length;
  85225. int h; /* heap index */
  85226. int n, m; /* iterate over the tree elements */
  85227. int bits; /* bit length */
  85228. int xbits; /* extra bits */
  85229. ush f; /* frequency */
  85230. int overflow = 0; /* number of elements with bit length too large */
  85231. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85232. /* In a first pass, compute the optimal bit lengths (which may
  85233. * overflow in the case of the bit length tree).
  85234. */
  85235. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85236. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85237. n = s->heap[h];
  85238. bits = tree[tree[n].Dad].Len + 1;
  85239. if (bits > max_length) bits = max_length, overflow++;
  85240. tree[n].Len = (ush)bits;
  85241. /* We overwrite tree[n].Dad which is no longer needed */
  85242. if (n > max_code) continue; /* not a leaf node */
  85243. s->bl_count[bits]++;
  85244. xbits = 0;
  85245. if (n >= base) xbits = extra[n-base];
  85246. f = tree[n].Freq;
  85247. s->opt_len += (ulg)f * (bits + xbits);
  85248. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85249. }
  85250. if (overflow == 0) return;
  85251. Trace((stderr,"\nbit length overflow\n"));
  85252. /* This happens for example on obj2 and pic of the Calgary corpus */
  85253. /* Find the first bit length which could increase: */
  85254. do {
  85255. bits = max_length-1;
  85256. while (s->bl_count[bits] == 0) bits--;
  85257. s->bl_count[bits]--; /* move one leaf down the tree */
  85258. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85259. s->bl_count[max_length]--;
  85260. /* The brother of the overflow item also moves one step up,
  85261. * but this does not affect bl_count[max_length]
  85262. */
  85263. overflow -= 2;
  85264. } while (overflow > 0);
  85265. /* Now recompute all bit lengths, scanning in increasing frequency.
  85266. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85267. * lengths instead of fixing only the wrong ones. This idea is taken
  85268. * from 'ar' written by Haruhiko Okumura.)
  85269. */
  85270. for (bits = max_length; bits != 0; bits--) {
  85271. n = s->bl_count[bits];
  85272. while (n != 0) {
  85273. m = s->heap[--h];
  85274. if (m > max_code) continue;
  85275. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85276. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85277. s->opt_len += ((long)bits - (long)tree[m].Len)
  85278. *(long)tree[m].Freq;
  85279. tree[m].Len = (ush)bits;
  85280. }
  85281. n--;
  85282. }
  85283. }
  85284. }
  85285. /* ===========================================================================
  85286. * Generate the codes for a given tree and bit counts (which need not be
  85287. * optimal).
  85288. * IN assertion: the array bl_count contains the bit length statistics for
  85289. * the given tree and the field len is set for all tree elements.
  85290. * OUT assertion: the field code is set for all tree elements of non
  85291. * zero code length.
  85292. */
  85293. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85294. int max_code, /* largest code with non zero frequency */
  85295. ushf *bl_count) /* number of codes at each bit length */
  85296. {
  85297. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85298. ush code = 0; /* running code value */
  85299. int bits; /* bit index */
  85300. int n; /* code index */
  85301. /* The distribution counts are first used to generate the code values
  85302. * without bit reversal.
  85303. */
  85304. for (bits = 1; bits <= MAX_BITS; bits++) {
  85305. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85306. }
  85307. /* Check that the bit counts in bl_count are consistent. The last code
  85308. * must be all ones.
  85309. */
  85310. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85311. "inconsistent bit counts");
  85312. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85313. for (n = 0; n <= max_code; n++) {
  85314. int len = tree[n].Len;
  85315. if (len == 0) continue;
  85316. /* Now reverse the bits */
  85317. tree[n].Code = bi_reverse(next_code[len]++, len);
  85318. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85319. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85320. }
  85321. }
  85322. /* ===========================================================================
  85323. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85324. * Update the total bit length for the current block.
  85325. * IN assertion: the field freq is set for all tree elements.
  85326. * OUT assertions: the fields len and code are set to the optimal bit length
  85327. * and corresponding code. The length opt_len is updated; static_len is
  85328. * also updated if stree is not null. The field max_code is set.
  85329. */
  85330. local void build_tree (deflate_state *s,
  85331. tree_desc *desc) /* the tree descriptor */
  85332. {
  85333. ct_data *tree = desc->dyn_tree;
  85334. const ct_data *stree = desc->stat_desc->static_tree;
  85335. int elems = desc->stat_desc->elems;
  85336. int n, m; /* iterate over heap elements */
  85337. int max_code = -1; /* largest code with non zero frequency */
  85338. int node; /* new node being created */
  85339. /* Construct the initial heap, with least frequent element in
  85340. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85341. * heap[0] is not used.
  85342. */
  85343. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85344. for (n = 0; n < elems; n++) {
  85345. if (tree[n].Freq != 0) {
  85346. s->heap[++(s->heap_len)] = max_code = n;
  85347. s->depth[n] = 0;
  85348. } else {
  85349. tree[n].Len = 0;
  85350. }
  85351. }
  85352. /* The pkzip format requires that at least one distance code exists,
  85353. * and that at least one bit should be sent even if there is only one
  85354. * possible code. So to avoid special checks later on we force at least
  85355. * two codes of non zero frequency.
  85356. */
  85357. while (s->heap_len < 2) {
  85358. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85359. tree[node].Freq = 1;
  85360. s->depth[node] = 0;
  85361. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85362. /* node is 0 or 1 so it does not have extra bits */
  85363. }
  85364. desc->max_code = max_code;
  85365. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85366. * establish sub-heaps of increasing lengths:
  85367. */
  85368. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85369. /* Construct the Huffman tree by repeatedly combining the least two
  85370. * frequent nodes.
  85371. */
  85372. node = elems; /* next internal node of the tree */
  85373. do {
  85374. pqremove(s, tree, n); /* n = node of least frequency */
  85375. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85376. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85377. s->heap[--(s->heap_max)] = m;
  85378. /* Create a new node father of n and m */
  85379. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85380. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85381. s->depth[n] : s->depth[m]) + 1);
  85382. tree[n].Dad = tree[m].Dad = (ush)node;
  85383. #ifdef DUMP_BL_TREE
  85384. if (tree == s->bl_tree) {
  85385. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85386. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85387. }
  85388. #endif
  85389. /* and insert the new node in the heap */
  85390. s->heap[SMALLEST] = node++;
  85391. pqdownheap(s, tree, SMALLEST);
  85392. } while (s->heap_len >= 2);
  85393. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85394. /* At this point, the fields freq and dad are set. We can now
  85395. * generate the bit lengths.
  85396. */
  85397. gen_bitlen(s, (tree_desc *)desc);
  85398. /* The field len is now set, we can generate the bit codes */
  85399. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85400. }
  85401. /* ===========================================================================
  85402. * Scan a literal or distance tree to determine the frequencies of the codes
  85403. * in the bit length tree.
  85404. */
  85405. local void scan_tree (deflate_state *s,
  85406. ct_data *tree, /* the tree to be scanned */
  85407. int max_code) /* and its largest code of non zero frequency */
  85408. {
  85409. int n; /* iterates over all tree elements */
  85410. int prevlen = -1; /* last emitted length */
  85411. int curlen; /* length of current code */
  85412. int nextlen = tree[0].Len; /* length of next code */
  85413. int count = 0; /* repeat count of the current code */
  85414. int max_count = 7; /* max repeat count */
  85415. int min_count = 4; /* min repeat count */
  85416. if (nextlen == 0) max_count = 138, min_count = 3;
  85417. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85418. for (n = 0; n <= max_code; n++) {
  85419. curlen = nextlen; nextlen = tree[n+1].Len;
  85420. if (++count < max_count && curlen == nextlen) {
  85421. continue;
  85422. } else if (count < min_count) {
  85423. s->bl_tree[curlen].Freq += count;
  85424. } else if (curlen != 0) {
  85425. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85426. s->bl_tree[REP_3_6].Freq++;
  85427. } else if (count <= 10) {
  85428. s->bl_tree[REPZ_3_10].Freq++;
  85429. } else {
  85430. s->bl_tree[REPZ_11_138].Freq++;
  85431. }
  85432. count = 0; prevlen = curlen;
  85433. if (nextlen == 0) {
  85434. max_count = 138, min_count = 3;
  85435. } else if (curlen == nextlen) {
  85436. max_count = 6, min_count = 3;
  85437. } else {
  85438. max_count = 7, min_count = 4;
  85439. }
  85440. }
  85441. }
  85442. /* ===========================================================================
  85443. * Send a literal or distance tree in compressed form, using the codes in
  85444. * bl_tree.
  85445. */
  85446. local void send_tree (deflate_state *s,
  85447. ct_data *tree, /* the tree to be scanned */
  85448. int max_code) /* and its largest code of non zero frequency */
  85449. {
  85450. int n; /* iterates over all tree elements */
  85451. int prevlen = -1; /* last emitted length */
  85452. int curlen; /* length of current code */
  85453. int nextlen = tree[0].Len; /* length of next code */
  85454. int count = 0; /* repeat count of the current code */
  85455. int max_count = 7; /* max repeat count */
  85456. int min_count = 4; /* min repeat count */
  85457. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85458. if (nextlen == 0) max_count = 138, min_count = 3;
  85459. for (n = 0; n <= max_code; n++) {
  85460. curlen = nextlen; nextlen = tree[n+1].Len;
  85461. if (++count < max_count && curlen == nextlen) {
  85462. continue;
  85463. } else if (count < min_count) {
  85464. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85465. } else if (curlen != 0) {
  85466. if (curlen != prevlen) {
  85467. send_code(s, curlen, s->bl_tree); count--;
  85468. }
  85469. Assert(count >= 3 && count <= 6, " 3_6?");
  85470. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85471. } else if (count <= 10) {
  85472. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85473. } else {
  85474. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85475. }
  85476. count = 0; prevlen = curlen;
  85477. if (nextlen == 0) {
  85478. max_count = 138, min_count = 3;
  85479. } else if (curlen == nextlen) {
  85480. max_count = 6, min_count = 3;
  85481. } else {
  85482. max_count = 7, min_count = 4;
  85483. }
  85484. }
  85485. }
  85486. /* ===========================================================================
  85487. * Construct the Huffman tree for the bit lengths and return the index in
  85488. * bl_order of the last bit length code to send.
  85489. */
  85490. local int build_bl_tree (deflate_state *s)
  85491. {
  85492. int max_blindex; /* index of last bit length code of non zero freq */
  85493. /* Determine the bit length frequencies for literal and distance trees */
  85494. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85495. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85496. /* Build the bit length tree: */
  85497. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85498. /* opt_len now includes the length of the tree representations, except
  85499. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85500. */
  85501. /* Determine the number of bit length codes to send. The pkzip format
  85502. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85503. * 3 but the actual value used is 4.)
  85504. */
  85505. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85506. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85507. }
  85508. /* Update opt_len to include the bit length tree and counts */
  85509. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85510. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85511. s->opt_len, s->static_len));
  85512. return max_blindex;
  85513. }
  85514. /* ===========================================================================
  85515. * Send the header for a block using dynamic Huffman trees: the counts, the
  85516. * lengths of the bit length codes, the literal tree and the distance tree.
  85517. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85518. */
  85519. local void send_all_trees (deflate_state *s,
  85520. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85521. {
  85522. int rank; /* index in bl_order */
  85523. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85524. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85525. "too many codes");
  85526. Tracev((stderr, "\nbl counts: "));
  85527. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85528. send_bits(s, dcodes-1, 5);
  85529. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85530. for (rank = 0; rank < blcodes; rank++) {
  85531. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85532. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85533. }
  85534. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85535. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85536. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85537. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85538. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85539. }
  85540. /* ===========================================================================
  85541. * Send a stored block
  85542. */
  85543. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85544. {
  85545. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85546. #ifdef DEBUG
  85547. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85548. s->compressed_len += (stored_len + 4) << 3;
  85549. #endif
  85550. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85551. }
  85552. /* ===========================================================================
  85553. * Send one empty static block to give enough lookahead for inflate.
  85554. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85555. * The current inflate code requires 9 bits of lookahead. If the
  85556. * last two codes for the previous block (real code plus EOB) were coded
  85557. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85558. * the last real code. In this case we send two empty static blocks instead
  85559. * of one. (There are no problems if the previous block is stored or fixed.)
  85560. * To simplify the code, we assume the worst case of last real code encoded
  85561. * on one bit only.
  85562. */
  85563. void _tr_align (deflate_state *s)
  85564. {
  85565. send_bits(s, STATIC_TREES<<1, 3);
  85566. send_code(s, END_BLOCK, static_ltree);
  85567. #ifdef DEBUG
  85568. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85569. #endif
  85570. bi_flush(s);
  85571. /* Of the 10 bits for the empty block, we have already sent
  85572. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85573. * the EOB of the previous block) was thus at least one plus the length
  85574. * of the EOB plus what we have just sent of the empty static block.
  85575. */
  85576. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85577. send_bits(s, STATIC_TREES<<1, 3);
  85578. send_code(s, END_BLOCK, static_ltree);
  85579. #ifdef DEBUG
  85580. s->compressed_len += 10L;
  85581. #endif
  85582. bi_flush(s);
  85583. }
  85584. s->last_eob_len = 7;
  85585. }
  85586. /* ===========================================================================
  85587. * Determine the best encoding for the current block: dynamic trees, static
  85588. * trees or store, and output the encoded block to the zip file.
  85589. */
  85590. void _tr_flush_block (deflate_state *s,
  85591. charf *buf, /* input block, or NULL if too old */
  85592. ulg stored_len, /* length of input block */
  85593. int eof) /* true if this is the last block for a file */
  85594. {
  85595. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85596. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85597. /* Build the Huffman trees unless a stored block is forced */
  85598. if (s->level > 0) {
  85599. /* Check if the file is binary or text */
  85600. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85601. set_data_type(s);
  85602. /* Construct the literal and distance trees */
  85603. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85604. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85605. s->static_len));
  85606. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85607. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85608. s->static_len));
  85609. /* At this point, opt_len and static_len are the total bit lengths of
  85610. * the compressed block data, excluding the tree representations.
  85611. */
  85612. /* Build the bit length tree for the above two trees, and get the index
  85613. * in bl_order of the last bit length code to send.
  85614. */
  85615. max_blindex = build_bl_tree(s);
  85616. /* Determine the best encoding. Compute the block lengths in bytes. */
  85617. opt_lenb = (s->opt_len+3+7)>>3;
  85618. static_lenb = (s->static_len+3+7)>>3;
  85619. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85620. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85621. s->last_lit));
  85622. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85623. } else {
  85624. Assert(buf != (char*)0, "lost buf");
  85625. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85626. }
  85627. #ifdef FORCE_STORED
  85628. if (buf != (char*)0) { /* force stored block */
  85629. #else
  85630. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85631. /* 4: two words for the lengths */
  85632. #endif
  85633. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85634. * Otherwise we can't have processed more than WSIZE input bytes since
  85635. * the last block flush, because compression would have been
  85636. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85637. * transform a block into a stored block.
  85638. */
  85639. _tr_stored_block(s, buf, stored_len, eof);
  85640. #ifdef FORCE_STATIC
  85641. } else if (static_lenb >= 0) { /* force static trees */
  85642. #else
  85643. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85644. #endif
  85645. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85646. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85647. #ifdef DEBUG
  85648. s->compressed_len += 3 + s->static_len;
  85649. #endif
  85650. } else {
  85651. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85652. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85653. max_blindex+1);
  85654. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85655. #ifdef DEBUG
  85656. s->compressed_len += 3 + s->opt_len;
  85657. #endif
  85658. }
  85659. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85660. /* The above check is made mod 2^32, for files larger than 512 MB
  85661. * and uLong implemented on 32 bits.
  85662. */
  85663. init_block(s);
  85664. if (eof) {
  85665. bi_windup(s);
  85666. #ifdef DEBUG
  85667. s->compressed_len += 7; /* align on byte boundary */
  85668. #endif
  85669. }
  85670. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85671. s->compressed_len-7*eof));
  85672. }
  85673. /* ===========================================================================
  85674. * Save the match info and tally the frequency counts. Return true if
  85675. * the current block must be flushed.
  85676. */
  85677. int _tr_tally (deflate_state *s,
  85678. unsigned dist, /* distance of matched string */
  85679. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85680. {
  85681. s->d_buf[s->last_lit] = (ush)dist;
  85682. s->l_buf[s->last_lit++] = (uch)lc;
  85683. if (dist == 0) {
  85684. /* lc is the unmatched char */
  85685. s->dyn_ltree[lc].Freq++;
  85686. } else {
  85687. s->matches++;
  85688. /* Here, lc is the match length - MIN_MATCH */
  85689. dist--; /* dist = match distance - 1 */
  85690. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85691. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85692. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85693. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85694. s->dyn_dtree[d_code(dist)].Freq++;
  85695. }
  85696. #ifdef TRUNCATE_BLOCK
  85697. /* Try to guess if it is profitable to stop the current block here */
  85698. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85699. /* Compute an upper bound for the compressed length */
  85700. ulg out_length = (ulg)s->last_lit*8L;
  85701. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85702. int dcode;
  85703. for (dcode = 0; dcode < D_CODES; dcode++) {
  85704. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85705. (5L+extra_dbits[dcode]);
  85706. }
  85707. out_length >>= 3;
  85708. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85709. s->last_lit, in_length, out_length,
  85710. 100L - out_length*100L/in_length));
  85711. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85712. }
  85713. #endif
  85714. return (s->last_lit == s->lit_bufsize-1);
  85715. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85716. * on 16 bit machines and because stored blocks are restricted to
  85717. * 64K-1 bytes.
  85718. */
  85719. }
  85720. /* ===========================================================================
  85721. * Send the block data compressed using the given Huffman trees
  85722. */
  85723. local void compress_block (deflate_state *s,
  85724. ct_data *ltree, /* literal tree */
  85725. ct_data *dtree) /* distance tree */
  85726. {
  85727. unsigned dist; /* distance of matched string */
  85728. int lc; /* match length or unmatched char (if dist == 0) */
  85729. unsigned lx = 0; /* running index in l_buf */
  85730. unsigned code; /* the code to send */
  85731. int extra; /* number of extra bits to send */
  85732. if (s->last_lit != 0) do {
  85733. dist = s->d_buf[lx];
  85734. lc = s->l_buf[lx++];
  85735. if (dist == 0) {
  85736. send_code(s, lc, ltree); /* send a literal byte */
  85737. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85738. } else {
  85739. /* Here, lc is the match length - MIN_MATCH */
  85740. code = _length_code[lc];
  85741. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85742. extra = extra_lbits[code];
  85743. if (extra != 0) {
  85744. lc -= base_length[code];
  85745. send_bits(s, lc, extra); /* send the extra length bits */
  85746. }
  85747. dist--; /* dist is now the match distance - 1 */
  85748. code = d_code(dist);
  85749. Assert (code < D_CODES, "bad d_code");
  85750. send_code(s, code, dtree); /* send the distance code */
  85751. extra = extra_dbits[code];
  85752. if (extra != 0) {
  85753. dist -= base_dist[code];
  85754. send_bits(s, dist, extra); /* send the extra distance bits */
  85755. }
  85756. } /* literal or match pair ? */
  85757. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85758. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85759. "pendingBuf overflow");
  85760. } while (lx < s->last_lit);
  85761. send_code(s, END_BLOCK, ltree);
  85762. s->last_eob_len = ltree[END_BLOCK].Len;
  85763. }
  85764. /* ===========================================================================
  85765. * Set the data type to BINARY or TEXT, using a crude approximation:
  85766. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85767. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85768. * IN assertion: the fields Freq of dyn_ltree are set.
  85769. */
  85770. local void set_data_type (deflate_state *s)
  85771. {
  85772. int n;
  85773. for (n = 0; n < 9; n++)
  85774. if (s->dyn_ltree[n].Freq != 0)
  85775. break;
  85776. if (n == 9)
  85777. for (n = 14; n < 32; n++)
  85778. if (s->dyn_ltree[n].Freq != 0)
  85779. break;
  85780. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85781. }
  85782. /* ===========================================================================
  85783. * Reverse the first len bits of a code, using straightforward code (a faster
  85784. * method would use a table)
  85785. * IN assertion: 1 <= len <= 15
  85786. */
  85787. local unsigned bi_reverse (unsigned code, int len)
  85788. {
  85789. register unsigned res = 0;
  85790. do {
  85791. res |= code & 1;
  85792. code >>= 1, res <<= 1;
  85793. } while (--len > 0);
  85794. return res >> 1;
  85795. }
  85796. /* ===========================================================================
  85797. * Flush the bit buffer, keeping at most 7 bits in it.
  85798. */
  85799. local void bi_flush (deflate_state *s)
  85800. {
  85801. if (s->bi_valid == 16) {
  85802. put_short(s, s->bi_buf);
  85803. s->bi_buf = 0;
  85804. s->bi_valid = 0;
  85805. } else if (s->bi_valid >= 8) {
  85806. put_byte(s, (Byte)s->bi_buf);
  85807. s->bi_buf >>= 8;
  85808. s->bi_valid -= 8;
  85809. }
  85810. }
  85811. /* ===========================================================================
  85812. * Flush the bit buffer and align the output on a byte boundary
  85813. */
  85814. local void bi_windup (deflate_state *s)
  85815. {
  85816. if (s->bi_valid > 8) {
  85817. put_short(s, s->bi_buf);
  85818. } else if (s->bi_valid > 0) {
  85819. put_byte(s, (Byte)s->bi_buf);
  85820. }
  85821. s->bi_buf = 0;
  85822. s->bi_valid = 0;
  85823. #ifdef DEBUG
  85824. s->bits_sent = (s->bits_sent+7) & ~7;
  85825. #endif
  85826. }
  85827. /* ===========================================================================
  85828. * Copy a stored block, storing first the length and its
  85829. * one's complement if requested.
  85830. */
  85831. local void copy_block(deflate_state *s,
  85832. charf *buf, /* the input data */
  85833. unsigned len, /* its length */
  85834. int header) /* true if block header must be written */
  85835. {
  85836. bi_windup(s); /* align on byte boundary */
  85837. s->last_eob_len = 8; /* enough lookahead for inflate */
  85838. if (header) {
  85839. put_short(s, (ush)len);
  85840. put_short(s, (ush)~len);
  85841. #ifdef DEBUG
  85842. s->bits_sent += 2*16;
  85843. #endif
  85844. }
  85845. #ifdef DEBUG
  85846. s->bits_sent += (ulg)len<<3;
  85847. #endif
  85848. while (len--) {
  85849. put_byte(s, *buf++);
  85850. }
  85851. }
  85852. /*** End of inlined file: trees.c ***/
  85853. /*** Start of inlined file: zutil.c ***/
  85854. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85855. #ifndef NO_DUMMY_DECL
  85856. struct internal_state {int dummy;}; /* for buggy compilers */
  85857. #endif
  85858. const char * const z_errmsg[10] = {
  85859. "need dictionary", /* Z_NEED_DICT 2 */
  85860. "stream end", /* Z_STREAM_END 1 */
  85861. "", /* Z_OK 0 */
  85862. "file error", /* Z_ERRNO (-1) */
  85863. "stream error", /* Z_STREAM_ERROR (-2) */
  85864. "data error", /* Z_DATA_ERROR (-3) */
  85865. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85866. "buffer error", /* Z_BUF_ERROR (-5) */
  85867. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85868. ""};
  85869. /*const char * ZEXPORT zlibVersion()
  85870. {
  85871. return ZLIB_VERSION;
  85872. }
  85873. uLong ZEXPORT zlibCompileFlags()
  85874. {
  85875. uLong flags;
  85876. flags = 0;
  85877. switch (sizeof(uInt)) {
  85878. case 2: break;
  85879. case 4: flags += 1; break;
  85880. case 8: flags += 2; break;
  85881. default: flags += 3;
  85882. }
  85883. switch (sizeof(uLong)) {
  85884. case 2: break;
  85885. case 4: flags += 1 << 2; break;
  85886. case 8: flags += 2 << 2; break;
  85887. default: flags += 3 << 2;
  85888. }
  85889. switch (sizeof(voidpf)) {
  85890. case 2: break;
  85891. case 4: flags += 1 << 4; break;
  85892. case 8: flags += 2 << 4; break;
  85893. default: flags += 3 << 4;
  85894. }
  85895. switch (sizeof(z_off_t)) {
  85896. case 2: break;
  85897. case 4: flags += 1 << 6; break;
  85898. case 8: flags += 2 << 6; break;
  85899. default: flags += 3 << 6;
  85900. }
  85901. #ifdef DEBUG
  85902. flags += 1 << 8;
  85903. #endif
  85904. #if defined(ASMV) || defined(ASMINF)
  85905. flags += 1 << 9;
  85906. #endif
  85907. #ifdef ZLIB_WINAPI
  85908. flags += 1 << 10;
  85909. #endif
  85910. #ifdef BUILDFIXED
  85911. flags += 1 << 12;
  85912. #endif
  85913. #ifdef DYNAMIC_CRC_TABLE
  85914. flags += 1 << 13;
  85915. #endif
  85916. #ifdef NO_GZCOMPRESS
  85917. flags += 1L << 16;
  85918. #endif
  85919. #ifdef NO_GZIP
  85920. flags += 1L << 17;
  85921. #endif
  85922. #ifdef PKZIP_BUG_WORKAROUND
  85923. flags += 1L << 20;
  85924. #endif
  85925. #ifdef FASTEST
  85926. flags += 1L << 21;
  85927. #endif
  85928. #ifdef STDC
  85929. # ifdef NO_vsnprintf
  85930. flags += 1L << 25;
  85931. # ifdef HAS_vsprintf_void
  85932. flags += 1L << 26;
  85933. # endif
  85934. # else
  85935. # ifdef HAS_vsnprintf_void
  85936. flags += 1L << 26;
  85937. # endif
  85938. # endif
  85939. #else
  85940. flags += 1L << 24;
  85941. # ifdef NO_snprintf
  85942. flags += 1L << 25;
  85943. # ifdef HAS_sprintf_void
  85944. flags += 1L << 26;
  85945. # endif
  85946. # else
  85947. # ifdef HAS_snprintf_void
  85948. flags += 1L << 26;
  85949. # endif
  85950. # endif
  85951. #endif
  85952. return flags;
  85953. }*/
  85954. #ifdef DEBUG
  85955. # ifndef verbose
  85956. # define verbose 0
  85957. # endif
  85958. int z_verbose = verbose;
  85959. void z_error (const char *m)
  85960. {
  85961. fprintf(stderr, "%s\n", m);
  85962. exit(1);
  85963. }
  85964. #endif
  85965. /* exported to allow conversion of error code to string for compress() and
  85966. * uncompress()
  85967. */
  85968. const char * ZEXPORT zError(int err)
  85969. {
  85970. return ERR_MSG(err);
  85971. }
  85972. #if defined(_WIN32_WCE)
  85973. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85974. * errno. We define it as a global variable to simplify porting.
  85975. * Its value is always 0 and should not be used.
  85976. */
  85977. int errno = 0;
  85978. #endif
  85979. #ifndef HAVE_MEMCPY
  85980. void zmemcpy(dest, source, len)
  85981. Bytef* dest;
  85982. const Bytef* source;
  85983. uInt len;
  85984. {
  85985. if (len == 0) return;
  85986. do {
  85987. *dest++ = *source++; /* ??? to be unrolled */
  85988. } while (--len != 0);
  85989. }
  85990. int zmemcmp(s1, s2, len)
  85991. const Bytef* s1;
  85992. const Bytef* s2;
  85993. uInt len;
  85994. {
  85995. uInt j;
  85996. for (j = 0; j < len; j++) {
  85997. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85998. }
  85999. return 0;
  86000. }
  86001. void zmemzero(dest, len)
  86002. Bytef* dest;
  86003. uInt len;
  86004. {
  86005. if (len == 0) return;
  86006. do {
  86007. *dest++ = 0; /* ??? to be unrolled */
  86008. } while (--len != 0);
  86009. }
  86010. #endif
  86011. #ifdef SYS16BIT
  86012. #ifdef __TURBOC__
  86013. /* Turbo C in 16-bit mode */
  86014. # define MY_ZCALLOC
  86015. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86016. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86017. * must fix the pointer. Warning: the pointer must be put back to its
  86018. * original form in order to free it, use zcfree().
  86019. */
  86020. #define MAX_PTR 10
  86021. /* 10*64K = 640K */
  86022. local int next_ptr = 0;
  86023. typedef struct ptr_table_s {
  86024. voidpf org_ptr;
  86025. voidpf new_ptr;
  86026. } ptr_table;
  86027. local ptr_table table[MAX_PTR];
  86028. /* This table is used to remember the original form of pointers
  86029. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86030. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86031. * protected from concurrent access. This hack doesn't work anyway on
  86032. * a protected system like OS/2. Use Microsoft C instead.
  86033. */
  86034. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86035. {
  86036. voidpf buf = opaque; /* just to make some compilers happy */
  86037. ulg bsize = (ulg)items*size;
  86038. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86039. * will return a usable pointer which doesn't have to be normalized.
  86040. */
  86041. if (bsize < 65520L) {
  86042. buf = farmalloc(bsize);
  86043. if (*(ush*)&buf != 0) return buf;
  86044. } else {
  86045. buf = farmalloc(bsize + 16L);
  86046. }
  86047. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86048. table[next_ptr].org_ptr = buf;
  86049. /* Normalize the pointer to seg:0 */
  86050. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86051. *(ush*)&buf = 0;
  86052. table[next_ptr++].new_ptr = buf;
  86053. return buf;
  86054. }
  86055. void zcfree (voidpf opaque, voidpf ptr)
  86056. {
  86057. int n;
  86058. if (*(ush*)&ptr != 0) { /* object < 64K */
  86059. farfree(ptr);
  86060. return;
  86061. }
  86062. /* Find the original pointer */
  86063. for (n = 0; n < next_ptr; n++) {
  86064. if (ptr != table[n].new_ptr) continue;
  86065. farfree(table[n].org_ptr);
  86066. while (++n < next_ptr) {
  86067. table[n-1] = table[n];
  86068. }
  86069. next_ptr--;
  86070. return;
  86071. }
  86072. ptr = opaque; /* just to make some compilers happy */
  86073. Assert(0, "zcfree: ptr not found");
  86074. }
  86075. #endif /* __TURBOC__ */
  86076. #ifdef M_I86
  86077. /* Microsoft C in 16-bit mode */
  86078. # define MY_ZCALLOC
  86079. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86080. # define _halloc halloc
  86081. # define _hfree hfree
  86082. #endif
  86083. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86084. {
  86085. if (opaque) opaque = 0; /* to make compiler happy */
  86086. return _halloc((long)items, size);
  86087. }
  86088. void zcfree (voidpf opaque, voidpf ptr)
  86089. {
  86090. if (opaque) opaque = 0; /* to make compiler happy */
  86091. _hfree(ptr);
  86092. }
  86093. #endif /* M_I86 */
  86094. #endif /* SYS16BIT */
  86095. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86096. #ifndef STDC
  86097. extern voidp malloc OF((uInt size));
  86098. extern voidp calloc OF((uInt items, uInt size));
  86099. extern void free OF((voidpf ptr));
  86100. #endif
  86101. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86102. {
  86103. if (opaque) items += size - size; /* make compiler happy */
  86104. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86105. (voidpf)calloc(items, size);
  86106. }
  86107. void zcfree (voidpf opaque, voidpf ptr)
  86108. {
  86109. free(ptr);
  86110. if (opaque) return; /* make compiler happy */
  86111. }
  86112. #endif /* MY_ZCALLOC */
  86113. /*** End of inlined file: zutil.c ***/
  86114. #undef Byte
  86115. #else
  86116. #include <zlib.h>
  86117. #endif
  86118. }
  86119. #if JUCE_MSVC
  86120. #pragma warning (pop)
  86121. #endif
  86122. BEGIN_JUCE_NAMESPACE
  86123. // internal helper object that holds the zlib structures so they don't have to be
  86124. // included publicly.
  86125. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86126. {
  86127. public:
  86128. GZIPDecompressHelper (const bool noWrap)
  86129. : finished (true),
  86130. needsDictionary (false),
  86131. error (true),
  86132. streamIsValid (false),
  86133. data (0),
  86134. dataSize (0)
  86135. {
  86136. using namespace zlibNamespace;
  86137. zerostruct (stream);
  86138. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86139. finished = error = ! streamIsValid;
  86140. }
  86141. ~GZIPDecompressHelper()
  86142. {
  86143. using namespace zlibNamespace;
  86144. if (streamIsValid)
  86145. inflateEnd (&stream);
  86146. }
  86147. bool needsInput() const throw() { return dataSize <= 0; }
  86148. void setInput (uint8* const data_, const int size) throw()
  86149. {
  86150. data = data_;
  86151. dataSize = size;
  86152. }
  86153. int doNextBlock (uint8* const dest, const int destSize)
  86154. {
  86155. using namespace zlibNamespace;
  86156. if (streamIsValid && data != 0 && ! finished)
  86157. {
  86158. stream.next_in = data;
  86159. stream.next_out = dest;
  86160. stream.avail_in = dataSize;
  86161. stream.avail_out = destSize;
  86162. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86163. {
  86164. case Z_STREAM_END:
  86165. finished = true;
  86166. // deliberate fall-through
  86167. case Z_OK:
  86168. data += dataSize - stream.avail_in;
  86169. dataSize = stream.avail_in;
  86170. return destSize - stream.avail_out;
  86171. case Z_NEED_DICT:
  86172. needsDictionary = true;
  86173. data += dataSize - stream.avail_in;
  86174. dataSize = stream.avail_in;
  86175. break;
  86176. case Z_DATA_ERROR:
  86177. case Z_MEM_ERROR:
  86178. error = true;
  86179. default:
  86180. break;
  86181. }
  86182. }
  86183. return 0;
  86184. }
  86185. bool finished, needsDictionary, error, streamIsValid;
  86186. enum { gzipDecompBufferSize = 32768 };
  86187. private:
  86188. zlibNamespace::z_stream stream;
  86189. uint8* data;
  86190. int dataSize;
  86191. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86192. };
  86193. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86194. const bool deleteSourceWhenDestroyed,
  86195. const bool noWrap_,
  86196. const int64 uncompressedStreamLength_)
  86197. : sourceStream (sourceStream_),
  86198. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86199. uncompressedStreamLength (uncompressedStreamLength_),
  86200. noWrap (noWrap_),
  86201. isEof (false),
  86202. activeBufferSize (0),
  86203. originalSourcePos (sourceStream_->getPosition()),
  86204. currentPos (0),
  86205. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86206. helper (new GZIPDecompressHelper (noWrap_))
  86207. {
  86208. }
  86209. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86210. : sourceStream (&sourceStream_),
  86211. uncompressedStreamLength (-1),
  86212. noWrap (false),
  86213. isEof (false),
  86214. activeBufferSize (0),
  86215. originalSourcePos (sourceStream_.getPosition()),
  86216. currentPos (0),
  86217. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86218. helper (new GZIPDecompressHelper (false))
  86219. {
  86220. }
  86221. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86222. {
  86223. }
  86224. int64 GZIPDecompressorInputStream::getTotalLength()
  86225. {
  86226. return uncompressedStreamLength;
  86227. }
  86228. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86229. {
  86230. if ((howMany > 0) && ! isEof)
  86231. {
  86232. jassert (destBuffer != 0);
  86233. if (destBuffer != 0)
  86234. {
  86235. int numRead = 0;
  86236. uint8* d = static_cast <uint8*> (destBuffer);
  86237. while (! helper->error)
  86238. {
  86239. const int n = helper->doNextBlock (d, howMany);
  86240. currentPos += n;
  86241. if (n == 0)
  86242. {
  86243. if (helper->finished || helper->needsDictionary)
  86244. {
  86245. isEof = true;
  86246. return numRead;
  86247. }
  86248. if (helper->needsInput())
  86249. {
  86250. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86251. if (activeBufferSize > 0)
  86252. {
  86253. helper->setInput (buffer, activeBufferSize);
  86254. }
  86255. else
  86256. {
  86257. isEof = true;
  86258. return numRead;
  86259. }
  86260. }
  86261. }
  86262. else
  86263. {
  86264. numRead += n;
  86265. howMany -= n;
  86266. d += n;
  86267. if (howMany <= 0)
  86268. return numRead;
  86269. }
  86270. }
  86271. }
  86272. }
  86273. return 0;
  86274. }
  86275. bool GZIPDecompressorInputStream::isExhausted()
  86276. {
  86277. return helper->error || isEof;
  86278. }
  86279. int64 GZIPDecompressorInputStream::getPosition()
  86280. {
  86281. return currentPos;
  86282. }
  86283. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86284. {
  86285. if (newPos < currentPos)
  86286. {
  86287. // to go backwards, reset the stream and start again..
  86288. isEof = false;
  86289. activeBufferSize = 0;
  86290. currentPos = 0;
  86291. helper = new GZIPDecompressHelper (noWrap);
  86292. sourceStream->setPosition (originalSourcePos);
  86293. }
  86294. skipNextBytes (newPos - currentPos);
  86295. return true;
  86296. }
  86297. END_JUCE_NAMESPACE
  86298. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86299. #endif
  86300. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86301. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86302. #if JUCE_USE_FLAC
  86303. #if JUCE_WINDOWS
  86304. #include <windows.h>
  86305. #endif
  86306. namespace FlacNamespace
  86307. {
  86308. #if JUCE_INCLUDE_FLAC_CODE
  86309. #if JUCE_MSVC
  86310. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86311. #endif
  86312. #define FLAC__NO_DLL 1
  86313. #if ! defined (SIZE_MAX)
  86314. #define SIZE_MAX 0xffffffff
  86315. #endif
  86316. #define __STDC_LIMIT_MACROS 1
  86317. /*** Start of inlined file: all.h ***/
  86318. #ifndef FLAC__ALL_H
  86319. #define FLAC__ALL_H
  86320. /*** Start of inlined file: export.h ***/
  86321. #ifndef FLAC__EXPORT_H
  86322. #define FLAC__EXPORT_H
  86323. /** \file include/FLAC/export.h
  86324. *
  86325. * \brief
  86326. * This module contains #defines and symbols for exporting function
  86327. * calls, and providing version information and compiled-in features.
  86328. *
  86329. * See the \link flac_export export \endlink module.
  86330. */
  86331. /** \defgroup flac_export FLAC/export.h: export symbols
  86332. * \ingroup flac
  86333. *
  86334. * \brief
  86335. * This module contains #defines and symbols for exporting function
  86336. * calls, and providing version information and compiled-in features.
  86337. *
  86338. * If you are compiling with MSVC and will link to the static library
  86339. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86340. * make sure the symbols are exported properly.
  86341. *
  86342. * \{
  86343. */
  86344. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86345. #define FLAC_API
  86346. #else
  86347. #ifdef FLAC_API_EXPORTS
  86348. #define FLAC_API _declspec(dllexport)
  86349. #else
  86350. #define FLAC_API _declspec(dllimport)
  86351. #endif
  86352. #endif
  86353. /** These #defines will mirror the libtool-based library version number, see
  86354. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86355. */
  86356. #define FLAC_API_VERSION_CURRENT 10
  86357. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86358. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86359. #ifdef __cplusplus
  86360. extern "C" {
  86361. #endif
  86362. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86363. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86364. #ifdef __cplusplus
  86365. }
  86366. #endif
  86367. /* \} */
  86368. #endif
  86369. /*** End of inlined file: export.h ***/
  86370. /*** Start of inlined file: assert.h ***/
  86371. #ifndef FLAC__ASSERT_H
  86372. #define FLAC__ASSERT_H
  86373. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86374. #ifdef DEBUG
  86375. #include <assert.h>
  86376. #define FLAC__ASSERT(x) assert(x)
  86377. #define FLAC__ASSERT_DECLARATION(x) x
  86378. #else
  86379. #define FLAC__ASSERT(x)
  86380. #define FLAC__ASSERT_DECLARATION(x)
  86381. #endif
  86382. #endif
  86383. /*** End of inlined file: assert.h ***/
  86384. /*** Start of inlined file: callback.h ***/
  86385. #ifndef FLAC__CALLBACK_H
  86386. #define FLAC__CALLBACK_H
  86387. /*** Start of inlined file: ordinals.h ***/
  86388. #ifndef FLAC__ORDINALS_H
  86389. #define FLAC__ORDINALS_H
  86390. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86391. #include <inttypes.h>
  86392. #endif
  86393. typedef signed char FLAC__int8;
  86394. typedef unsigned char FLAC__uint8;
  86395. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86396. typedef __int16 FLAC__int16;
  86397. typedef __int32 FLAC__int32;
  86398. typedef __int64 FLAC__int64;
  86399. typedef unsigned __int16 FLAC__uint16;
  86400. typedef unsigned __int32 FLAC__uint32;
  86401. typedef unsigned __int64 FLAC__uint64;
  86402. #elif defined(__EMX__)
  86403. typedef short FLAC__int16;
  86404. typedef long FLAC__int32;
  86405. typedef long long FLAC__int64;
  86406. typedef unsigned short FLAC__uint16;
  86407. typedef unsigned long FLAC__uint32;
  86408. typedef unsigned long long FLAC__uint64;
  86409. #else
  86410. typedef int16_t FLAC__int16;
  86411. typedef int32_t FLAC__int32;
  86412. typedef int64_t FLAC__int64;
  86413. typedef uint16_t FLAC__uint16;
  86414. typedef uint32_t FLAC__uint32;
  86415. typedef uint64_t FLAC__uint64;
  86416. #endif
  86417. typedef int FLAC__bool;
  86418. typedef FLAC__uint8 FLAC__byte;
  86419. #ifdef true
  86420. #undef true
  86421. #endif
  86422. #ifdef false
  86423. #undef false
  86424. #endif
  86425. #ifndef __cplusplus
  86426. #define true 1
  86427. #define false 0
  86428. #endif
  86429. #endif
  86430. /*** End of inlined file: ordinals.h ***/
  86431. #include <stdlib.h> /* for size_t */
  86432. /** \file include/FLAC/callback.h
  86433. *
  86434. * \brief
  86435. * This module defines the structures for describing I/O callbacks
  86436. * to the other FLAC interfaces.
  86437. *
  86438. * See the detailed documentation for callbacks in the
  86439. * \link flac_callbacks callbacks \endlink module.
  86440. */
  86441. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86442. * \ingroup flac
  86443. *
  86444. * \brief
  86445. * This module defines the structures for describing I/O callbacks
  86446. * to the other FLAC interfaces.
  86447. *
  86448. * The purpose of the I/O callback functions is to create a common way
  86449. * for the metadata interfaces to handle I/O.
  86450. *
  86451. * Originally the metadata interfaces required filenames as the way of
  86452. * specifying FLAC files to operate on. This is problematic in some
  86453. * environments so there is an additional option to specify a set of
  86454. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86455. *
  86456. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86457. * opaque structure for a data source.
  86458. *
  86459. * The callback function prototypes are similar (but not identical) to the
  86460. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86461. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86462. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86463. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86464. * is required. \warning You generally CANNOT directly use fseek or ftell
  86465. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86466. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86467. * large files. You will have to find an equivalent function (e.g. ftello),
  86468. * or write a wrapper. The same is true for feof() since this is usually
  86469. * implemented as a macro, not as a function whose address can be taken.
  86470. *
  86471. * \{
  86472. */
  86473. #ifdef __cplusplus
  86474. extern "C" {
  86475. #endif
  86476. /** This is the opaque handle type used by the callbacks. Typically
  86477. * this is a \c FILE* or address of a file descriptor.
  86478. */
  86479. typedef void* FLAC__IOHandle;
  86480. /** Signature for the read callback.
  86481. * The signature and semantics match POSIX fread() implementations
  86482. * and can generally be used interchangeably.
  86483. *
  86484. * \param ptr The address of the read buffer.
  86485. * \param size The size of the records to be read.
  86486. * \param nmemb The number of records to be read.
  86487. * \param handle The handle to the data source.
  86488. * \retval size_t
  86489. * The number of records read.
  86490. */
  86491. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86492. /** Signature for the write callback.
  86493. * The signature and semantics match POSIX fwrite() implementations
  86494. * and can generally be used interchangeably.
  86495. *
  86496. * \param ptr The address of the write buffer.
  86497. * \param size The size of the records to be written.
  86498. * \param nmemb The number of records to be written.
  86499. * \param handle The handle to the data source.
  86500. * \retval size_t
  86501. * The number of records written.
  86502. */
  86503. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86504. /** Signature for the seek callback.
  86505. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86506. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86507. * and 32-bits wide.
  86508. *
  86509. * \param handle The handle to the data source.
  86510. * \param offset The new position, relative to \a whence
  86511. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86512. * \retval int
  86513. * \c 0 on success, \c -1 on error.
  86514. */
  86515. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86516. /** Signature for the tell callback.
  86517. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86518. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86519. * and 32-bits wide.
  86520. *
  86521. * \param handle The handle to the data source.
  86522. * \retval FLAC__int64
  86523. * The current position on success, \c -1 on error.
  86524. */
  86525. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86526. /** Signature for the EOF callback.
  86527. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86528. * on many systems, feof() is a macro, so in this case a wrapper function
  86529. * must be provided instead.
  86530. *
  86531. * \param handle The handle to the data source.
  86532. * \retval int
  86533. * \c 0 if not at end of file, nonzero if at end of file.
  86534. */
  86535. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86536. /** Signature for the close callback.
  86537. * The signature and semantics match POSIX fclose() implementations
  86538. * and can generally be used interchangeably.
  86539. *
  86540. * \param handle The handle to the data source.
  86541. * \retval int
  86542. * \c 0 on success, \c EOF on error.
  86543. */
  86544. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86545. /** A structure for holding a set of callbacks.
  86546. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86547. * describe which of the callbacks are required. The ones that are not
  86548. * required may be set to NULL.
  86549. *
  86550. * If the seek requirement for an interface is optional, you can signify that
  86551. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86552. */
  86553. typedef struct {
  86554. FLAC__IOCallback_Read read;
  86555. FLAC__IOCallback_Write write;
  86556. FLAC__IOCallback_Seek seek;
  86557. FLAC__IOCallback_Tell tell;
  86558. FLAC__IOCallback_Eof eof;
  86559. FLAC__IOCallback_Close close;
  86560. } FLAC__IOCallbacks;
  86561. /* \} */
  86562. #ifdef __cplusplus
  86563. }
  86564. #endif
  86565. #endif
  86566. /*** End of inlined file: callback.h ***/
  86567. /*** Start of inlined file: format.h ***/
  86568. #ifndef FLAC__FORMAT_H
  86569. #define FLAC__FORMAT_H
  86570. #ifdef __cplusplus
  86571. extern "C" {
  86572. #endif
  86573. /** \file include/FLAC/format.h
  86574. *
  86575. * \brief
  86576. * This module contains structure definitions for the representation
  86577. * of FLAC format components in memory. These are the basic
  86578. * structures used by the rest of the interfaces.
  86579. *
  86580. * See the detailed documentation in the
  86581. * \link flac_format format \endlink module.
  86582. */
  86583. /** \defgroup flac_format FLAC/format.h: format components
  86584. * \ingroup flac
  86585. *
  86586. * \brief
  86587. * This module contains structure definitions for the representation
  86588. * of FLAC format components in memory. These are the basic
  86589. * structures used by the rest of the interfaces.
  86590. *
  86591. * First, you should be familiar with the
  86592. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86593. * follow directly from the specification. As a user of libFLAC, the
  86594. * interesting parts really are the structures that describe the frame
  86595. * header and metadata blocks.
  86596. *
  86597. * The format structures here are very primitive, designed to store
  86598. * information in an efficient way. Reading information from the
  86599. * structures is easy but creating or modifying them directly is
  86600. * more complex. For the most part, as a user of a library, editing
  86601. * is not necessary; however, for metadata blocks it is, so there are
  86602. * convenience functions provided in the \link flac_metadata metadata
  86603. * module \endlink to simplify the manipulation of metadata blocks.
  86604. *
  86605. * \note
  86606. * It's not the best convention, but symbols ending in _LEN are in bits
  86607. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86608. * global variables because they are usually used when declaring byte
  86609. * arrays and some compilers require compile-time knowledge of array
  86610. * sizes when declared on the stack.
  86611. *
  86612. * \{
  86613. */
  86614. /*
  86615. Most of the values described in this file are defined by the FLAC
  86616. format specification. There is nothing to tune here.
  86617. */
  86618. /** The largest legal metadata type code. */
  86619. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86620. /** The minimum block size, in samples, permitted by the format. */
  86621. #define FLAC__MIN_BLOCK_SIZE (16u)
  86622. /** The maximum block size, in samples, permitted by the format. */
  86623. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86624. /** The maximum block size, in samples, permitted by the FLAC subset for
  86625. * sample rates up to 48kHz. */
  86626. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86627. /** The maximum number of channels permitted by the format. */
  86628. #define FLAC__MAX_CHANNELS (8u)
  86629. /** The minimum sample resolution permitted by the format. */
  86630. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86631. /** The maximum sample resolution permitted by the format. */
  86632. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86633. /** The maximum sample resolution permitted by libFLAC.
  86634. *
  86635. * \warning
  86636. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86637. * the reference encoder/decoder is currently limited to 24 bits because
  86638. * of prevalent 32-bit math, so make sure and use this value when
  86639. * appropriate.
  86640. */
  86641. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86642. /** The maximum sample rate permitted by the format. The value is
  86643. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86644. * as to why.
  86645. */
  86646. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86647. /** The maximum LPC order permitted by the format. */
  86648. #define FLAC__MAX_LPC_ORDER (32u)
  86649. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86650. * up to 48kHz. */
  86651. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86652. /** The minimum quantized linear predictor coefficient precision
  86653. * permitted by the format.
  86654. */
  86655. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86656. /** The maximum quantized linear predictor coefficient precision
  86657. * permitted by the format.
  86658. */
  86659. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86660. /** The maximum order of the fixed predictors permitted by the format. */
  86661. #define FLAC__MAX_FIXED_ORDER (4u)
  86662. /** The maximum Rice partition order permitted by the format. */
  86663. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86664. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86665. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86666. /** The version string of the release, stamped onto the libraries and binaries.
  86667. *
  86668. * \note
  86669. * This does not correspond to the shared library version number, which
  86670. * is used to determine binary compatibility.
  86671. */
  86672. extern FLAC_API const char *FLAC__VERSION_STRING;
  86673. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86674. * This is a NUL-terminated ASCII string; when inserted into the
  86675. * VORBIS_COMMENT the trailing null is stripped.
  86676. */
  86677. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86678. /** The byte string representation of the beginning of a FLAC stream. */
  86679. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86680. /** The 32-bit integer big-endian representation of the beginning of
  86681. * a FLAC stream.
  86682. */
  86683. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86684. /** The length of the FLAC signature in bits. */
  86685. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86686. /** The length of the FLAC signature in bytes. */
  86687. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86688. /*****************************************************************************
  86689. *
  86690. * Subframe structures
  86691. *
  86692. *****************************************************************************/
  86693. /*****************************************************************************/
  86694. /** An enumeration of the available entropy coding methods. */
  86695. typedef enum {
  86696. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86697. /**< Residual is coded by partitioning into contexts, each with it's own
  86698. * 4-bit Rice parameter. */
  86699. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86700. /**< Residual is coded by partitioning into contexts, each with it's own
  86701. * 5-bit Rice parameter. */
  86702. } FLAC__EntropyCodingMethodType;
  86703. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86704. *
  86705. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86706. * give the string equivalent. The contents should not be modified.
  86707. */
  86708. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86709. /** Contents of a Rice partitioned residual
  86710. */
  86711. typedef struct {
  86712. unsigned *parameters;
  86713. /**< The Rice parameters for each context. */
  86714. unsigned *raw_bits;
  86715. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86716. * partitions and zero for unescaped partitions.
  86717. */
  86718. unsigned capacity_by_order;
  86719. /**< The capacity of the \a parameters and \a raw_bits arrays
  86720. * specified as an order, i.e. the number of array elements
  86721. * allocated is 2 ^ \a capacity_by_order.
  86722. */
  86723. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86724. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86725. */
  86726. typedef struct {
  86727. unsigned order;
  86728. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86729. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86730. /**< The context's Rice parameters and/or raw bits. */
  86731. } FLAC__EntropyCodingMethod_PartitionedRice;
  86732. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86733. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86734. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86735. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86736. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86737. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86738. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86739. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86740. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86741. */
  86742. typedef struct {
  86743. FLAC__EntropyCodingMethodType type;
  86744. union {
  86745. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86746. } data;
  86747. } FLAC__EntropyCodingMethod;
  86748. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86749. /*****************************************************************************/
  86750. /** An enumeration of the available subframe types. */
  86751. typedef enum {
  86752. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86753. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86754. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86755. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86756. } FLAC__SubframeType;
  86757. /** Maps a FLAC__SubframeType to a C string.
  86758. *
  86759. * Using a FLAC__SubframeType as the index to this array will
  86760. * give the string equivalent. The contents should not be modified.
  86761. */
  86762. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86763. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86764. */
  86765. typedef struct {
  86766. FLAC__int32 value; /**< The constant signal value. */
  86767. } FLAC__Subframe_Constant;
  86768. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86769. */
  86770. typedef struct {
  86771. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86772. } FLAC__Subframe_Verbatim;
  86773. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86774. */
  86775. typedef struct {
  86776. FLAC__EntropyCodingMethod entropy_coding_method;
  86777. /**< The residual coding method. */
  86778. unsigned order;
  86779. /**< The polynomial order. */
  86780. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86781. /**< Warmup samples to prime the predictor, length == order. */
  86782. const FLAC__int32 *residual;
  86783. /**< The residual signal, length == (blocksize minus order) samples. */
  86784. } FLAC__Subframe_Fixed;
  86785. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86786. */
  86787. typedef struct {
  86788. FLAC__EntropyCodingMethod entropy_coding_method;
  86789. /**< The residual coding method. */
  86790. unsigned order;
  86791. /**< The FIR order. */
  86792. unsigned qlp_coeff_precision;
  86793. /**< Quantized FIR filter coefficient precision in bits. */
  86794. int quantization_level;
  86795. /**< The qlp coeff shift needed. */
  86796. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86797. /**< FIR filter coefficients. */
  86798. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86799. /**< Warmup samples to prime the predictor, length == order. */
  86800. const FLAC__int32 *residual;
  86801. /**< The residual signal, length == (blocksize minus order) samples. */
  86802. } FLAC__Subframe_LPC;
  86803. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86804. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86805. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86806. */
  86807. typedef struct {
  86808. FLAC__SubframeType type;
  86809. union {
  86810. FLAC__Subframe_Constant constant;
  86811. FLAC__Subframe_Fixed fixed;
  86812. FLAC__Subframe_LPC lpc;
  86813. FLAC__Subframe_Verbatim verbatim;
  86814. } data;
  86815. unsigned wasted_bits;
  86816. } FLAC__Subframe;
  86817. /** == 1 (bit)
  86818. *
  86819. * This used to be a zero-padding bit (hence the name
  86820. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86821. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86822. * to mean something else.
  86823. */
  86824. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86825. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86826. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86827. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86828. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86829. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86830. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86831. /*****************************************************************************/
  86832. /*****************************************************************************
  86833. *
  86834. * Frame structures
  86835. *
  86836. *****************************************************************************/
  86837. /** An enumeration of the available channel assignments. */
  86838. typedef enum {
  86839. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86840. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86841. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86842. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86843. } FLAC__ChannelAssignment;
  86844. /** Maps a FLAC__ChannelAssignment to a C string.
  86845. *
  86846. * Using a FLAC__ChannelAssignment as the index to this array will
  86847. * give the string equivalent. The contents should not be modified.
  86848. */
  86849. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86850. /** An enumeration of the possible frame numbering methods. */
  86851. typedef enum {
  86852. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86853. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86854. } FLAC__FrameNumberType;
  86855. /** Maps a FLAC__FrameNumberType to a C string.
  86856. *
  86857. * Using a FLAC__FrameNumberType as the index to this array will
  86858. * give the string equivalent. The contents should not be modified.
  86859. */
  86860. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86861. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86862. */
  86863. typedef struct {
  86864. unsigned blocksize;
  86865. /**< The number of samples per subframe. */
  86866. unsigned sample_rate;
  86867. /**< The sample rate in Hz. */
  86868. unsigned channels;
  86869. /**< The number of channels (== number of subframes). */
  86870. FLAC__ChannelAssignment channel_assignment;
  86871. /**< The channel assignment for the frame. */
  86872. unsigned bits_per_sample;
  86873. /**< The sample resolution. */
  86874. FLAC__FrameNumberType number_type;
  86875. /**< The numbering scheme used for the frame. As a convenience, the
  86876. * decoder will always convert a frame number to a sample number because
  86877. * the rules are complex. */
  86878. union {
  86879. FLAC__uint32 frame_number;
  86880. FLAC__uint64 sample_number;
  86881. } number;
  86882. /**< The frame number or sample number of first sample in frame;
  86883. * use the \a number_type value to determine which to use. */
  86884. FLAC__uint8 crc;
  86885. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86886. * of the raw frame header bytes, meaning everything before the CRC byte
  86887. * including the sync code.
  86888. */
  86889. } FLAC__FrameHeader;
  86890. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86891. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86892. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86893. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86894. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86895. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86896. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86897. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86898. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86899. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86900. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86901. */
  86902. typedef struct {
  86903. FLAC__uint16 crc;
  86904. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86905. * 0) of the bytes before the crc, back to and including the frame header
  86906. * sync code.
  86907. */
  86908. } FLAC__FrameFooter;
  86909. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86910. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86911. */
  86912. typedef struct {
  86913. FLAC__FrameHeader header;
  86914. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86915. FLAC__FrameFooter footer;
  86916. } FLAC__Frame;
  86917. /*****************************************************************************/
  86918. /*****************************************************************************
  86919. *
  86920. * Meta-data structures
  86921. *
  86922. *****************************************************************************/
  86923. /** An enumeration of the available metadata block types. */
  86924. typedef enum {
  86925. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86926. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86927. FLAC__METADATA_TYPE_PADDING = 1,
  86928. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86929. FLAC__METADATA_TYPE_APPLICATION = 2,
  86930. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86931. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86932. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86933. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86934. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86935. FLAC__METADATA_TYPE_CUESHEET = 5,
  86936. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86937. FLAC__METADATA_TYPE_PICTURE = 6,
  86938. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86939. FLAC__METADATA_TYPE_UNDEFINED = 7
  86940. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86941. } FLAC__MetadataType;
  86942. /** Maps a FLAC__MetadataType to a C string.
  86943. *
  86944. * Using a FLAC__MetadataType as the index to this array will
  86945. * give the string equivalent. The contents should not be modified.
  86946. */
  86947. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86948. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86949. */
  86950. typedef struct {
  86951. unsigned min_blocksize, max_blocksize;
  86952. unsigned min_framesize, max_framesize;
  86953. unsigned sample_rate;
  86954. unsigned channels;
  86955. unsigned bits_per_sample;
  86956. FLAC__uint64 total_samples;
  86957. FLAC__byte md5sum[16];
  86958. } FLAC__StreamMetadata_StreamInfo;
  86959. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86960. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86961. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86962. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86963. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86964. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86965. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86966. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86967. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86968. /** The total stream length of the STREAMINFO block in bytes. */
  86969. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86970. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86971. */
  86972. typedef struct {
  86973. int dummy;
  86974. /**< Conceptually this is an empty struct since we don't store the
  86975. * padding bytes. Empty structs are not allowed by some C compilers,
  86976. * hence the dummy.
  86977. */
  86978. } FLAC__StreamMetadata_Padding;
  86979. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86980. */
  86981. typedef struct {
  86982. FLAC__byte id[4];
  86983. FLAC__byte *data;
  86984. } FLAC__StreamMetadata_Application;
  86985. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86986. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86987. */
  86988. typedef struct {
  86989. FLAC__uint64 sample_number;
  86990. /**< The sample number of the target frame. */
  86991. FLAC__uint64 stream_offset;
  86992. /**< The offset, in bytes, of the target frame with respect to
  86993. * beginning of the first frame. */
  86994. unsigned frame_samples;
  86995. /**< The number of samples in the target frame. */
  86996. } FLAC__StreamMetadata_SeekPoint;
  86997. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86998. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86999. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87000. /** The total stream length of a seek point in bytes. */
  87001. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87002. /** The value used in the \a sample_number field of
  87003. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87004. * point (== 0xffffffffffffffff).
  87005. */
  87006. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87007. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87008. *
  87009. * \note From the format specification:
  87010. * - The seek points must be sorted by ascending sample number.
  87011. * - Each seek point's sample number must be the first sample of the
  87012. * target frame.
  87013. * - Each seek point's sample number must be unique within the table.
  87014. * - Existence of a SEEKTABLE block implies a correct setting of
  87015. * total_samples in the stream_info block.
  87016. * - Behavior is undefined when more than one SEEKTABLE block is
  87017. * present in a stream.
  87018. */
  87019. typedef struct {
  87020. unsigned num_points;
  87021. FLAC__StreamMetadata_SeekPoint *points;
  87022. } FLAC__StreamMetadata_SeekTable;
  87023. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87024. *
  87025. * For convenience, the APIs maintain a trailing NUL character at the end of
  87026. * \a entry which is not counted toward \a length, i.e.
  87027. * \code strlen(entry) == length \endcode
  87028. */
  87029. typedef struct {
  87030. FLAC__uint32 length;
  87031. FLAC__byte *entry;
  87032. } FLAC__StreamMetadata_VorbisComment_Entry;
  87033. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87034. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87035. */
  87036. typedef struct {
  87037. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87038. FLAC__uint32 num_comments;
  87039. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87040. } FLAC__StreamMetadata_VorbisComment;
  87041. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87042. /** FLAC CUESHEET track index structure. (See the
  87043. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87044. * the full description of each field.)
  87045. */
  87046. typedef struct {
  87047. FLAC__uint64 offset;
  87048. /**< Offset in samples, relative to the track offset, of the index
  87049. * point.
  87050. */
  87051. FLAC__byte number;
  87052. /**< The index point number. */
  87053. } FLAC__StreamMetadata_CueSheet_Index;
  87054. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87055. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87056. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87057. /** FLAC CUESHEET track structure. (See the
  87058. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87059. * the full description of each field.)
  87060. */
  87061. typedef struct {
  87062. FLAC__uint64 offset;
  87063. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87064. FLAC__byte number;
  87065. /**< The track number. */
  87066. char isrc[13];
  87067. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87068. unsigned type:1;
  87069. /**< The track type: 0 for audio, 1 for non-audio. */
  87070. unsigned pre_emphasis:1;
  87071. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87072. FLAC__byte num_indices;
  87073. /**< The number of track index points. */
  87074. FLAC__StreamMetadata_CueSheet_Index *indices;
  87075. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87076. } FLAC__StreamMetadata_CueSheet_Track;
  87077. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87078. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87079. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87080. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87081. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87082. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87083. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87084. /** FLAC CUESHEET structure. (See the
  87085. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87086. * for the full description of each field.)
  87087. */
  87088. typedef struct {
  87089. char media_catalog_number[129];
  87090. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87091. * general, the media catalog number may be 0 to 128 bytes long; any
  87092. * unused characters should be right-padded with NUL characters.
  87093. */
  87094. FLAC__uint64 lead_in;
  87095. /**< The number of lead-in samples. */
  87096. FLAC__bool is_cd;
  87097. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87098. unsigned num_tracks;
  87099. /**< The number of tracks. */
  87100. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87101. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87102. } FLAC__StreamMetadata_CueSheet;
  87103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87104. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87105. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87106. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87107. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87108. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87109. typedef enum {
  87110. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87111. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87112. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87113. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87114. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87115. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87116. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87117. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87118. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87119. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87120. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87121. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87122. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87123. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87124. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87125. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87126. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87127. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87128. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87129. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87130. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87131. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87132. } FLAC__StreamMetadata_Picture_Type;
  87133. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87134. *
  87135. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87136. * will give the string equivalent. The contents should not be
  87137. * modified.
  87138. */
  87139. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87140. /** FLAC PICTURE structure. (See the
  87141. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87142. * for the full description of each field.)
  87143. */
  87144. typedef struct {
  87145. FLAC__StreamMetadata_Picture_Type type;
  87146. /**< The kind of picture stored. */
  87147. char *mime_type;
  87148. /**< Picture data's MIME type, in ASCII printable characters
  87149. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87150. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87151. * MIME type of '-->' is also allowed, in which case the picture
  87152. * data should be a complete URL. In file storage, the MIME type is
  87153. * stored as a 32-bit length followed by the ASCII string with no NUL
  87154. * terminator, but is converted to a plain C string in this structure
  87155. * for convenience.
  87156. */
  87157. FLAC__byte *description;
  87158. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87159. * the description is stored as a 32-bit length followed by the UTF-8
  87160. * string with no NUL terminator, but is converted to a plain C string
  87161. * in this structure for convenience.
  87162. */
  87163. FLAC__uint32 width;
  87164. /**< Picture's width in pixels. */
  87165. FLAC__uint32 height;
  87166. /**< Picture's height in pixels. */
  87167. FLAC__uint32 depth;
  87168. /**< Picture's color depth in bits-per-pixel. */
  87169. FLAC__uint32 colors;
  87170. /**< For indexed palettes (like GIF), picture's number of colors (the
  87171. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87172. */
  87173. FLAC__uint32 data_length;
  87174. /**< Length of binary picture data in bytes. */
  87175. FLAC__byte *data;
  87176. /**< Binary picture data. */
  87177. } FLAC__StreamMetadata_Picture;
  87178. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87179. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87180. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87181. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87182. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87183. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87184. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87185. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87186. /** Structure that is used when a metadata block of unknown type is loaded.
  87187. * The contents are opaque. The structure is used only internally to
  87188. * correctly handle unknown metadata.
  87189. */
  87190. typedef struct {
  87191. FLAC__byte *data;
  87192. } FLAC__StreamMetadata_Unknown;
  87193. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87194. */
  87195. typedef struct {
  87196. FLAC__MetadataType type;
  87197. /**< The type of the metadata block; used determine which member of the
  87198. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87199. * then \a data.unknown must be used. */
  87200. FLAC__bool is_last;
  87201. /**< \c true if this metadata block is the last, else \a false */
  87202. unsigned length;
  87203. /**< Length, in bytes, of the block data as it appears in the stream. */
  87204. union {
  87205. FLAC__StreamMetadata_StreamInfo stream_info;
  87206. FLAC__StreamMetadata_Padding padding;
  87207. FLAC__StreamMetadata_Application application;
  87208. FLAC__StreamMetadata_SeekTable seek_table;
  87209. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87210. FLAC__StreamMetadata_CueSheet cue_sheet;
  87211. FLAC__StreamMetadata_Picture picture;
  87212. FLAC__StreamMetadata_Unknown unknown;
  87213. } data;
  87214. /**< Polymorphic block data; use the \a type value to determine which
  87215. * to use. */
  87216. } FLAC__StreamMetadata;
  87217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87220. /** The total stream length of a metadata block header in bytes. */
  87221. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87222. /*****************************************************************************/
  87223. /*****************************************************************************
  87224. *
  87225. * Utility functions
  87226. *
  87227. *****************************************************************************/
  87228. /** Tests that a sample rate is valid for FLAC.
  87229. *
  87230. * \param sample_rate The sample rate to test for compliance.
  87231. * \retval FLAC__bool
  87232. * \c true if the given sample rate conforms to the specification, else
  87233. * \c false.
  87234. */
  87235. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87236. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87237. * for valid sample rates are slightly more complex since the rate has to
  87238. * be expressible completely in the frame header.
  87239. *
  87240. * \param sample_rate The sample rate to test for compliance.
  87241. * \retval FLAC__bool
  87242. * \c true if the given sample rate conforms to the specification for the
  87243. * subset, else \c false.
  87244. */
  87245. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87246. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87247. * comment specification.
  87248. *
  87249. * Vorbis comment names must be composed only of characters from
  87250. * [0x20-0x3C,0x3E-0x7D].
  87251. *
  87252. * \param name A NUL-terminated string to be checked.
  87253. * \assert
  87254. * \code name != NULL \endcode
  87255. * \retval FLAC__bool
  87256. * \c false if entry name is illegal, else \c true.
  87257. */
  87258. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87259. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87260. * comment specification.
  87261. *
  87262. * Vorbis comment values must be valid UTF-8 sequences.
  87263. *
  87264. * \param value A string to be checked.
  87265. * \param length A the length of \a value in bytes. May be
  87266. * \c (unsigned)(-1) to indicate that \a value is a plain
  87267. * UTF-8 NUL-terminated string.
  87268. * \assert
  87269. * \code value != NULL \endcode
  87270. * \retval FLAC__bool
  87271. * \c false if entry name is illegal, else \c true.
  87272. */
  87273. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87274. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87275. * comment specification.
  87276. *
  87277. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87278. * 'value' must be legal according to
  87279. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87280. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87281. *
  87282. * \param entry An entry to be checked.
  87283. * \param length The length of \a entry in bytes.
  87284. * \assert
  87285. * \code value != NULL \endcode
  87286. * \retval FLAC__bool
  87287. * \c false if entry name is illegal, else \c true.
  87288. */
  87289. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87290. /** Check a seek table to see if it conforms to the FLAC specification.
  87291. * See the format specification for limits on the contents of the
  87292. * seek table.
  87293. *
  87294. * \param seek_table A pointer to a seek table to be checked.
  87295. * \assert
  87296. * \code seek_table != NULL \endcode
  87297. * \retval FLAC__bool
  87298. * \c false if seek table is illegal, else \c true.
  87299. */
  87300. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87301. /** Sort a seek table's seek points according to the format specification.
  87302. * This includes a "unique-ification" step to remove duplicates, i.e.
  87303. * seek points with identical \a sample_number values. Duplicate seek
  87304. * points are converted into placeholder points and sorted to the end of
  87305. * the table.
  87306. *
  87307. * \param seek_table A pointer to a seek table to be sorted.
  87308. * \assert
  87309. * \code seek_table != NULL \endcode
  87310. * \retval unsigned
  87311. * The number of duplicate seek points converted into placeholders.
  87312. */
  87313. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87314. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87315. * See the format specification for limits on the contents of the
  87316. * cue sheet.
  87317. *
  87318. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87319. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87320. * stringent requirements for a CD-DA (audio) disc.
  87321. * \param violation Address of a pointer to a string. If there is a
  87322. * violation, a pointer to a string explanation of the
  87323. * violation will be returned here. \a violation may be
  87324. * \c NULL if you don't need the returned string. Do not
  87325. * free the returned string; it will always point to static
  87326. * data.
  87327. * \assert
  87328. * \code cue_sheet != NULL \endcode
  87329. * \retval FLAC__bool
  87330. * \c false if cue sheet is illegal, else \c true.
  87331. */
  87332. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87333. /** Check picture data to see if it conforms to the FLAC specification.
  87334. * See the format specification for limits on the contents of the
  87335. * PICTURE block.
  87336. *
  87337. * \param picture A pointer to existing picture data to be checked.
  87338. * \param violation Address of a pointer to a string. If there is a
  87339. * violation, a pointer to a string explanation of the
  87340. * violation will be returned here. \a violation may be
  87341. * \c NULL if you don't need the returned string. Do not
  87342. * free the returned string; it will always point to static
  87343. * data.
  87344. * \assert
  87345. * \code picture != NULL \endcode
  87346. * \retval FLAC__bool
  87347. * \c false if picture data is illegal, else \c true.
  87348. */
  87349. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87350. /* \} */
  87351. #ifdef __cplusplus
  87352. }
  87353. #endif
  87354. #endif
  87355. /*** End of inlined file: format.h ***/
  87356. /*** Start of inlined file: metadata.h ***/
  87357. #ifndef FLAC__METADATA_H
  87358. #define FLAC__METADATA_H
  87359. #include <sys/types.h> /* for off_t */
  87360. /* --------------------------------------------------------------------
  87361. (For an example of how all these routines are used, see the source
  87362. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87363. metaflac in src/metaflac/)
  87364. ------------------------------------------------------------------*/
  87365. /** \file include/FLAC/metadata.h
  87366. *
  87367. * \brief
  87368. * This module provides functions for creating and manipulating FLAC
  87369. * metadata blocks in memory, and three progressively more powerful
  87370. * interfaces for traversing and editing metadata in FLAC files.
  87371. *
  87372. * See the detailed documentation for each interface in the
  87373. * \link flac_metadata metadata \endlink module.
  87374. */
  87375. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87376. * \ingroup flac
  87377. *
  87378. * \brief
  87379. * This module provides functions for creating and manipulating FLAC
  87380. * metadata blocks in memory, and three progressively more powerful
  87381. * interfaces for traversing and editing metadata in native FLAC files.
  87382. * Note that currently only the Chain interface (level 2) supports Ogg
  87383. * FLAC files, and it is read-only i.e. no writing back changed
  87384. * metadata to file.
  87385. *
  87386. * There are three metadata interfaces of increasing complexity:
  87387. *
  87388. * Level 0:
  87389. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87390. * PICTURE blocks.
  87391. *
  87392. * Level 1:
  87393. * Read-write access to all metadata blocks. This level is write-
  87394. * efficient in most cases (more on this below), and uses less memory
  87395. * than level 2.
  87396. *
  87397. * Level 2:
  87398. * Read-write access to all metadata blocks. This level is write-
  87399. * efficient in all cases, but uses more memory since all metadata for
  87400. * the whole file is read into memory and manipulated before writing
  87401. * out again.
  87402. *
  87403. * What do we mean by efficient? Since FLAC metadata appears at the
  87404. * beginning of the file, when writing metadata back to a FLAC file
  87405. * it is possible to grow or shrink the metadata such that the entire
  87406. * file must be rewritten. However, if the size remains the same during
  87407. * changes or PADDING blocks are utilized, only the metadata needs to be
  87408. * overwritten, which is much faster.
  87409. *
  87410. * Efficient means the whole file is rewritten at most one time, and only
  87411. * when necessary. Level 1 is not efficient only in the case that you
  87412. * cause more than one metadata block to grow or shrink beyond what can
  87413. * be accomodated by padding. In this case you should probably use level
  87414. * 2, which allows you to edit all the metadata for a file in memory and
  87415. * write it out all at once.
  87416. *
  87417. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87418. * front of the file.
  87419. *
  87420. * All levels access files via their filenames. In addition, level 2
  87421. * has additional alternative read and write functions that take an I/O
  87422. * handle and callbacks, for situations where access by filename is not
  87423. * possible.
  87424. *
  87425. * In addition to the three interfaces, this module defines functions for
  87426. * creating and manipulating various metadata objects in memory. As we see
  87427. * from the Format module, FLAC metadata blocks in memory are very primitive
  87428. * structures for storing information in an efficient way. Reading
  87429. * information from the structures is easy but creating or modifying them
  87430. * directly is more complex. The metadata object routines here facilitate
  87431. * this by taking care of the consistency and memory management drudgery.
  87432. *
  87433. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87434. * metadata however, you will not probably not need these.
  87435. *
  87436. * From a dependency standpoint, none of the encoders or decoders require
  87437. * the metadata module. This is so that embedded users can strip out the
  87438. * metadata module from libFLAC to reduce the size and complexity.
  87439. */
  87440. #ifdef __cplusplus
  87441. extern "C" {
  87442. #endif
  87443. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87444. * \ingroup flac_metadata
  87445. *
  87446. * \brief
  87447. * The level 0 interface consists of individual routines to read the
  87448. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87449. * only a filename.
  87450. *
  87451. * They try to skip any ID3v2 tag at the head of the file.
  87452. *
  87453. * \{
  87454. */
  87455. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87456. * will try to skip any ID3v2 tag at the head of the file.
  87457. *
  87458. * \param filename The path to the FLAC file to read.
  87459. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87460. * FLAC__StreamMetadata is a simple structure with no
  87461. * memory allocation involved, you pass the address of
  87462. * an existing structure. It need not be initialized.
  87463. * \assert
  87464. * \code filename != NULL \endcode
  87465. * \code streaminfo != NULL \endcode
  87466. * \retval FLAC__bool
  87467. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87468. * \c false if there was a memory allocation error, a file decoder error,
  87469. * or the file contained no STREAMINFO block. (A memory allocation error
  87470. * is possible because this function must set up a file decoder.)
  87471. */
  87472. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87473. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87474. * function will try to skip any ID3v2 tag at the head of the file.
  87475. *
  87476. * \param filename The path to the FLAC file to read.
  87477. * \param tags The address where the returned pointer will be
  87478. * stored. The \a tags object must be deleted by
  87479. * the caller using FLAC__metadata_object_delete().
  87480. * \assert
  87481. * \code filename != NULL \endcode
  87482. * \code tags != NULL \endcode
  87483. * \retval FLAC__bool
  87484. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87485. * and \a *tags will be set to the address of the metadata structure.
  87486. * Returns \c false if there was a memory allocation error, a file
  87487. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87488. * \a *tags will be set to \c NULL.
  87489. */
  87490. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87491. /** Read the CUESHEET metadata block of the given FLAC file. This
  87492. * function will try to skip any ID3v2 tag at the head of the file.
  87493. *
  87494. * \param filename The path to the FLAC file to read.
  87495. * \param cuesheet The address where the returned pointer will be
  87496. * stored. The \a cuesheet object must be deleted by
  87497. * the caller using FLAC__metadata_object_delete().
  87498. * \assert
  87499. * \code filename != NULL \endcode
  87500. * \code cuesheet != NULL \endcode
  87501. * \retval FLAC__bool
  87502. * \c true if a valid CUESHEET block was read from \a filename,
  87503. * and \a *cuesheet will be set to the address of the metadata
  87504. * structure. Returns \c false if there was a memory allocation
  87505. * error, a file decoder error, or the file contained no CUESHEET
  87506. * block, and \a *cuesheet will be set to \c NULL.
  87507. */
  87508. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87509. /** Read a PICTURE metadata block of the given FLAC file. This
  87510. * function will try to skip any ID3v2 tag at the head of the file.
  87511. * Since there can be more than one PICTURE block in a file, this
  87512. * function takes a number of parameters that act as constraints to
  87513. * the search. The PICTURE block with the largest area matching all
  87514. * the constraints will be returned, or \a *picture will be set to
  87515. * \c NULL if there was no such block.
  87516. *
  87517. * \param filename The path to the FLAC file to read.
  87518. * \param picture The address where the returned pointer will be
  87519. * stored. The \a picture object must be deleted by
  87520. * the caller using FLAC__metadata_object_delete().
  87521. * \param type The desired picture type. Use \c -1 to mean
  87522. * "any type".
  87523. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87524. * string will be matched exactly. Use \c NULL to
  87525. * mean "any MIME type".
  87526. * \param description The desired description. The string will be
  87527. * matched exactly. Use \c NULL to mean "any
  87528. * description".
  87529. * \param max_width The maximum width in pixels desired. Use
  87530. * \c (unsigned)(-1) to mean "any width".
  87531. * \param max_height The maximum height in pixels desired. Use
  87532. * \c (unsigned)(-1) to mean "any height".
  87533. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87534. * Use \c (unsigned)(-1) to mean "any depth".
  87535. * \param max_colors The maximum number of colors desired. Use
  87536. * \c (unsigned)(-1) to mean "any number of colors".
  87537. * \assert
  87538. * \code filename != NULL \endcode
  87539. * \code picture != NULL \endcode
  87540. * \retval FLAC__bool
  87541. * \c true if a valid PICTURE block was read from \a filename,
  87542. * and \a *picture will be set to the address of the metadata
  87543. * structure. Returns \c false if there was a memory allocation
  87544. * error, a file decoder error, or the file contained no PICTURE
  87545. * block, and \a *picture will be set to \c NULL.
  87546. */
  87547. 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);
  87548. /* \} */
  87549. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87550. * \ingroup flac_metadata
  87551. *
  87552. * \brief
  87553. * The level 1 interface provides read-write access to FLAC file metadata and
  87554. * operates directly on the FLAC file.
  87555. *
  87556. * The general usage of this interface is:
  87557. *
  87558. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87559. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87560. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87561. * see if the file is writable, or only read access is allowed.
  87562. * - Use FLAC__metadata_simple_iterator_next() and
  87563. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87564. * This is does not read the actual blocks themselves.
  87565. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87566. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87567. * forward from the front of the file.
  87568. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87569. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87570. * the current iterator position. The returned object is yours to modify
  87571. * and free.
  87572. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87573. * back. You must have write permission to the original file. Make sure to
  87574. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87575. * below.
  87576. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87577. * Use the object creation functions from
  87578. * \link flac_metadata_object here \endlink to generate new objects.
  87579. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87580. * currently referred to by the iterator, or replace it with padding.
  87581. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87582. * finished.
  87583. *
  87584. * \note
  87585. * The FLAC file remains open the whole time between
  87586. * FLAC__metadata_simple_iterator_init() and
  87587. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87588. * the file during this time.
  87589. *
  87590. * \note
  87591. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87592. * FLAC__StreamMetadata objects. These are managed automatically.
  87593. *
  87594. * \note
  87595. * If any of the modification functions
  87596. * (FLAC__metadata_simple_iterator_set_block(),
  87597. * FLAC__metadata_simple_iterator_delete_block(),
  87598. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87599. * you should delete the iterator as it may no longer be valid.
  87600. *
  87601. * \{
  87602. */
  87603. struct FLAC__Metadata_SimpleIterator;
  87604. /** The opaque structure definition for the level 1 iterator type.
  87605. * See the
  87606. * \link flac_metadata_level1 metadata level 1 module \endlink
  87607. * for a detailed description.
  87608. */
  87609. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87610. /** Status type for FLAC__Metadata_SimpleIterator.
  87611. *
  87612. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87613. */
  87614. typedef enum {
  87615. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87616. /**< The iterator is in the normal OK state */
  87617. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87618. /**< The data passed into a function violated the function's usage criteria */
  87619. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87620. /**< The iterator could not open the target file */
  87621. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87622. /**< The iterator could not find the FLAC signature at the start of the file */
  87623. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87624. /**< The iterator tried to write to a file that was not writable */
  87625. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87626. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87627. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87628. /**< The iterator encountered an error while reading the FLAC file */
  87629. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87630. /**< The iterator encountered an error while seeking in the FLAC file */
  87631. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87632. /**< The iterator encountered an error while writing the FLAC file */
  87633. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87634. /**< The iterator encountered an error renaming the FLAC file */
  87635. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87636. /**< The iterator encountered an error removing the temporary file */
  87637. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87638. /**< Memory allocation failed */
  87639. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87640. /**< The caller violated an assertion or an unexpected error occurred */
  87641. } FLAC__Metadata_SimpleIteratorStatus;
  87642. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87643. *
  87644. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87645. * will give the string equivalent. The contents should not be modified.
  87646. */
  87647. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87648. /** Create a new iterator instance.
  87649. *
  87650. * \retval FLAC__Metadata_SimpleIterator*
  87651. * \c NULL if there was an error allocating memory, else the new instance.
  87652. */
  87653. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87654. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87655. *
  87656. * \param iterator A pointer to an existing iterator.
  87657. * \assert
  87658. * \code iterator != NULL \endcode
  87659. */
  87660. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87661. /** Get the current status of the iterator. Call this after a function
  87662. * returns \c false to get the reason for the error. Also resets the status
  87663. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87664. *
  87665. * \param iterator A pointer to an existing iterator.
  87666. * \assert
  87667. * \code iterator != NULL \endcode
  87668. * \retval FLAC__Metadata_SimpleIteratorStatus
  87669. * The current status of the iterator.
  87670. */
  87671. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87672. /** Initialize the iterator to point to the first metadata block in the
  87673. * given FLAC file.
  87674. *
  87675. * \param iterator A pointer to an existing iterator.
  87676. * \param filename The path to the FLAC file.
  87677. * \param read_only If \c true, the FLAC file will be opened
  87678. * in read-only mode; if \c false, the FLAC
  87679. * file will be opened for edit even if no
  87680. * edits are performed.
  87681. * \param preserve_file_stats If \c true, the owner and modification
  87682. * time will be preserved even if the FLAC
  87683. * file is written to.
  87684. * \assert
  87685. * \code iterator != NULL \endcode
  87686. * \code filename != NULL \endcode
  87687. * \retval FLAC__bool
  87688. * \c false if a memory allocation error occurs, the file can't be
  87689. * opened, or another error occurs, else \c true.
  87690. */
  87691. 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);
  87692. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87693. * FLAC__metadata_simple_iterator_set_block() and
  87694. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87695. *
  87696. * \param iterator A pointer to an existing iterator.
  87697. * \assert
  87698. * \code iterator != NULL \endcode
  87699. * \retval FLAC__bool
  87700. * See above.
  87701. */
  87702. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87703. /** Moves the iterator forward one metadata block, returning \c false if
  87704. * already at the end.
  87705. *
  87706. * \param iterator A pointer to an existing initialized iterator.
  87707. * \assert
  87708. * \code iterator != NULL \endcode
  87709. * \a iterator has been successfully initialized with
  87710. * FLAC__metadata_simple_iterator_init()
  87711. * \retval FLAC__bool
  87712. * \c false if already at the last metadata block of the chain, else
  87713. * \c true.
  87714. */
  87715. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87716. /** Moves the iterator backward one metadata block, returning \c false if
  87717. * already at the beginning.
  87718. *
  87719. * \param iterator A pointer to an existing initialized iterator.
  87720. * \assert
  87721. * \code iterator != NULL \endcode
  87722. * \a iterator has been successfully initialized with
  87723. * FLAC__metadata_simple_iterator_init()
  87724. * \retval FLAC__bool
  87725. * \c false if already at the first metadata block of the chain, else
  87726. * \c true.
  87727. */
  87728. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87729. /** Returns a flag telling if the current metadata block is the last.
  87730. *
  87731. * \param iterator A pointer to an existing initialized iterator.
  87732. * \assert
  87733. * \code iterator != NULL \endcode
  87734. * \a iterator has been successfully initialized with
  87735. * FLAC__metadata_simple_iterator_init()
  87736. * \retval FLAC__bool
  87737. * \c true if the current metadata block is the last in the file,
  87738. * else \c false.
  87739. */
  87740. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87741. /** Get the offset of the metadata block at the current position. This
  87742. * avoids reading the actual block data which can save time for large
  87743. * blocks.
  87744. *
  87745. * \param iterator A pointer to an existing initialized iterator.
  87746. * \assert
  87747. * \code iterator != NULL \endcode
  87748. * \a iterator has been successfully initialized with
  87749. * FLAC__metadata_simple_iterator_init()
  87750. * \retval off_t
  87751. * The offset of the metadata block at the current iterator position.
  87752. * This is the byte offset relative to the beginning of the file of
  87753. * the current metadata block's header.
  87754. */
  87755. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87756. /** Get the type of the metadata block at the current position. This
  87757. * avoids reading the actual block data which can save time for large
  87758. * blocks.
  87759. *
  87760. * \param iterator A pointer to an existing initialized iterator.
  87761. * \assert
  87762. * \code iterator != NULL \endcode
  87763. * \a iterator has been successfully initialized with
  87764. * FLAC__metadata_simple_iterator_init()
  87765. * \retval FLAC__MetadataType
  87766. * The type of the metadata block at the current iterator position.
  87767. */
  87768. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87769. /** Get the length of the metadata block at the current position. This
  87770. * avoids reading the actual block data which can save time for large
  87771. * blocks.
  87772. *
  87773. * \param iterator A pointer to an existing initialized iterator.
  87774. * \assert
  87775. * \code iterator != NULL \endcode
  87776. * \a iterator has been successfully initialized with
  87777. * FLAC__metadata_simple_iterator_init()
  87778. * \retval unsigned
  87779. * The length of the metadata block at the current iterator position.
  87780. * The is same length as that in the
  87781. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87782. * i.e. the length of the metadata body that follows the header.
  87783. */
  87784. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87785. /** Get the application ID of the \c APPLICATION block at the current
  87786. * position. This avoids reading the actual block data which can save
  87787. * time for large blocks.
  87788. *
  87789. * \param iterator A pointer to an existing initialized iterator.
  87790. * \param id A pointer to a buffer of at least \c 4 bytes where
  87791. * the ID will be stored.
  87792. * \assert
  87793. * \code iterator != NULL \endcode
  87794. * \code id != NULL \endcode
  87795. * \a iterator has been successfully initialized with
  87796. * FLAC__metadata_simple_iterator_init()
  87797. * \retval FLAC__bool
  87798. * \c true if the ID was successfully read, else \c false, in which
  87799. * case you should check FLAC__metadata_simple_iterator_status() to
  87800. * find out why. If the status is
  87801. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87802. * current metadata block is not an \c APPLICATION block. Otherwise
  87803. * if the status is
  87804. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87805. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87806. * occurred and the iterator can no longer be used.
  87807. */
  87808. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87809. /** Get the metadata block at the current position. You can modify the
  87810. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87811. * write it back to the FLAC file.
  87812. *
  87813. * You must call FLAC__metadata_object_delete() on the returned object
  87814. * when you are finished with it.
  87815. *
  87816. * \param iterator A pointer to an existing initialized iterator.
  87817. * \assert
  87818. * \code iterator != NULL \endcode
  87819. * \a iterator has been successfully initialized with
  87820. * FLAC__metadata_simple_iterator_init()
  87821. * \retval FLAC__StreamMetadata*
  87822. * The current metadata block, or \c NULL if there was a memory
  87823. * allocation error.
  87824. */
  87825. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87826. /** Write a block back to the FLAC file. This function tries to be
  87827. * as efficient as possible; how the block is actually written is
  87828. * shown by the following:
  87829. *
  87830. * Existing block is a STREAMINFO block and the new block is a
  87831. * STREAMINFO block: the new block is written in place. Make sure
  87832. * you know what you're doing when changing the values of a
  87833. * STREAMINFO block.
  87834. *
  87835. * Existing block is a STREAMINFO block and the new block is a
  87836. * not a STREAMINFO block: this is an error since the first block
  87837. * must be a STREAMINFO block. Returns \c false without altering the
  87838. * file.
  87839. *
  87840. * Existing block is not a STREAMINFO block and the new block is a
  87841. * STREAMINFO block: this is an error since there may be only one
  87842. * STREAMINFO block. Returns \c false without altering the file.
  87843. *
  87844. * Existing block and new block are the same length: the existing
  87845. * block will be replaced by the new block, written in place.
  87846. *
  87847. * Existing block is longer than new block: if use_padding is \c true,
  87848. * the existing block will be overwritten in place with the new
  87849. * block followed by a PADDING block, if possible, to make the total
  87850. * size the same as the existing block. Remember that a padding
  87851. * block requires at least four bytes so if the difference in size
  87852. * between the new block and existing block is less than that, the
  87853. * entire file will have to be rewritten, using the new block's
  87854. * exact size. If use_padding is \c false, the entire file will be
  87855. * rewritten, replacing the existing block by the new block.
  87856. *
  87857. * Existing block is shorter than new block: if use_padding is \c true,
  87858. * the function will try and expand the new block into the following
  87859. * PADDING block, if it exists and doing so won't shrink the PADDING
  87860. * block to less than 4 bytes. If there is no following PADDING
  87861. * block, or it will shrink to less than 4 bytes, or use_padding is
  87862. * \c false, the entire file is rewritten, replacing the existing block
  87863. * with the new block. Note that in this case any following PADDING
  87864. * block is preserved as is.
  87865. *
  87866. * After writing the block, the iterator will remain in the same
  87867. * place, i.e. pointing to the new block.
  87868. *
  87869. * \param iterator A pointer to an existing initialized iterator.
  87870. * \param block The block to set.
  87871. * \param use_padding See above.
  87872. * \assert
  87873. * \code iterator != NULL \endcode
  87874. * \a iterator has been successfully initialized with
  87875. * FLAC__metadata_simple_iterator_init()
  87876. * \code block != NULL \endcode
  87877. * \retval FLAC__bool
  87878. * \c true if successful, else \c false.
  87879. */
  87880. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87881. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87882. * except that instead of writing over an existing block, it appends
  87883. * a block after the existing block. \a use_padding is again used to
  87884. * tell the function to try an expand into following padding in an
  87885. * attempt to avoid rewriting the entire file.
  87886. *
  87887. * This function will fail and return \c false if given a STREAMINFO
  87888. * block.
  87889. *
  87890. * After writing the block, the iterator will be pointing to the
  87891. * new block.
  87892. *
  87893. * \param iterator A pointer to an existing initialized iterator.
  87894. * \param block The block to set.
  87895. * \param use_padding See above.
  87896. * \assert
  87897. * \code iterator != NULL \endcode
  87898. * \a iterator has been successfully initialized with
  87899. * FLAC__metadata_simple_iterator_init()
  87900. * \code block != NULL \endcode
  87901. * \retval FLAC__bool
  87902. * \c true if successful, else \c false.
  87903. */
  87904. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87905. /** Deletes the block at the current position. This will cause the
  87906. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87907. * in which case the block will be replaced by an equal-sized PADDING
  87908. * block. The iterator will be left pointing to the block before the
  87909. * one just deleted.
  87910. *
  87911. * You may not delete the STREAMINFO block.
  87912. *
  87913. * \param iterator A pointer to an existing initialized iterator.
  87914. * \param use_padding See above.
  87915. * \assert
  87916. * \code iterator != NULL \endcode
  87917. * \a iterator has been successfully initialized with
  87918. * FLAC__metadata_simple_iterator_init()
  87919. * \retval FLAC__bool
  87920. * \c true if successful, else \c false.
  87921. */
  87922. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87923. /* \} */
  87924. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87925. * \ingroup flac_metadata
  87926. *
  87927. * \brief
  87928. * The level 2 interface provides read-write access to FLAC file metadata;
  87929. * all metadata is read into memory, operated on in memory, and then written
  87930. * to file, which is more efficient than level 1 when editing multiple blocks.
  87931. *
  87932. * Currently Ogg FLAC is supported for read only, via
  87933. * FLAC__metadata_chain_read_ogg() but a subsequent
  87934. * FLAC__metadata_chain_write() will fail.
  87935. *
  87936. * The general usage of this interface is:
  87937. *
  87938. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87939. * linked list of FLAC metadata blocks.
  87940. * - Read all metadata into the the chain from a FLAC file using
  87941. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87942. * check the status.
  87943. * - Optionally, consolidate the padding using
  87944. * FLAC__metadata_chain_merge_padding() or
  87945. * FLAC__metadata_chain_sort_padding().
  87946. * - Create a new iterator using FLAC__metadata_iterator_new()
  87947. * - Initialize the iterator to point to the first element in the chain
  87948. * using FLAC__metadata_iterator_init()
  87949. * - Traverse the chain using FLAC__metadata_iterator_next and
  87950. * FLAC__metadata_iterator_prev().
  87951. * - Get a block for reading or modification using
  87952. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87953. * inside the chain is returned, so the block is yours to modify.
  87954. * Changes will be reflected in the FLAC file when you write the
  87955. * chain. You can also add and delete blocks (see functions below).
  87956. * - When done, write out the chain using FLAC__metadata_chain_write().
  87957. * Make sure to read the whole comment to the function below.
  87958. * - Delete the chain using FLAC__metadata_chain_delete().
  87959. *
  87960. * \note
  87961. * Even though the FLAC file is not open while the chain is being
  87962. * manipulated, you must not alter the file externally during
  87963. * this time. The chain assumes the FLAC file will not change
  87964. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87965. * and FLAC__metadata_chain_write().
  87966. *
  87967. * \note
  87968. * Do not modify the is_last, length, or type fields of returned
  87969. * FLAC__StreamMetadata objects. These are managed automatically.
  87970. *
  87971. * \note
  87972. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87973. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87974. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87975. * become owned by the chain and they will be deleted when the chain is
  87976. * deleted.
  87977. *
  87978. * \{
  87979. */
  87980. struct FLAC__Metadata_Chain;
  87981. /** The opaque structure definition for the level 2 chain type.
  87982. */
  87983. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87984. struct FLAC__Metadata_Iterator;
  87985. /** The opaque structure definition for the level 2 iterator type.
  87986. */
  87987. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87988. typedef enum {
  87989. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87990. /**< The chain is in the normal OK state */
  87991. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87992. /**< The data passed into a function violated the function's usage criteria */
  87993. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87994. /**< The chain could not open the target file */
  87995. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87996. /**< The chain could not find the FLAC signature at the start of the file */
  87997. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87998. /**< The chain tried to write to a file that was not writable */
  87999. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88000. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88001. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88002. /**< The chain encountered an error while reading the FLAC file */
  88003. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88004. /**< The chain encountered an error while seeking in the FLAC file */
  88005. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88006. /**< The chain encountered an error while writing the FLAC file */
  88007. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88008. /**< The chain encountered an error renaming the FLAC file */
  88009. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88010. /**< The chain encountered an error removing the temporary file */
  88011. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88012. /**< Memory allocation failed */
  88013. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88014. /**< The caller violated an assertion or an unexpected error occurred */
  88015. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88016. /**< One or more of the required callbacks was NULL */
  88017. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88018. /**< FLAC__metadata_chain_write() was called on a chain read by
  88019. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88020. * or
  88021. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88022. * was called on a chain read by
  88023. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88024. * Matching read/write methods must always be used. */
  88025. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88026. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88027. * chain write requires a tempfile; use
  88028. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88029. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88030. * called when the chain write does not require a tempfile; use
  88031. * FLAC__metadata_chain_write_with_callbacks() instead.
  88032. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88033. * before writing via callbacks. */
  88034. } FLAC__Metadata_ChainStatus;
  88035. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88036. *
  88037. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88038. * will give the string equivalent. The contents should not be modified.
  88039. */
  88040. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88041. /*********** FLAC__Metadata_Chain ***********/
  88042. /** Create a new chain instance.
  88043. *
  88044. * \retval FLAC__Metadata_Chain*
  88045. * \c NULL if there was an error allocating memory, else the new instance.
  88046. */
  88047. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88048. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88049. *
  88050. * \param chain A pointer to an existing chain.
  88051. * \assert
  88052. * \code chain != NULL \endcode
  88053. */
  88054. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88055. /** Get the current status of the chain. Call this after a function
  88056. * returns \c false to get the reason for the error. Also resets the
  88057. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88058. *
  88059. * \param chain A pointer to an existing chain.
  88060. * \assert
  88061. * \code chain != NULL \endcode
  88062. * \retval FLAC__Metadata_ChainStatus
  88063. * The current status of the chain.
  88064. */
  88065. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88066. /** Read all metadata from a FLAC file into the chain.
  88067. *
  88068. * \param chain A pointer to an existing chain.
  88069. * \param filename The path to the FLAC file to read.
  88070. * \assert
  88071. * \code chain != NULL \endcode
  88072. * \code filename != NULL \endcode
  88073. * \retval FLAC__bool
  88074. * \c true if a valid list of metadata blocks was read from
  88075. * \a filename, else \c false. On failure, check the status with
  88076. * FLAC__metadata_chain_status().
  88077. */
  88078. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88079. /** Read all metadata from an Ogg FLAC file into the chain.
  88080. *
  88081. * \note Ogg FLAC metadata data writing is not supported yet and
  88082. * FLAC__metadata_chain_write() will fail.
  88083. *
  88084. * \param chain A pointer to an existing chain.
  88085. * \param filename The path to the Ogg FLAC file to read.
  88086. * \assert
  88087. * \code chain != NULL \endcode
  88088. * \code filename != NULL \endcode
  88089. * \retval FLAC__bool
  88090. * \c true if a valid list of metadata blocks was read from
  88091. * \a filename, else \c false. On failure, check the status with
  88092. * FLAC__metadata_chain_status().
  88093. */
  88094. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88095. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88096. *
  88097. * The \a handle need only be open for reading, but must be seekable.
  88098. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88099. * for Windows).
  88100. *
  88101. * \param chain A pointer to an existing chain.
  88102. * \param handle The I/O handle of the FLAC stream to read. The
  88103. * handle will NOT be closed after the metadata is read;
  88104. * that is the duty of the caller.
  88105. * \param callbacks
  88106. * A set of callbacks to use for I/O. The mandatory
  88107. * callbacks are \a read, \a seek, and \a tell.
  88108. * \assert
  88109. * \code chain != NULL \endcode
  88110. * \retval FLAC__bool
  88111. * \c true if a valid list of metadata blocks was read from
  88112. * \a handle, else \c false. On failure, check the status with
  88113. * FLAC__metadata_chain_status().
  88114. */
  88115. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88116. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88117. *
  88118. * The \a handle need only be open for reading, but must be seekable.
  88119. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88120. * for Windows).
  88121. *
  88122. * \note Ogg FLAC metadata data writing is not supported yet and
  88123. * FLAC__metadata_chain_write() will fail.
  88124. *
  88125. * \param chain A pointer to an existing chain.
  88126. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88127. * handle will NOT be closed after the metadata is read;
  88128. * that is the duty of the caller.
  88129. * \param callbacks
  88130. * A set of callbacks to use for I/O. The mandatory
  88131. * callbacks are \a read, \a seek, and \a tell.
  88132. * \assert
  88133. * \code chain != NULL \endcode
  88134. * \retval FLAC__bool
  88135. * \c true if a valid list of metadata blocks was read from
  88136. * \a handle, else \c false. On failure, check the status with
  88137. * FLAC__metadata_chain_status().
  88138. */
  88139. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88140. /** Checks if writing the given chain would require the use of a
  88141. * temporary file, or if it could be written in place.
  88142. *
  88143. * Under certain conditions, padding can be utilized so that writing
  88144. * edited metadata back to the FLAC file does not require rewriting the
  88145. * entire file. If rewriting is required, then a temporary workfile is
  88146. * required. When writing metadata using callbacks, you must check
  88147. * this function to know whether to call
  88148. * FLAC__metadata_chain_write_with_callbacks() or
  88149. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88150. * writing with FLAC__metadata_chain_write(), the temporary file is
  88151. * handled internally.
  88152. *
  88153. * \param chain A pointer to an existing chain.
  88154. * \param use_padding
  88155. * Whether or not padding will be allowed to be used
  88156. * during the write. The value of \a use_padding given
  88157. * here must match the value later passed to
  88158. * FLAC__metadata_chain_write_with_callbacks() or
  88159. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88160. * \assert
  88161. * \code chain != NULL \endcode
  88162. * \retval FLAC__bool
  88163. * \c true if writing the current chain would require a tempfile, or
  88164. * \c false if metadata can be written in place.
  88165. */
  88166. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88167. /** Write all metadata out to the FLAC file. This function tries to be as
  88168. * efficient as possible; how the metadata is actually written is shown by
  88169. * the following:
  88170. *
  88171. * If the current chain is the same size as the existing metadata, the new
  88172. * data is written in place.
  88173. *
  88174. * If the current chain is longer than the existing metadata, and
  88175. * \a use_padding is \c true, and the last block is a PADDING block of
  88176. * sufficient length, the function will truncate the final padding block
  88177. * so that the overall size of the metadata is the same as the existing
  88178. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88179. * the above conditions are met, the entire FLAC file must be rewritten.
  88180. * If you want to use padding this way it is a good idea to call
  88181. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88182. * amount of padding to work with, unless you need to preserve ordering
  88183. * of the PADDING blocks for some reason.
  88184. *
  88185. * If the current chain is shorter than the existing metadata, and
  88186. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88187. * is extended to make the overall size the same as the existing data. If
  88188. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88189. * PADDING block is added to the end of the new data to make it the same
  88190. * size as the existing data (if possible, see the note to
  88191. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88192. * and the new data is written in place. If none of the above apply or
  88193. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88194. *
  88195. * If \a preserve_file_stats is \c true, the owner and modification time will
  88196. * be preserved even if the FLAC file is written.
  88197. *
  88198. * For this write function to be used, the chain must have been read with
  88199. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88200. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88201. *
  88202. * \param chain A pointer to an existing chain.
  88203. * \param use_padding See above.
  88204. * \param preserve_file_stats See above.
  88205. * \assert
  88206. * \code chain != NULL \endcode
  88207. * \retval FLAC__bool
  88208. * \c true if the write succeeded, else \c false. On failure,
  88209. * check the status with FLAC__metadata_chain_status().
  88210. */
  88211. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88212. /** Write all metadata out to a FLAC stream via callbacks.
  88213. *
  88214. * (See FLAC__metadata_chain_write() for the details on how padding is
  88215. * used to write metadata in place if possible.)
  88216. *
  88217. * The \a handle must be open for updating and be seekable. The
  88218. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88219. * for Windows).
  88220. *
  88221. * For this write function to be used, the chain must have been read with
  88222. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88223. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88224. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88225. * \c false.
  88226. *
  88227. * \param chain A pointer to an existing chain.
  88228. * \param use_padding See FLAC__metadata_chain_write()
  88229. * \param handle The I/O handle of the FLAC stream to write. The
  88230. * handle will NOT be closed after the metadata is
  88231. * written; that is the duty of the caller.
  88232. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88233. * callbacks are \a write and \a seek.
  88234. * \assert
  88235. * \code chain != NULL \endcode
  88236. * \retval FLAC__bool
  88237. * \c true if the write succeeded, else \c false. On failure,
  88238. * check the status with FLAC__metadata_chain_status().
  88239. */
  88240. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88241. /** Write all metadata out to a FLAC stream via callbacks.
  88242. *
  88243. * (See FLAC__metadata_chain_write() for the details on how padding is
  88244. * used to write metadata in place if possible.)
  88245. *
  88246. * This version of the write-with-callbacks function must be used when
  88247. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88248. * this function, you must supply an I/O handle corresponding to the
  88249. * FLAC file to edit, and a temporary handle to which the new FLAC
  88250. * file will be written. It is the caller's job to move this temporary
  88251. * FLAC file on top of the original FLAC file to complete the metadata
  88252. * edit.
  88253. *
  88254. * The \a handle must be open for reading and be seekable. The
  88255. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88256. * for Windows).
  88257. *
  88258. * The \a temp_handle must be open for writing. The
  88259. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88260. * for Windows). It should be an empty stream, or at least positioned
  88261. * at the start-of-file (in which case it is the caller's duty to
  88262. * truncate it on return).
  88263. *
  88264. * For this write function to be used, the chain must have been read with
  88265. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88266. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88267. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88268. * \c true.
  88269. *
  88270. * \param chain A pointer to an existing chain.
  88271. * \param use_padding See FLAC__metadata_chain_write()
  88272. * \param handle The I/O handle of the original FLAC stream to read.
  88273. * The handle will NOT be closed after the metadata is
  88274. * written; that is the duty of the caller.
  88275. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88276. * The mandatory callbacks are \a read, \a seek, and
  88277. * \a eof.
  88278. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88279. * handle will NOT be closed after the metadata is
  88280. * written; that is the duty of the caller.
  88281. * \param temp_callbacks
  88282. * A set of callbacks to use for I/O on temp_handle.
  88283. * The only mandatory callback is \a write.
  88284. * \assert
  88285. * \code chain != NULL \endcode
  88286. * \retval FLAC__bool
  88287. * \c true if the write succeeded, else \c false. On failure,
  88288. * check the status with FLAC__metadata_chain_status().
  88289. */
  88290. 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);
  88291. /** Merge adjacent PADDING blocks into a single block.
  88292. *
  88293. * \note This function does not write to the FLAC file, it only
  88294. * modifies the chain.
  88295. *
  88296. * \warning Any iterator on the current chain will become invalid after this
  88297. * call. You should delete the iterator and get a new one.
  88298. *
  88299. * \param chain A pointer to an existing chain.
  88300. * \assert
  88301. * \code chain != NULL \endcode
  88302. */
  88303. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88304. /** This function will move all PADDING blocks to the end on the metadata,
  88305. * then merge them into a single block.
  88306. *
  88307. * \note This function does not write to the FLAC file, it only
  88308. * modifies the chain.
  88309. *
  88310. * \warning Any iterator on the current chain will become invalid after this
  88311. * call. You should delete the iterator and get a new one.
  88312. *
  88313. * \param chain A pointer to an existing chain.
  88314. * \assert
  88315. * \code chain != NULL \endcode
  88316. */
  88317. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88318. /*********** FLAC__Metadata_Iterator ***********/
  88319. /** Create a new iterator instance.
  88320. *
  88321. * \retval FLAC__Metadata_Iterator*
  88322. * \c NULL if there was an error allocating memory, else the new instance.
  88323. */
  88324. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88325. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88326. *
  88327. * \param iterator A pointer to an existing iterator.
  88328. * \assert
  88329. * \code iterator != NULL \endcode
  88330. */
  88331. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88332. /** Initialize the iterator to point to the first metadata block in the
  88333. * given chain.
  88334. *
  88335. * \param iterator A pointer to an existing iterator.
  88336. * \param chain A pointer to an existing and initialized (read) chain.
  88337. * \assert
  88338. * \code iterator != NULL \endcode
  88339. * \code chain != NULL \endcode
  88340. */
  88341. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88342. /** Moves the iterator forward one metadata block, returning \c false if
  88343. * already at the end.
  88344. *
  88345. * \param iterator A pointer to an existing initialized iterator.
  88346. * \assert
  88347. * \code iterator != NULL \endcode
  88348. * \a iterator has been successfully initialized with
  88349. * FLAC__metadata_iterator_init()
  88350. * \retval FLAC__bool
  88351. * \c false if already at the last metadata block of the chain, else
  88352. * \c true.
  88353. */
  88354. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88355. /** Moves the iterator backward one metadata block, returning \c false if
  88356. * already at the beginning.
  88357. *
  88358. * \param iterator A pointer to an existing initialized iterator.
  88359. * \assert
  88360. * \code iterator != NULL \endcode
  88361. * \a iterator has been successfully initialized with
  88362. * FLAC__metadata_iterator_init()
  88363. * \retval FLAC__bool
  88364. * \c false if already at the first metadata block of the chain, else
  88365. * \c true.
  88366. */
  88367. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88368. /** Get the type of the metadata block at the current position.
  88369. *
  88370. * \param iterator A pointer to an existing initialized iterator.
  88371. * \assert
  88372. * \code iterator != NULL \endcode
  88373. * \a iterator has been successfully initialized with
  88374. * FLAC__metadata_iterator_init()
  88375. * \retval FLAC__MetadataType
  88376. * The type of the metadata block at the current iterator position.
  88377. */
  88378. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88379. /** Get the metadata block at the current position. You can modify
  88380. * the block in place but must write the chain before the changes
  88381. * are reflected to the FLAC file. You do not need to call
  88382. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88383. * the pointer returned by FLAC__metadata_iterator_get_block()
  88384. * points directly into the chain.
  88385. *
  88386. * \warning
  88387. * Do not call FLAC__metadata_object_delete() on the returned object;
  88388. * to delete a block use FLAC__metadata_iterator_delete_block().
  88389. *
  88390. * \param iterator A pointer to an existing initialized iterator.
  88391. * \assert
  88392. * \code iterator != NULL \endcode
  88393. * \a iterator has been successfully initialized with
  88394. * FLAC__metadata_iterator_init()
  88395. * \retval FLAC__StreamMetadata*
  88396. * The current metadata block.
  88397. */
  88398. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88399. /** Set the metadata block at the current position, replacing the existing
  88400. * block. The new block passed in becomes owned by the chain and it will be
  88401. * deleted when the chain is deleted.
  88402. *
  88403. * \param iterator A pointer to an existing initialized iterator.
  88404. * \param block A pointer to a metadata block.
  88405. * \assert
  88406. * \code iterator != NULL \endcode
  88407. * \a iterator has been successfully initialized with
  88408. * FLAC__metadata_iterator_init()
  88409. * \code block != NULL \endcode
  88410. * \retval FLAC__bool
  88411. * \c false if the conditions in the above description are not met, or
  88412. * a memory allocation error occurs, otherwise \c true.
  88413. */
  88414. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88415. /** Removes the current block from the chain. If \a replace_with_padding is
  88416. * \c true, the block will instead be replaced with a padding block of equal
  88417. * size. You can not delete the STREAMINFO block. The iterator will be
  88418. * left pointing to the block before the one just "deleted", even if
  88419. * \a replace_with_padding is \c true.
  88420. *
  88421. * \param iterator A pointer to an existing initialized iterator.
  88422. * \param replace_with_padding See above.
  88423. * \assert
  88424. * \code iterator != NULL \endcode
  88425. * \a iterator has been successfully initialized with
  88426. * FLAC__metadata_iterator_init()
  88427. * \retval FLAC__bool
  88428. * \c false if the conditions in the above description are not met,
  88429. * otherwise \c true.
  88430. */
  88431. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88432. /** Insert a new block before the current block. You cannot insert a block
  88433. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88434. * as there can be only one, the one that already exists at the head when you
  88435. * read in a chain. The chain takes ownership of the new block and it will be
  88436. * deleted when the chain is deleted. The iterator will be left pointing to
  88437. * the new block.
  88438. *
  88439. * \param iterator A pointer to an existing initialized iterator.
  88440. * \param block A pointer to a metadata block to insert.
  88441. * \assert
  88442. * \code iterator != NULL \endcode
  88443. * \a iterator has been successfully initialized with
  88444. * FLAC__metadata_iterator_init()
  88445. * \retval FLAC__bool
  88446. * \c false if the conditions in the above description are not met, or
  88447. * a memory allocation error occurs, otherwise \c true.
  88448. */
  88449. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88450. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88451. * block as there can be only one, the one that already exists at the head when
  88452. * you read in a chain. The chain takes ownership of the new block and it will
  88453. * be deleted when the chain is deleted. The iterator will be left pointing to
  88454. * the new block.
  88455. *
  88456. * \param iterator A pointer to an existing initialized iterator.
  88457. * \param block A pointer to a metadata block to insert.
  88458. * \assert
  88459. * \code iterator != NULL \endcode
  88460. * \a iterator has been successfully initialized with
  88461. * FLAC__metadata_iterator_init()
  88462. * \retval FLAC__bool
  88463. * \c false if the conditions in the above description are not met, or
  88464. * a memory allocation error occurs, otherwise \c true.
  88465. */
  88466. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88467. /* \} */
  88468. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88469. * \ingroup flac_metadata
  88470. *
  88471. * \brief
  88472. * This module contains methods for manipulating FLAC metadata objects.
  88473. *
  88474. * Since many are variable length we have to be careful about the memory
  88475. * management. We decree that all pointers to data in the object are
  88476. * owned by the object and memory-managed by the object.
  88477. *
  88478. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88479. * functions to create all instances. When using the
  88480. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88481. * \a copy to \c true to have the function make it's own copy of the data, or
  88482. * to \c false to give the object ownership of your data. In the latter case
  88483. * your pointer must be freeable by free() and will be free()d when the object
  88484. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88485. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88486. * the length argument is 0 and the \a copy argument is \c false.
  88487. *
  88488. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88489. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88490. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88491. * case of a memory allocation error.
  88492. *
  88493. * We don't have the convenience of C++ here, so note that the library relies
  88494. * on you to keep the types straight. In other words, if you pass, for
  88495. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88496. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88497. * failure.
  88498. *
  88499. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88500. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88501. * toward the length or stored in the stream, but it can make working with plain
  88502. * comments (those that don't contain embedded-NULs in the value) easier.
  88503. * Entries passed into these functions have trailing NULs added if missing, and
  88504. * returned entries are guaranteed to have a trailing NUL.
  88505. *
  88506. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88507. * comment entry/name/value will first validate that it complies with the Vorbis
  88508. * comment specification and return false if it does not.
  88509. *
  88510. * There is no need to recalculate the length field on metadata blocks you
  88511. * have modified. They will be calculated automatically before they are
  88512. * written back to a file.
  88513. *
  88514. * \{
  88515. */
  88516. /** Create a new metadata object instance of the given type.
  88517. *
  88518. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88519. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88520. * the vendor string set (but zero comments).
  88521. *
  88522. * Do not pass in a value greater than or equal to
  88523. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88524. * doing.
  88525. *
  88526. * \param type Type of object to create
  88527. * \retval FLAC__StreamMetadata*
  88528. * \c NULL if there was an error allocating memory or the type code is
  88529. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88530. */
  88531. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88532. /** Create a copy of an existing metadata object.
  88533. *
  88534. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88535. * object is also copied. The caller takes ownership of the new block and
  88536. * is responsible for freeing it with FLAC__metadata_object_delete().
  88537. *
  88538. * \param object Pointer to object to copy.
  88539. * \assert
  88540. * \code object != NULL \endcode
  88541. * \retval FLAC__StreamMetadata*
  88542. * \c NULL if there was an error allocating memory, else the new instance.
  88543. */
  88544. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88545. /** Free a metadata object. Deletes the object pointed to by \a object.
  88546. *
  88547. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88548. * object is also deleted.
  88549. *
  88550. * \param object A pointer to an existing object.
  88551. * \assert
  88552. * \code object != NULL \endcode
  88553. */
  88554. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88555. /** Compares two metadata objects.
  88556. *
  88557. * The compare is "deep", i.e. dynamically allocated data within the
  88558. * object is also compared.
  88559. *
  88560. * \param block1 A pointer to an existing object.
  88561. * \param block2 A pointer to an existing object.
  88562. * \assert
  88563. * \code block1 != NULL \endcode
  88564. * \code block2 != NULL \endcode
  88565. * \retval FLAC__bool
  88566. * \c true if objects are identical, else \c false.
  88567. */
  88568. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88569. /** Sets the application data of an APPLICATION block.
  88570. *
  88571. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88572. * takes ownership of the pointer. The existing data will be freed if this
  88573. * function is successful, otherwise the original data will remain if \a copy
  88574. * is \c true and malloc() fails.
  88575. *
  88576. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88577. *
  88578. * \param object A pointer to an existing APPLICATION object.
  88579. * \param data A pointer to the data to set.
  88580. * \param length The length of \a data in bytes.
  88581. * \param copy See above.
  88582. * \assert
  88583. * \code object != NULL \endcode
  88584. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88585. * \code (data != NULL && length > 0) ||
  88586. * (data == NULL && length == 0 && copy == false) \endcode
  88587. * \retval FLAC__bool
  88588. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88589. */
  88590. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88591. /** Resize the seekpoint array.
  88592. *
  88593. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88594. * points will be added to the end.
  88595. *
  88596. * \param object A pointer to an existing SEEKTABLE object.
  88597. * \param new_num_points The desired length of the array; may be \c 0.
  88598. * \assert
  88599. * \code object != NULL \endcode
  88600. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88601. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88602. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88603. * \retval FLAC__bool
  88604. * \c false if memory allocation error, else \c true.
  88605. */
  88606. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88607. /** Set a seekpoint in a seektable.
  88608. *
  88609. * \param object A pointer to an existing SEEKTABLE object.
  88610. * \param point_num Index into seekpoint array to set.
  88611. * \param point The point to set.
  88612. * \assert
  88613. * \code object != NULL \endcode
  88614. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88615. * \code object->data.seek_table.num_points > point_num \endcode
  88616. */
  88617. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88618. /** Insert a seekpoint into a seektable.
  88619. *
  88620. * \param object A pointer to an existing SEEKTABLE object.
  88621. * \param point_num Index into seekpoint array to set.
  88622. * \param point The point to set.
  88623. * \assert
  88624. * \code object != NULL \endcode
  88625. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88626. * \code object->data.seek_table.num_points >= point_num \endcode
  88627. * \retval FLAC__bool
  88628. * \c false if memory allocation error, else \c true.
  88629. */
  88630. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88631. /** Delete a seekpoint from a seektable.
  88632. *
  88633. * \param object A pointer to an existing SEEKTABLE object.
  88634. * \param point_num Index into seekpoint array to set.
  88635. * \assert
  88636. * \code object != NULL \endcode
  88637. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88638. * \code object->data.seek_table.num_points > point_num \endcode
  88639. * \retval FLAC__bool
  88640. * \c false if memory allocation error, else \c true.
  88641. */
  88642. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88643. /** Check a seektable to see if it conforms to the FLAC specification.
  88644. * See the format specification for limits on the contents of the
  88645. * seektable.
  88646. *
  88647. * \param object A pointer to an existing SEEKTABLE object.
  88648. * \assert
  88649. * \code object != NULL \endcode
  88650. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88651. * \retval FLAC__bool
  88652. * \c false if seek table is illegal, else \c true.
  88653. */
  88654. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88655. /** Append a number of placeholder points to the end of a seek table.
  88656. *
  88657. * \note
  88658. * As with the other ..._seektable_template_... functions, you should
  88659. * call FLAC__metadata_object_seektable_template_sort() when finished
  88660. * to make the seek table legal.
  88661. *
  88662. * \param object A pointer to an existing SEEKTABLE object.
  88663. * \param num The number of placeholder points to append.
  88664. * \assert
  88665. * \code object != NULL \endcode
  88666. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88667. * \retval FLAC__bool
  88668. * \c false if memory allocation fails, else \c true.
  88669. */
  88670. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88671. /** Append a specific seek point template to the end of a seek table.
  88672. *
  88673. * \note
  88674. * As with the other ..._seektable_template_... functions, you should
  88675. * call FLAC__metadata_object_seektable_template_sort() when finished
  88676. * to make the seek table legal.
  88677. *
  88678. * \param object A pointer to an existing SEEKTABLE object.
  88679. * \param sample_number The sample number of the seek point template.
  88680. * \assert
  88681. * \code object != NULL \endcode
  88682. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88683. * \retval FLAC__bool
  88684. * \c false if memory allocation fails, else \c true.
  88685. */
  88686. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88687. /** Append specific seek point templates to the end of a seek table.
  88688. *
  88689. * \note
  88690. * As with the other ..._seektable_template_... functions, you should
  88691. * call FLAC__metadata_object_seektable_template_sort() when finished
  88692. * to make the seek table legal.
  88693. *
  88694. * \param object A pointer to an existing SEEKTABLE object.
  88695. * \param sample_numbers An array of sample numbers for the seek points.
  88696. * \param num The number of seek point templates to append.
  88697. * \assert
  88698. * \code object != NULL \endcode
  88699. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88700. * \retval FLAC__bool
  88701. * \c false if memory allocation fails, else \c true.
  88702. */
  88703. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88704. /** Append a set of evenly-spaced seek point templates to the end of a
  88705. * seek table.
  88706. *
  88707. * \note
  88708. * As with the other ..._seektable_template_... functions, you should
  88709. * call FLAC__metadata_object_seektable_template_sort() when finished
  88710. * to make the seek table legal.
  88711. *
  88712. * \param object A pointer to an existing SEEKTABLE object.
  88713. * \param num The number of placeholder points to append.
  88714. * \param total_samples The total number of samples to be encoded;
  88715. * the seekpoints will be spaced approximately
  88716. * \a total_samples / \a num samples apart.
  88717. * \assert
  88718. * \code object != NULL \endcode
  88719. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88720. * \code total_samples > 0 \endcode
  88721. * \retval FLAC__bool
  88722. * \c false if memory allocation fails, else \c true.
  88723. */
  88724. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88725. /** Append a set of evenly-spaced seek point templates to the end of a
  88726. * seek table.
  88727. *
  88728. * \note
  88729. * As with the other ..._seektable_template_... functions, you should
  88730. * call FLAC__metadata_object_seektable_template_sort() when finished
  88731. * to make the seek table legal.
  88732. *
  88733. * \param object A pointer to an existing SEEKTABLE object.
  88734. * \param samples The number of samples apart to space the placeholder
  88735. * points. The first point will be at sample \c 0, the
  88736. * second at sample \a samples, then 2*\a samples, and
  88737. * so on. As long as \a samples and \a total_samples
  88738. * are greater than \c 0, there will always be at least
  88739. * one seekpoint at sample \c 0.
  88740. * \param total_samples The total number of samples to be encoded;
  88741. * the seekpoints will be spaced
  88742. * \a samples samples apart.
  88743. * \assert
  88744. * \code object != NULL \endcode
  88745. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88746. * \code samples > 0 \endcode
  88747. * \code total_samples > 0 \endcode
  88748. * \retval FLAC__bool
  88749. * \c false if memory allocation fails, else \c true.
  88750. */
  88751. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88752. /** Sort a seek table's seek points according to the format specification,
  88753. * removing duplicates.
  88754. *
  88755. * \param object A pointer to a seek table to be sorted.
  88756. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88757. * If \c true, duplicates are deleted and the seek table is
  88758. * shrunk appropriately; the number of placeholder points
  88759. * present in the seek table will be the same after the call
  88760. * as before.
  88761. * \assert
  88762. * \code object != NULL \endcode
  88763. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88764. * \retval FLAC__bool
  88765. * \c false if realloc() fails, else \c true.
  88766. */
  88767. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88768. /** Sets the vendor string in a VORBIS_COMMENT block.
  88769. *
  88770. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88771. * one already.
  88772. *
  88773. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88774. * takes ownership of the \c entry.entry pointer.
  88775. *
  88776. * \note If this function returns \c false, the caller still owns the
  88777. * pointer.
  88778. *
  88779. * \param object A pointer to an existing VORBIS_COMMENT object.
  88780. * \param entry The entry to set the vendor string to.
  88781. * \param copy See above.
  88782. * \assert
  88783. * \code object != NULL \endcode
  88784. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88785. * \code (entry.entry != NULL && entry.length > 0) ||
  88786. * (entry.entry == NULL && entry.length == 0) \endcode
  88787. * \retval FLAC__bool
  88788. * \c false if memory allocation fails or \a entry does not comply with the
  88789. * Vorbis comment specification, else \c true.
  88790. */
  88791. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88792. /** Resize the comment array.
  88793. *
  88794. * If the size shrinks, elements will truncated; if it grows, new empty
  88795. * fields will be added to the end.
  88796. *
  88797. * \param object A pointer to an existing VORBIS_COMMENT object.
  88798. * \param new_num_comments The desired length of the array; may be \c 0.
  88799. * \assert
  88800. * \code object != NULL \endcode
  88801. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88802. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88803. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88804. * \retval FLAC__bool
  88805. * \c false if memory allocation fails, else \c true.
  88806. */
  88807. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88808. /** Sets a comment in a VORBIS_COMMENT block.
  88809. *
  88810. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88811. * one already.
  88812. *
  88813. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88814. * takes ownership of the \c entry.entry pointer.
  88815. *
  88816. * \note If this function returns \c false, the caller still owns the
  88817. * pointer.
  88818. *
  88819. * \param object A pointer to an existing VORBIS_COMMENT object.
  88820. * \param comment_num Index into comment array to set.
  88821. * \param entry The entry to set the comment to.
  88822. * \param copy See above.
  88823. * \assert
  88824. * \code object != NULL \endcode
  88825. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88826. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88827. * \code (entry.entry != NULL && entry.length > 0) ||
  88828. * (entry.entry == NULL && entry.length == 0) \endcode
  88829. * \retval FLAC__bool
  88830. * \c false if memory allocation fails or \a entry does not comply with the
  88831. * Vorbis comment specification, else \c true.
  88832. */
  88833. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88834. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88835. *
  88836. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88837. * one already.
  88838. *
  88839. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88840. * takes ownership of the \c entry.entry pointer.
  88841. *
  88842. * \note If this function returns \c false, the caller still owns the
  88843. * pointer.
  88844. *
  88845. * \param object A pointer to an existing VORBIS_COMMENT object.
  88846. * \param comment_num The index at which to insert the comment. The comments
  88847. * at and after \a comment_num move right one position.
  88848. * To append a comment to the end, set \a comment_num to
  88849. * \c object->data.vorbis_comment.num_comments .
  88850. * \param entry The comment to insert.
  88851. * \param copy See above.
  88852. * \assert
  88853. * \code object != NULL \endcode
  88854. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88855. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88856. * \code (entry.entry != NULL && entry.length > 0) ||
  88857. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88858. * \retval FLAC__bool
  88859. * \c false if memory allocation fails or \a entry does not comply with the
  88860. * Vorbis comment specification, else \c true.
  88861. */
  88862. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88863. /** Appends a comment to a VORBIS_COMMENT block.
  88864. *
  88865. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88866. * one already.
  88867. *
  88868. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88869. * takes ownership of the \c entry.entry pointer.
  88870. *
  88871. * \note If this function returns \c false, the caller still owns the
  88872. * pointer.
  88873. *
  88874. * \param object A pointer to an existing VORBIS_COMMENT object.
  88875. * \param entry The comment to insert.
  88876. * \param copy See above.
  88877. * \assert
  88878. * \code object != NULL \endcode
  88879. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88880. * \code (entry.entry != NULL && entry.length > 0) ||
  88881. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88882. * \retval FLAC__bool
  88883. * \c false if memory allocation fails or \a entry does not comply with the
  88884. * Vorbis comment specification, else \c true.
  88885. */
  88886. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88887. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88888. *
  88889. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88890. * one already.
  88891. *
  88892. * Depending on the the value of \a all, either all or just the first comment
  88893. * whose field name(s) match the given entry's name will be replaced by the
  88894. * given entry. If no comments match, \a entry will simply be appended.
  88895. *
  88896. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88897. * takes ownership of the \c entry.entry pointer.
  88898. *
  88899. * \note If this function returns \c false, the caller still owns the
  88900. * pointer.
  88901. *
  88902. * \param object A pointer to an existing VORBIS_COMMENT object.
  88903. * \param entry The comment to insert.
  88904. * \param all If \c true, all comments whose field name matches
  88905. * \a entry's field name will be removed, and \a entry will
  88906. * be inserted at the position of the first matching
  88907. * comment. If \c false, only the first comment whose
  88908. * field name matches \a entry's field name will be
  88909. * replaced with \a entry.
  88910. * \param copy See above.
  88911. * \assert
  88912. * \code object != NULL \endcode
  88913. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88914. * \code (entry.entry != NULL && entry.length > 0) ||
  88915. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88916. * \retval FLAC__bool
  88917. * \c false if memory allocation fails or \a entry does not comply with the
  88918. * Vorbis comment specification, else \c true.
  88919. */
  88920. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88921. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88922. *
  88923. * \param object A pointer to an existing VORBIS_COMMENT object.
  88924. * \param comment_num The index of the comment to delete.
  88925. * \assert
  88926. * \code object != NULL \endcode
  88927. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88928. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88929. * \retval FLAC__bool
  88930. * \c false if realloc() fails, else \c true.
  88931. */
  88932. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88933. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88934. *
  88935. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88936. * memory and shall be owned by the caller. For convenience the entry will
  88937. * have a terminating NUL.
  88938. *
  88939. * \param entry A pointer to a Vorbis comment entry. The entry's
  88940. * \c entry pointer should not point to allocated
  88941. * memory as it will be overwritten.
  88942. * \param field_name The field name in ASCII, \c NUL terminated.
  88943. * \param field_value The field value in UTF-8, \c NUL terminated.
  88944. * \assert
  88945. * \code entry != NULL \endcode
  88946. * \code field_name != NULL \endcode
  88947. * \code field_value != NULL \endcode
  88948. * \retval FLAC__bool
  88949. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88950. * not comply with the Vorbis comment specification, else \c true.
  88951. */
  88952. 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);
  88953. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88954. *
  88955. * The returned pointers to name and value will be allocated by malloc()
  88956. * and shall be owned by the caller.
  88957. *
  88958. * \param entry An existing Vorbis comment entry.
  88959. * \param field_name The address of where the returned pointer to the
  88960. * field name will be stored.
  88961. * \param field_value The address of where the returned pointer to the
  88962. * field value will be stored.
  88963. * \assert
  88964. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88965. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88966. * \code field_name != NULL \endcode
  88967. * \code field_value != NULL \endcode
  88968. * \retval FLAC__bool
  88969. * \c false if memory allocation fails or \a entry does not comply with the
  88970. * Vorbis comment specification, else \c true.
  88971. */
  88972. 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);
  88973. /** Check if the given Vorbis comment entry's field name matches the given
  88974. * field name.
  88975. *
  88976. * \param entry An existing Vorbis comment entry.
  88977. * \param field_name The field name to check.
  88978. * \param field_name_length The length of \a field_name, not including the
  88979. * terminating \c NUL.
  88980. * \assert
  88981. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88982. * \retval FLAC__bool
  88983. * \c true if the field names match, else \c false
  88984. */
  88985. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88986. /** Find a Vorbis comment with the given field name.
  88987. *
  88988. * The search begins at entry number \a offset; use an offset of 0 to
  88989. * search from the beginning of the comment array.
  88990. *
  88991. * \param object A pointer to an existing VORBIS_COMMENT object.
  88992. * \param offset The offset into the comment array from where to start
  88993. * the search.
  88994. * \param field_name The field name of the comment to find.
  88995. * \assert
  88996. * \code object != NULL \endcode
  88997. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88998. * \code field_name != NULL \endcode
  88999. * \retval int
  89000. * The offset in the comment array of the first comment whose field
  89001. * name matches \a field_name, or \c -1 if no match was found.
  89002. */
  89003. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89004. /** Remove first Vorbis comment matching the given field name.
  89005. *
  89006. * \param object A pointer to an existing VORBIS_COMMENT object.
  89007. * \param field_name The field name of comment to delete.
  89008. * \assert
  89009. * \code object != NULL \endcode
  89010. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89011. * \retval int
  89012. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89013. * \c 1 for one matching entry deleted.
  89014. */
  89015. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89016. /** Remove all Vorbis comments matching the given field name.
  89017. *
  89018. * \param object A pointer to an existing VORBIS_COMMENT object.
  89019. * \param field_name The field name of comments to delete.
  89020. * \assert
  89021. * \code object != NULL \endcode
  89022. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89023. * \retval int
  89024. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89025. * else the number of matching entries deleted.
  89026. */
  89027. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89028. /** Create a new CUESHEET track instance.
  89029. *
  89030. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89031. *
  89032. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89033. * \c NULL if there was an error allocating memory, else the new instance.
  89034. */
  89035. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89036. /** Create a copy of an existing CUESHEET track object.
  89037. *
  89038. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89039. * object is also copied. The caller takes ownership of the new object and
  89040. * is responsible for freeing it with
  89041. * FLAC__metadata_object_cuesheet_track_delete().
  89042. *
  89043. * \param object Pointer to object to copy.
  89044. * \assert
  89045. * \code object != NULL \endcode
  89046. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89047. * \c NULL if there was an error allocating memory, else the new instance.
  89048. */
  89049. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89050. /** Delete a CUESHEET track object
  89051. *
  89052. * \param object A pointer to an existing CUESHEET track object.
  89053. * \assert
  89054. * \code object != NULL \endcode
  89055. */
  89056. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89057. /** Resize a track's index point array.
  89058. *
  89059. * If the size shrinks, elements will truncated; if it grows, new blank
  89060. * indices will be added to the end.
  89061. *
  89062. * \param object A pointer to an existing CUESHEET object.
  89063. * \param track_num The index of the track to modify. NOTE: this is not
  89064. * necessarily the same as the track's \a number field.
  89065. * \param new_num_indices The desired length of the array; may be \c 0.
  89066. * \assert
  89067. * \code object != NULL \endcode
  89068. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89069. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89070. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89071. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89072. * \retval FLAC__bool
  89073. * \c false if memory allocation error, else \c true.
  89074. */
  89075. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89076. /** Insert an index point in a CUESHEET track at the given index.
  89077. *
  89078. * \param object A pointer to an existing CUESHEET object.
  89079. * \param track_num The index of the track to modify. NOTE: this is not
  89080. * necessarily the same as the track's \a number field.
  89081. * \param index_num The index into the track's index array at which to
  89082. * insert the index point. NOTE: this is not necessarily
  89083. * the same as the index point's \a number field. The
  89084. * indices at and after \a index_num move right one
  89085. * position. To append an index point to the end, set
  89086. * \a index_num to
  89087. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89088. * \param index The index point to insert.
  89089. * \assert
  89090. * \code object != NULL \endcode
  89091. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89092. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89093. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89094. * \retval FLAC__bool
  89095. * \c false if realloc() fails, else \c true.
  89096. */
  89097. 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);
  89098. /** Insert a blank index point in a CUESHEET track at the given index.
  89099. *
  89100. * A blank index point is one in which all field values are zero.
  89101. *
  89102. * \param object A pointer to an existing CUESHEET object.
  89103. * \param track_num The index of the track to modify. NOTE: this is not
  89104. * necessarily the same as the track's \a number field.
  89105. * \param index_num The index into the track's index array at which to
  89106. * insert the index point. NOTE: this is not necessarily
  89107. * the same as the index point's \a number field. The
  89108. * indices at and after \a index_num move right one
  89109. * position. To append an index point to the end, set
  89110. * \a index_num to
  89111. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89112. * \assert
  89113. * \code object != NULL \endcode
  89114. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89115. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89116. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89117. * \retval FLAC__bool
  89118. * \c false if realloc() fails, else \c true.
  89119. */
  89120. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89121. /** Delete an index point in a CUESHEET track at the given index.
  89122. *
  89123. * \param object A pointer to an existing CUESHEET object.
  89124. * \param track_num The index into the track array of the track to
  89125. * modify. NOTE: this is not necessarily the same
  89126. * as the track's \a number field.
  89127. * \param index_num The index into the track's index array of the index
  89128. * to delete. NOTE: this is not necessarily the same
  89129. * as the index's \a number field.
  89130. * \assert
  89131. * \code object != NULL \endcode
  89132. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89133. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89134. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89135. * \retval FLAC__bool
  89136. * \c false if realloc() fails, else \c true.
  89137. */
  89138. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89139. /** Resize the track array.
  89140. *
  89141. * If the size shrinks, elements will truncated; if it grows, new blank
  89142. * tracks will be added to the end.
  89143. *
  89144. * \param object A pointer to an existing CUESHEET object.
  89145. * \param new_num_tracks The desired length of the array; may be \c 0.
  89146. * \assert
  89147. * \code object != NULL \endcode
  89148. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89149. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89150. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89151. * \retval FLAC__bool
  89152. * \c false if memory allocation error, else \c true.
  89153. */
  89154. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89155. /** Sets a track in a CUESHEET block.
  89156. *
  89157. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89158. * takes ownership of the \a track pointer.
  89159. *
  89160. * \param object A pointer to an existing CUESHEET object.
  89161. * \param track_num Index into track array to set. NOTE: this is not
  89162. * necessarily the same as the track's \a number field.
  89163. * \param track The track to set the track to. You may safely pass in
  89164. * a const pointer if \a copy is \c true.
  89165. * \param copy See above.
  89166. * \assert
  89167. * \code object != NULL \endcode
  89168. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89169. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89170. * \code (track->indices != NULL && track->num_indices > 0) ||
  89171. * (track->indices == NULL && track->num_indices == 0)
  89172. * \retval FLAC__bool
  89173. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89174. */
  89175. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89176. /** Insert a track in a CUESHEET block at the given index.
  89177. *
  89178. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89179. * takes ownership of the \a track pointer.
  89180. *
  89181. * \param object A pointer to an existing CUESHEET object.
  89182. * \param track_num The index at which to insert the track. NOTE: this
  89183. * is not necessarily the same as the track's \a number
  89184. * field. The tracks at and after \a track_num move right
  89185. * one position. To append a track to the end, set
  89186. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89187. * \param track The track to insert. You may safely pass in a const
  89188. * pointer if \a copy is \c true.
  89189. * \param copy See above.
  89190. * \assert
  89191. * \code object != NULL \endcode
  89192. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89193. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89194. * \retval FLAC__bool
  89195. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89196. */
  89197. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89198. /** Insert a blank track in a CUESHEET block at the given index.
  89199. *
  89200. * A blank track is one in which all field values are zero.
  89201. *
  89202. * \param object A pointer to an existing CUESHEET object.
  89203. * \param track_num The index at which to insert the track. NOTE: this
  89204. * is not necessarily the same as the track's \a number
  89205. * field. The tracks at and after \a track_num move right
  89206. * one position. To append a track to the end, set
  89207. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89208. * \assert
  89209. * \code object != NULL \endcode
  89210. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89211. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89212. * \retval FLAC__bool
  89213. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89214. */
  89215. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89216. /** Delete a track in a CUESHEET block at the given index.
  89217. *
  89218. * \param object A pointer to an existing CUESHEET object.
  89219. * \param track_num The index into the track array of the track to
  89220. * delete. NOTE: this is not necessarily the same
  89221. * as the track's \a number field.
  89222. * \assert
  89223. * \code object != NULL \endcode
  89224. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89225. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89226. * \retval FLAC__bool
  89227. * \c false if realloc() fails, else \c true.
  89228. */
  89229. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89230. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89231. * See the format specification for limits on the contents of the
  89232. * cue sheet.
  89233. *
  89234. * \param object A pointer to an existing CUESHEET object.
  89235. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89236. * stringent requirements for a CD-DA (audio) disc.
  89237. * \param violation Address of a pointer to a string. If there is a
  89238. * violation, a pointer to a string explanation of the
  89239. * violation will be returned here. \a violation may be
  89240. * \c NULL if you don't need the returned string. Do not
  89241. * free the returned string; it will always point to static
  89242. * data.
  89243. * \assert
  89244. * \code object != NULL \endcode
  89245. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89246. * \retval FLAC__bool
  89247. * \c false if cue sheet is illegal, else \c true.
  89248. */
  89249. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89250. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89251. * assumes the cue sheet corresponds to a CD; the result is undefined
  89252. * if the cuesheet's is_cd bit is not set.
  89253. *
  89254. * \param object A pointer to an existing CUESHEET object.
  89255. * \assert
  89256. * \code object != NULL \endcode
  89257. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89258. * \retval FLAC__uint32
  89259. * The unsigned integer representation of the CDDB/freedb ID
  89260. */
  89261. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89262. /** Sets the MIME type of a PICTURE block.
  89263. *
  89264. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89265. * takes ownership of the pointer. The existing string will be freed if this
  89266. * function is successful, otherwise the original string will remain if \a copy
  89267. * is \c true and malloc() fails.
  89268. *
  89269. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89270. *
  89271. * \param object A pointer to an existing PICTURE object.
  89272. * \param mime_type A pointer to the MIME type string. The string must be
  89273. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89274. * is done.
  89275. * \param copy See above.
  89276. * \assert
  89277. * \code object != NULL \endcode
  89278. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89279. * \code (mime_type != NULL) \endcode
  89280. * \retval FLAC__bool
  89281. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89282. */
  89283. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89284. /** Sets the description of a PICTURE block.
  89285. *
  89286. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89287. * takes ownership of the pointer. The existing string will be freed if this
  89288. * function is successful, otherwise the original string will remain if \a copy
  89289. * is \c true and malloc() fails.
  89290. *
  89291. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89292. *
  89293. * \param object A pointer to an existing PICTURE object.
  89294. * \param description A pointer to the description string. The string must be
  89295. * valid UTF-8, NUL-terminated. No validation is done.
  89296. * \param copy See above.
  89297. * \assert
  89298. * \code object != NULL \endcode
  89299. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89300. * \code (description != NULL) \endcode
  89301. * \retval FLAC__bool
  89302. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89303. */
  89304. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89305. /** Sets the picture data of a PICTURE block.
  89306. *
  89307. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89308. * takes ownership of the pointer. Also sets the \a data_length field of the
  89309. * metadata object to what is passed in as the \a length parameter. The
  89310. * existing data will be freed if this function is successful, otherwise the
  89311. * original data and data_length will remain if \a copy is \c true and
  89312. * malloc() fails.
  89313. *
  89314. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89315. *
  89316. * \param object A pointer to an existing PICTURE object.
  89317. * \param data A pointer to the data to set.
  89318. * \param length The length of \a data in bytes.
  89319. * \param copy See above.
  89320. * \assert
  89321. * \code object != NULL \endcode
  89322. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89323. * \code (data != NULL && length > 0) ||
  89324. * (data == NULL && length == 0 && copy == false) \endcode
  89325. * \retval FLAC__bool
  89326. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89327. */
  89328. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89329. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89330. * See the format specification for limits on the contents of the
  89331. * PICTURE block.
  89332. *
  89333. * \param object A pointer to existing PICTURE block to be checked.
  89334. * \param violation Address of a pointer to a string. If there is a
  89335. * violation, a pointer to a string explanation of the
  89336. * violation will be returned here. \a violation may be
  89337. * \c NULL if you don't need the returned string. Do not
  89338. * free the returned string; it will always point to static
  89339. * data.
  89340. * \assert
  89341. * \code object != NULL \endcode
  89342. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89343. * \retval FLAC__bool
  89344. * \c false if PICTURE block is illegal, else \c true.
  89345. */
  89346. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89347. /* \} */
  89348. #ifdef __cplusplus
  89349. }
  89350. #endif
  89351. #endif
  89352. /*** End of inlined file: metadata.h ***/
  89353. /*** Start of inlined file: stream_decoder.h ***/
  89354. #ifndef FLAC__STREAM_DECODER_H
  89355. #define FLAC__STREAM_DECODER_H
  89356. #include <stdio.h> /* for FILE */
  89357. #ifdef __cplusplus
  89358. extern "C" {
  89359. #endif
  89360. /** \file include/FLAC/stream_decoder.h
  89361. *
  89362. * \brief
  89363. * This module contains the functions which implement the stream
  89364. * decoder.
  89365. *
  89366. * See the detailed documentation in the
  89367. * \link flac_stream_decoder stream decoder \endlink module.
  89368. */
  89369. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89370. * \ingroup flac
  89371. *
  89372. * \brief
  89373. * This module describes the decoder layers provided by libFLAC.
  89374. *
  89375. * The stream decoder can be used to decode complete streams either from
  89376. * the client via callbacks, or directly from a file, depending on how
  89377. * it is initialized. When decoding via callbacks, the client provides
  89378. * callbacks for reading FLAC data and writing decoded samples, and
  89379. * handling metadata and errors. If the client also supplies seek-related
  89380. * callback, the decoder function for sample-accurate seeking within the
  89381. * FLAC input is also available. When decoding from a file, the client
  89382. * needs only supply a filename or open \c FILE* and write/metadata/error
  89383. * callbacks; the rest of the callbacks are supplied internally. For more
  89384. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89385. */
  89386. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89387. * \ingroup flac_decoder
  89388. *
  89389. * \brief
  89390. * This module contains the functions which implement the stream
  89391. * decoder.
  89392. *
  89393. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89394. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89395. *
  89396. * The basic usage of this decoder is as follows:
  89397. * - The program creates an instance of a decoder using
  89398. * FLAC__stream_decoder_new().
  89399. * - The program overrides the default settings using
  89400. * FLAC__stream_decoder_set_*() functions.
  89401. * - The program initializes the instance to validate the settings and
  89402. * prepare for decoding using
  89403. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89404. * or FLAC__stream_decoder_init_file() for native FLAC,
  89405. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89406. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89407. * - The program calls the FLAC__stream_decoder_process_*() functions
  89408. * to decode data, which subsequently calls the callbacks.
  89409. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89410. * which flushes the input and output and resets the decoder to the
  89411. * uninitialized state.
  89412. * - The instance may be used again or deleted with
  89413. * FLAC__stream_decoder_delete().
  89414. *
  89415. * In more detail, the program will create a new instance by calling
  89416. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89417. * functions to override the default decoder options, and call
  89418. * one of the FLAC__stream_decoder_init_*() functions.
  89419. *
  89420. * There are three initialization functions for native FLAC, one for
  89421. * setting up the decoder to decode FLAC data from the client via
  89422. * callbacks, and two for decoding directly from a FLAC file.
  89423. *
  89424. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89425. * You must also supply several callbacks for handling I/O. Some (like
  89426. * seeking) are optional, depending on the capabilities of the input.
  89427. *
  89428. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89429. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89430. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89431. * the other callbacks internally.
  89432. *
  89433. * There are three similarly-named init functions for decoding from Ogg
  89434. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89435. * library has been built with Ogg support.
  89436. *
  89437. * Once the decoder is initialized, your program will call one of several
  89438. * functions to start the decoding process:
  89439. *
  89440. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89441. * most one metadata block or audio frame and return, calling either the
  89442. * metadata callback or write callback, respectively, once. If the decoder
  89443. * loses sync it will return with only the error callback being called.
  89444. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89445. * to process the stream from the current location and stop upon reaching
  89446. * the first audio frame. The client will get one metadata, write, or error
  89447. * callback per metadata block, audio frame, or sync error, respectively.
  89448. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89449. * to process the stream from the current location until the read callback
  89450. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89451. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89452. * write, or error callback per metadata block, audio frame, or sync error,
  89453. * respectively.
  89454. *
  89455. * When the decoder has finished decoding (normally or through an abort),
  89456. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89457. * ensures the decoder is in the correct state and frees memory. Then the
  89458. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89459. * again to decode another stream.
  89460. *
  89461. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89462. * At any point after the stream decoder has been initialized, the client can
  89463. * call this function to seek to an exact sample within the stream.
  89464. * Subsequently, the first time the write callback is called it will be
  89465. * passed a (possibly partial) block starting at that sample.
  89466. *
  89467. * If the client cannot seek via the callback interface provided, but still
  89468. * has another way of seeking, it can flush the decoder using
  89469. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89470. * through the read callback.
  89471. *
  89472. * The stream decoder also provides MD5 signature checking. If this is
  89473. * turned on before initialization, FLAC__stream_decoder_finish() will
  89474. * report when the decoded MD5 signature does not match the one stored
  89475. * in the STREAMINFO block. MD5 checking is automatically turned off
  89476. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89477. * in the STREAMINFO block or when a seek is attempted.
  89478. *
  89479. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89480. * attention. By default, the decoder only calls the metadata_callback for
  89481. * the STREAMINFO block. These functions allow you to tell the decoder
  89482. * explicitly which blocks to parse and return via the metadata_callback
  89483. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89484. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89485. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89486. * which blocks to return. Remember that metadata blocks can potentially
  89487. * be big (for example, cover art) so filtering out the ones you don't
  89488. * use can reduce the memory requirements of the decoder. Also note the
  89489. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89490. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89491. * filtering APPLICATION blocks based on the application ID.
  89492. *
  89493. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89494. * they still can legally be filtered from the metadata_callback.
  89495. *
  89496. * \note
  89497. * The "set" functions may only be called when the decoder is in the
  89498. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89499. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89500. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89501. * return \c true, otherwise \c false.
  89502. *
  89503. * \note
  89504. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89505. * defaults, including the callbacks.
  89506. *
  89507. * \{
  89508. */
  89509. /** State values for a FLAC__StreamDecoder
  89510. *
  89511. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89512. */
  89513. typedef enum {
  89514. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89515. /**< The decoder is ready to search for metadata. */
  89516. FLAC__STREAM_DECODER_READ_METADATA,
  89517. /**< The decoder is ready to or is in the process of reading metadata. */
  89518. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89519. /**< The decoder is ready to or is in the process of searching for the
  89520. * frame sync code.
  89521. */
  89522. FLAC__STREAM_DECODER_READ_FRAME,
  89523. /**< The decoder is ready to or is in the process of reading a frame. */
  89524. FLAC__STREAM_DECODER_END_OF_STREAM,
  89525. /**< The decoder has reached the end of the stream. */
  89526. FLAC__STREAM_DECODER_OGG_ERROR,
  89527. /**< An error occurred in the underlying Ogg layer. */
  89528. FLAC__STREAM_DECODER_SEEK_ERROR,
  89529. /**< An error occurred while seeking. The decoder must be flushed
  89530. * with FLAC__stream_decoder_flush() or reset with
  89531. * FLAC__stream_decoder_reset() before decoding can continue.
  89532. */
  89533. FLAC__STREAM_DECODER_ABORTED,
  89534. /**< The decoder was aborted by the read callback. */
  89535. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89536. /**< An error occurred allocating memory. The decoder is in an invalid
  89537. * state and can no longer be used.
  89538. */
  89539. FLAC__STREAM_DECODER_UNINITIALIZED
  89540. /**< The decoder is in the uninitialized state; one of the
  89541. * FLAC__stream_decoder_init_*() functions must be called before samples
  89542. * can be processed.
  89543. */
  89544. } FLAC__StreamDecoderState;
  89545. /** Maps a FLAC__StreamDecoderState to a C string.
  89546. *
  89547. * Using a FLAC__StreamDecoderState as the index to this array
  89548. * will give the string equivalent. The contents should not be modified.
  89549. */
  89550. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89551. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89552. */
  89553. typedef enum {
  89554. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89555. /**< Initialization was successful. */
  89556. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89557. /**< The library was not compiled with support for the given container
  89558. * format.
  89559. */
  89560. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89561. /**< A required callback was not supplied. */
  89562. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89563. /**< An error occurred allocating memory. */
  89564. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89565. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89566. * FLAC__stream_decoder_init_ogg_file(). */
  89567. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89568. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89569. * already initialized, usually because
  89570. * FLAC__stream_decoder_finish() was not called.
  89571. */
  89572. } FLAC__StreamDecoderInitStatus;
  89573. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89574. *
  89575. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89576. * will give the string equivalent. The contents should not be modified.
  89577. */
  89578. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89579. /** Return values for the FLAC__StreamDecoder read callback.
  89580. */
  89581. typedef enum {
  89582. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89583. /**< The read was OK and decoding can continue. */
  89584. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89585. /**< The read was attempted while at the end of the stream. Note that
  89586. * the client must only return this value when the read callback was
  89587. * called when already at the end of the stream. Otherwise, if the read
  89588. * itself moves to the end of the stream, the client should still return
  89589. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89590. * the next read callback it should return
  89591. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89592. * of \c 0.
  89593. */
  89594. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89595. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89596. } FLAC__StreamDecoderReadStatus;
  89597. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89598. *
  89599. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89600. * will give the string equivalent. The contents should not be modified.
  89601. */
  89602. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89603. /** Return values for the FLAC__StreamDecoder seek callback.
  89604. */
  89605. typedef enum {
  89606. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89607. /**< The seek was OK and decoding can continue. */
  89608. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89609. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89610. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89611. /**< Client does not support seeking. */
  89612. } FLAC__StreamDecoderSeekStatus;
  89613. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89614. *
  89615. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89616. * will give the string equivalent. The contents should not be modified.
  89617. */
  89618. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89619. /** Return values for the FLAC__StreamDecoder tell callback.
  89620. */
  89621. typedef enum {
  89622. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89623. /**< The tell was OK and decoding can continue. */
  89624. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89625. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89626. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89627. /**< Client does not support telling the position. */
  89628. } FLAC__StreamDecoderTellStatus;
  89629. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89630. *
  89631. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89632. * will give the string equivalent. The contents should not be modified.
  89633. */
  89634. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89635. /** Return values for the FLAC__StreamDecoder length callback.
  89636. */
  89637. typedef enum {
  89638. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89639. /**< The length call was OK and decoding can continue. */
  89640. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89641. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89642. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89643. /**< Client does not support reporting the length. */
  89644. } FLAC__StreamDecoderLengthStatus;
  89645. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89646. *
  89647. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89648. * will give the string equivalent. The contents should not be modified.
  89649. */
  89650. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89651. /** Return values for the FLAC__StreamDecoder write callback.
  89652. */
  89653. typedef enum {
  89654. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89655. /**< The write was OK and decoding can continue. */
  89656. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89657. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89658. } FLAC__StreamDecoderWriteStatus;
  89659. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89660. *
  89661. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89662. * will give the string equivalent. The contents should not be modified.
  89663. */
  89664. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89665. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89666. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89667. * all. The rest could be caused by bad sync (false synchronization on
  89668. * data that is not the start of a frame) or corrupted data. The error
  89669. * itself is the decoder's best guess at what happened assuming a correct
  89670. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89671. * could be caused by a correct sync on the start of a frame, but some
  89672. * data in the frame header was corrupted. Or it could be the result of
  89673. * syncing on a point the stream that looked like the starting of a frame
  89674. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89675. * could be because the decoder encountered a valid frame made by a future
  89676. * version of the encoder which it cannot parse, or because of a false
  89677. * sync making it appear as though an encountered frame was generated by
  89678. * a future encoder.
  89679. */
  89680. typedef enum {
  89681. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89682. /**< An error in the stream caused the decoder to lose synchronization. */
  89683. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89684. /**< The decoder encountered a corrupted frame header. */
  89685. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89686. /**< The frame's data did not match the CRC in the footer. */
  89687. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89688. /**< The decoder encountered reserved fields in use in the stream. */
  89689. } FLAC__StreamDecoderErrorStatus;
  89690. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89691. *
  89692. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89693. * will give the string equivalent. The contents should not be modified.
  89694. */
  89695. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89696. /***********************************************************************
  89697. *
  89698. * class FLAC__StreamDecoder
  89699. *
  89700. ***********************************************************************/
  89701. struct FLAC__StreamDecoderProtected;
  89702. struct FLAC__StreamDecoderPrivate;
  89703. /** The opaque structure definition for the stream decoder type.
  89704. * See the \link flac_stream_decoder stream decoder module \endlink
  89705. * for a detailed description.
  89706. */
  89707. typedef struct {
  89708. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89709. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89710. } FLAC__StreamDecoder;
  89711. /** Signature for the read callback.
  89712. *
  89713. * A function pointer matching this signature must be passed to
  89714. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89715. * called when the decoder needs more input data. The address of the
  89716. * buffer to be filled is supplied, along with the number of bytes the
  89717. * buffer can hold. The callback may choose to supply less data and
  89718. * modify the byte count but must be careful not to overflow the buffer.
  89719. * The callback then returns a status code chosen from
  89720. * FLAC__StreamDecoderReadStatus.
  89721. *
  89722. * Here is an example of a read callback for stdio streams:
  89723. * \code
  89724. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89725. * {
  89726. * FILE *file = ((MyClientData*)client_data)->file;
  89727. * if(*bytes > 0) {
  89728. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89729. * if(ferror(file))
  89730. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89731. * else if(*bytes == 0)
  89732. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89733. * else
  89734. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89735. * }
  89736. * else
  89737. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89738. * }
  89739. * \endcode
  89740. *
  89741. * \note In general, FLAC__StreamDecoder functions which change the
  89742. * state should not be called on the \a decoder while in the callback.
  89743. *
  89744. * \param decoder The decoder instance calling the callback.
  89745. * \param buffer A pointer to a location for the callee to store
  89746. * data to be decoded.
  89747. * \param bytes A pointer to the size of the buffer. On entry
  89748. * to the callback, it contains the maximum number
  89749. * of bytes that may be stored in \a buffer. The
  89750. * callee must set it to the actual number of bytes
  89751. * stored (0 in case of error or end-of-stream) before
  89752. * returning.
  89753. * \param client_data The callee's client data set through
  89754. * FLAC__stream_decoder_init_*().
  89755. * \retval FLAC__StreamDecoderReadStatus
  89756. * The callee's return status. Note that the callback should return
  89757. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89758. * zero bytes were read and there is no more data to be read.
  89759. */
  89760. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89761. /** Signature for the seek callback.
  89762. *
  89763. * A function pointer matching this signature may be passed to
  89764. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89765. * called when the decoder needs to seek the input stream. The decoder
  89766. * will pass the absolute byte offset to seek to, 0 meaning the
  89767. * beginning of the stream.
  89768. *
  89769. * Here is an example of a seek callback for stdio streams:
  89770. * \code
  89771. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89772. * {
  89773. * FILE *file = ((MyClientData*)client_data)->file;
  89774. * if(file == stdin)
  89775. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89776. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89777. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89778. * else
  89779. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89780. * }
  89781. * \endcode
  89782. *
  89783. * \note In general, FLAC__StreamDecoder functions which change the
  89784. * state should not be called on the \a decoder while in the callback.
  89785. *
  89786. * \param decoder The decoder instance calling the callback.
  89787. * \param absolute_byte_offset The offset from the beginning of the stream
  89788. * to seek to.
  89789. * \param client_data The callee's client data set through
  89790. * FLAC__stream_decoder_init_*().
  89791. * \retval FLAC__StreamDecoderSeekStatus
  89792. * The callee's return status.
  89793. */
  89794. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89795. /** Signature for the tell callback.
  89796. *
  89797. * A function pointer matching this signature may be passed to
  89798. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89799. * called when the decoder wants to know the current position of the
  89800. * stream. The callback should return the byte offset from the
  89801. * beginning of the stream.
  89802. *
  89803. * Here is an example of a tell callback for stdio streams:
  89804. * \code
  89805. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89806. * {
  89807. * FILE *file = ((MyClientData*)client_data)->file;
  89808. * off_t pos;
  89809. * if(file == stdin)
  89810. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89811. * else if((pos = ftello(file)) < 0)
  89812. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89813. * else {
  89814. * *absolute_byte_offset = (FLAC__uint64)pos;
  89815. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89816. * }
  89817. * }
  89818. * \endcode
  89819. *
  89820. * \note In general, FLAC__StreamDecoder functions which change the
  89821. * state should not be called on the \a decoder while in the callback.
  89822. *
  89823. * \param decoder The decoder instance calling the callback.
  89824. * \param absolute_byte_offset A pointer to storage for the current offset
  89825. * from the beginning of the stream.
  89826. * \param client_data The callee's client data set through
  89827. * FLAC__stream_decoder_init_*().
  89828. * \retval FLAC__StreamDecoderTellStatus
  89829. * The callee's return status.
  89830. */
  89831. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89832. /** Signature for the length callback.
  89833. *
  89834. * A function pointer matching this signature may be passed to
  89835. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89836. * called when the decoder wants to know the total length of the stream
  89837. * in bytes.
  89838. *
  89839. * Here is an example of a length callback for stdio streams:
  89840. * \code
  89841. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89842. * {
  89843. * FILE *file = ((MyClientData*)client_data)->file;
  89844. * struct stat filestats;
  89845. *
  89846. * if(file == stdin)
  89847. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89848. * else if(fstat(fileno(file), &filestats) != 0)
  89849. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89850. * else {
  89851. * *stream_length = (FLAC__uint64)filestats.st_size;
  89852. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89853. * }
  89854. * }
  89855. * \endcode
  89856. *
  89857. * \note In general, FLAC__StreamDecoder functions which change the
  89858. * state should not be called on the \a decoder while in the callback.
  89859. *
  89860. * \param decoder The decoder instance calling the callback.
  89861. * \param stream_length A pointer to storage for the length of the stream
  89862. * in bytes.
  89863. * \param client_data The callee's client data set through
  89864. * FLAC__stream_decoder_init_*().
  89865. * \retval FLAC__StreamDecoderLengthStatus
  89866. * The callee's return status.
  89867. */
  89868. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89869. /** Signature for the EOF callback.
  89870. *
  89871. * A function pointer matching this signature may be passed to
  89872. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89873. * called when the decoder needs to know if the end of the stream has
  89874. * been reached.
  89875. *
  89876. * Here is an example of a EOF callback for stdio streams:
  89877. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89878. * \code
  89879. * {
  89880. * FILE *file = ((MyClientData*)client_data)->file;
  89881. * return feof(file)? true : false;
  89882. * }
  89883. * \endcode
  89884. *
  89885. * \note In general, FLAC__StreamDecoder functions which change the
  89886. * state should not be called on the \a decoder while in the callback.
  89887. *
  89888. * \param decoder The decoder instance calling the callback.
  89889. * \param client_data The callee's client data set through
  89890. * FLAC__stream_decoder_init_*().
  89891. * \retval FLAC__bool
  89892. * \c true if the currently at the end of the stream, else \c false.
  89893. */
  89894. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89895. /** Signature for the write callback.
  89896. *
  89897. * A function pointer matching this signature must be passed to one of
  89898. * the FLAC__stream_decoder_init_*() functions.
  89899. * The supplied function will be called when the decoder has decoded a
  89900. * single audio frame. The decoder will pass the frame metadata as well
  89901. * as an array of pointers (one for each channel) pointing to the
  89902. * decoded audio.
  89903. *
  89904. * \note In general, FLAC__StreamDecoder functions which change the
  89905. * state should not be called on the \a decoder while in the callback.
  89906. *
  89907. * \param decoder The decoder instance calling the callback.
  89908. * \param frame The description of the decoded frame. See
  89909. * FLAC__Frame.
  89910. * \param buffer An array of pointers to decoded channels of data.
  89911. * Each pointer will point to an array of signed
  89912. * samples of length \a frame->header.blocksize.
  89913. * Channels will be ordered according to the FLAC
  89914. * specification; see the documentation for the
  89915. * <A HREF="../format.html#frame_header">frame header</A>.
  89916. * \param client_data The callee's client data set through
  89917. * FLAC__stream_decoder_init_*().
  89918. * \retval FLAC__StreamDecoderWriteStatus
  89919. * The callee's return status.
  89920. */
  89921. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89922. /** Signature for the metadata callback.
  89923. *
  89924. * A function pointer matching this signature must be passed to one of
  89925. * the FLAC__stream_decoder_init_*() functions.
  89926. * The supplied function will be called when the decoder has decoded a
  89927. * metadata block. In a valid FLAC file there will always be one
  89928. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89929. * These will be supplied by the decoder in the same order as they
  89930. * appear in the stream and always before the first audio frame (i.e.
  89931. * write callback). The metadata block that is passed in must not be
  89932. * modified, and it doesn't live beyond the callback, so you should make
  89933. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89934. * elsewhere. Since metadata blocks can potentially be large, by
  89935. * default the decoder only calls the metadata callback for the
  89936. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89937. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89938. *
  89939. * \note In general, FLAC__StreamDecoder functions which change the
  89940. * state should not be called on the \a decoder while in the callback.
  89941. *
  89942. * \param decoder The decoder instance calling the callback.
  89943. * \param metadata The decoded metadata block.
  89944. * \param client_data The callee's client data set through
  89945. * FLAC__stream_decoder_init_*().
  89946. */
  89947. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89948. /** Signature for the error callback.
  89949. *
  89950. * A function pointer matching this signature must be passed to one of
  89951. * the FLAC__stream_decoder_init_*() functions.
  89952. * The supplied function will be called whenever an error occurs during
  89953. * decoding.
  89954. *
  89955. * \note In general, FLAC__StreamDecoder functions which change the
  89956. * state should not be called on the \a decoder while in the callback.
  89957. *
  89958. * \param decoder The decoder instance calling the callback.
  89959. * \param status The error encountered by the decoder.
  89960. * \param client_data The callee's client data set through
  89961. * FLAC__stream_decoder_init_*().
  89962. */
  89963. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89964. /***********************************************************************
  89965. *
  89966. * Class constructor/destructor
  89967. *
  89968. ***********************************************************************/
  89969. /** Create a new stream decoder instance. The instance is created with
  89970. * default settings; see the individual FLAC__stream_decoder_set_*()
  89971. * functions for each setting's default.
  89972. *
  89973. * \retval FLAC__StreamDecoder*
  89974. * \c NULL if there was an error allocating memory, else the new instance.
  89975. */
  89976. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89977. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89978. *
  89979. * \param decoder A pointer to an existing decoder.
  89980. * \assert
  89981. * \code decoder != NULL \endcode
  89982. */
  89983. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89984. /***********************************************************************
  89985. *
  89986. * Public class method prototypes
  89987. *
  89988. ***********************************************************************/
  89989. /** Set the serial number for the FLAC stream within the Ogg container.
  89990. * The default behavior is to use the serial number of the first Ogg
  89991. * page. Setting a serial number here will explicitly specify which
  89992. * stream is to be decoded.
  89993. *
  89994. * \note
  89995. * This does not need to be set for native FLAC decoding.
  89996. *
  89997. * \default \c use serial number of first page
  89998. * \param decoder A decoder instance to set.
  89999. * \param serial_number See above.
  90000. * \assert
  90001. * \code decoder != NULL \endcode
  90002. * \retval FLAC__bool
  90003. * \c false if the decoder is already initialized, else \c true.
  90004. */
  90005. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90006. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90007. * compute the MD5 signature of the unencoded audio data while decoding
  90008. * and compare it to the signature from the STREAMINFO block, if it
  90009. * exists, during FLAC__stream_decoder_finish().
  90010. *
  90011. * MD5 signature checking will be turned off (until the next
  90012. * FLAC__stream_decoder_reset()) if there is no signature in the
  90013. * STREAMINFO block or when a seek is attempted.
  90014. *
  90015. * Clients that do not use the MD5 check should leave this off to speed
  90016. * up decoding.
  90017. *
  90018. * \default \c false
  90019. * \param decoder A decoder instance to set.
  90020. * \param value Flag value (see above).
  90021. * \assert
  90022. * \code decoder != NULL \endcode
  90023. * \retval FLAC__bool
  90024. * \c false if the decoder is already initialized, else \c true.
  90025. */
  90026. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90027. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90028. *
  90029. * \default By default, only the \c STREAMINFO block is returned via the
  90030. * metadata callback.
  90031. * \param decoder A decoder instance to set.
  90032. * \param type See above.
  90033. * \assert
  90034. * \code decoder != NULL \endcode
  90035. * \a type is valid
  90036. * \retval FLAC__bool
  90037. * \c false if the decoder is already initialized, else \c true.
  90038. */
  90039. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90040. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90041. * given \a id.
  90042. *
  90043. * \default By default, only the \c STREAMINFO block is returned via the
  90044. * metadata callback.
  90045. * \param decoder A decoder instance to set.
  90046. * \param id See above.
  90047. * \assert
  90048. * \code decoder != NULL \endcode
  90049. * \code id != NULL \endcode
  90050. * \retval FLAC__bool
  90051. * \c false if the decoder is already initialized, else \c true.
  90052. */
  90053. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90054. /** Direct the decoder to pass on all metadata blocks of any type.
  90055. *
  90056. * \default By default, only the \c STREAMINFO block is returned via the
  90057. * metadata callback.
  90058. * \param decoder A decoder instance to set.
  90059. * \assert
  90060. * \code decoder != NULL \endcode
  90061. * \retval FLAC__bool
  90062. * \c false if the decoder is already initialized, else \c true.
  90063. */
  90064. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90065. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90066. *
  90067. * \default By default, only the \c STREAMINFO block is returned via the
  90068. * metadata callback.
  90069. * \param decoder A decoder instance to set.
  90070. * \param type See above.
  90071. * \assert
  90072. * \code decoder != NULL \endcode
  90073. * \a type is valid
  90074. * \retval FLAC__bool
  90075. * \c false if the decoder is already initialized, else \c true.
  90076. */
  90077. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90078. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90079. * the given \a id.
  90080. *
  90081. * \default By default, only the \c STREAMINFO block is returned via the
  90082. * metadata callback.
  90083. * \param decoder A decoder instance to set.
  90084. * \param id See above.
  90085. * \assert
  90086. * \code decoder != NULL \endcode
  90087. * \code id != NULL \endcode
  90088. * \retval FLAC__bool
  90089. * \c false if the decoder is already initialized, else \c true.
  90090. */
  90091. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90092. /** Direct the decoder to filter out all metadata blocks of any type.
  90093. *
  90094. * \default By default, only the \c STREAMINFO block is returned via the
  90095. * metadata callback.
  90096. * \param decoder A decoder instance to set.
  90097. * \assert
  90098. * \code decoder != NULL \endcode
  90099. * \retval FLAC__bool
  90100. * \c false if the decoder is already initialized, else \c true.
  90101. */
  90102. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90103. /** Get the current decoder state.
  90104. *
  90105. * \param decoder A decoder instance to query.
  90106. * \assert
  90107. * \code decoder != NULL \endcode
  90108. * \retval FLAC__StreamDecoderState
  90109. * The current decoder state.
  90110. */
  90111. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90112. /** Get the current decoder state as a C string.
  90113. *
  90114. * \param decoder A decoder instance to query.
  90115. * \assert
  90116. * \code decoder != NULL \endcode
  90117. * \retval const char *
  90118. * The decoder state as a C string. Do not modify the contents.
  90119. */
  90120. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90121. /** Get the "MD5 signature checking" flag.
  90122. * This is the value of the setting, not whether or not the decoder is
  90123. * currently checking the MD5 (remember, it can be turned off automatically
  90124. * by a seek). When the decoder is reset the flag will be restored to the
  90125. * value returned by this function.
  90126. *
  90127. * \param decoder A decoder instance to query.
  90128. * \assert
  90129. * \code decoder != NULL \endcode
  90130. * \retval FLAC__bool
  90131. * See above.
  90132. */
  90133. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90134. /** Get the total number of samples in the stream being decoded.
  90135. * Will only be valid after decoding has started and will contain the
  90136. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90137. *
  90138. * \param decoder A decoder instance to query.
  90139. * \assert
  90140. * \code decoder != NULL \endcode
  90141. * \retval unsigned
  90142. * See above.
  90143. */
  90144. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90145. /** Get the current number of channels in the stream being decoded.
  90146. * Will only be valid after decoding has started and will contain the
  90147. * value from the most recently decoded frame header.
  90148. *
  90149. * \param decoder A decoder instance to query.
  90150. * \assert
  90151. * \code decoder != NULL \endcode
  90152. * \retval unsigned
  90153. * See above.
  90154. */
  90155. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90156. /** Get the current channel assignment in the stream being decoded.
  90157. * Will only be valid after decoding has started and will contain the
  90158. * value from the most recently decoded frame header.
  90159. *
  90160. * \param decoder A decoder instance to query.
  90161. * \assert
  90162. * \code decoder != NULL \endcode
  90163. * \retval FLAC__ChannelAssignment
  90164. * See above.
  90165. */
  90166. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90167. /** Get the current sample resolution in the stream being decoded.
  90168. * Will only be valid after decoding has started and will contain the
  90169. * value from the most recently decoded frame header.
  90170. *
  90171. * \param decoder A decoder instance to query.
  90172. * \assert
  90173. * \code decoder != NULL \endcode
  90174. * \retval unsigned
  90175. * See above.
  90176. */
  90177. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90178. /** Get the current sample rate in Hz of the stream being decoded.
  90179. * Will only be valid after decoding has started and will contain the
  90180. * value from the most recently decoded frame header.
  90181. *
  90182. * \param decoder A decoder instance to query.
  90183. * \assert
  90184. * \code decoder != NULL \endcode
  90185. * \retval unsigned
  90186. * See above.
  90187. */
  90188. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90189. /** Get the current blocksize of the stream being decoded.
  90190. * Will only be valid after decoding has started and will contain the
  90191. * value from the most recently decoded frame header.
  90192. *
  90193. * \param decoder A decoder instance to query.
  90194. * \assert
  90195. * \code decoder != NULL \endcode
  90196. * \retval unsigned
  90197. * See above.
  90198. */
  90199. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90200. /** Returns the decoder's current read position within the stream.
  90201. * The position is the byte offset from the start of the stream.
  90202. * Bytes before this position have been fully decoded. Note that
  90203. * there may still be undecoded bytes in the decoder's read FIFO.
  90204. * The returned position is correct even after a seek.
  90205. *
  90206. * \warning This function currently only works for native FLAC,
  90207. * not Ogg FLAC streams.
  90208. *
  90209. * \param decoder A decoder instance to query.
  90210. * \param position Address at which to return the desired position.
  90211. * \assert
  90212. * \code decoder != NULL \endcode
  90213. * \code position != NULL \endcode
  90214. * \retval FLAC__bool
  90215. * \c true if successful, \c false if the stream is not native FLAC,
  90216. * or there was an error from the 'tell' callback or it returned
  90217. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90218. */
  90219. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90220. /** Initialize the decoder instance to decode native FLAC streams.
  90221. *
  90222. * This flavor of initialization sets up the decoder to decode from a
  90223. * native FLAC stream. I/O is performed via callbacks to the client.
  90224. * For decoding from a plain file via filename or open FILE*,
  90225. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90226. * provide a simpler interface.
  90227. *
  90228. * This function should be called after FLAC__stream_decoder_new() and
  90229. * FLAC__stream_decoder_set_*() but before any of the
  90230. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90231. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90232. * if initialization succeeded.
  90233. *
  90234. * \param decoder An uninitialized decoder instance.
  90235. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90236. * pointer must not be \c NULL.
  90237. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90238. * pointer may be \c NULL if seeking is not
  90239. * supported. If \a seek_callback is not \c NULL then a
  90240. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90241. * Alternatively, a dummy seek callback that just
  90242. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90243. * may also be supplied, all though this is slightly
  90244. * less efficient for the decoder.
  90245. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90246. * pointer may be \c NULL if not supported by the client. If
  90247. * \a seek_callback is not \c NULL then a
  90248. * \a tell_callback must also be supplied.
  90249. * Alternatively, a dummy tell callback that just
  90250. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90251. * may also be supplied, all though this is slightly
  90252. * less efficient for the decoder.
  90253. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90254. * pointer may be \c NULL if not supported by the client. If
  90255. * \a seek_callback is not \c NULL then a
  90256. * \a length_callback must also be supplied.
  90257. * Alternatively, a dummy length callback that just
  90258. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90259. * may also be supplied, all though this is slightly
  90260. * less efficient for the decoder.
  90261. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90262. * pointer may be \c NULL if not supported by the client. If
  90263. * \a seek_callback is not \c NULL then a
  90264. * \a eof_callback must also be supplied.
  90265. * Alternatively, a dummy length callback that just
  90266. * returns \c false
  90267. * may also be supplied, all though this is slightly
  90268. * less efficient for the decoder.
  90269. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90270. * pointer must not be \c NULL.
  90271. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90272. * pointer may be \c NULL if the callback is not
  90273. * desired.
  90274. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90275. * pointer must not be \c NULL.
  90276. * \param client_data This value will be supplied to callbacks in their
  90277. * \a client_data argument.
  90278. * \assert
  90279. * \code decoder != NULL \endcode
  90280. * \retval FLAC__StreamDecoderInitStatus
  90281. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90282. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90283. */
  90284. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90285. FLAC__StreamDecoder *decoder,
  90286. FLAC__StreamDecoderReadCallback read_callback,
  90287. FLAC__StreamDecoderSeekCallback seek_callback,
  90288. FLAC__StreamDecoderTellCallback tell_callback,
  90289. FLAC__StreamDecoderLengthCallback length_callback,
  90290. FLAC__StreamDecoderEofCallback eof_callback,
  90291. FLAC__StreamDecoderWriteCallback write_callback,
  90292. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90293. FLAC__StreamDecoderErrorCallback error_callback,
  90294. void *client_data
  90295. );
  90296. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90297. *
  90298. * This flavor of initialization sets up the decoder to decode from a
  90299. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90300. * client. For decoding from a plain file via filename or open FILE*,
  90301. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90302. * provide a simpler interface.
  90303. *
  90304. * This function should be called after FLAC__stream_decoder_new() and
  90305. * FLAC__stream_decoder_set_*() but before any of the
  90306. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90307. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90308. * if initialization succeeded.
  90309. *
  90310. * \note Support for Ogg FLAC in the library is optional. If this
  90311. * library has been built without support for Ogg FLAC, this function
  90312. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90313. *
  90314. * \param decoder An uninitialized decoder instance.
  90315. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90316. * pointer must not be \c NULL.
  90317. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90318. * pointer may be \c NULL if seeking is not
  90319. * supported. If \a seek_callback is not \c NULL then a
  90320. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90321. * Alternatively, a dummy seek callback that just
  90322. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90323. * may also be supplied, all though this is slightly
  90324. * less efficient for the decoder.
  90325. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90326. * pointer may be \c NULL if not supported by the client. If
  90327. * \a seek_callback is not \c NULL then a
  90328. * \a tell_callback must also be supplied.
  90329. * Alternatively, a dummy tell callback that just
  90330. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90331. * may also be supplied, all though this is slightly
  90332. * less efficient for the decoder.
  90333. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90334. * pointer may be \c NULL if not supported by the client. If
  90335. * \a seek_callback is not \c NULL then a
  90336. * \a length_callback must also be supplied.
  90337. * Alternatively, a dummy length callback that just
  90338. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90339. * may also be supplied, all though this is slightly
  90340. * less efficient for the decoder.
  90341. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90342. * pointer may be \c NULL if not supported by the client. If
  90343. * \a seek_callback is not \c NULL then a
  90344. * \a eof_callback must also be supplied.
  90345. * Alternatively, a dummy length callback that just
  90346. * returns \c false
  90347. * may also be supplied, all though this is slightly
  90348. * less efficient for the decoder.
  90349. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90350. * pointer must not be \c NULL.
  90351. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90352. * pointer may be \c NULL if the callback is not
  90353. * desired.
  90354. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90355. * pointer must not be \c NULL.
  90356. * \param client_data This value will be supplied to callbacks in their
  90357. * \a client_data argument.
  90358. * \assert
  90359. * \code decoder != NULL \endcode
  90360. * \retval FLAC__StreamDecoderInitStatus
  90361. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90362. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90363. */
  90364. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90365. FLAC__StreamDecoder *decoder,
  90366. FLAC__StreamDecoderReadCallback read_callback,
  90367. FLAC__StreamDecoderSeekCallback seek_callback,
  90368. FLAC__StreamDecoderTellCallback tell_callback,
  90369. FLAC__StreamDecoderLengthCallback length_callback,
  90370. FLAC__StreamDecoderEofCallback eof_callback,
  90371. FLAC__StreamDecoderWriteCallback write_callback,
  90372. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90373. FLAC__StreamDecoderErrorCallback error_callback,
  90374. void *client_data
  90375. );
  90376. /** Initialize the decoder instance to decode native FLAC files.
  90377. *
  90378. * This flavor of initialization sets up the decoder to decode from a
  90379. * plain native FLAC file. For non-stdio streams, you must use
  90380. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90381. *
  90382. * This function should be called after FLAC__stream_decoder_new() and
  90383. * FLAC__stream_decoder_set_*() but before any of the
  90384. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90385. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90386. * if initialization succeeded.
  90387. *
  90388. * \param decoder An uninitialized decoder instance.
  90389. * \param file An open FLAC file. The file should have been
  90390. * opened with mode \c "rb" and rewound. The file
  90391. * becomes owned by the decoder and should not be
  90392. * manipulated by the client while decoding.
  90393. * Unless \a file is \c stdin, it will be closed
  90394. * when FLAC__stream_decoder_finish() is called.
  90395. * Note however that seeking will not work when
  90396. * decoding from \c stdout since it is not seekable.
  90397. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90398. * pointer must not be \c NULL.
  90399. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90400. * pointer may be \c NULL if the callback is not
  90401. * desired.
  90402. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90403. * pointer must not be \c NULL.
  90404. * \param client_data This value will be supplied to callbacks in their
  90405. * \a client_data argument.
  90406. * \assert
  90407. * \code decoder != NULL \endcode
  90408. * \code file != NULL \endcode
  90409. * \retval FLAC__StreamDecoderInitStatus
  90410. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90411. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90412. */
  90413. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90414. FLAC__StreamDecoder *decoder,
  90415. FILE *file,
  90416. FLAC__StreamDecoderWriteCallback write_callback,
  90417. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90418. FLAC__StreamDecoderErrorCallback error_callback,
  90419. void *client_data
  90420. );
  90421. /** Initialize the decoder instance to decode Ogg FLAC files.
  90422. *
  90423. * This flavor of initialization sets up the decoder to decode from a
  90424. * plain Ogg FLAC file. For non-stdio streams, you must use
  90425. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90426. *
  90427. * This function should be called after FLAC__stream_decoder_new() and
  90428. * FLAC__stream_decoder_set_*() but before any of the
  90429. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90430. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90431. * if initialization succeeded.
  90432. *
  90433. * \note Support for Ogg FLAC in the library is optional. If this
  90434. * library has been built without support for Ogg FLAC, this function
  90435. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90436. *
  90437. * \param decoder An uninitialized decoder instance.
  90438. * \param file An open FLAC file. The file should have been
  90439. * opened with mode \c "rb" and rewound. The file
  90440. * becomes owned by the decoder and should not be
  90441. * manipulated by the client while decoding.
  90442. * Unless \a file is \c stdin, it will be closed
  90443. * when FLAC__stream_decoder_finish() is called.
  90444. * Note however that seeking will not work when
  90445. * decoding from \c stdout since it is not seekable.
  90446. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90447. * pointer must not be \c NULL.
  90448. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90449. * pointer may be \c NULL if the callback is not
  90450. * desired.
  90451. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90452. * pointer must not be \c NULL.
  90453. * \param client_data This value will be supplied to callbacks in their
  90454. * \a client_data argument.
  90455. * \assert
  90456. * \code decoder != NULL \endcode
  90457. * \code file != NULL \endcode
  90458. * \retval FLAC__StreamDecoderInitStatus
  90459. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90460. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90461. */
  90462. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90463. FLAC__StreamDecoder *decoder,
  90464. FILE *file,
  90465. FLAC__StreamDecoderWriteCallback write_callback,
  90466. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90467. FLAC__StreamDecoderErrorCallback error_callback,
  90468. void *client_data
  90469. );
  90470. /** Initialize the decoder instance to decode native FLAC files.
  90471. *
  90472. * This flavor of initialization sets up the decoder to decode from a plain
  90473. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90474. * example, with Unicode filenames on Windows), you must use
  90475. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90476. * and provide callbacks for the I/O.
  90477. *
  90478. * This function should be called after FLAC__stream_decoder_new() and
  90479. * FLAC__stream_decoder_set_*() but before any of the
  90480. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90481. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90482. * if initialization succeeded.
  90483. *
  90484. * \param decoder An uninitialized decoder instance.
  90485. * \param filename The name of the file to decode from. The file will
  90486. * be opened with fopen(). Use \c NULL to decode from
  90487. * \c stdin. Note that \c stdin is not seekable.
  90488. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90489. * pointer must not be \c NULL.
  90490. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90491. * pointer may be \c NULL if the callback is not
  90492. * desired.
  90493. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90494. * pointer must not be \c NULL.
  90495. * \param client_data This value will be supplied to callbacks in their
  90496. * \a client_data argument.
  90497. * \assert
  90498. * \code decoder != NULL \endcode
  90499. * \retval FLAC__StreamDecoderInitStatus
  90500. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90501. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90502. */
  90503. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90504. FLAC__StreamDecoder *decoder,
  90505. const char *filename,
  90506. FLAC__StreamDecoderWriteCallback write_callback,
  90507. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90508. FLAC__StreamDecoderErrorCallback error_callback,
  90509. void *client_data
  90510. );
  90511. /** Initialize the decoder instance to decode Ogg FLAC files.
  90512. *
  90513. * This flavor of initialization sets up the decoder to decode from a plain
  90514. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90515. * example, with Unicode filenames on Windows), you must use
  90516. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90517. * and provide callbacks for the I/O.
  90518. *
  90519. * This function should be called after FLAC__stream_decoder_new() and
  90520. * FLAC__stream_decoder_set_*() but before any of the
  90521. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90522. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90523. * if initialization succeeded.
  90524. *
  90525. * \note Support for Ogg FLAC in the library is optional. If this
  90526. * library has been built without support for Ogg FLAC, this function
  90527. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90528. *
  90529. * \param decoder An uninitialized decoder instance.
  90530. * \param filename The name of the file to decode from. The file will
  90531. * be opened with fopen(). Use \c NULL to decode from
  90532. * \c stdin. Note that \c stdin is not seekable.
  90533. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90534. * pointer must not be \c NULL.
  90535. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90536. * pointer may be \c NULL if the callback is not
  90537. * desired.
  90538. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90539. * pointer must not be \c NULL.
  90540. * \param client_data This value will be supplied to callbacks in their
  90541. * \a client_data argument.
  90542. * \assert
  90543. * \code decoder != NULL \endcode
  90544. * \retval FLAC__StreamDecoderInitStatus
  90545. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90546. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90547. */
  90548. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90549. FLAC__StreamDecoder *decoder,
  90550. const char *filename,
  90551. FLAC__StreamDecoderWriteCallback write_callback,
  90552. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90553. FLAC__StreamDecoderErrorCallback error_callback,
  90554. void *client_data
  90555. );
  90556. /** Finish the decoding process.
  90557. * Flushes the decoding buffer, releases resources, resets the decoder
  90558. * settings to their defaults, and returns the decoder state to
  90559. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90560. *
  90561. * In the event of a prematurely-terminated decode, it is not strictly
  90562. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90563. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90564. * with a FLAC__stream_decoder_finish().
  90565. *
  90566. * \param decoder An uninitialized decoder instance.
  90567. * \assert
  90568. * \code decoder != NULL \endcode
  90569. * \retval FLAC__bool
  90570. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90571. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90572. * signature does not match the one computed by the decoder; else
  90573. * \c true.
  90574. */
  90575. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90576. /** Flush the stream input.
  90577. * The decoder's input buffer will be cleared and the state set to
  90578. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90579. * off MD5 checking.
  90580. *
  90581. * \param decoder A decoder instance.
  90582. * \assert
  90583. * \code decoder != NULL \endcode
  90584. * \retval FLAC__bool
  90585. * \c true if successful, else \c false if a memory allocation
  90586. * error occurs (in which case the state will be set to
  90587. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90588. */
  90589. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90590. /** Reset the decoding process.
  90591. * The decoder's input buffer will be cleared and the state set to
  90592. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90593. * FLAC__stream_decoder_finish() except that the settings are
  90594. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90595. * before decoding again. MD5 checking will be restored to its original
  90596. * setting.
  90597. *
  90598. * If the decoder is seekable, or was initialized with
  90599. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90600. * the decoder will also attempt to seek to the beginning of the file.
  90601. * If this rewind fails, this function will return \c false. It follows
  90602. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90603. * \c stdin.
  90604. *
  90605. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90606. * and is not seekable (i.e. no seek callback was provided or the seek
  90607. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90608. * is the duty of the client to start feeding data from the beginning of
  90609. * the stream on the next FLAC__stream_decoder_process() or
  90610. * FLAC__stream_decoder_process_interleaved() call.
  90611. *
  90612. * \param decoder A decoder instance.
  90613. * \assert
  90614. * \code decoder != NULL \endcode
  90615. * \retval FLAC__bool
  90616. * \c true if successful, else \c false if a memory allocation occurs
  90617. * (in which case the state will be set to
  90618. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90619. * occurs (the state will be unchanged).
  90620. */
  90621. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90622. /** Decode one metadata block or audio frame.
  90623. * This version instructs the decoder to decode a either a single metadata
  90624. * block or a single frame and stop, unless the callbacks return a fatal
  90625. * error or the read callback returns
  90626. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90627. *
  90628. * As the decoder needs more input it will call the read callback.
  90629. * Depending on what was decoded, the metadata or write callback will be
  90630. * called with the decoded metadata block or audio frame.
  90631. *
  90632. * Unless there is a fatal read error or end of stream, this function
  90633. * will return once one whole frame is decoded. In other words, if the
  90634. * stream is not synchronized or points to a corrupt frame header, the
  90635. * decoder will continue to try and resync until it gets to a valid
  90636. * frame, then decode one frame, then return. If the decoder points to
  90637. * a frame whose frame CRC in the frame footer does not match the
  90638. * computed frame CRC, this function will issue a
  90639. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90640. * error callback, and return, having decoded one complete, although
  90641. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90642. * correct length to the write callback.)
  90643. *
  90644. * \param decoder An initialized decoder instance.
  90645. * \assert
  90646. * \code decoder != NULL \endcode
  90647. * \retval FLAC__bool
  90648. * \c false if any fatal read, write, or memory allocation error
  90649. * occurred (meaning decoding must stop), else \c true; for more
  90650. * information about the decoder, check the decoder state with
  90651. * FLAC__stream_decoder_get_state().
  90652. */
  90653. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90654. /** Decode until the end of the metadata.
  90655. * This version instructs the decoder to decode from the current position
  90656. * and continue until all the metadata has been read, or until the
  90657. * callbacks return a fatal error or the read callback returns
  90658. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90659. *
  90660. * As the decoder needs more input it will call the read callback.
  90661. * As each metadata block is decoded, the metadata callback will be called
  90662. * with the decoded metadata.
  90663. *
  90664. * \param decoder An initialized decoder instance.
  90665. * \assert
  90666. * \code decoder != NULL \endcode
  90667. * \retval FLAC__bool
  90668. * \c false if any fatal read, write, or memory allocation error
  90669. * occurred (meaning decoding must stop), else \c true; for more
  90670. * information about the decoder, check the decoder state with
  90671. * FLAC__stream_decoder_get_state().
  90672. */
  90673. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90674. /** Decode until the end of the stream.
  90675. * This version instructs the decoder to decode from the current position
  90676. * and continue until the end of stream (the read callback returns
  90677. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90678. * callbacks return a fatal error.
  90679. *
  90680. * As the decoder needs more input it will call the read callback.
  90681. * As each metadata block and frame is decoded, the metadata or write
  90682. * callback will be called with the decoded metadata or frame.
  90683. *
  90684. * \param decoder An initialized decoder instance.
  90685. * \assert
  90686. * \code decoder != NULL \endcode
  90687. * \retval FLAC__bool
  90688. * \c false if any fatal read, write, or memory allocation error
  90689. * occurred (meaning decoding must stop), else \c true; for more
  90690. * information about the decoder, check the decoder state with
  90691. * FLAC__stream_decoder_get_state().
  90692. */
  90693. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90694. /** Skip one audio frame.
  90695. * This version instructs the decoder to 'skip' a single frame and stop,
  90696. * unless the callbacks return a fatal error or the read callback returns
  90697. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90698. *
  90699. * The decoding flow is the same as what occurs when
  90700. * FLAC__stream_decoder_process_single() is called to process an audio
  90701. * frame, except that this function does not decode the parsed data into
  90702. * PCM or call the write callback. The integrity of the frame is still
  90703. * checked the same way as in the other process functions.
  90704. *
  90705. * This function will return once one whole frame is skipped, in the
  90706. * same way that FLAC__stream_decoder_process_single() will return once
  90707. * one whole frame is decoded.
  90708. *
  90709. * This function can be used in more quickly determining FLAC frame
  90710. * boundaries when decoding of the actual data is not needed, for
  90711. * example when an application is separating a FLAC stream into frames
  90712. * for editing or storing in a container. To do this, the application
  90713. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90714. * to the next frame, then use
  90715. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90716. * boundary.
  90717. *
  90718. * This function should only be called when the stream has advanced
  90719. * past all the metadata, otherwise it will return \c false.
  90720. *
  90721. * \param decoder An initialized decoder instance not in a metadata
  90722. * state.
  90723. * \assert
  90724. * \code decoder != NULL \endcode
  90725. * \retval FLAC__bool
  90726. * \c false if any fatal read, write, or memory allocation error
  90727. * occurred (meaning decoding must stop), or if the decoder
  90728. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90729. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90730. * information about the decoder, check the decoder state with
  90731. * FLAC__stream_decoder_get_state().
  90732. */
  90733. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90734. /** Flush the input and seek to an absolute sample.
  90735. * Decoding will resume at the given sample. Note that because of
  90736. * this, the next write callback may contain a partial block. The
  90737. * client must support seeking the input or this function will fail
  90738. * and return \c false. Furthermore, if the decoder state is
  90739. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90740. * with FLAC__stream_decoder_flush() or reset with
  90741. * FLAC__stream_decoder_reset() before decoding can continue.
  90742. *
  90743. * \param decoder A decoder instance.
  90744. * \param sample The target sample number to seek to.
  90745. * \assert
  90746. * \code decoder != NULL \endcode
  90747. * \retval FLAC__bool
  90748. * \c true if successful, else \c false.
  90749. */
  90750. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90751. /* \} */
  90752. #ifdef __cplusplus
  90753. }
  90754. #endif
  90755. #endif
  90756. /*** End of inlined file: stream_decoder.h ***/
  90757. /*** Start of inlined file: stream_encoder.h ***/
  90758. #ifndef FLAC__STREAM_ENCODER_H
  90759. #define FLAC__STREAM_ENCODER_H
  90760. #include <stdio.h> /* for FILE */
  90761. #ifdef __cplusplus
  90762. extern "C" {
  90763. #endif
  90764. /** \file include/FLAC/stream_encoder.h
  90765. *
  90766. * \brief
  90767. * This module contains the functions which implement the stream
  90768. * encoder.
  90769. *
  90770. * See the detailed documentation in the
  90771. * \link flac_stream_encoder stream encoder \endlink module.
  90772. */
  90773. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90774. * \ingroup flac
  90775. *
  90776. * \brief
  90777. * This module describes the encoder layers provided by libFLAC.
  90778. *
  90779. * The stream encoder can be used to encode complete streams either to the
  90780. * client via callbacks, or directly to a file, depending on how it is
  90781. * initialized. When encoding via callbacks, the client provides a write
  90782. * callback which will be called whenever FLAC data is ready to be written.
  90783. * If the client also supplies a seek callback, the encoder will also
  90784. * automatically handle the writing back of metadata discovered while
  90785. * encoding, like stream info, seek points offsets, etc. When encoding to
  90786. * a file, the client needs only supply a filename or open \c FILE* and an
  90787. * optional progress callback for periodic notification of progress; the
  90788. * write and seek callbacks are supplied internally. For more info see the
  90789. * \link flac_stream_encoder stream encoder \endlink module.
  90790. */
  90791. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90792. * \ingroup flac_encoder
  90793. *
  90794. * \brief
  90795. * This module contains the functions which implement the stream
  90796. * encoder.
  90797. *
  90798. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90799. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90800. *
  90801. * The basic usage of this encoder is as follows:
  90802. * - The program creates an instance of an encoder using
  90803. * FLAC__stream_encoder_new().
  90804. * - The program overrides the default settings using
  90805. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90806. * functions should be called:
  90807. * - FLAC__stream_encoder_set_channels()
  90808. * - FLAC__stream_encoder_set_bits_per_sample()
  90809. * - FLAC__stream_encoder_set_sample_rate()
  90810. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90811. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90812. * - If the application wants to control the compression level or set its own
  90813. * metadata, then the following should also be called:
  90814. * - FLAC__stream_encoder_set_compression_level()
  90815. * - FLAC__stream_encoder_set_verify()
  90816. * - FLAC__stream_encoder_set_metadata()
  90817. * - The rest of the set functions should only be called if the client needs
  90818. * exact control over how the audio is compressed; thorough understanding
  90819. * of the FLAC format is necessary to achieve good results.
  90820. * - The program initializes the instance to validate the settings and
  90821. * prepare for encoding using
  90822. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90823. * or FLAC__stream_encoder_init_file() for native FLAC
  90824. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90825. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90826. * - The program calls FLAC__stream_encoder_process() or
  90827. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90828. * subsequently calls the callbacks when there is encoder data ready
  90829. * to be written.
  90830. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90831. * which causes the encoder to encode any data still in its input pipe,
  90832. * update the metadata with the final encoding statistics if output
  90833. * seeking is possible, and finally reset the encoder to the
  90834. * uninitialized state.
  90835. * - The instance may be used again or deleted with
  90836. * FLAC__stream_encoder_delete().
  90837. *
  90838. * In more detail, the stream encoder functions similarly to the
  90839. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90840. * callbacks and more options. Typically the client will create a new
  90841. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90842. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90843. * calling one of the FLAC__stream_encoder_init_*() functions.
  90844. *
  90845. * Unlike the decoders, the stream encoder has many options that can
  90846. * affect the speed and compression ratio. When setting these parameters
  90847. * you should have some basic knowledge of the format (see the
  90848. * <A HREF="../documentation.html#format">user-level documentation</A>
  90849. * or the <A HREF="../format.html">formal description</A>). The
  90850. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90851. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90852. * functions will do this, so make sure to pay attention to the state
  90853. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90854. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90855. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90856. * the constructor.
  90857. *
  90858. * There are three initialization functions for native FLAC, one for
  90859. * setting up the encoder to encode FLAC data to the client via
  90860. * callbacks, and two for encoding directly to a file.
  90861. *
  90862. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90863. * You must also supply a write callback which will be called anytime
  90864. * there is raw encoded data to write. If the client can seek the output
  90865. * it is best to also supply seek and tell callbacks, as this allows the
  90866. * encoder to go back after encoding is finished to write back
  90867. * information that was collected while encoding, like seek point offsets,
  90868. * frame sizes, etc.
  90869. *
  90870. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90871. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90872. * filename or open \c FILE*; the encoder will handle all the callbacks
  90873. * internally. You may also supply a progress callback for periodic
  90874. * notification of the encoding progress.
  90875. *
  90876. * There are three similarly-named init functions for encoding to Ogg
  90877. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90878. * library has been built with Ogg support.
  90879. *
  90880. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90881. * call the write callback several times, once with the \c fLaC signature,
  90882. * and once for each encoded metadata block. Note that for Ogg FLAC
  90883. * encoding you will usually get at least twice the number of callbacks than
  90884. * with native FLAC, one for the Ogg page header and one for the page body.
  90885. *
  90886. * After initializing the instance, the client may feed audio data to the
  90887. * encoder in one of two ways:
  90888. *
  90889. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90890. * will pass an array of pointers to buffers, one for each channel, to
  90891. * the encoder, each of the same length. The samples need not be
  90892. * block-aligned, but each channel should have the same number of samples.
  90893. * - Channel interleaved, through
  90894. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90895. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90896. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90897. * Again, the samples need not be block-aligned but they must be
  90898. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90899. * the last value channelN_sampleM.
  90900. *
  90901. * Note that for either process call, each sample in the buffers should be a
  90902. * signed integer, right-justified to the resolution set by
  90903. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90904. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90905. *
  90906. * When the client is finished encoding data, it calls
  90907. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90908. * data still in its input pipe, and call the metadata callback with the
  90909. * final encoding statistics. Then the instance may be deleted with
  90910. * FLAC__stream_encoder_delete() or initialized again to encode another
  90911. * stream.
  90912. *
  90913. * For programs that write their own metadata, but that do not know the
  90914. * actual metadata until after encoding, it is advantageous to instruct
  90915. * the encoder to write a PADDING block of the correct size, so that
  90916. * instead of rewriting the whole stream after encoding, the program can
  90917. * just overwrite the PADDING block. If only the maximum size of the
  90918. * metadata is known, the program can write a slightly larger padding
  90919. * block, then split it after encoding.
  90920. *
  90921. * Make sure you understand how lengths are calculated. All FLAC metadata
  90922. * blocks have a 4 byte header which contains the type and length. This
  90923. * length does not include the 4 bytes of the header. See the format page
  90924. * for the specification of metadata blocks and their lengths.
  90925. *
  90926. * \note
  90927. * If you are writing the FLAC data to a file via callbacks, make sure it
  90928. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90929. * after the first encoding pass, the encoder will try to seek back to the
  90930. * beginning of the stream, to the STREAMINFO block, to write some data
  90931. * there. (If using FLAC__stream_encoder_init*_file() or
  90932. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90933. *
  90934. * \note
  90935. * The "set" functions may only be called when the encoder is in the
  90936. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90937. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90938. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90939. * return \c true, otherwise \c false.
  90940. *
  90941. * \note
  90942. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90943. * defaults.
  90944. *
  90945. * \{
  90946. */
  90947. /** State values for a FLAC__StreamEncoder.
  90948. *
  90949. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90950. *
  90951. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90952. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90953. * must be deleted with FLAC__stream_encoder_delete().
  90954. */
  90955. typedef enum {
  90956. FLAC__STREAM_ENCODER_OK = 0,
  90957. /**< The encoder is in the normal OK state and samples can be processed. */
  90958. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90959. /**< The encoder is in the uninitialized state; one of the
  90960. * FLAC__stream_encoder_init_*() functions must be called before samples
  90961. * can be processed.
  90962. */
  90963. FLAC__STREAM_ENCODER_OGG_ERROR,
  90964. /**< An error occurred in the underlying Ogg layer. */
  90965. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90966. /**< An error occurred in the underlying verify stream decoder;
  90967. * check FLAC__stream_encoder_get_verify_decoder_state().
  90968. */
  90969. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90970. /**< The verify decoder detected a mismatch between the original
  90971. * audio signal and the decoded audio signal.
  90972. */
  90973. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90974. /**< One of the callbacks returned a fatal error. */
  90975. FLAC__STREAM_ENCODER_IO_ERROR,
  90976. /**< An I/O error occurred while opening/reading/writing a file.
  90977. * Check \c errno.
  90978. */
  90979. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90980. /**< An error occurred while writing the stream; usually, the
  90981. * write_callback returned an error.
  90982. */
  90983. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90984. /**< Memory allocation failed. */
  90985. } FLAC__StreamEncoderState;
  90986. /** Maps a FLAC__StreamEncoderState to a C string.
  90987. *
  90988. * Using a FLAC__StreamEncoderState as the index to this array
  90989. * will give the string equivalent. The contents should not be modified.
  90990. */
  90991. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90992. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90993. */
  90994. typedef enum {
  90995. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90996. /**< Initialization was successful. */
  90997. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90998. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90999. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91000. /**< The library was not compiled with support for the given container
  91001. * format.
  91002. */
  91003. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91004. /**< A required callback was not supplied. */
  91005. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91006. /**< The encoder has an invalid setting for number of channels. */
  91007. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91008. /**< The encoder has an invalid setting for bits-per-sample.
  91009. * FLAC supports 4-32 bps but the reference encoder currently supports
  91010. * only up to 24 bps.
  91011. */
  91012. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91013. /**< The encoder has an invalid setting for the input sample rate. */
  91014. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91015. /**< The encoder has an invalid setting for the block size. */
  91016. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91017. /**< The encoder has an invalid setting for the maximum LPC order. */
  91018. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91019. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91020. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91021. /**< The specified block size is less than the maximum LPC order. */
  91022. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91023. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91024. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91025. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91026. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91027. * - One of the metadata blocks contains an undefined type
  91028. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91029. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91030. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91031. */
  91032. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91033. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91034. * already initialized, usually because
  91035. * FLAC__stream_encoder_finish() was not called.
  91036. */
  91037. } FLAC__StreamEncoderInitStatus;
  91038. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91039. *
  91040. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91041. * will give the string equivalent. The contents should not be modified.
  91042. */
  91043. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91044. /** Return values for the FLAC__StreamEncoder read callback.
  91045. */
  91046. typedef enum {
  91047. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91048. /**< The read was OK and decoding can continue. */
  91049. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91050. /**< The read was attempted at the end of the stream. */
  91051. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91052. /**< An unrecoverable error occurred. */
  91053. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91054. /**< Client does not support reading back from the output. */
  91055. } FLAC__StreamEncoderReadStatus;
  91056. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91057. *
  91058. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91059. * will give the string equivalent. The contents should not be modified.
  91060. */
  91061. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91062. /** Return values for the FLAC__StreamEncoder write callback.
  91063. */
  91064. typedef enum {
  91065. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91066. /**< The write was OK and encoding can continue. */
  91067. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91068. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91069. } FLAC__StreamEncoderWriteStatus;
  91070. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91071. *
  91072. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91073. * will give the string equivalent. The contents should not be modified.
  91074. */
  91075. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91076. /** Return values for the FLAC__StreamEncoder seek callback.
  91077. */
  91078. typedef enum {
  91079. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91080. /**< The seek was OK and encoding can continue. */
  91081. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91082. /**< An unrecoverable error occurred. */
  91083. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91084. /**< Client does not support seeking. */
  91085. } FLAC__StreamEncoderSeekStatus;
  91086. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91087. *
  91088. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91089. * will give the string equivalent. The contents should not be modified.
  91090. */
  91091. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91092. /** Return values for the FLAC__StreamEncoder tell callback.
  91093. */
  91094. typedef enum {
  91095. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91096. /**< The tell was OK and encoding can continue. */
  91097. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91098. /**< An unrecoverable error occurred. */
  91099. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91100. /**< Client does not support seeking. */
  91101. } FLAC__StreamEncoderTellStatus;
  91102. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91103. *
  91104. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91105. * will give the string equivalent. The contents should not be modified.
  91106. */
  91107. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91108. /***********************************************************************
  91109. *
  91110. * class FLAC__StreamEncoder
  91111. *
  91112. ***********************************************************************/
  91113. struct FLAC__StreamEncoderProtected;
  91114. struct FLAC__StreamEncoderPrivate;
  91115. /** The opaque structure definition for the stream encoder type.
  91116. * See the \link flac_stream_encoder stream encoder module \endlink
  91117. * for a detailed description.
  91118. */
  91119. typedef struct {
  91120. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91121. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91122. } FLAC__StreamEncoder;
  91123. /** Signature for the read callback.
  91124. *
  91125. * A function pointer matching this signature must be passed to
  91126. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91127. * The supplied function will be called when the encoder needs to read back
  91128. * encoded data. This happens during the metadata callback, when the encoder
  91129. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91130. * while encoding. The address of the buffer to be filled is supplied, along
  91131. * with the number of bytes the buffer can hold. The callback may choose to
  91132. * supply less data and modify the byte count but must be careful not to
  91133. * overflow the buffer. The callback then returns a status code chosen from
  91134. * FLAC__StreamEncoderReadStatus.
  91135. *
  91136. * Here is an example of a read callback for stdio streams:
  91137. * \code
  91138. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91139. * {
  91140. * FILE *file = ((MyClientData*)client_data)->file;
  91141. * if(*bytes > 0) {
  91142. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91143. * if(ferror(file))
  91144. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91145. * else if(*bytes == 0)
  91146. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91147. * else
  91148. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91149. * }
  91150. * else
  91151. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91152. * }
  91153. * \endcode
  91154. *
  91155. * \note In general, FLAC__StreamEncoder functions which change the
  91156. * state should not be called on the \a encoder while in the callback.
  91157. *
  91158. * \param encoder The encoder instance calling the callback.
  91159. * \param buffer A pointer to a location for the callee to store
  91160. * data to be encoded.
  91161. * \param bytes A pointer to the size of the buffer. On entry
  91162. * to the callback, it contains the maximum number
  91163. * of bytes that may be stored in \a buffer. The
  91164. * callee must set it to the actual number of bytes
  91165. * stored (0 in case of error or end-of-stream) before
  91166. * returning.
  91167. * \param client_data The callee's client data set through
  91168. * FLAC__stream_encoder_set_client_data().
  91169. * \retval FLAC__StreamEncoderReadStatus
  91170. * The callee's return status.
  91171. */
  91172. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91173. /** Signature for the write callback.
  91174. *
  91175. * A function pointer matching this signature must be passed to
  91176. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91177. * by the encoder anytime there is raw encoded data ready to write. It may
  91178. * include metadata mixed with encoded audio frames and the data is not
  91179. * guaranteed to be aligned on frame or metadata block boundaries.
  91180. *
  91181. * The only duty of the callback is to write out the \a bytes worth of data
  91182. * in \a buffer to the current position in the output stream. The arguments
  91183. * \a samples and \a current_frame are purely informational. If \a samples
  91184. * is greater than \c 0, then \a current_frame will hold the current frame
  91185. * number that is being written; otherwise it indicates that the write
  91186. * callback is being called to write metadata.
  91187. *
  91188. * \note
  91189. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91190. * write callback will be called twice when writing each audio
  91191. * frame; once for the page header, and once for the page body.
  91192. * When writing the page header, the \a samples argument to the
  91193. * write callback will be \c 0.
  91194. *
  91195. * \note In general, FLAC__StreamEncoder functions which change the
  91196. * state should not be called on the \a encoder while in the callback.
  91197. *
  91198. * \param encoder The encoder instance calling the callback.
  91199. * \param buffer An array of encoded data of length \a bytes.
  91200. * \param bytes The byte length of \a buffer.
  91201. * \param samples The number of samples encoded by \a buffer.
  91202. * \c 0 has a special meaning; see above.
  91203. * \param current_frame The number of the current frame being encoded.
  91204. * \param client_data The callee's client data set through
  91205. * FLAC__stream_encoder_init_*().
  91206. * \retval FLAC__StreamEncoderWriteStatus
  91207. * The callee's return status.
  91208. */
  91209. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91210. /** Signature for the seek callback.
  91211. *
  91212. * A function pointer matching this signature may be passed to
  91213. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91214. * when the encoder needs to seek the output stream. The encoder will pass
  91215. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91216. *
  91217. * Here is an example of a seek callback for stdio streams:
  91218. * \code
  91219. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91220. * {
  91221. * FILE *file = ((MyClientData*)client_data)->file;
  91222. * if(file == stdin)
  91223. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91224. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91225. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91226. * else
  91227. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91228. * }
  91229. * \endcode
  91230. *
  91231. * \note In general, FLAC__StreamEncoder functions which change the
  91232. * state should not be called on the \a encoder while in the callback.
  91233. *
  91234. * \param encoder The encoder instance calling the callback.
  91235. * \param absolute_byte_offset The offset from the beginning of the stream
  91236. * to seek to.
  91237. * \param client_data The callee's client data set through
  91238. * FLAC__stream_encoder_init_*().
  91239. * \retval FLAC__StreamEncoderSeekStatus
  91240. * The callee's return status.
  91241. */
  91242. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91243. /** Signature for the tell callback.
  91244. *
  91245. * A function pointer matching this signature may be passed to
  91246. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91247. * when the encoder needs to know the current position of the output stream.
  91248. *
  91249. * \warning
  91250. * The callback must return the true current byte offset of the output to
  91251. * which the encoder is writing. If you are buffering the output, make
  91252. * sure and take this into account. If you are writing directly to a
  91253. * FILE* from your write callback, ftell() is sufficient. If you are
  91254. * writing directly to a file descriptor from your write callback, you
  91255. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91256. * these points to rewrite metadata after encoding.
  91257. *
  91258. * Here is an example of a tell callback for stdio streams:
  91259. * \code
  91260. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91261. * {
  91262. * FILE *file = ((MyClientData*)client_data)->file;
  91263. * off_t pos;
  91264. * if(file == stdin)
  91265. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91266. * else if((pos = ftello(file)) < 0)
  91267. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91268. * else {
  91269. * *absolute_byte_offset = (FLAC__uint64)pos;
  91270. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91271. * }
  91272. * }
  91273. * \endcode
  91274. *
  91275. * \note In general, FLAC__StreamEncoder functions which change the
  91276. * state should not be called on the \a encoder while in the callback.
  91277. *
  91278. * \param encoder The encoder instance calling the callback.
  91279. * \param absolute_byte_offset The address at which to store the current
  91280. * position of the output.
  91281. * \param client_data The callee's client data set through
  91282. * FLAC__stream_encoder_init_*().
  91283. * \retval FLAC__StreamEncoderTellStatus
  91284. * The callee's return status.
  91285. */
  91286. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91287. /** Signature for the metadata callback.
  91288. *
  91289. * A function pointer matching this signature may be passed to
  91290. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91291. * once at the end of encoding with the populated STREAMINFO structure. This
  91292. * is so the client can seek back to the beginning of the file and write the
  91293. * STREAMINFO block with the correct statistics after encoding (like
  91294. * minimum/maximum frame size and total samples).
  91295. *
  91296. * \note In general, FLAC__StreamEncoder functions which change the
  91297. * state should not be called on the \a encoder while in the callback.
  91298. *
  91299. * \param encoder The encoder instance calling the callback.
  91300. * \param metadata The final populated STREAMINFO block.
  91301. * \param client_data The callee's client data set through
  91302. * FLAC__stream_encoder_init_*().
  91303. */
  91304. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91305. /** Signature for the progress callback.
  91306. *
  91307. * A function pointer matching this signature may be passed to
  91308. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91309. * The supplied function will be called when the encoder has finished
  91310. * writing a frame. The \c total_frames_estimate argument to the
  91311. * callback will be based on the value from
  91312. * FLAC__stream_encoder_set_total_samples_estimate().
  91313. *
  91314. * \note In general, FLAC__StreamEncoder functions which change the
  91315. * state should not be called on the \a encoder while in the callback.
  91316. *
  91317. * \param encoder The encoder instance calling the callback.
  91318. * \param bytes_written Bytes written so far.
  91319. * \param samples_written Samples written so far.
  91320. * \param frames_written Frames written so far.
  91321. * \param total_frames_estimate The estimate of the total number of
  91322. * frames to be written.
  91323. * \param client_data The callee's client data set through
  91324. * FLAC__stream_encoder_init_*().
  91325. */
  91326. 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);
  91327. /***********************************************************************
  91328. *
  91329. * Class constructor/destructor
  91330. *
  91331. ***********************************************************************/
  91332. /** Create a new stream encoder instance. The instance is created with
  91333. * default settings; see the individual FLAC__stream_encoder_set_*()
  91334. * functions for each setting's default.
  91335. *
  91336. * \retval FLAC__StreamEncoder*
  91337. * \c NULL if there was an error allocating memory, else the new instance.
  91338. */
  91339. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91340. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91341. *
  91342. * \param encoder A pointer to an existing encoder.
  91343. * \assert
  91344. * \code encoder != NULL \endcode
  91345. */
  91346. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91347. /***********************************************************************
  91348. *
  91349. * Public class method prototypes
  91350. *
  91351. ***********************************************************************/
  91352. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91353. *
  91354. * \note
  91355. * This does not need to be set for native FLAC encoding.
  91356. *
  91357. * \note
  91358. * It is recommended to set a serial number explicitly as the default of '0'
  91359. * may collide with other streams.
  91360. *
  91361. * \default \c 0
  91362. * \param encoder An encoder instance to set.
  91363. * \param serial_number See above.
  91364. * \assert
  91365. * \code encoder != NULL \endcode
  91366. * \retval FLAC__bool
  91367. * \c false if the encoder is already initialized, else \c true.
  91368. */
  91369. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91370. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91371. * encoded output by feeding it through an internal decoder and comparing
  91372. * the original signal against the decoded signal. If a mismatch occurs,
  91373. * the process call will return \c false. Note that this will slow the
  91374. * encoding process by the extra time required for decoding and comparison.
  91375. *
  91376. * \default \c false
  91377. * \param encoder An encoder instance to set.
  91378. * \param value Flag value (see above).
  91379. * \assert
  91380. * \code encoder != NULL \endcode
  91381. * \retval FLAC__bool
  91382. * \c false if the encoder is already initialized, else \c true.
  91383. */
  91384. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91385. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91386. * the encoder will comply with the Subset and will check the
  91387. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91388. * comply. If \c false, the settings may take advantage of the full
  91389. * range that the format allows.
  91390. *
  91391. * Make sure you know what it entails before setting this to \c false.
  91392. *
  91393. * \default \c true
  91394. * \param encoder An encoder instance to set.
  91395. * \param value Flag value (see above).
  91396. * \assert
  91397. * \code encoder != NULL \endcode
  91398. * \retval FLAC__bool
  91399. * \c false if the encoder is already initialized, else \c true.
  91400. */
  91401. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91402. /** Set the number of channels to be encoded.
  91403. *
  91404. * \default \c 2
  91405. * \param encoder An encoder instance to set.
  91406. * \param value See above.
  91407. * \assert
  91408. * \code encoder != NULL \endcode
  91409. * \retval FLAC__bool
  91410. * \c false if the encoder is already initialized, else \c true.
  91411. */
  91412. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91413. /** Set the sample resolution of the input to be encoded.
  91414. *
  91415. * \warning
  91416. * Do not feed the encoder data that is wider than the value you
  91417. * set here or you will generate an invalid stream.
  91418. *
  91419. * \default \c 16
  91420. * \param encoder An encoder instance to set.
  91421. * \param value See above.
  91422. * \assert
  91423. * \code encoder != NULL \endcode
  91424. * \retval FLAC__bool
  91425. * \c false if the encoder is already initialized, else \c true.
  91426. */
  91427. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91428. /** Set the sample rate (in Hz) of the input to be encoded.
  91429. *
  91430. * \default \c 44100
  91431. * \param encoder An encoder instance to set.
  91432. * \param value See above.
  91433. * \assert
  91434. * \code encoder != NULL \endcode
  91435. * \retval FLAC__bool
  91436. * \c false if the encoder is already initialized, else \c true.
  91437. */
  91438. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91439. /** Set the compression level
  91440. *
  91441. * The compression level is roughly proportional to the amount of effort
  91442. * the encoder expends to compress the file. A higher level usually
  91443. * means more computation but higher compression. The default level is
  91444. * suitable for most applications.
  91445. *
  91446. * Currently the levels range from \c 0 (fastest, least compression) to
  91447. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91448. * treated as \c 8.
  91449. *
  91450. * This function automatically calls the following other \c _set_
  91451. * functions with appropriate values, so the client does not need to
  91452. * unless it specifically wants to override them:
  91453. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91454. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91455. * - FLAC__stream_encoder_set_apodization()
  91456. * - FLAC__stream_encoder_set_max_lpc_order()
  91457. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91458. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91459. * - FLAC__stream_encoder_set_do_escape_coding()
  91460. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91461. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91462. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91463. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91464. *
  91465. * The actual values set for each level are:
  91466. * <table>
  91467. * <tr>
  91468. * <td><b>level</b><td>
  91469. * <td>do mid-side stereo<td>
  91470. * <td>loose mid-side stereo<td>
  91471. * <td>apodization<td>
  91472. * <td>max lpc order<td>
  91473. * <td>qlp coeff precision<td>
  91474. * <td>qlp coeff prec search<td>
  91475. * <td>escape coding<td>
  91476. * <td>exhaustive model search<td>
  91477. * <td>min residual partition order<td>
  91478. * <td>max residual partition order<td>
  91479. * <td>rice parameter search dist<td>
  91480. * </tr>
  91481. * <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>
  91482. * <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>
  91483. * <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>
  91484. * <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>
  91485. * <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>
  91486. * <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>
  91487. * <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>
  91488. * <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>
  91489. * <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>
  91490. * </table>
  91491. *
  91492. * \default \c 5
  91493. * \param encoder An encoder instance to set.
  91494. * \param value See above.
  91495. * \assert
  91496. * \code encoder != NULL \endcode
  91497. * \retval FLAC__bool
  91498. * \c false if the encoder is already initialized, else \c true.
  91499. */
  91500. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91501. /** Set the blocksize to use while encoding.
  91502. *
  91503. * The number of samples to use per frame. Use \c 0 to let the encoder
  91504. * estimate a blocksize; this is usually best.
  91505. *
  91506. * \default \c 0
  91507. * \param encoder An encoder instance to set.
  91508. * \param value See above.
  91509. * \assert
  91510. * \code encoder != NULL \endcode
  91511. * \retval FLAC__bool
  91512. * \c false if the encoder is already initialized, else \c true.
  91513. */
  91514. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91515. /** Set to \c true to enable mid-side encoding on stereo input. The
  91516. * number of channels must be 2 for this to have any effect. Set to
  91517. * \c false to use only independent channel coding.
  91518. *
  91519. * \default \c false
  91520. * \param encoder An encoder instance to set.
  91521. * \param value Flag value (see above).
  91522. * \assert
  91523. * \code encoder != NULL \endcode
  91524. * \retval FLAC__bool
  91525. * \c false if the encoder is already initialized, else \c true.
  91526. */
  91527. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91528. /** Set to \c true to enable adaptive switching between mid-side and
  91529. * left-right encoding on stereo input. Set to \c false to use
  91530. * exhaustive searching. Setting this to \c true requires
  91531. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91532. * \c true in order to have any effect.
  91533. *
  91534. * \default \c false
  91535. * \param encoder An encoder instance to set.
  91536. * \param value Flag value (see above).
  91537. * \assert
  91538. * \code encoder != NULL \endcode
  91539. * \retval FLAC__bool
  91540. * \c false if the encoder is already initialized, else \c true.
  91541. */
  91542. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91543. /** Sets the apodization function(s) the encoder will use when windowing
  91544. * audio data for LPC analysis.
  91545. *
  91546. * The \a specification is a plain ASCII string which specifies exactly
  91547. * which functions to use. There may be more than one (up to 32),
  91548. * separated by \c ';' characters. Some functions take one or more
  91549. * comma-separated arguments in parentheses.
  91550. *
  91551. * The available functions are \c bartlett, \c bartlett_hann,
  91552. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91553. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91554. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91555. *
  91556. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91557. * (0<STDDEV<=0.5).
  91558. *
  91559. * For \c tukey(P), P specifies the fraction of the window that is
  91560. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91561. * corresponds to \c hann.
  91562. *
  91563. * Example specifications are \c "blackman" or
  91564. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91565. *
  91566. * Any function that is specified erroneously is silently dropped. Up
  91567. * to 32 functions are kept, the rest are dropped. If the specification
  91568. * is empty the encoder defaults to \c "tukey(0.5)".
  91569. *
  91570. * When more than one function is specified, then for every subframe the
  91571. * encoder will try each of them separately and choose the window that
  91572. * results in the smallest compressed subframe.
  91573. *
  91574. * Note that each function specified causes the encoder to occupy a
  91575. * floating point array in which to store the window.
  91576. *
  91577. * \default \c "tukey(0.5)"
  91578. * \param encoder An encoder instance to set.
  91579. * \param specification See above.
  91580. * \assert
  91581. * \code encoder != NULL \endcode
  91582. * \code specification != NULL \endcode
  91583. * \retval FLAC__bool
  91584. * \c false if the encoder is already initialized, else \c true.
  91585. */
  91586. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91587. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91588. *
  91589. * \default \c 0
  91590. * \param encoder An encoder instance to set.
  91591. * \param value See above.
  91592. * \assert
  91593. * \code encoder != NULL \endcode
  91594. * \retval FLAC__bool
  91595. * \c false if the encoder is already initialized, else \c true.
  91596. */
  91597. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91598. /** Set the precision, in bits, of the quantized linear predictor
  91599. * coefficients, or \c 0 to let the encoder select it based on the
  91600. * blocksize.
  91601. *
  91602. * \note
  91603. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91604. * be less than 32.
  91605. *
  91606. * \default \c 0
  91607. * \param encoder An encoder instance to set.
  91608. * \param value 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_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91615. /** Set to \c false to use only the specified quantized linear predictor
  91616. * coefficient precision, or \c true to search neighboring precision
  91617. * values and use the best one.
  91618. *
  91619. * \default \c false
  91620. * \param encoder An encoder instance to set.
  91621. * \param value See above.
  91622. * \assert
  91623. * \code encoder != NULL \endcode
  91624. * \retval FLAC__bool
  91625. * \c false if the encoder is already initialized, else \c true.
  91626. */
  91627. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91628. /** Deprecated. Setting this value has no effect.
  91629. *
  91630. * \default \c false
  91631. * \param encoder An encoder instance to set.
  91632. * \param value See above.
  91633. * \assert
  91634. * \code encoder != NULL \endcode
  91635. * \retval FLAC__bool
  91636. * \c false if the encoder is already initialized, else \c true.
  91637. */
  91638. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91639. /** Set to \c false to let the encoder estimate the best model order
  91640. * based on the residual signal energy, or \c true to force the
  91641. * encoder to evaluate all order models and select the best.
  91642. *
  91643. * \default \c false
  91644. * \param encoder An encoder instance to set.
  91645. * \param value See above.
  91646. * \assert
  91647. * \code encoder != NULL \endcode
  91648. * \retval FLAC__bool
  91649. * \c false if the encoder is already initialized, else \c true.
  91650. */
  91651. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91652. /** Set the minimum partition order to search when coding the residual.
  91653. * This is used in tandem with
  91654. * FLAC__stream_encoder_set_max_residual_partition_order().
  91655. *
  91656. * The partition order determines the context size in the residual.
  91657. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91658. *
  91659. * Set both min and max values to \c 0 to force a single context,
  91660. * whose Rice parameter is based on the residual signal variance.
  91661. * Otherwise, set a min and max order, and the encoder will search
  91662. * all orders, using the mean of each context for its Rice parameter,
  91663. * and use the best.
  91664. *
  91665. * \default \c 0
  91666. * \param encoder An encoder instance to set.
  91667. * \param value See above.
  91668. * \assert
  91669. * \code encoder != NULL \endcode
  91670. * \retval FLAC__bool
  91671. * \c false if the encoder is already initialized, else \c true.
  91672. */
  91673. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91674. /** Set the maximum partition order to search when coding the residual.
  91675. * This is used in tandem with
  91676. * FLAC__stream_encoder_set_min_residual_partition_order().
  91677. *
  91678. * The partition order determines the context size in the residual.
  91679. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91680. *
  91681. * Set both min and max values to \c 0 to force a single context,
  91682. * whose Rice parameter is based on the residual signal variance.
  91683. * Otherwise, set a min and max order, and the encoder will search
  91684. * all orders, using the mean of each context for its Rice parameter,
  91685. * and use the best.
  91686. *
  91687. * \default \c 0
  91688. * \param encoder An encoder instance to set.
  91689. * \param value See above.
  91690. * \assert
  91691. * \code encoder != NULL \endcode
  91692. * \retval FLAC__bool
  91693. * \c false if the encoder is already initialized, else \c true.
  91694. */
  91695. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91696. /** Deprecated. Setting this value has no effect.
  91697. *
  91698. * \default \c 0
  91699. * \param encoder An encoder instance to set.
  91700. * \param value See above.
  91701. * \assert
  91702. * \code encoder != NULL \endcode
  91703. * \retval FLAC__bool
  91704. * \c false if the encoder is already initialized, else \c true.
  91705. */
  91706. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91707. /** Set an estimate of the total samples that will be encoded.
  91708. * This is merely an estimate and may be set to \c 0 if unknown.
  91709. * This value will be written to the STREAMINFO block before encoding,
  91710. * and can remove the need for the caller to rewrite the value later
  91711. * if the value is known before encoding.
  91712. *
  91713. * \default \c 0
  91714. * \param encoder An encoder instance to set.
  91715. * \param value See above.
  91716. * \assert
  91717. * \code encoder != NULL \endcode
  91718. * \retval FLAC__bool
  91719. * \c false if the encoder is already initialized, else \c true.
  91720. */
  91721. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91722. /** Set the metadata blocks to be emitted to the stream before encoding.
  91723. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91724. * array of pointers to metadata blocks. The array is non-const since
  91725. * the encoder may need to change the \a is_last flag inside them, and
  91726. * in some cases update seek point offsets. Otherwise, the encoder will
  91727. * not modify or free the blocks. It is up to the caller to free the
  91728. * metadata blocks after encoding finishes.
  91729. *
  91730. * \note
  91731. * The encoder stores only copies of the pointers in the \a metadata array;
  91732. * the metadata blocks themselves must survive at least until after
  91733. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91734. *
  91735. * \note
  91736. * The STREAMINFO block is always written and no STREAMINFO block may
  91737. * occur in the supplied array.
  91738. *
  91739. * \note
  91740. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91741. * in the \a metadata array, but the client has specified that it does not
  91742. * support seeking, then the SEEKTABLE will be written verbatim. However
  91743. * by itself this is not very useful as the client will not know the stream
  91744. * offsets for the seekpoints ahead of time. In order to get a proper
  91745. * seektable the client must support seeking. See next note.
  91746. *
  91747. * \note
  91748. * SEEKTABLE blocks are handled specially. Since you will not know
  91749. * the values for the seek point stream offsets, you should pass in
  91750. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91751. * required sample numbers (or placeholder points), with \c 0 for the
  91752. * \a frame_samples and \a stream_offset fields for each point. If the
  91753. * client has specified that it supports seeking by providing a seek
  91754. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91755. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91756. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91757. * then while it is encoding the encoder will fill the stream offsets in
  91758. * for you and when encoding is finished, it will seek back and write the
  91759. * real values into the SEEKTABLE block in the stream. There are helper
  91760. * routines for manipulating seektable template blocks; see metadata.h:
  91761. * FLAC__metadata_object_seektable_template_*(). If the client does
  91762. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91763. * will slow down or remove the ability to seek in the FLAC stream.
  91764. *
  91765. * \note
  91766. * The encoder instance \b will modify the first \c SEEKTABLE block
  91767. * as it transforms the template to a valid seektable while encoding,
  91768. * but it is still up to the caller to free all metadata blocks after
  91769. * encoding.
  91770. *
  91771. * \note
  91772. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91773. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91774. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91775. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91776. * block is present in the \a metadata array, libFLAC will write an
  91777. * empty one, containing only the vendor string.
  91778. *
  91779. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91780. * the second metadata block of the stream. The encoder already supplies
  91781. * the STREAMINFO block automatically. If \a metadata does not contain a
  91782. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91783. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91784. * first, the init function will reorder \a metadata by moving the
  91785. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91786. * blocks will remain as they were.
  91787. *
  91788. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91789. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91790. * return \c false.
  91791. *
  91792. * \default \c NULL, 0
  91793. * \param encoder An encoder instance to set.
  91794. * \param metadata See above.
  91795. * \param num_blocks See above.
  91796. * \assert
  91797. * \code encoder != NULL \endcode
  91798. * \retval FLAC__bool
  91799. * \c false if the encoder is already initialized, else \c true.
  91800. * \c false if the encoder is already initialized, or if
  91801. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91802. */
  91803. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91804. /** Get the current encoder state.
  91805. *
  91806. * \param encoder An encoder instance to query.
  91807. * \assert
  91808. * \code encoder != NULL \endcode
  91809. * \retval FLAC__StreamEncoderState
  91810. * The current encoder state.
  91811. */
  91812. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91813. /** Get the state of the verify stream decoder.
  91814. * Useful when the stream encoder state is
  91815. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91816. *
  91817. * \param encoder An encoder instance to query.
  91818. * \assert
  91819. * \code encoder != NULL \endcode
  91820. * \retval FLAC__StreamDecoderState
  91821. * The verify stream decoder state.
  91822. */
  91823. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91824. /** Get the current encoder state as a C string.
  91825. * This version automatically resolves
  91826. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91827. * verify decoder's state.
  91828. *
  91829. * \param encoder A encoder instance to query.
  91830. * \assert
  91831. * \code encoder != NULL \endcode
  91832. * \retval const char *
  91833. * The encoder state as a C string. Do not modify the contents.
  91834. */
  91835. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91836. /** Get relevant values about the nature of a verify decoder error.
  91837. * Useful when the stream encoder state is
  91838. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91839. * be addresses in which the stats will be returned, or NULL if value
  91840. * is not desired.
  91841. *
  91842. * \param encoder An encoder instance to query.
  91843. * \param absolute_sample The absolute sample number of the mismatch.
  91844. * \param frame_number The number of the frame in which the mismatch occurred.
  91845. * \param channel The channel in which the mismatch occurred.
  91846. * \param sample The number of the sample (relative to the frame) in
  91847. * which the mismatch occurred.
  91848. * \param expected The expected value for the sample in question.
  91849. * \param got The actual value returned by the decoder.
  91850. * \assert
  91851. * \code encoder != NULL \endcode
  91852. */
  91853. 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);
  91854. /** Get the "verify" flag.
  91855. *
  91856. * \param encoder An encoder instance to query.
  91857. * \assert
  91858. * \code encoder != NULL \endcode
  91859. * \retval FLAC__bool
  91860. * See FLAC__stream_encoder_set_verify().
  91861. */
  91862. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91863. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91864. *
  91865. * \param encoder An encoder instance to query.
  91866. * \assert
  91867. * \code encoder != NULL \endcode
  91868. * \retval FLAC__bool
  91869. * See FLAC__stream_encoder_set_streamable_subset().
  91870. */
  91871. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91872. /** Get the number of input channels being processed.
  91873. *
  91874. * \param encoder An encoder instance to query.
  91875. * \assert
  91876. * \code encoder != NULL \endcode
  91877. * \retval unsigned
  91878. * See FLAC__stream_encoder_set_channels().
  91879. */
  91880. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91881. /** Get the input sample resolution setting.
  91882. *
  91883. * \param encoder An encoder instance to query.
  91884. * \assert
  91885. * \code encoder != NULL \endcode
  91886. * \retval unsigned
  91887. * See FLAC__stream_encoder_set_bits_per_sample().
  91888. */
  91889. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91890. /** Get the input sample rate setting.
  91891. *
  91892. * \param encoder An encoder instance to query.
  91893. * \assert
  91894. * \code encoder != NULL \endcode
  91895. * \retval unsigned
  91896. * See FLAC__stream_encoder_set_sample_rate().
  91897. */
  91898. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91899. /** Get the blocksize setting.
  91900. *
  91901. * \param encoder An encoder instance to query.
  91902. * \assert
  91903. * \code encoder != NULL \endcode
  91904. * \retval unsigned
  91905. * See FLAC__stream_encoder_set_blocksize().
  91906. */
  91907. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91908. /** Get the "mid/side stereo coding" flag.
  91909. *
  91910. * \param encoder An encoder instance to query.
  91911. * \assert
  91912. * \code encoder != NULL \endcode
  91913. * \retval FLAC__bool
  91914. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91915. */
  91916. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91917. /** Get the "adaptive mid/side switching" flag.
  91918. *
  91919. * \param encoder An encoder instance to query.
  91920. * \assert
  91921. * \code encoder != NULL \endcode
  91922. * \retval FLAC__bool
  91923. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91924. */
  91925. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91926. /** Get the maximum LPC order setting.
  91927. *
  91928. * \param encoder An encoder instance to query.
  91929. * \assert
  91930. * \code encoder != NULL \endcode
  91931. * \retval unsigned
  91932. * See FLAC__stream_encoder_set_max_lpc_order().
  91933. */
  91934. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91935. /** Get the quantized linear predictor coefficient precision setting.
  91936. *
  91937. * \param encoder An encoder instance to query.
  91938. * \assert
  91939. * \code encoder != NULL \endcode
  91940. * \retval unsigned
  91941. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91942. */
  91943. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91944. /** Get the qlp coefficient precision search flag.
  91945. *
  91946. * \param encoder An encoder instance to query.
  91947. * \assert
  91948. * \code encoder != NULL \endcode
  91949. * \retval FLAC__bool
  91950. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91951. */
  91952. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91953. /** Get the "escape coding" flag.
  91954. *
  91955. * \param encoder An encoder instance to query.
  91956. * \assert
  91957. * \code encoder != NULL \endcode
  91958. * \retval FLAC__bool
  91959. * See FLAC__stream_encoder_set_do_escape_coding().
  91960. */
  91961. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91962. /** Get the exhaustive model search flag.
  91963. *
  91964. * \param encoder An encoder instance to query.
  91965. * \assert
  91966. * \code encoder != NULL \endcode
  91967. * \retval FLAC__bool
  91968. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91969. */
  91970. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91971. /** Get the minimum residual partition order setting.
  91972. *
  91973. * \param encoder An encoder instance to query.
  91974. * \assert
  91975. * \code encoder != NULL \endcode
  91976. * \retval unsigned
  91977. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91978. */
  91979. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91980. /** Get maximum residual partition order setting.
  91981. *
  91982. * \param encoder An encoder instance to query.
  91983. * \assert
  91984. * \code encoder != NULL \endcode
  91985. * \retval unsigned
  91986. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91987. */
  91988. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91989. /** Get the Rice parameter search distance setting.
  91990. *
  91991. * \param encoder An encoder instance to query.
  91992. * \assert
  91993. * \code encoder != NULL \endcode
  91994. * \retval unsigned
  91995. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91996. */
  91997. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91998. /** Get the previously set estimate of the total samples to be encoded.
  91999. * The encoder merely mimics back the value given to
  92000. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92001. * other way of knowing how many samples the client will encode.
  92002. *
  92003. * \param encoder An encoder instance to set.
  92004. * \assert
  92005. * \code encoder != NULL \endcode
  92006. * \retval FLAC__uint64
  92007. * See FLAC__stream_encoder_get_total_samples_estimate().
  92008. */
  92009. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92010. /** Initialize the encoder instance to encode native FLAC streams.
  92011. *
  92012. * This flavor of initialization sets up the encoder to encode to a
  92013. * native FLAC stream. I/O is performed via callbacks to the client.
  92014. * For encoding to a plain file via filename or open \c FILE*,
  92015. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92016. * provide a simpler interface.
  92017. *
  92018. * This function should be called after FLAC__stream_encoder_new() and
  92019. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92020. * or FLAC__stream_encoder_process_interleaved().
  92021. * initialization succeeded.
  92022. *
  92023. * The call to FLAC__stream_encoder_init_stream() currently will also
  92024. * immediately call the write callback several times, once with the \c fLaC
  92025. * signature, and once for each encoded metadata block.
  92026. *
  92027. * \param encoder An uninitialized encoder instance.
  92028. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92029. * pointer must not be \c NULL.
  92030. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92031. * pointer may be \c NULL if seeking is not
  92032. * supported. The encoder uses seeking to go back
  92033. * and write some some stream statistics to the
  92034. * STREAMINFO block; this is recommended but not
  92035. * necessary to create a valid FLAC stream. If
  92036. * \a seek_callback is not \c NULL then a
  92037. * \a tell_callback must also be supplied.
  92038. * Alternatively, a dummy seek callback that just
  92039. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92040. * may also be supplied, all though this is slightly
  92041. * less efficient for the encoder.
  92042. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92043. * pointer may be \c NULL if seeking is not
  92044. * supported. If \a seek_callback is \c NULL then
  92045. * this argument will be ignored. If
  92046. * \a seek_callback is not \c NULL then a
  92047. * \a tell_callback must also be supplied.
  92048. * Alternatively, a dummy tell callback that just
  92049. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92050. * may also be supplied, all though this is slightly
  92051. * less efficient for the encoder.
  92052. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92053. * pointer may be \c NULL if the callback is not
  92054. * desired. If the client provides a seek callback,
  92055. * this function is not necessary as the encoder
  92056. * will automatically seek back and update the
  92057. * STREAMINFO block. It may also be \c NULL if the
  92058. * client does not support seeking, since it will
  92059. * have no way of going back to update the
  92060. * STREAMINFO. However the client can still supply
  92061. * a callback if it would like to know the details
  92062. * from the STREAMINFO.
  92063. * \param client_data This value will be supplied to callbacks in their
  92064. * \a client_data argument.
  92065. * \assert
  92066. * \code encoder != NULL \endcode
  92067. * \retval FLAC__StreamEncoderInitStatus
  92068. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92069. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92070. */
  92071. 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);
  92072. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92073. *
  92074. * This flavor of initialization sets up the encoder to encode to a FLAC
  92075. * stream in an Ogg container. I/O is performed via callbacks to the
  92076. * client. For encoding to a plain file via filename or open \c FILE*,
  92077. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92078. * provide a simpler interface.
  92079. *
  92080. * This function should be called after FLAC__stream_encoder_new() and
  92081. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92082. * or FLAC__stream_encoder_process_interleaved().
  92083. * initialization succeeded.
  92084. *
  92085. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92086. * immediately call the write callback several times to write the metadata
  92087. * packets.
  92088. *
  92089. * \param encoder An uninitialized encoder instance.
  92090. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92091. * pointer must not be \c NULL if \a seek_callback
  92092. * is non-NULL since they are both needed to be
  92093. * able to write data back to the Ogg FLAC stream
  92094. * in the post-encode phase.
  92095. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92096. * pointer must not be \c NULL.
  92097. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92098. * pointer may be \c NULL if seeking is not
  92099. * supported. The encoder uses seeking to go back
  92100. * and write some some stream statistics to the
  92101. * STREAMINFO block; this is recommended but not
  92102. * necessary to create a valid FLAC stream. If
  92103. * \a seek_callback is not \c NULL then a
  92104. * \a tell_callback must also be supplied.
  92105. * Alternatively, a dummy seek callback that just
  92106. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92107. * may also be supplied, all though this is slightly
  92108. * less efficient for the encoder.
  92109. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92110. * pointer may be \c NULL if seeking is not
  92111. * supported. If \a seek_callback is \c NULL then
  92112. * this argument will be ignored. If
  92113. * \a seek_callback is not \c NULL then a
  92114. * \a tell_callback must also be supplied.
  92115. * Alternatively, a dummy tell callback that just
  92116. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92117. * may also be supplied, all though this is slightly
  92118. * less efficient for the encoder.
  92119. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92120. * pointer may be \c NULL if the callback is not
  92121. * desired. If the client provides a seek callback,
  92122. * this function is not necessary as the encoder
  92123. * will automatically seek back and update the
  92124. * STREAMINFO block. It may also be \c NULL if the
  92125. * client does not support seeking, since it will
  92126. * have no way of going back to update the
  92127. * STREAMINFO. However the client can still supply
  92128. * a callback if it would like to know the details
  92129. * from the STREAMINFO.
  92130. * \param client_data This value will be supplied to callbacks in their
  92131. * \a client_data argument.
  92132. * \assert
  92133. * \code encoder != NULL \endcode
  92134. * \retval FLAC__StreamEncoderInitStatus
  92135. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92136. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92137. */
  92138. 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);
  92139. /** Initialize the encoder instance to encode native FLAC files.
  92140. *
  92141. * This flavor of initialization sets up the encoder to encode to a
  92142. * plain native FLAC file. For non-stdio streams, you must use
  92143. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92144. *
  92145. * This function should be called after FLAC__stream_encoder_new() and
  92146. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92147. * or FLAC__stream_encoder_process_interleaved().
  92148. * initialization succeeded.
  92149. *
  92150. * \param encoder An uninitialized encoder instance.
  92151. * \param file An open file. The file should have been opened
  92152. * with mode \c "w+b" and rewound. The file
  92153. * becomes owned by the encoder and should not be
  92154. * manipulated by the client while encoding.
  92155. * Unless \a file is \c stdout, it will be closed
  92156. * when FLAC__stream_encoder_finish() is called.
  92157. * Note however that a proper SEEKTABLE cannot be
  92158. * created when encoding to \c stdout since it is
  92159. * not seekable.
  92160. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92161. * pointer may be \c NULL if the callback is not
  92162. * desired.
  92163. * \param client_data This value will be supplied to callbacks in their
  92164. * \a client_data argument.
  92165. * \assert
  92166. * \code encoder != NULL \endcode
  92167. * \code file != NULL \endcode
  92168. * \retval FLAC__StreamEncoderInitStatus
  92169. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92170. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92171. */
  92172. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92173. /** Initialize the encoder instance to encode Ogg FLAC files.
  92174. *
  92175. * This flavor of initialization sets up the encoder to encode to a
  92176. * plain Ogg FLAC file. For non-stdio streams, you must use
  92177. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92178. *
  92179. * This function should be called after FLAC__stream_encoder_new() and
  92180. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92181. * or FLAC__stream_encoder_process_interleaved().
  92182. * initialization succeeded.
  92183. *
  92184. * \param encoder An uninitialized encoder instance.
  92185. * \param file An open file. The file should have been opened
  92186. * with mode \c "w+b" and rewound. The file
  92187. * becomes owned by the encoder and should not be
  92188. * manipulated by the client while encoding.
  92189. * Unless \a file is \c stdout, it will be closed
  92190. * when FLAC__stream_encoder_finish() is called.
  92191. * Note however that a proper SEEKTABLE cannot be
  92192. * created when encoding to \c stdout since it is
  92193. * not seekable.
  92194. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92195. * pointer may be \c NULL if the callback is not
  92196. * desired.
  92197. * \param client_data This value will be supplied to callbacks in their
  92198. * \a client_data argument.
  92199. * \assert
  92200. * \code encoder != NULL \endcode
  92201. * \code file != NULL \endcode
  92202. * \retval FLAC__StreamEncoderInitStatus
  92203. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92204. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92205. */
  92206. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92207. /** Initialize the encoder instance to encode native FLAC files.
  92208. *
  92209. * This flavor of initialization sets up the encoder to encode to a plain
  92210. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92211. * with Unicode filenames on Windows), you must use
  92212. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92213. * and provide callbacks for the I/O.
  92214. *
  92215. * This function should be called after FLAC__stream_encoder_new() and
  92216. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92217. * or FLAC__stream_encoder_process_interleaved().
  92218. * initialization succeeded.
  92219. *
  92220. * \param encoder An uninitialized encoder instance.
  92221. * \param filename The name of the file to encode to. The file will
  92222. * be opened with fopen(). Use \c NULL to encode to
  92223. * \c stdout. Note however that a proper SEEKTABLE
  92224. * cannot be created when encoding to \c stdout since
  92225. * it is not seekable.
  92226. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92227. * pointer may be \c NULL if the callback is not
  92228. * desired.
  92229. * \param client_data This value will be supplied to callbacks in their
  92230. * \a client_data argument.
  92231. * \assert
  92232. * \code encoder != NULL \endcode
  92233. * \retval FLAC__StreamEncoderInitStatus
  92234. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92235. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92236. */
  92237. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92238. /** Initialize the encoder instance to encode Ogg FLAC files.
  92239. *
  92240. * This flavor of initialization sets up the encoder to encode to a plain
  92241. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92242. * with Unicode filenames on Windows), you must use
  92243. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92244. * and provide callbacks for the I/O.
  92245. *
  92246. * This function should be called after FLAC__stream_encoder_new() and
  92247. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92248. * or FLAC__stream_encoder_process_interleaved().
  92249. * initialization succeeded.
  92250. *
  92251. * \param encoder An uninitialized encoder instance.
  92252. * \param filename The name of the file to encode to. The file will
  92253. * be opened with fopen(). Use \c NULL to encode to
  92254. * \c stdout. Note however that a proper SEEKTABLE
  92255. * cannot be created when encoding to \c stdout since
  92256. * it is not seekable.
  92257. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92258. * pointer may be \c NULL if the callback is not
  92259. * desired.
  92260. * \param client_data This value will be supplied to callbacks in their
  92261. * \a client_data argument.
  92262. * \assert
  92263. * \code encoder != NULL \endcode
  92264. * \retval FLAC__StreamEncoderInitStatus
  92265. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92266. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92267. */
  92268. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92269. /** Finish the encoding process.
  92270. * Flushes the encoding buffer, releases resources, resets the encoder
  92271. * settings to their defaults, and returns the encoder state to
  92272. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92273. * one or more write callbacks before returning, and will generate
  92274. * a metadata callback.
  92275. *
  92276. * Note that in the course of processing the last frame, errors can
  92277. * occur, so the caller should be sure to check the return value to
  92278. * ensure the file was encoded properly.
  92279. *
  92280. * In the event of a prematurely-terminated encode, it is not strictly
  92281. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92282. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92283. * with a FLAC__stream_encoder_finish().
  92284. *
  92285. * \param encoder An uninitialized encoder instance.
  92286. * \assert
  92287. * \code encoder != NULL \endcode
  92288. * \retval FLAC__bool
  92289. * \c false if an error occurred processing the last frame; or if verify
  92290. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92291. * verify mismatch; else \c true. If \c false, caller should check the
  92292. * state with FLAC__stream_encoder_get_state() for more information
  92293. * about the error.
  92294. */
  92295. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92296. /** Submit data for encoding.
  92297. * This version allows you to supply the input data via an array of
  92298. * pointers, each pointer pointing to an array of \a samples samples
  92299. * representing one channel. The samples need not be block-aligned,
  92300. * but each channel should have the same number of samples. Each sample
  92301. * should be a signed integer, right-justified to the resolution set by
  92302. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92303. * resolution is 16 bits per sample, the samples should all be in the
  92304. * range [-32768,32767].
  92305. *
  92306. * For applications where channel order is important, channels must
  92307. * follow the order as described in the
  92308. * <A HREF="../format.html#frame_header">frame header</A>.
  92309. *
  92310. * \param encoder An initialized encoder instance in the OK state.
  92311. * \param buffer An array of pointers to each channel's signal.
  92312. * \param samples The number of samples in one channel.
  92313. * \assert
  92314. * \code encoder != NULL \endcode
  92315. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92316. * \retval FLAC__bool
  92317. * \c true if successful, else \c false; in this case, check the
  92318. * encoder state with FLAC__stream_encoder_get_state() to see what
  92319. * went wrong.
  92320. */
  92321. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92322. /** Submit data for encoding.
  92323. * This version allows you to supply the input data where the channels
  92324. * are interleaved into a single array (i.e. channel0_sample0,
  92325. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92326. * The samples need not be block-aligned but they must be
  92327. * sample-aligned, i.e. the first value should be channel0_sample0
  92328. * and the last value channelN_sampleM. Each sample should be a signed
  92329. * integer, right-justified to the resolution set by
  92330. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92331. * resolution is 16 bits per sample, the samples should all be in the
  92332. * range [-32768,32767].
  92333. *
  92334. * For applications where channel order is important, channels must
  92335. * follow the order as described in the
  92336. * <A HREF="../format.html#frame_header">frame header</A>.
  92337. *
  92338. * \param encoder An initialized encoder instance in the OK state.
  92339. * \param buffer An array of channel-interleaved data (see above).
  92340. * \param samples The number of samples in one channel, the same as for
  92341. * FLAC__stream_encoder_process(). For example, if
  92342. * encoding two channels, \c 1000 \a samples corresponds
  92343. * to a \a buffer of 2000 values.
  92344. * \assert
  92345. * \code encoder != NULL \endcode
  92346. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92347. * \retval FLAC__bool
  92348. * \c true if successful, else \c false; in this case, check the
  92349. * encoder state with FLAC__stream_encoder_get_state() to see what
  92350. * went wrong.
  92351. */
  92352. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92353. /* \} */
  92354. #ifdef __cplusplus
  92355. }
  92356. #endif
  92357. #endif
  92358. /*** End of inlined file: stream_encoder.h ***/
  92359. #ifdef _MSC_VER
  92360. /* OPT: an MSVC built-in would be better */
  92361. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92362. {
  92363. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92364. return (x>>16) | (x<<16);
  92365. }
  92366. #endif
  92367. #if defined(_MSC_VER) && defined(_X86_)
  92368. /* OPT: an MSVC built-in would be better */
  92369. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92370. {
  92371. __asm {
  92372. mov edx, start
  92373. mov ecx, len
  92374. test ecx, ecx
  92375. loop1:
  92376. jz done1
  92377. mov eax, [edx]
  92378. bswap eax
  92379. mov [edx], eax
  92380. add edx, 4
  92381. dec ecx
  92382. jmp short loop1
  92383. done1:
  92384. }
  92385. }
  92386. #endif
  92387. /** \mainpage
  92388. *
  92389. * \section intro Introduction
  92390. *
  92391. * This is the documentation for the FLAC C and C++ APIs. It is
  92392. * highly interconnected; this introduction should give you a top
  92393. * level idea of the structure and how to find the information you
  92394. * need. As a prerequisite you should have at least a basic
  92395. * knowledge of the FLAC format, documented
  92396. * <A HREF="../format.html">here</A>.
  92397. *
  92398. * \section c_api FLAC C API
  92399. *
  92400. * The FLAC C API is the interface to libFLAC, a set of structures
  92401. * describing the components of FLAC streams, and functions for
  92402. * encoding and decoding streams, as well as manipulating FLAC
  92403. * metadata in files. The public include files will be installed
  92404. * in your include area (for example /usr/include/FLAC/...).
  92405. *
  92406. * By writing a little code and linking against libFLAC, it is
  92407. * relatively easy to add FLAC support to another program. The
  92408. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92409. * Complete source code of libFLAC as well as the command-line
  92410. * encoder and plugins is available and is a useful source of
  92411. * examples.
  92412. *
  92413. * Aside from encoders and decoders, libFLAC provides a powerful
  92414. * metadata interface for manipulating metadata in FLAC files. It
  92415. * allows the user to add, delete, and modify FLAC metadata blocks
  92416. * and it can automatically take advantage of PADDING blocks to avoid
  92417. * rewriting the entire FLAC file when changing the size of the
  92418. * metadata.
  92419. *
  92420. * libFLAC usually only requires the standard C library and C math
  92421. * library. In particular, threading is not used so there is no
  92422. * dependency on a thread library. However, libFLAC does not use
  92423. * global variables and should be thread-safe.
  92424. *
  92425. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92426. * However the metadata editing interfaces currently have limited
  92427. * read-only support for Ogg FLAC files.
  92428. *
  92429. * \section cpp_api FLAC C++ API
  92430. *
  92431. * The FLAC C++ API is a set of classes that encapsulate the
  92432. * structures and functions in libFLAC. They provide slightly more
  92433. * functionality with respect to metadata but are otherwise
  92434. * equivalent. For the most part, they share the same usage as
  92435. * their counterparts in libFLAC, and the FLAC C API documentation
  92436. * can be used as a supplement. The public include files
  92437. * for the C++ API will be installed in your include area (for
  92438. * example /usr/include/FLAC++/...).
  92439. *
  92440. * libFLAC++ is also licensed under
  92441. * <A HREF="../license.html">Xiph's BSD license</A>.
  92442. *
  92443. * \section getting_started Getting Started
  92444. *
  92445. * A good starting point for learning the API is to browse through
  92446. * the <A HREF="modules.html">modules</A>. Modules are logical
  92447. * groupings of related functions or classes, which correspond roughly
  92448. * to header files or sections of header files. Each module includes a
  92449. * detailed description of the general usage of its functions or
  92450. * classes.
  92451. *
  92452. * From there you can go on to look at the documentation of
  92453. * individual functions. You can see different views of the individual
  92454. * functions through the links in top bar across this page.
  92455. *
  92456. * If you prefer a more hands-on approach, you can jump right to some
  92457. * <A HREF="../documentation_example_code.html">example code</A>.
  92458. *
  92459. * \section porting_guide Porting Guide
  92460. *
  92461. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92462. * has been introduced which gives detailed instructions on how to
  92463. * port your code to newer versions of FLAC.
  92464. *
  92465. * \section embedded_developers Embedded Developers
  92466. *
  92467. * libFLAC has grown larger over time as more functionality has been
  92468. * included, but much of it may be unnecessary for a particular embedded
  92469. * implementation. Unused parts may be pruned by some simple editing of
  92470. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92471. * metadata interface are all independent from each other.
  92472. *
  92473. * It is easiest to just describe the dependencies:
  92474. *
  92475. * - All modules depend on the \link flac_format Format \endlink module.
  92476. * - The decoders and encoders depend on the bitbuffer.
  92477. * - The decoder is independent of the encoder. The encoder uses the
  92478. * decoder because of the verify feature, but this can be removed if
  92479. * not needed.
  92480. * - Parts of the metadata interface require the stream decoder (but not
  92481. * the encoder).
  92482. * - Ogg support is selectable through the compile time macro
  92483. * \c FLAC__HAS_OGG.
  92484. *
  92485. * For example, if your application only requires the stream decoder, no
  92486. * encoder, and no metadata interface, you can remove the stream encoder
  92487. * and the metadata interface, which will greatly reduce the size of the
  92488. * library.
  92489. *
  92490. * Also, there are several places in the libFLAC code with comments marked
  92491. * with "OPT:" where a #define can be changed to enable code that might be
  92492. * faster on a specific platform. Experimenting with these can yield faster
  92493. * binaries.
  92494. */
  92495. /** \defgroup porting Porting Guide for New Versions
  92496. *
  92497. * This module describes differences in the library interfaces from
  92498. * version to version. It assists in the porting of code that uses
  92499. * the libraries to newer versions of FLAC.
  92500. *
  92501. * One simple facility for making porting easier that has been added
  92502. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92503. * library's includes (e.g. \c include/FLAC/export.h). The
  92504. * \c #defines mirror the libraries'
  92505. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92506. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92507. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92508. * These can be used to support multiple versions of an API during the
  92509. * transition phase, e.g.
  92510. *
  92511. * \code
  92512. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92513. * legacy code
  92514. * #else
  92515. * new code
  92516. * #endif
  92517. * \endcode
  92518. *
  92519. * The the source will work for multiple versions and the legacy code can
  92520. * easily be removed when the transition is complete.
  92521. *
  92522. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92523. * include/FLAC/export.h), which can be used to determine whether or not
  92524. * the library has been compiled with support for Ogg FLAC. This is
  92525. * simpler than trying to call an Ogg init function and catching the
  92526. * error.
  92527. */
  92528. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92529. * \ingroup porting
  92530. *
  92531. * \brief
  92532. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92533. *
  92534. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92535. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92536. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92537. * decoding layers and three encoding layers have been merged into a
  92538. * single stream decoder and stream encoder. That is, the functionality
  92539. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92540. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92541. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92542. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92543. * is there is now a single API that can be used to encode or decode
  92544. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92545. * on both seekable and non-seekable streams.
  92546. *
  92547. * Instead of creating an encoder or decoder of a certain layer, now the
  92548. * client will always create a FLAC__StreamEncoder or
  92549. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92550. * initialization function. For example, for the decoder,
  92551. * FLAC__stream_decoder_init() has been replaced by
  92552. * FLAC__stream_decoder_init_stream(). This init function takes
  92553. * callbacks for the I/O, and the seeking callbacks are optional. This
  92554. * allows the client to use the same object for seekable and
  92555. * non-seekable streams. For decoding a FLAC file directly, the client
  92556. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92557. * and fewer callbacks; most of the other callbacks are supplied
  92558. * internally. For situations where fopen()ing by filename is not
  92559. * possible (e.g. Unicode filenames on Windows) the client can instead
  92560. * open the file itself and supply the FILE* to
  92561. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92562. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92563. * Since the callbacks and client data are now passed to the init
  92564. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92565. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92566. * rest of the calls to the decoder are the same as before.
  92567. *
  92568. * There are counterpart init functions for Ogg FLAC, e.g.
  92569. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92570. * and callbacks are the same as for native FLAC.
  92571. *
  92572. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92573. * been set up like so:
  92574. *
  92575. * \code
  92576. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92577. * if(decoder == NULL) do_something;
  92578. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92579. * [... other settings ...]
  92580. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92581. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92582. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92583. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92584. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92585. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92586. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92587. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92588. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92589. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92590. * \endcode
  92591. *
  92592. * In FLAC 1.1.3 it is like this:
  92593. *
  92594. * \code
  92595. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92596. * if(decoder == NULL) do_something;
  92597. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92598. * [... other settings ...]
  92599. * if(FLAC__stream_decoder_init_stream(
  92600. * decoder,
  92601. * my_read_callback,
  92602. * my_seek_callback, // or NULL
  92603. * my_tell_callback, // or NULL
  92604. * my_length_callback, // or NULL
  92605. * my_eof_callback, // or NULL
  92606. * my_write_callback,
  92607. * my_metadata_callback, // or NULL
  92608. * my_error_callback,
  92609. * my_client_data
  92610. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92611. * \endcode
  92612. *
  92613. * or you could do;
  92614. *
  92615. * \code
  92616. * [...]
  92617. * FILE *file = fopen("somefile.flac","rb");
  92618. * if(file == NULL) do_somthing;
  92619. * if(FLAC__stream_decoder_init_FILE(
  92620. * decoder,
  92621. * file,
  92622. * my_write_callback,
  92623. * my_metadata_callback, // or NULL
  92624. * my_error_callback,
  92625. * my_client_data
  92626. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92627. * \endcode
  92628. *
  92629. * or just:
  92630. *
  92631. * \code
  92632. * [...]
  92633. * if(FLAC__stream_decoder_init_file(
  92634. * decoder,
  92635. * "somefile.flac",
  92636. * my_write_callback,
  92637. * my_metadata_callback, // or NULL
  92638. * my_error_callback,
  92639. * my_client_data
  92640. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92641. * \endcode
  92642. *
  92643. * Another small change to the decoder is in how it handles unparseable
  92644. * streams. Before, when the decoder found an unparseable stream
  92645. * (reserved for when the decoder encounters a stream from a future
  92646. * encoder that it can't parse), it changed the state to
  92647. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92648. * drops sync and calls the error callback with a new error code
  92649. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92650. * more robust. If your error callback does not discriminate on the the
  92651. * error state, your code does not need to be changed.
  92652. *
  92653. * The encoder now has a new setting:
  92654. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92655. * method used to window the data before LPC analysis. You only need to
  92656. * add a call to this function if the default is not suitable. There
  92657. * are also two new convenience functions that may be useful:
  92658. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92659. * FLAC__metadata_get_cuesheet().
  92660. *
  92661. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92662. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92663. * is now \c size_t instead of \c unsigned.
  92664. */
  92665. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92666. * \ingroup porting
  92667. *
  92668. * \brief
  92669. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92670. *
  92671. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92672. * There was a slight change in the implementation of
  92673. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92674. * of the \a metadata array of pointers so the client no longer needs
  92675. * to maintain it after the call. The objects themselves that are
  92676. * pointed to by the array are still not copied though and must be
  92677. * maintained until the call to FLAC__stream_encoder_finish().
  92678. */
  92679. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92680. * \ingroup porting
  92681. *
  92682. * \brief
  92683. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92684. *
  92685. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92686. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92687. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92688. *
  92689. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92690. * has changed to reflect the conversion of one of the reserved bits
  92691. * into active use. It used to be \c 2 and now is \c 1. However the
  92692. * FLAC frame header length has not changed, so to skip the proper
  92693. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92694. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92695. */
  92696. /** \defgroup flac FLAC C API
  92697. *
  92698. * The FLAC C API is the interface to libFLAC, a set of structures
  92699. * describing the components of FLAC streams, and functions for
  92700. * encoding and decoding streams, as well as manipulating FLAC
  92701. * metadata in files.
  92702. *
  92703. * You should start with the format components as all other modules
  92704. * are dependent on it.
  92705. */
  92706. #endif
  92707. /*** End of inlined file: all.h ***/
  92708. /*** Start of inlined file: bitmath.c ***/
  92709. /*** Start of inlined file: juce_FlacHeader.h ***/
  92710. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92711. // tasks..
  92712. #define VERSION "1.2.1"
  92713. #define FLAC__NO_DLL 1
  92714. #if JUCE_MSVC
  92715. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92716. #endif
  92717. #if JUCE_MAC
  92718. #define FLAC__SYS_DARWIN 1
  92719. #endif
  92720. /*** End of inlined file: juce_FlacHeader.h ***/
  92721. #if JUCE_USE_FLAC
  92722. #if HAVE_CONFIG_H
  92723. # include <config.h>
  92724. #endif
  92725. /*** Start of inlined file: bitmath.h ***/
  92726. #ifndef FLAC__PRIVATE__BITMATH_H
  92727. #define FLAC__PRIVATE__BITMATH_H
  92728. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92729. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92730. unsigned FLAC__bitmath_silog2(int v);
  92731. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92732. #endif
  92733. /*** End of inlined file: bitmath.h ***/
  92734. /* An example of what FLAC__bitmath_ilog2() computes:
  92735. *
  92736. * ilog2( 0) = assertion failure
  92737. * ilog2( 1) = 0
  92738. * ilog2( 2) = 1
  92739. * ilog2( 3) = 1
  92740. * ilog2( 4) = 2
  92741. * ilog2( 5) = 2
  92742. * ilog2( 6) = 2
  92743. * ilog2( 7) = 2
  92744. * ilog2( 8) = 3
  92745. * ilog2( 9) = 3
  92746. * ilog2(10) = 3
  92747. * ilog2(11) = 3
  92748. * ilog2(12) = 3
  92749. * ilog2(13) = 3
  92750. * ilog2(14) = 3
  92751. * ilog2(15) = 3
  92752. * ilog2(16) = 4
  92753. * ilog2(17) = 4
  92754. * ilog2(18) = 4
  92755. */
  92756. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92757. {
  92758. unsigned l = 0;
  92759. FLAC__ASSERT(v > 0);
  92760. while(v >>= 1)
  92761. l++;
  92762. return l;
  92763. }
  92764. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92765. {
  92766. unsigned l = 0;
  92767. FLAC__ASSERT(v > 0);
  92768. while(v >>= 1)
  92769. l++;
  92770. return l;
  92771. }
  92772. /* An example of what FLAC__bitmath_silog2() computes:
  92773. *
  92774. * silog2(-10) = 5
  92775. * silog2(- 9) = 5
  92776. * silog2(- 8) = 4
  92777. * silog2(- 7) = 4
  92778. * silog2(- 6) = 4
  92779. * silog2(- 5) = 4
  92780. * silog2(- 4) = 3
  92781. * silog2(- 3) = 3
  92782. * silog2(- 2) = 2
  92783. * silog2(- 1) = 2
  92784. * silog2( 0) = 0
  92785. * silog2( 1) = 2
  92786. * silog2( 2) = 3
  92787. * silog2( 3) = 3
  92788. * silog2( 4) = 4
  92789. * silog2( 5) = 4
  92790. * silog2( 6) = 4
  92791. * silog2( 7) = 4
  92792. * silog2( 8) = 5
  92793. * silog2( 9) = 5
  92794. * silog2( 10) = 5
  92795. */
  92796. unsigned FLAC__bitmath_silog2(int v)
  92797. {
  92798. while(1) {
  92799. if(v == 0) {
  92800. return 0;
  92801. }
  92802. else if(v > 0) {
  92803. unsigned l = 0;
  92804. while(v) {
  92805. l++;
  92806. v >>= 1;
  92807. }
  92808. return l+1;
  92809. }
  92810. else if(v == -1) {
  92811. return 2;
  92812. }
  92813. else {
  92814. v++;
  92815. v = -v;
  92816. }
  92817. }
  92818. }
  92819. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92820. {
  92821. while(1) {
  92822. if(v == 0) {
  92823. return 0;
  92824. }
  92825. else if(v > 0) {
  92826. unsigned l = 0;
  92827. while(v) {
  92828. l++;
  92829. v >>= 1;
  92830. }
  92831. return l+1;
  92832. }
  92833. else if(v == -1) {
  92834. return 2;
  92835. }
  92836. else {
  92837. v++;
  92838. v = -v;
  92839. }
  92840. }
  92841. }
  92842. #endif
  92843. /*** End of inlined file: bitmath.c ***/
  92844. /*** Start of inlined file: bitreader.c ***/
  92845. /*** Start of inlined file: juce_FlacHeader.h ***/
  92846. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92847. // tasks..
  92848. #define VERSION "1.2.1"
  92849. #define FLAC__NO_DLL 1
  92850. #if JUCE_MSVC
  92851. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92852. #endif
  92853. #if JUCE_MAC
  92854. #define FLAC__SYS_DARWIN 1
  92855. #endif
  92856. /*** End of inlined file: juce_FlacHeader.h ***/
  92857. #if JUCE_USE_FLAC
  92858. #if HAVE_CONFIG_H
  92859. # include <config.h>
  92860. #endif
  92861. #include <stdlib.h> /* for malloc() */
  92862. #include <string.h> /* for memcpy(), memset() */
  92863. #ifdef _MSC_VER
  92864. #include <winsock.h> /* for ntohl() */
  92865. #elif defined FLAC__SYS_DARWIN
  92866. #include <machine/endian.h> /* for ntohl() */
  92867. #elif defined __MINGW32__
  92868. #include <winsock.h> /* for ntohl() */
  92869. #else
  92870. #include <netinet/in.h> /* for ntohl() */
  92871. #endif
  92872. /*** Start of inlined file: bitreader.h ***/
  92873. #ifndef FLAC__PRIVATE__BITREADER_H
  92874. #define FLAC__PRIVATE__BITREADER_H
  92875. #include <stdio.h> /* for FILE */
  92876. /*** Start of inlined file: cpu.h ***/
  92877. #ifndef FLAC__PRIVATE__CPU_H
  92878. #define FLAC__PRIVATE__CPU_H
  92879. #ifdef HAVE_CONFIG_H
  92880. #include <config.h>
  92881. #endif
  92882. typedef enum {
  92883. FLAC__CPUINFO_TYPE_IA32,
  92884. FLAC__CPUINFO_TYPE_PPC,
  92885. FLAC__CPUINFO_TYPE_UNKNOWN
  92886. } FLAC__CPUInfo_Type;
  92887. typedef struct {
  92888. FLAC__bool cpuid;
  92889. FLAC__bool bswap;
  92890. FLAC__bool cmov;
  92891. FLAC__bool mmx;
  92892. FLAC__bool fxsr;
  92893. FLAC__bool sse;
  92894. FLAC__bool sse2;
  92895. FLAC__bool sse3;
  92896. FLAC__bool ssse3;
  92897. FLAC__bool _3dnow;
  92898. FLAC__bool ext3dnow;
  92899. FLAC__bool extmmx;
  92900. } FLAC__CPUInfo_IA32;
  92901. typedef struct {
  92902. FLAC__bool altivec;
  92903. FLAC__bool ppc64;
  92904. } FLAC__CPUInfo_PPC;
  92905. typedef struct {
  92906. FLAC__bool use_asm;
  92907. FLAC__CPUInfo_Type type;
  92908. union {
  92909. FLAC__CPUInfo_IA32 ia32;
  92910. FLAC__CPUInfo_PPC ppc;
  92911. } data;
  92912. } FLAC__CPUInfo;
  92913. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92914. #ifndef FLAC__NO_ASM
  92915. #ifdef FLAC__CPU_IA32
  92916. #ifdef FLAC__HAS_NASM
  92917. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92918. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92919. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92920. #endif
  92921. #endif
  92922. #endif
  92923. #endif
  92924. /*** End of inlined file: cpu.h ***/
  92925. /*
  92926. * opaque structure definition
  92927. */
  92928. struct FLAC__BitReader;
  92929. typedef struct FLAC__BitReader FLAC__BitReader;
  92930. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92931. /*
  92932. * construction, deletion, initialization, etc functions
  92933. */
  92934. FLAC__BitReader *FLAC__bitreader_new(void);
  92935. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92936. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92937. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92938. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92939. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92940. /*
  92941. * CRC functions
  92942. */
  92943. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92944. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92945. /*
  92946. * info functions
  92947. */
  92948. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92949. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92950. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92951. /*
  92952. * read functions
  92953. */
  92954. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92955. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92956. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92957. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92958. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92959. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92960. 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! */
  92961. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92962. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92963. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92964. #ifndef FLAC__NO_ASM
  92965. # ifdef FLAC__CPU_IA32
  92966. # ifdef FLAC__HAS_NASM
  92967. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92968. # endif
  92969. # endif
  92970. #endif
  92971. #if 0 /* UNUSED */
  92972. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92973. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92974. #endif
  92975. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92976. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92977. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92978. #endif
  92979. /*** End of inlined file: bitreader.h ***/
  92980. /*** Start of inlined file: crc.h ***/
  92981. #ifndef FLAC__PRIVATE__CRC_H
  92982. #define FLAC__PRIVATE__CRC_H
  92983. /* 8 bit CRC generator, MSB shifted first
  92984. ** polynomial = x^8 + x^2 + x^1 + x^0
  92985. ** init = 0
  92986. */
  92987. extern FLAC__byte const FLAC__crc8_table[256];
  92988. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92989. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92990. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92991. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92992. /* 16 bit CRC generator, MSB shifted first
  92993. ** polynomial = x^16 + x^15 + x^2 + x^0
  92994. ** init = 0
  92995. */
  92996. extern unsigned FLAC__crc16_table[256];
  92997. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92998. /* this alternate may be faster on some systems/compilers */
  92999. #if 0
  93000. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93001. #endif
  93002. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93003. #endif
  93004. /*** End of inlined file: crc.h ***/
  93005. /* Things should be fastest when this matches the machine word size */
  93006. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93007. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93008. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93009. typedef FLAC__uint32 brword;
  93010. #define FLAC__BYTES_PER_WORD 4
  93011. #define FLAC__BITS_PER_WORD 32
  93012. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93013. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93014. #if WORDS_BIGENDIAN
  93015. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93016. #else
  93017. #if defined (_MSC_VER) && defined (_X86_)
  93018. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93019. #else
  93020. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93021. #endif
  93022. #endif
  93023. /* counts the # of zero MSBs in a word */
  93024. #define COUNT_ZERO_MSBS(word) ( \
  93025. (word) <= 0xffff ? \
  93026. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93027. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93028. )
  93029. /* this alternate might be slightly faster on some systems/compilers: */
  93030. #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])) )
  93031. /*
  93032. * This should be at least twice as large as the largest number of words
  93033. * required to represent any 'number' (in any encoding) you are going to
  93034. * read. With FLAC this is on the order of maybe a few hundred bits.
  93035. * If the buffer is smaller than that, the decoder won't be able to read
  93036. * in a whole number that is in a variable length encoding (e.g. Rice).
  93037. * But to be practical it should be at least 1K bytes.
  93038. *
  93039. * Increase this number to decrease the number of read callbacks, at the
  93040. * expense of using more memory. Or decrease for the reverse effect,
  93041. * keeping in mind the limit from the first paragraph. The optimal size
  93042. * also depends on the CPU cache size and other factors; some twiddling
  93043. * may be necessary to squeeze out the best performance.
  93044. */
  93045. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93046. static const unsigned char byte_to_unary_table[] = {
  93047. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93048. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93049. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93050. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93051. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93052. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93053. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93054. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93063. };
  93064. #ifdef min
  93065. #undef min
  93066. #endif
  93067. #define min(x,y) ((x)<(y)?(x):(y))
  93068. #ifdef max
  93069. #undef max
  93070. #endif
  93071. #define max(x,y) ((x)>(y)?(x):(y))
  93072. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93073. #ifdef _MSC_VER
  93074. #define FLAC__U64L(x) x
  93075. #else
  93076. #define FLAC__U64L(x) x##LLU
  93077. #endif
  93078. #ifndef FLaC__INLINE
  93079. #define FLaC__INLINE
  93080. #endif
  93081. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93082. struct FLAC__BitReader {
  93083. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93084. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93085. brword *buffer;
  93086. unsigned capacity; /* in words */
  93087. unsigned words; /* # of completed words in buffer */
  93088. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93089. unsigned consumed_words; /* #words ... */
  93090. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93091. unsigned read_crc16; /* the running frame CRC */
  93092. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93093. FLAC__BitReaderReadCallback read_callback;
  93094. void *client_data;
  93095. FLAC__CPUInfo cpu_info;
  93096. };
  93097. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93098. {
  93099. register unsigned crc = br->read_crc16;
  93100. #if FLAC__BYTES_PER_WORD == 4
  93101. switch(br->crc16_align) {
  93102. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93103. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93104. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93105. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93106. }
  93107. #elif FLAC__BYTES_PER_WORD == 8
  93108. switch(br->crc16_align) {
  93109. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93110. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93111. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93112. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93113. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93114. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93115. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93116. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93117. }
  93118. #else
  93119. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93120. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93121. br->read_crc16 = crc;
  93122. #endif
  93123. br->crc16_align = 0;
  93124. }
  93125. /* would be static except it needs to be called by asm routines */
  93126. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93127. {
  93128. unsigned start, end;
  93129. size_t bytes;
  93130. FLAC__byte *target;
  93131. /* first shift the unconsumed buffer data toward the front as much as possible */
  93132. if(br->consumed_words > 0) {
  93133. start = br->consumed_words;
  93134. end = br->words + (br->bytes? 1:0);
  93135. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93136. br->words -= start;
  93137. br->consumed_words = 0;
  93138. }
  93139. /*
  93140. * set the target for reading, taking into account word alignment and endianness
  93141. */
  93142. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93143. if(bytes == 0)
  93144. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93145. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93146. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93147. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93148. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93149. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93150. * ^^-------target, bytes=3
  93151. * on LE machines, have to byteswap the odd tail word so nothing is
  93152. * overwritten:
  93153. */
  93154. #if WORDS_BIGENDIAN
  93155. #else
  93156. if(br->bytes)
  93157. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93158. #endif
  93159. /* now it looks like:
  93160. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93161. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93162. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93163. * ^^-------target, bytes=3
  93164. */
  93165. /* read in the data; note that the callback may return a smaller number of bytes */
  93166. if(!br->read_callback(target, &bytes, br->client_data))
  93167. return false;
  93168. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93169. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93170. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93171. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93172. * now have to byteswap on LE machines:
  93173. */
  93174. #if WORDS_BIGENDIAN
  93175. #else
  93176. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93177. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93178. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93179. start = br->words;
  93180. local_swap32_block_(br->buffer + start, end - start);
  93181. }
  93182. else
  93183. # endif
  93184. for(start = br->words; start < end; start++)
  93185. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93186. #endif
  93187. /* now it looks like:
  93188. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93189. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93190. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93191. * finally we'll update the reader values:
  93192. */
  93193. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93194. br->words = end / FLAC__BYTES_PER_WORD;
  93195. br->bytes = end % FLAC__BYTES_PER_WORD;
  93196. return true;
  93197. }
  93198. /***********************************************************************
  93199. *
  93200. * Class constructor/destructor
  93201. *
  93202. ***********************************************************************/
  93203. FLAC__BitReader *FLAC__bitreader_new(void)
  93204. {
  93205. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93206. /* calloc() implies:
  93207. memset(br, 0, sizeof(FLAC__BitReader));
  93208. br->buffer = 0;
  93209. br->capacity = 0;
  93210. br->words = br->bytes = 0;
  93211. br->consumed_words = br->consumed_bits = 0;
  93212. br->read_callback = 0;
  93213. br->client_data = 0;
  93214. */
  93215. return br;
  93216. }
  93217. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93218. {
  93219. FLAC__ASSERT(0 != br);
  93220. FLAC__bitreader_free(br);
  93221. free(br);
  93222. }
  93223. /***********************************************************************
  93224. *
  93225. * Public class methods
  93226. *
  93227. ***********************************************************************/
  93228. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93229. {
  93230. FLAC__ASSERT(0 != br);
  93231. br->words = br->bytes = 0;
  93232. br->consumed_words = br->consumed_bits = 0;
  93233. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93234. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93235. if(br->buffer == 0)
  93236. return false;
  93237. br->read_callback = rcb;
  93238. br->client_data = cd;
  93239. br->cpu_info = cpu;
  93240. return true;
  93241. }
  93242. void FLAC__bitreader_free(FLAC__BitReader *br)
  93243. {
  93244. FLAC__ASSERT(0 != br);
  93245. if(0 != br->buffer)
  93246. free(br->buffer);
  93247. br->buffer = 0;
  93248. br->capacity = 0;
  93249. br->words = br->bytes = 0;
  93250. br->consumed_words = br->consumed_bits = 0;
  93251. br->read_callback = 0;
  93252. br->client_data = 0;
  93253. }
  93254. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93255. {
  93256. br->words = br->bytes = 0;
  93257. br->consumed_words = br->consumed_bits = 0;
  93258. return true;
  93259. }
  93260. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93261. {
  93262. unsigned i, j;
  93263. if(br == 0) {
  93264. fprintf(out, "bitreader is NULL\n");
  93265. }
  93266. else {
  93267. 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);
  93268. for(i = 0; i < br->words; i++) {
  93269. fprintf(out, "%08X: ", i);
  93270. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93271. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93272. fprintf(out, ".");
  93273. else
  93274. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93275. fprintf(out, "\n");
  93276. }
  93277. if(br->bytes > 0) {
  93278. fprintf(out, "%08X: ", i);
  93279. for(j = 0; j < br->bytes*8; j++)
  93280. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93281. fprintf(out, ".");
  93282. else
  93283. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93284. fprintf(out, "\n");
  93285. }
  93286. }
  93287. }
  93288. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93289. {
  93290. FLAC__ASSERT(0 != br);
  93291. FLAC__ASSERT(0 != br->buffer);
  93292. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93293. br->read_crc16 = (unsigned)seed;
  93294. br->crc16_align = br->consumed_bits;
  93295. }
  93296. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93297. {
  93298. FLAC__ASSERT(0 != br);
  93299. FLAC__ASSERT(0 != br->buffer);
  93300. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93301. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93302. /* CRC any tail bytes in a partially-consumed word */
  93303. if(br->consumed_bits) {
  93304. const brword tail = br->buffer[br->consumed_words];
  93305. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93306. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93307. }
  93308. return br->read_crc16;
  93309. }
  93310. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93311. {
  93312. return ((br->consumed_bits & 7) == 0);
  93313. }
  93314. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93315. {
  93316. return 8 - (br->consumed_bits & 7);
  93317. }
  93318. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93319. {
  93320. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93321. }
  93322. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93323. {
  93324. FLAC__ASSERT(0 != br);
  93325. FLAC__ASSERT(0 != br->buffer);
  93326. FLAC__ASSERT(bits <= 32);
  93327. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93328. FLAC__ASSERT(br->consumed_words <= br->words);
  93329. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93330. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93331. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93332. *val = 0;
  93333. return true;
  93334. }
  93335. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93336. if(!bitreader_read_from_client_(br))
  93337. return false;
  93338. }
  93339. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93340. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93341. if(br->consumed_bits) {
  93342. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93343. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93344. const brword word = br->buffer[br->consumed_words];
  93345. if(bits < n) {
  93346. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93347. br->consumed_bits += bits;
  93348. return true;
  93349. }
  93350. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93351. bits -= n;
  93352. crc16_update_word_(br, word);
  93353. br->consumed_words++;
  93354. br->consumed_bits = 0;
  93355. 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 */
  93356. *val <<= bits;
  93357. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93358. br->consumed_bits = bits;
  93359. }
  93360. return true;
  93361. }
  93362. else {
  93363. const brword word = br->buffer[br->consumed_words];
  93364. if(bits < FLAC__BITS_PER_WORD) {
  93365. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93366. br->consumed_bits = bits;
  93367. return true;
  93368. }
  93369. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93370. *val = word;
  93371. crc16_update_word_(br, word);
  93372. br->consumed_words++;
  93373. return true;
  93374. }
  93375. }
  93376. else {
  93377. /* in this case we're starting our read at a partial tail word;
  93378. * the reader has guaranteed that we have at least 'bits' bits
  93379. * available to read, which makes this case simpler.
  93380. */
  93381. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93382. if(br->consumed_bits) {
  93383. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93384. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93385. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93386. br->consumed_bits += bits;
  93387. return true;
  93388. }
  93389. else {
  93390. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93391. br->consumed_bits += bits;
  93392. return true;
  93393. }
  93394. }
  93395. }
  93396. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93397. {
  93398. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93399. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93400. return false;
  93401. /* sign-extend: */
  93402. *val <<= (32-bits);
  93403. *val >>= (32-bits);
  93404. return true;
  93405. }
  93406. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93407. {
  93408. FLAC__uint32 hi, lo;
  93409. if(bits > 32) {
  93410. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93411. return false;
  93412. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93413. return false;
  93414. *val = hi;
  93415. *val <<= 32;
  93416. *val |= lo;
  93417. }
  93418. else {
  93419. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93420. return false;
  93421. *val = lo;
  93422. }
  93423. return true;
  93424. }
  93425. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93426. {
  93427. FLAC__uint32 x8, x32 = 0;
  93428. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93429. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93430. return false;
  93431. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93432. return false;
  93433. x32 |= (x8 << 8);
  93434. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93435. return false;
  93436. x32 |= (x8 << 16);
  93437. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93438. return false;
  93439. x32 |= (x8 << 24);
  93440. *val = x32;
  93441. return true;
  93442. }
  93443. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93444. {
  93445. /*
  93446. * OPT: a faster implementation is possible but probably not that useful
  93447. * since this is only called a couple of times in the metadata readers.
  93448. */
  93449. FLAC__ASSERT(0 != br);
  93450. FLAC__ASSERT(0 != br->buffer);
  93451. if(bits > 0) {
  93452. const unsigned n = br->consumed_bits & 7;
  93453. unsigned m;
  93454. FLAC__uint32 x;
  93455. if(n != 0) {
  93456. m = min(8-n, bits);
  93457. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93458. return false;
  93459. bits -= m;
  93460. }
  93461. m = bits / 8;
  93462. if(m > 0) {
  93463. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93464. return false;
  93465. bits %= 8;
  93466. }
  93467. if(bits > 0) {
  93468. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93469. return false;
  93470. }
  93471. }
  93472. return true;
  93473. }
  93474. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93475. {
  93476. FLAC__uint32 x;
  93477. FLAC__ASSERT(0 != br);
  93478. FLAC__ASSERT(0 != br->buffer);
  93479. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93480. /* step 1: skip over partial head word to get word aligned */
  93481. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93482. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93483. return false;
  93484. nvals--;
  93485. }
  93486. if(0 == nvals)
  93487. return true;
  93488. /* step 2: skip whole words in chunks */
  93489. while(nvals >= FLAC__BYTES_PER_WORD) {
  93490. if(br->consumed_words < br->words) {
  93491. br->consumed_words++;
  93492. nvals -= FLAC__BYTES_PER_WORD;
  93493. }
  93494. else if(!bitreader_read_from_client_(br))
  93495. return false;
  93496. }
  93497. /* step 3: skip any remainder from partial tail bytes */
  93498. while(nvals) {
  93499. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93500. return false;
  93501. nvals--;
  93502. }
  93503. return true;
  93504. }
  93505. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93506. {
  93507. FLAC__uint32 x;
  93508. FLAC__ASSERT(0 != br);
  93509. FLAC__ASSERT(0 != br->buffer);
  93510. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93511. /* step 1: read from partial head word to get word aligned */
  93512. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93513. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93514. return false;
  93515. *val++ = (FLAC__byte)x;
  93516. nvals--;
  93517. }
  93518. if(0 == nvals)
  93519. return true;
  93520. /* step 2: read whole words in chunks */
  93521. while(nvals >= FLAC__BYTES_PER_WORD) {
  93522. if(br->consumed_words < br->words) {
  93523. const brword word = br->buffer[br->consumed_words++];
  93524. #if FLAC__BYTES_PER_WORD == 4
  93525. val[0] = (FLAC__byte)(word >> 24);
  93526. val[1] = (FLAC__byte)(word >> 16);
  93527. val[2] = (FLAC__byte)(word >> 8);
  93528. val[3] = (FLAC__byte)word;
  93529. #elif FLAC__BYTES_PER_WORD == 8
  93530. val[0] = (FLAC__byte)(word >> 56);
  93531. val[1] = (FLAC__byte)(word >> 48);
  93532. val[2] = (FLAC__byte)(word >> 40);
  93533. val[3] = (FLAC__byte)(word >> 32);
  93534. val[4] = (FLAC__byte)(word >> 24);
  93535. val[5] = (FLAC__byte)(word >> 16);
  93536. val[6] = (FLAC__byte)(word >> 8);
  93537. val[7] = (FLAC__byte)word;
  93538. #else
  93539. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93540. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93541. #endif
  93542. val += FLAC__BYTES_PER_WORD;
  93543. nvals -= FLAC__BYTES_PER_WORD;
  93544. }
  93545. else if(!bitreader_read_from_client_(br))
  93546. return false;
  93547. }
  93548. /* step 3: read any remainder from partial tail bytes */
  93549. while(nvals) {
  93550. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93551. return false;
  93552. *val++ = (FLAC__byte)x;
  93553. nvals--;
  93554. }
  93555. return true;
  93556. }
  93557. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93558. #if 0 /* slow but readable version */
  93559. {
  93560. unsigned bit;
  93561. FLAC__ASSERT(0 != br);
  93562. FLAC__ASSERT(0 != br->buffer);
  93563. *val = 0;
  93564. while(1) {
  93565. if(!FLAC__bitreader_read_bit(br, &bit))
  93566. return false;
  93567. if(bit)
  93568. break;
  93569. else
  93570. *val++;
  93571. }
  93572. return true;
  93573. }
  93574. #else
  93575. {
  93576. unsigned i;
  93577. FLAC__ASSERT(0 != br);
  93578. FLAC__ASSERT(0 != br->buffer);
  93579. *val = 0;
  93580. while(1) {
  93581. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93582. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93583. if(b) {
  93584. i = COUNT_ZERO_MSBS(b);
  93585. *val += i;
  93586. i++;
  93587. br->consumed_bits += i;
  93588. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93589. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93590. br->consumed_words++;
  93591. br->consumed_bits = 0;
  93592. }
  93593. return true;
  93594. }
  93595. else {
  93596. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93597. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93598. br->consumed_words++;
  93599. br->consumed_bits = 0;
  93600. /* didn't find stop bit yet, have to keep going... */
  93601. }
  93602. }
  93603. /* at this point we've eaten up all the whole words; have to try
  93604. * reading through any tail bytes before calling the read callback.
  93605. * this is a repeat of the above logic adjusted for the fact we
  93606. * don't have a whole word. note though if the client is feeding
  93607. * us data a byte at a time (unlikely), br->consumed_bits may not
  93608. * be zero.
  93609. */
  93610. if(br->bytes) {
  93611. const unsigned end = br->bytes * 8;
  93612. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93613. if(b) {
  93614. i = COUNT_ZERO_MSBS(b);
  93615. *val += i;
  93616. i++;
  93617. br->consumed_bits += i;
  93618. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93619. return true;
  93620. }
  93621. else {
  93622. *val += end - br->consumed_bits;
  93623. br->consumed_bits += end;
  93624. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93625. /* didn't find stop bit yet, have to keep going... */
  93626. }
  93627. }
  93628. if(!bitreader_read_from_client_(br))
  93629. return false;
  93630. }
  93631. }
  93632. #endif
  93633. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93634. {
  93635. FLAC__uint32 lsbs = 0, msbs = 0;
  93636. unsigned uval;
  93637. FLAC__ASSERT(0 != br);
  93638. FLAC__ASSERT(0 != br->buffer);
  93639. FLAC__ASSERT(parameter <= 31);
  93640. /* read the unary MSBs and end bit */
  93641. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93642. return false;
  93643. /* read the binary LSBs */
  93644. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93645. return false;
  93646. /* compose the value */
  93647. uval = (msbs << parameter) | lsbs;
  93648. if(uval & 1)
  93649. *val = -((int)(uval >> 1)) - 1;
  93650. else
  93651. *val = (int)(uval >> 1);
  93652. return true;
  93653. }
  93654. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93655. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93656. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93657. /* OPT: possibly faster version for use with MSVC */
  93658. #ifdef _MSC_VER
  93659. {
  93660. unsigned i;
  93661. unsigned uval = 0;
  93662. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93663. /* try and get br->consumed_words and br->consumed_bits into register;
  93664. * must remember to flush them back to *br before calling other
  93665. * bitwriter functions that use them, and before returning */
  93666. register unsigned cwords;
  93667. register unsigned cbits;
  93668. FLAC__ASSERT(0 != br);
  93669. FLAC__ASSERT(0 != br->buffer);
  93670. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93671. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93672. FLAC__ASSERT(parameter < 32);
  93673. /* 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 */
  93674. if(nvals == 0)
  93675. return true;
  93676. cbits = br->consumed_bits;
  93677. cwords = br->consumed_words;
  93678. while(1) {
  93679. /* read unary part */
  93680. while(1) {
  93681. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93682. brword b = br->buffer[cwords] << cbits;
  93683. if(b) {
  93684. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93685. __asm {
  93686. bsr eax, b
  93687. not eax
  93688. and eax, 31
  93689. mov i, eax
  93690. }
  93691. #else
  93692. i = COUNT_ZERO_MSBS(b);
  93693. #endif
  93694. uval += i;
  93695. bits = parameter;
  93696. i++;
  93697. cbits += i;
  93698. if(cbits == FLAC__BITS_PER_WORD) {
  93699. crc16_update_word_(br, br->buffer[cwords]);
  93700. cwords++;
  93701. cbits = 0;
  93702. }
  93703. goto break1;
  93704. }
  93705. else {
  93706. uval += FLAC__BITS_PER_WORD - cbits;
  93707. crc16_update_word_(br, br->buffer[cwords]);
  93708. cwords++;
  93709. cbits = 0;
  93710. /* didn't find stop bit yet, have to keep going... */
  93711. }
  93712. }
  93713. /* at this point we've eaten up all the whole words; have to try
  93714. * reading through any tail bytes before calling the read callback.
  93715. * this is a repeat of the above logic adjusted for the fact we
  93716. * don't have a whole word. note though if the client is feeding
  93717. * us data a byte at a time (unlikely), br->consumed_bits may not
  93718. * be zero.
  93719. */
  93720. if(br->bytes) {
  93721. const unsigned end = br->bytes * 8;
  93722. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93723. if(b) {
  93724. i = COUNT_ZERO_MSBS(b);
  93725. uval += i;
  93726. bits = parameter;
  93727. i++;
  93728. cbits += i;
  93729. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93730. goto break1;
  93731. }
  93732. else {
  93733. uval += end - cbits;
  93734. cbits += end;
  93735. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93736. /* didn't find stop bit yet, have to keep going... */
  93737. }
  93738. }
  93739. /* flush registers and read; bitreader_read_from_client_() does
  93740. * not touch br->consumed_bits at all but we still need to set
  93741. * it in case it fails and we have to return false.
  93742. */
  93743. br->consumed_bits = cbits;
  93744. br->consumed_words = cwords;
  93745. if(!bitreader_read_from_client_(br))
  93746. return false;
  93747. cwords = br->consumed_words;
  93748. }
  93749. break1:
  93750. /* read binary part */
  93751. FLAC__ASSERT(cwords <= br->words);
  93752. if(bits) {
  93753. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93754. /* flush registers and read; bitreader_read_from_client_() does
  93755. * not touch br->consumed_bits at all but we still need to set
  93756. * it in case it fails and we have to return false.
  93757. */
  93758. br->consumed_bits = cbits;
  93759. br->consumed_words = cwords;
  93760. if(!bitreader_read_from_client_(br))
  93761. return false;
  93762. cwords = br->consumed_words;
  93763. }
  93764. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93765. if(cbits) {
  93766. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93767. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93768. const brword word = br->buffer[cwords];
  93769. if(bits < n) {
  93770. uval <<= bits;
  93771. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93772. cbits += bits;
  93773. goto break2;
  93774. }
  93775. uval <<= n;
  93776. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93777. bits -= n;
  93778. crc16_update_word_(br, word);
  93779. cwords++;
  93780. cbits = 0;
  93781. 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 */
  93782. uval <<= bits;
  93783. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93784. cbits = bits;
  93785. }
  93786. goto break2;
  93787. }
  93788. else {
  93789. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93790. uval <<= bits;
  93791. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93792. cbits = bits;
  93793. goto break2;
  93794. }
  93795. }
  93796. else {
  93797. /* in this case we're starting our read at a partial tail word;
  93798. * the reader has guaranteed that we have at least 'bits' bits
  93799. * available to read, which makes this case simpler.
  93800. */
  93801. uval <<= bits;
  93802. if(cbits) {
  93803. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93804. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93805. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93806. cbits += bits;
  93807. goto break2;
  93808. }
  93809. else {
  93810. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93811. cbits += bits;
  93812. goto break2;
  93813. }
  93814. }
  93815. }
  93816. break2:
  93817. /* compose the value */
  93818. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93819. /* are we done? */
  93820. --nvals;
  93821. if(nvals == 0) {
  93822. br->consumed_bits = cbits;
  93823. br->consumed_words = cwords;
  93824. return true;
  93825. }
  93826. uval = 0;
  93827. ++vals;
  93828. }
  93829. }
  93830. #else
  93831. {
  93832. unsigned i;
  93833. unsigned uval = 0;
  93834. /* try and get br->consumed_words and br->consumed_bits into register;
  93835. * must remember to flush them back to *br before calling other
  93836. * bitwriter functions that use them, and before returning */
  93837. register unsigned cwords;
  93838. register unsigned cbits;
  93839. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93840. FLAC__ASSERT(0 != br);
  93841. FLAC__ASSERT(0 != br->buffer);
  93842. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93843. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93844. FLAC__ASSERT(parameter < 32);
  93845. /* 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 */
  93846. if(nvals == 0)
  93847. return true;
  93848. cbits = br->consumed_bits;
  93849. cwords = br->consumed_words;
  93850. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93851. while(1) {
  93852. /* read unary part */
  93853. while(1) {
  93854. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93855. brword b = br->buffer[cwords] << cbits;
  93856. if(b) {
  93857. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93858. asm volatile (
  93859. "bsrl %1, %0;"
  93860. "notl %0;"
  93861. "andl $31, %0;"
  93862. : "=r"(i)
  93863. : "r"(b)
  93864. );
  93865. #else
  93866. i = COUNT_ZERO_MSBS(b);
  93867. #endif
  93868. uval += i;
  93869. cbits += i;
  93870. cbits++; /* skip over stop bit */
  93871. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93872. crc16_update_word_(br, br->buffer[cwords]);
  93873. cwords++;
  93874. cbits = 0;
  93875. }
  93876. goto break1;
  93877. }
  93878. else {
  93879. uval += FLAC__BITS_PER_WORD - cbits;
  93880. crc16_update_word_(br, br->buffer[cwords]);
  93881. cwords++;
  93882. cbits = 0;
  93883. /* didn't find stop bit yet, have to keep going... */
  93884. }
  93885. }
  93886. /* at this point we've eaten up all the whole words; have to try
  93887. * reading through any tail bytes before calling the read callback.
  93888. * this is a repeat of the above logic adjusted for the fact we
  93889. * don't have a whole word. note though if the client is feeding
  93890. * us data a byte at a time (unlikely), br->consumed_bits may not
  93891. * be zero.
  93892. */
  93893. if(br->bytes) {
  93894. const unsigned end = br->bytes * 8;
  93895. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93896. if(b) {
  93897. i = COUNT_ZERO_MSBS(b);
  93898. uval += i;
  93899. cbits += i;
  93900. cbits++; /* skip over stop bit */
  93901. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93902. goto break1;
  93903. }
  93904. else {
  93905. uval += end - cbits;
  93906. cbits += end;
  93907. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93908. /* didn't find stop bit yet, have to keep going... */
  93909. }
  93910. }
  93911. /* flush registers and read; bitreader_read_from_client_() does
  93912. * not touch br->consumed_bits at all but we still need to set
  93913. * it in case it fails and we have to return false.
  93914. */
  93915. br->consumed_bits = cbits;
  93916. br->consumed_words = cwords;
  93917. if(!bitreader_read_from_client_(br))
  93918. return false;
  93919. cwords = br->consumed_words;
  93920. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93921. /* + uval to offset our count by the # of unary bits already
  93922. * consumed before the read, because we will add these back
  93923. * in all at once at break1
  93924. */
  93925. }
  93926. break1:
  93927. ucbits -= uval;
  93928. ucbits--; /* account for stop bit */
  93929. /* read binary part */
  93930. FLAC__ASSERT(cwords <= br->words);
  93931. if(parameter) {
  93932. while(ucbits < parameter) {
  93933. /* flush registers and read; bitreader_read_from_client_() does
  93934. * not touch br->consumed_bits at all but we still need to set
  93935. * it in case it fails and we have to return false.
  93936. */
  93937. br->consumed_bits = cbits;
  93938. br->consumed_words = cwords;
  93939. if(!bitreader_read_from_client_(br))
  93940. return false;
  93941. cwords = br->consumed_words;
  93942. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93943. }
  93944. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93945. if(cbits) {
  93946. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93947. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93948. const brword word = br->buffer[cwords];
  93949. if(parameter < n) {
  93950. uval <<= parameter;
  93951. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93952. cbits += parameter;
  93953. }
  93954. else {
  93955. uval <<= n;
  93956. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93957. crc16_update_word_(br, word);
  93958. cwords++;
  93959. cbits = parameter - n;
  93960. 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 */
  93961. uval <<= cbits;
  93962. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93963. }
  93964. }
  93965. }
  93966. else {
  93967. cbits = parameter;
  93968. uval <<= parameter;
  93969. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93970. }
  93971. }
  93972. else {
  93973. /* in this case we're starting our read at a partial tail word;
  93974. * the reader has guaranteed that we have at least 'parameter'
  93975. * bits available to read, which makes this case simpler.
  93976. */
  93977. uval <<= parameter;
  93978. if(cbits) {
  93979. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93980. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93981. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93982. cbits += parameter;
  93983. }
  93984. else {
  93985. cbits = parameter;
  93986. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93987. }
  93988. }
  93989. }
  93990. ucbits -= parameter;
  93991. /* compose the value */
  93992. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93993. /* are we done? */
  93994. --nvals;
  93995. if(nvals == 0) {
  93996. br->consumed_bits = cbits;
  93997. br->consumed_words = cwords;
  93998. return true;
  93999. }
  94000. uval = 0;
  94001. ++vals;
  94002. }
  94003. }
  94004. #endif
  94005. #if 0 /* UNUSED */
  94006. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94007. {
  94008. FLAC__uint32 lsbs = 0, msbs = 0;
  94009. unsigned bit, uval, k;
  94010. FLAC__ASSERT(0 != br);
  94011. FLAC__ASSERT(0 != br->buffer);
  94012. k = FLAC__bitmath_ilog2(parameter);
  94013. /* read the unary MSBs and end bit */
  94014. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94015. return false;
  94016. /* read the binary LSBs */
  94017. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94018. return false;
  94019. if(parameter == 1u<<k) {
  94020. /* compose the value */
  94021. uval = (msbs << k) | lsbs;
  94022. }
  94023. else {
  94024. unsigned d = (1 << (k+1)) - parameter;
  94025. if(lsbs >= d) {
  94026. if(!FLAC__bitreader_read_bit(br, &bit))
  94027. return false;
  94028. lsbs <<= 1;
  94029. lsbs |= bit;
  94030. lsbs -= d;
  94031. }
  94032. /* compose the value */
  94033. uval = msbs * parameter + lsbs;
  94034. }
  94035. /* unfold unsigned to signed */
  94036. if(uval & 1)
  94037. *val = -((int)(uval >> 1)) - 1;
  94038. else
  94039. *val = (int)(uval >> 1);
  94040. return true;
  94041. }
  94042. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94043. {
  94044. FLAC__uint32 lsbs, msbs = 0;
  94045. unsigned bit, k;
  94046. FLAC__ASSERT(0 != br);
  94047. FLAC__ASSERT(0 != br->buffer);
  94048. k = FLAC__bitmath_ilog2(parameter);
  94049. /* read the unary MSBs and end bit */
  94050. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94051. return false;
  94052. /* read the binary LSBs */
  94053. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94054. return false;
  94055. if(parameter == 1u<<k) {
  94056. /* compose the value */
  94057. *val = (msbs << k) | lsbs;
  94058. }
  94059. else {
  94060. unsigned d = (1 << (k+1)) - parameter;
  94061. if(lsbs >= d) {
  94062. if(!FLAC__bitreader_read_bit(br, &bit))
  94063. return false;
  94064. lsbs <<= 1;
  94065. lsbs |= bit;
  94066. lsbs -= d;
  94067. }
  94068. /* compose the value */
  94069. *val = msbs * parameter + lsbs;
  94070. }
  94071. return true;
  94072. }
  94073. #endif /* UNUSED */
  94074. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94075. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94076. {
  94077. FLAC__uint32 v = 0;
  94078. FLAC__uint32 x;
  94079. unsigned i;
  94080. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94081. return false;
  94082. if(raw)
  94083. raw[(*rawlen)++] = (FLAC__byte)x;
  94084. if(!(x & 0x80)) { /* 0xxxxxxx */
  94085. v = x;
  94086. i = 0;
  94087. }
  94088. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94089. v = x & 0x1F;
  94090. i = 1;
  94091. }
  94092. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94093. v = x & 0x0F;
  94094. i = 2;
  94095. }
  94096. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94097. v = x & 0x07;
  94098. i = 3;
  94099. }
  94100. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94101. v = x & 0x03;
  94102. i = 4;
  94103. }
  94104. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94105. v = x & 0x01;
  94106. i = 5;
  94107. }
  94108. else {
  94109. *val = 0xffffffff;
  94110. return true;
  94111. }
  94112. for( ; i; i--) {
  94113. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94114. return false;
  94115. if(raw)
  94116. raw[(*rawlen)++] = (FLAC__byte)x;
  94117. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94118. *val = 0xffffffff;
  94119. return true;
  94120. }
  94121. v <<= 6;
  94122. v |= (x & 0x3F);
  94123. }
  94124. *val = v;
  94125. return true;
  94126. }
  94127. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94128. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94129. {
  94130. FLAC__uint64 v = 0;
  94131. FLAC__uint32 x;
  94132. unsigned i;
  94133. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94134. return false;
  94135. if(raw)
  94136. raw[(*rawlen)++] = (FLAC__byte)x;
  94137. if(!(x & 0x80)) { /* 0xxxxxxx */
  94138. v = x;
  94139. i = 0;
  94140. }
  94141. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94142. v = x & 0x1F;
  94143. i = 1;
  94144. }
  94145. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94146. v = x & 0x0F;
  94147. i = 2;
  94148. }
  94149. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94150. v = x & 0x07;
  94151. i = 3;
  94152. }
  94153. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94154. v = x & 0x03;
  94155. i = 4;
  94156. }
  94157. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94158. v = x & 0x01;
  94159. i = 5;
  94160. }
  94161. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94162. v = 0;
  94163. i = 6;
  94164. }
  94165. else {
  94166. *val = FLAC__U64L(0xffffffffffffffff);
  94167. return true;
  94168. }
  94169. for( ; i; i--) {
  94170. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94171. return false;
  94172. if(raw)
  94173. raw[(*rawlen)++] = (FLAC__byte)x;
  94174. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94175. *val = FLAC__U64L(0xffffffffffffffff);
  94176. return true;
  94177. }
  94178. v <<= 6;
  94179. v |= (x & 0x3F);
  94180. }
  94181. *val = v;
  94182. return true;
  94183. }
  94184. #endif
  94185. /*** End of inlined file: bitreader.c ***/
  94186. /*** Start of inlined file: bitwriter.c ***/
  94187. /*** Start of inlined file: juce_FlacHeader.h ***/
  94188. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94189. // tasks..
  94190. #define VERSION "1.2.1"
  94191. #define FLAC__NO_DLL 1
  94192. #if JUCE_MSVC
  94193. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94194. #endif
  94195. #if JUCE_MAC
  94196. #define FLAC__SYS_DARWIN 1
  94197. #endif
  94198. /*** End of inlined file: juce_FlacHeader.h ***/
  94199. #if JUCE_USE_FLAC
  94200. #if HAVE_CONFIG_H
  94201. # include <config.h>
  94202. #endif
  94203. #include <stdlib.h> /* for malloc() */
  94204. #include <string.h> /* for memcpy(), memset() */
  94205. #ifdef _MSC_VER
  94206. #include <winsock.h> /* for ntohl() */
  94207. #elif defined FLAC__SYS_DARWIN
  94208. #include <machine/endian.h> /* for ntohl() */
  94209. #elif defined __MINGW32__
  94210. #include <winsock.h> /* for ntohl() */
  94211. #else
  94212. #include <netinet/in.h> /* for ntohl() */
  94213. #endif
  94214. #if 0 /* UNUSED */
  94215. #endif
  94216. /*** Start of inlined file: bitwriter.h ***/
  94217. #ifndef FLAC__PRIVATE__BITWRITER_H
  94218. #define FLAC__PRIVATE__BITWRITER_H
  94219. #include <stdio.h> /* for FILE */
  94220. /*
  94221. * opaque structure definition
  94222. */
  94223. struct FLAC__BitWriter;
  94224. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94225. /*
  94226. * construction, deletion, initialization, etc functions
  94227. */
  94228. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94229. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94230. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94231. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94232. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94233. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94234. /*
  94235. * CRC functions
  94236. *
  94237. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94238. */
  94239. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94240. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94241. /*
  94242. * info functions
  94243. */
  94244. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94245. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94246. /*
  94247. * direct buffer access
  94248. *
  94249. * there may be no calls on the bitwriter between get and release.
  94250. * the bitwriter continues to own the returned buffer.
  94251. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94252. */
  94253. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94254. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94255. /*
  94256. * write functions
  94257. */
  94258. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94259. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94260. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94261. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94262. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94263. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94264. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94265. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94266. #if 0 /* UNUSED */
  94267. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94268. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94269. #endif
  94270. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94271. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94272. #if 0 /* UNUSED */
  94273. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94274. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94275. #endif
  94276. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94277. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94278. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94279. #endif
  94280. /*** End of inlined file: bitwriter.h ***/
  94281. /*** Start of inlined file: alloc.h ***/
  94282. #ifndef FLAC__SHARE__ALLOC_H
  94283. #define FLAC__SHARE__ALLOC_H
  94284. #if HAVE_CONFIG_H
  94285. # include <config.h>
  94286. #endif
  94287. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94288. * before #including this file, otherwise SIZE_MAX might not be defined
  94289. */
  94290. #include <limits.h> /* for SIZE_MAX */
  94291. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94292. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94293. #endif
  94294. #include <stdlib.h> /* for size_t, malloc(), etc */
  94295. #ifndef SIZE_MAX
  94296. # ifndef SIZE_T_MAX
  94297. # ifdef _MSC_VER
  94298. # define SIZE_T_MAX UINT_MAX
  94299. # else
  94300. # error
  94301. # endif
  94302. # endif
  94303. # define SIZE_MAX SIZE_T_MAX
  94304. #endif
  94305. #ifndef FLaC__INLINE
  94306. #define FLaC__INLINE
  94307. #endif
  94308. /* avoid malloc()ing 0 bytes, see:
  94309. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94310. */
  94311. static FLaC__INLINE void *safe_malloc_(size_t size)
  94312. {
  94313. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94314. if(!size)
  94315. size++;
  94316. return malloc(size);
  94317. }
  94318. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94319. {
  94320. if(!nmemb || !size)
  94321. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94322. return calloc(nmemb, size);
  94323. }
  94324. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94325. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94326. {
  94327. size2 += size1;
  94328. if(size2 < size1)
  94329. return 0;
  94330. return safe_malloc_(size2);
  94331. }
  94332. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94333. {
  94334. size2 += size1;
  94335. if(size2 < size1)
  94336. return 0;
  94337. size3 += size2;
  94338. if(size3 < size2)
  94339. return 0;
  94340. return safe_malloc_(size3);
  94341. }
  94342. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94343. {
  94344. size2 += size1;
  94345. if(size2 < size1)
  94346. return 0;
  94347. size3 += size2;
  94348. if(size3 < size2)
  94349. return 0;
  94350. size4 += size3;
  94351. if(size4 < size3)
  94352. return 0;
  94353. return safe_malloc_(size4);
  94354. }
  94355. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94356. #if 0
  94357. needs support for cases where sizeof(size_t) != 4
  94358. {
  94359. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94360. if(sizeof(size_t) == 4) {
  94361. if ((double)size1 * (double)size2 < 4294967296.0)
  94362. return malloc(size1*size2);
  94363. }
  94364. return 0;
  94365. }
  94366. #else
  94367. /* better? */
  94368. {
  94369. if(!size1 || !size2)
  94370. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94371. if(size1 > SIZE_MAX / size2)
  94372. return 0;
  94373. return malloc(size1*size2);
  94374. }
  94375. #endif
  94376. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94377. {
  94378. if(!size1 || !size2 || !size3)
  94379. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94380. if(size1 > SIZE_MAX / size2)
  94381. return 0;
  94382. size1 *= size2;
  94383. if(size1 > SIZE_MAX / size3)
  94384. return 0;
  94385. return malloc(size1*size3);
  94386. }
  94387. /* size1*size2 + size3 */
  94388. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94389. {
  94390. if(!size1 || !size2)
  94391. return safe_malloc_(size3);
  94392. if(size1 > SIZE_MAX / size2)
  94393. return 0;
  94394. return safe_malloc_add_2op_(size1*size2, size3);
  94395. }
  94396. /* size1 * (size2 + size3) */
  94397. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94398. {
  94399. if(!size1 || (!size2 && !size3))
  94400. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94401. size2 += size3;
  94402. if(size2 < size3)
  94403. return 0;
  94404. return safe_malloc_mul_2op_(size1, size2);
  94405. }
  94406. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94407. {
  94408. size2 += size1;
  94409. if(size2 < size1)
  94410. return 0;
  94411. return realloc(ptr, size2);
  94412. }
  94413. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94414. {
  94415. size2 += size1;
  94416. if(size2 < size1)
  94417. return 0;
  94418. size3 += size2;
  94419. if(size3 < size2)
  94420. return 0;
  94421. return realloc(ptr, size3);
  94422. }
  94423. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94424. {
  94425. size2 += size1;
  94426. if(size2 < size1)
  94427. return 0;
  94428. size3 += size2;
  94429. if(size3 < size2)
  94430. return 0;
  94431. size4 += size3;
  94432. if(size4 < size3)
  94433. return 0;
  94434. return realloc(ptr, size4);
  94435. }
  94436. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94437. {
  94438. if(!size1 || !size2)
  94439. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94440. if(size1 > SIZE_MAX / size2)
  94441. return 0;
  94442. return realloc(ptr, size1*size2);
  94443. }
  94444. /* size1 * (size2 + size3) */
  94445. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94446. {
  94447. if(!size1 || (!size2 && !size3))
  94448. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94449. size2 += size3;
  94450. if(size2 < size3)
  94451. return 0;
  94452. return safe_realloc_mul_2op_(ptr, size1, size2);
  94453. }
  94454. #endif
  94455. /*** End of inlined file: alloc.h ***/
  94456. /* Things should be fastest when this matches the machine word size */
  94457. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94458. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94459. typedef FLAC__uint32 bwword;
  94460. #define FLAC__BYTES_PER_WORD 4
  94461. #define FLAC__BITS_PER_WORD 32
  94462. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94463. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94464. #if WORDS_BIGENDIAN
  94465. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94466. #else
  94467. #ifdef _MSC_VER
  94468. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94469. #else
  94470. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94471. #endif
  94472. #endif
  94473. /*
  94474. * The default capacity here doesn't matter too much. The buffer always grows
  94475. * to hold whatever is written to it. Usually the encoder will stop adding at
  94476. * a frame or metadata block, then write that out and clear the buffer for the
  94477. * next one.
  94478. */
  94479. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94480. /* When growing, increment 4K at a time */
  94481. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94482. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94483. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94484. #ifdef min
  94485. #undef min
  94486. #endif
  94487. #define min(x,y) ((x)<(y)?(x):(y))
  94488. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94489. #ifdef _MSC_VER
  94490. #define FLAC__U64L(x) x
  94491. #else
  94492. #define FLAC__U64L(x) x##LLU
  94493. #endif
  94494. #ifndef FLaC__INLINE
  94495. #define FLaC__INLINE
  94496. #endif
  94497. struct FLAC__BitWriter {
  94498. bwword *buffer;
  94499. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94500. unsigned capacity; /* capacity of buffer in words */
  94501. unsigned words; /* # of complete words in buffer */
  94502. unsigned bits; /* # of used bits in accum */
  94503. };
  94504. /* * WATCHOUT: The current implementation only grows the buffer. */
  94505. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94506. {
  94507. unsigned new_capacity;
  94508. bwword *new_buffer;
  94509. FLAC__ASSERT(0 != bw);
  94510. FLAC__ASSERT(0 != bw->buffer);
  94511. /* calculate total words needed to store 'bits_to_add' additional bits */
  94512. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94513. /* it's possible (due to pessimism in the growth estimation that
  94514. * leads to this call) that we don't actually need to grow
  94515. */
  94516. if(bw->capacity >= new_capacity)
  94517. return true;
  94518. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94519. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94520. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94521. /* make sure we got everything right */
  94522. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94523. FLAC__ASSERT(new_capacity > bw->capacity);
  94524. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94525. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94526. if(new_buffer == 0)
  94527. return false;
  94528. bw->buffer = new_buffer;
  94529. bw->capacity = new_capacity;
  94530. return true;
  94531. }
  94532. /***********************************************************************
  94533. *
  94534. * Class constructor/destructor
  94535. *
  94536. ***********************************************************************/
  94537. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94538. {
  94539. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94540. /* note that calloc() sets all members to 0 for us */
  94541. return bw;
  94542. }
  94543. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94544. {
  94545. FLAC__ASSERT(0 != bw);
  94546. FLAC__bitwriter_free(bw);
  94547. free(bw);
  94548. }
  94549. /***********************************************************************
  94550. *
  94551. * Public class methods
  94552. *
  94553. ***********************************************************************/
  94554. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94555. {
  94556. FLAC__ASSERT(0 != bw);
  94557. bw->words = bw->bits = 0;
  94558. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94559. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94560. if(bw->buffer == 0)
  94561. return false;
  94562. return true;
  94563. }
  94564. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94565. {
  94566. FLAC__ASSERT(0 != bw);
  94567. if(0 != bw->buffer)
  94568. free(bw->buffer);
  94569. bw->buffer = 0;
  94570. bw->capacity = 0;
  94571. bw->words = bw->bits = 0;
  94572. }
  94573. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94574. {
  94575. bw->words = bw->bits = 0;
  94576. }
  94577. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94578. {
  94579. unsigned i, j;
  94580. if(bw == 0) {
  94581. fprintf(out, "bitwriter is NULL\n");
  94582. }
  94583. else {
  94584. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94585. for(i = 0; i < bw->words; i++) {
  94586. fprintf(out, "%08X: ", i);
  94587. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94588. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94589. fprintf(out, "\n");
  94590. }
  94591. if(bw->bits > 0) {
  94592. fprintf(out, "%08X: ", i);
  94593. for(j = 0; j < bw->bits; j++)
  94594. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94595. fprintf(out, "\n");
  94596. }
  94597. }
  94598. }
  94599. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94600. {
  94601. const FLAC__byte *buffer;
  94602. size_t bytes;
  94603. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94604. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94605. return false;
  94606. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94607. FLAC__bitwriter_release_buffer(bw);
  94608. return true;
  94609. }
  94610. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94611. {
  94612. const FLAC__byte *buffer;
  94613. size_t bytes;
  94614. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94615. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94616. return false;
  94617. *crc = FLAC__crc8(buffer, bytes);
  94618. FLAC__bitwriter_release_buffer(bw);
  94619. return true;
  94620. }
  94621. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94622. {
  94623. return ((bw->bits & 7) == 0);
  94624. }
  94625. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94626. {
  94627. return FLAC__TOTAL_BITS(bw);
  94628. }
  94629. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94630. {
  94631. FLAC__ASSERT((bw->bits & 7) == 0);
  94632. /* double protection */
  94633. if(bw->bits & 7)
  94634. return false;
  94635. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94636. if(bw->bits) {
  94637. FLAC__ASSERT(bw->words <= bw->capacity);
  94638. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94639. return false;
  94640. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94641. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94642. }
  94643. /* now we can just return what we have */
  94644. *buffer = (FLAC__byte*)bw->buffer;
  94645. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94646. return true;
  94647. }
  94648. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94649. {
  94650. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94651. * get-mode' flag could be added everywhere and then cleared here
  94652. */
  94653. (void)bw;
  94654. }
  94655. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94656. {
  94657. unsigned n;
  94658. FLAC__ASSERT(0 != bw);
  94659. FLAC__ASSERT(0 != bw->buffer);
  94660. if(bits == 0)
  94661. return true;
  94662. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94663. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94664. return false;
  94665. /* first part gets to word alignment */
  94666. if(bw->bits) {
  94667. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94668. bw->accum <<= n;
  94669. bits -= n;
  94670. bw->bits += n;
  94671. if(bw->bits == FLAC__BITS_PER_WORD) {
  94672. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94673. bw->bits = 0;
  94674. }
  94675. else
  94676. return true;
  94677. }
  94678. /* do whole words */
  94679. while(bits >= FLAC__BITS_PER_WORD) {
  94680. bw->buffer[bw->words++] = 0;
  94681. bits -= FLAC__BITS_PER_WORD;
  94682. }
  94683. /* do any leftovers */
  94684. if(bits > 0) {
  94685. bw->accum = 0;
  94686. bw->bits = bits;
  94687. }
  94688. return true;
  94689. }
  94690. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94691. {
  94692. register unsigned left;
  94693. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94694. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94695. FLAC__ASSERT(0 != bw);
  94696. FLAC__ASSERT(0 != bw->buffer);
  94697. FLAC__ASSERT(bits <= 32);
  94698. if(bits == 0)
  94699. return true;
  94700. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94701. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94702. return false;
  94703. left = FLAC__BITS_PER_WORD - bw->bits;
  94704. if(bits < left) {
  94705. bw->accum <<= bits;
  94706. bw->accum |= val;
  94707. bw->bits += bits;
  94708. }
  94709. 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 */
  94710. bw->accum <<= left;
  94711. bw->accum |= val >> (bw->bits = bits - left);
  94712. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94713. bw->accum = val;
  94714. }
  94715. else {
  94716. bw->accum = val;
  94717. bw->bits = 0;
  94718. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94719. }
  94720. return true;
  94721. }
  94722. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94723. {
  94724. /* zero-out unused bits */
  94725. if(bits < 32)
  94726. val &= (~(0xffffffff << bits));
  94727. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94728. }
  94729. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94730. {
  94731. /* this could be a little faster but it's not used for much */
  94732. if(bits > 32) {
  94733. return
  94734. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94735. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94736. }
  94737. else
  94738. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94739. }
  94740. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94741. {
  94742. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94743. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94744. return false;
  94745. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94746. return false;
  94747. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94748. return false;
  94749. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94750. return false;
  94751. return true;
  94752. }
  94753. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94754. {
  94755. unsigned i;
  94756. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94757. for(i = 0; i < nvals; i++) {
  94758. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94759. return false;
  94760. }
  94761. return true;
  94762. }
  94763. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94764. {
  94765. if(val < 32)
  94766. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94767. else
  94768. return
  94769. FLAC__bitwriter_write_zeroes(bw, val) &&
  94770. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94771. }
  94772. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94773. {
  94774. FLAC__uint32 uval;
  94775. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94776. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94777. uval = (val<<1) ^ (val>>31);
  94778. return 1 + parameter + (uval >> parameter);
  94779. }
  94780. #if 0 /* UNUSED */
  94781. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94782. {
  94783. unsigned bits, msbs, uval;
  94784. unsigned k;
  94785. FLAC__ASSERT(parameter > 0);
  94786. /* fold signed to unsigned */
  94787. if(val < 0)
  94788. uval = (unsigned)(((-(++val)) << 1) + 1);
  94789. else
  94790. uval = (unsigned)(val << 1);
  94791. k = FLAC__bitmath_ilog2(parameter);
  94792. if(parameter == 1u<<k) {
  94793. FLAC__ASSERT(k <= 30);
  94794. msbs = uval >> k;
  94795. bits = 1 + k + msbs;
  94796. }
  94797. else {
  94798. unsigned q, r, d;
  94799. d = (1 << (k+1)) - parameter;
  94800. q = uval / parameter;
  94801. r = uval - (q * parameter);
  94802. bits = 1 + q + k;
  94803. if(r >= d)
  94804. bits++;
  94805. }
  94806. return bits;
  94807. }
  94808. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94809. {
  94810. unsigned bits, msbs;
  94811. unsigned k;
  94812. FLAC__ASSERT(parameter > 0);
  94813. k = FLAC__bitmath_ilog2(parameter);
  94814. if(parameter == 1u<<k) {
  94815. FLAC__ASSERT(k <= 30);
  94816. msbs = uval >> k;
  94817. bits = 1 + k + msbs;
  94818. }
  94819. else {
  94820. unsigned q, r, d;
  94821. d = (1 << (k+1)) - parameter;
  94822. q = uval / parameter;
  94823. r = uval - (q * parameter);
  94824. bits = 1 + q + k;
  94825. if(r >= d)
  94826. bits++;
  94827. }
  94828. return bits;
  94829. }
  94830. #endif /* UNUSED */
  94831. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94832. {
  94833. unsigned total_bits, interesting_bits, msbs;
  94834. FLAC__uint32 uval, pattern;
  94835. FLAC__ASSERT(0 != bw);
  94836. FLAC__ASSERT(0 != bw->buffer);
  94837. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94838. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94839. uval = (val<<1) ^ (val>>31);
  94840. msbs = uval >> parameter;
  94841. interesting_bits = 1 + parameter;
  94842. total_bits = interesting_bits + msbs;
  94843. pattern = 1 << parameter; /* the unary end bit */
  94844. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94845. if(total_bits <= 32)
  94846. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94847. else
  94848. return
  94849. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94850. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94851. }
  94852. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94853. {
  94854. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94855. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94856. FLAC__uint32 uval;
  94857. unsigned left;
  94858. const unsigned lsbits = 1 + parameter;
  94859. unsigned msbits;
  94860. FLAC__ASSERT(0 != bw);
  94861. FLAC__ASSERT(0 != bw->buffer);
  94862. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94863. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94864. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94865. while(nvals) {
  94866. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94867. uval = (*vals<<1) ^ (*vals>>31);
  94868. msbits = uval >> parameter;
  94869. #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) */
  94870. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94871. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94872. bw->bits = bw->bits + msbits + lsbits;
  94873. uval |= mask1; /* set stop bit */
  94874. uval &= mask2; /* mask off unused top bits */
  94875. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94876. bw->accum <<= msbits;
  94877. bw->accum <<= lsbits;
  94878. bw->accum |= uval;
  94879. if(bw->bits == FLAC__BITS_PER_WORD) {
  94880. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94881. bw->bits = 0;
  94882. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94883. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94884. FLAC__ASSERT(bw->capacity == bw->words);
  94885. return false;
  94886. }
  94887. }
  94888. }
  94889. else {
  94890. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94891. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94892. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94893. bw->bits = bw->bits + msbits + lsbits;
  94894. uval |= mask1; /* set stop bit */
  94895. uval &= mask2; /* mask off unused top bits */
  94896. bw->accum <<= msbits + lsbits;
  94897. bw->accum |= uval;
  94898. }
  94899. else {
  94900. #endif
  94901. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94902. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94903. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94904. return false;
  94905. if(msbits) {
  94906. /* first part gets to word alignment */
  94907. if(bw->bits) {
  94908. left = FLAC__BITS_PER_WORD - bw->bits;
  94909. if(msbits < left) {
  94910. bw->accum <<= msbits;
  94911. bw->bits += msbits;
  94912. goto break1;
  94913. }
  94914. else {
  94915. bw->accum <<= left;
  94916. msbits -= left;
  94917. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94918. bw->bits = 0;
  94919. }
  94920. }
  94921. /* do whole words */
  94922. while(msbits >= FLAC__BITS_PER_WORD) {
  94923. bw->buffer[bw->words++] = 0;
  94924. msbits -= FLAC__BITS_PER_WORD;
  94925. }
  94926. /* do any leftovers */
  94927. if(msbits > 0) {
  94928. bw->accum = 0;
  94929. bw->bits = msbits;
  94930. }
  94931. }
  94932. break1:
  94933. uval |= mask1; /* set stop bit */
  94934. uval &= mask2; /* mask off unused top bits */
  94935. left = FLAC__BITS_PER_WORD - bw->bits;
  94936. if(lsbits < left) {
  94937. bw->accum <<= lsbits;
  94938. bw->accum |= uval;
  94939. bw->bits += lsbits;
  94940. }
  94941. else {
  94942. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94943. * be > lsbits (because of previous assertions) so it would have
  94944. * triggered the (lsbits<left) case above.
  94945. */
  94946. FLAC__ASSERT(bw->bits);
  94947. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94948. bw->accum <<= left;
  94949. bw->accum |= uval >> (bw->bits = lsbits - left);
  94950. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94951. bw->accum = uval;
  94952. }
  94953. #if 1
  94954. }
  94955. #endif
  94956. vals++;
  94957. nvals--;
  94958. }
  94959. return true;
  94960. }
  94961. #if 0 /* UNUSED */
  94962. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94963. {
  94964. unsigned total_bits, msbs, uval;
  94965. unsigned k;
  94966. FLAC__ASSERT(0 != bw);
  94967. FLAC__ASSERT(0 != bw->buffer);
  94968. FLAC__ASSERT(parameter > 0);
  94969. /* fold signed to unsigned */
  94970. if(val < 0)
  94971. uval = (unsigned)(((-(++val)) << 1) + 1);
  94972. else
  94973. uval = (unsigned)(val << 1);
  94974. k = FLAC__bitmath_ilog2(parameter);
  94975. if(parameter == 1u<<k) {
  94976. unsigned pattern;
  94977. FLAC__ASSERT(k <= 30);
  94978. msbs = uval >> k;
  94979. total_bits = 1 + k + msbs;
  94980. pattern = 1 << k; /* the unary end bit */
  94981. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94982. if(total_bits <= 32) {
  94983. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94984. return false;
  94985. }
  94986. else {
  94987. /* write the unary MSBs */
  94988. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94989. return false;
  94990. /* write the unary end bit and binary LSBs */
  94991. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94992. return false;
  94993. }
  94994. }
  94995. else {
  94996. unsigned q, r, d;
  94997. d = (1 << (k+1)) - parameter;
  94998. q = uval / parameter;
  94999. r = uval - (q * parameter);
  95000. /* write the unary MSBs */
  95001. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95002. return false;
  95003. /* write the unary end bit */
  95004. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95005. return false;
  95006. /* write the binary LSBs */
  95007. if(r >= d) {
  95008. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95009. return false;
  95010. }
  95011. else {
  95012. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95013. return false;
  95014. }
  95015. }
  95016. return true;
  95017. }
  95018. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95019. {
  95020. unsigned total_bits, msbs;
  95021. unsigned k;
  95022. FLAC__ASSERT(0 != bw);
  95023. FLAC__ASSERT(0 != bw->buffer);
  95024. FLAC__ASSERT(parameter > 0);
  95025. k = FLAC__bitmath_ilog2(parameter);
  95026. if(parameter == 1u<<k) {
  95027. unsigned pattern;
  95028. FLAC__ASSERT(k <= 30);
  95029. msbs = uval >> k;
  95030. total_bits = 1 + k + msbs;
  95031. pattern = 1 << k; /* the unary end bit */
  95032. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95033. if(total_bits <= 32) {
  95034. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95035. return false;
  95036. }
  95037. else {
  95038. /* write the unary MSBs */
  95039. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95040. return false;
  95041. /* write the unary end bit and binary LSBs */
  95042. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95043. return false;
  95044. }
  95045. }
  95046. else {
  95047. unsigned q, r, d;
  95048. d = (1 << (k+1)) - parameter;
  95049. q = uval / parameter;
  95050. r = uval - (q * parameter);
  95051. /* write the unary MSBs */
  95052. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95053. return false;
  95054. /* write the unary end bit */
  95055. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95056. return false;
  95057. /* write the binary LSBs */
  95058. if(r >= d) {
  95059. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95060. return false;
  95061. }
  95062. else {
  95063. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95064. return false;
  95065. }
  95066. }
  95067. return true;
  95068. }
  95069. #endif /* UNUSED */
  95070. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95071. {
  95072. FLAC__bool ok = 1;
  95073. FLAC__ASSERT(0 != bw);
  95074. FLAC__ASSERT(0 != bw->buffer);
  95075. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95076. if(val < 0x80) {
  95077. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95078. }
  95079. else if(val < 0x800) {
  95080. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95081. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95082. }
  95083. else if(val < 0x10000) {
  95084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95085. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95086. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95087. }
  95088. else if(val < 0x200000) {
  95089. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95090. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95091. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95092. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95093. }
  95094. else if(val < 0x4000000) {
  95095. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95096. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95097. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95098. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95099. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95100. }
  95101. else {
  95102. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95103. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95104. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95105. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95107. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95108. }
  95109. return ok;
  95110. }
  95111. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95112. {
  95113. FLAC__bool ok = 1;
  95114. FLAC__ASSERT(0 != bw);
  95115. FLAC__ASSERT(0 != bw->buffer);
  95116. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95117. if(val < 0x80) {
  95118. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95119. }
  95120. else if(val < 0x800) {
  95121. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95122. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95123. }
  95124. else if(val < 0x10000) {
  95125. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95128. }
  95129. else if(val < 0x200000) {
  95130. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95131. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95132. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95134. }
  95135. else if(val < 0x4000000) {
  95136. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95137. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95139. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95140. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95141. }
  95142. else if(val < 0x80000000) {
  95143. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95144. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95145. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95148. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95149. }
  95150. else {
  95151. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95152. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95153. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95154. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95155. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95156. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95157. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95158. }
  95159. return ok;
  95160. }
  95161. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95162. {
  95163. /* 0-pad to byte boundary */
  95164. if(bw->bits & 7u)
  95165. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95166. else
  95167. return true;
  95168. }
  95169. #endif
  95170. /*** End of inlined file: bitwriter.c ***/
  95171. /*** Start of inlined file: cpu.c ***/
  95172. /*** Start of inlined file: juce_FlacHeader.h ***/
  95173. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95174. // tasks..
  95175. #define VERSION "1.2.1"
  95176. #define FLAC__NO_DLL 1
  95177. #if JUCE_MSVC
  95178. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95179. #endif
  95180. #if JUCE_MAC
  95181. #define FLAC__SYS_DARWIN 1
  95182. #endif
  95183. /*** End of inlined file: juce_FlacHeader.h ***/
  95184. #if JUCE_USE_FLAC
  95185. #if HAVE_CONFIG_H
  95186. # include <config.h>
  95187. #endif
  95188. #include <stdlib.h>
  95189. #include <stdio.h>
  95190. #if defined FLAC__CPU_IA32
  95191. # include <signal.h>
  95192. #elif defined FLAC__CPU_PPC
  95193. # if !defined FLAC__NO_ASM
  95194. # if defined FLAC__SYS_DARWIN
  95195. # include <sys/sysctl.h>
  95196. # include <mach/mach.h>
  95197. # include <mach/mach_host.h>
  95198. # include <mach/host_info.h>
  95199. # include <mach/machine.h>
  95200. # ifndef CPU_SUBTYPE_POWERPC_970
  95201. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95202. # endif
  95203. # else /* FLAC__SYS_DARWIN */
  95204. # include <signal.h>
  95205. # include <setjmp.h>
  95206. static sigjmp_buf jmpbuf;
  95207. static volatile sig_atomic_t canjump = 0;
  95208. static void sigill_handler (int sig)
  95209. {
  95210. if (!canjump) {
  95211. signal (sig, SIG_DFL);
  95212. raise (sig);
  95213. }
  95214. canjump = 0;
  95215. siglongjmp (jmpbuf, 1);
  95216. }
  95217. # endif /* FLAC__SYS_DARWIN */
  95218. # endif /* FLAC__NO_ASM */
  95219. #endif /* FLAC__CPU_PPC */
  95220. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95221. #include <sys/param.h>
  95222. #include <sys/sysctl.h>
  95223. #include <machine/cpu.h>
  95224. #endif
  95225. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95226. #include <sys/types.h>
  95227. #include <sys/sysctl.h>
  95228. #endif
  95229. #if defined(__APPLE__)
  95230. /* how to get sysctlbyname()? */
  95231. #endif
  95232. /* these are flags in EDX of CPUID AX=00000001 */
  95233. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95234. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95235. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95236. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95237. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95238. /* these are flags in ECX of CPUID AX=00000001 */
  95239. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95240. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95241. /* these are flags in EDX of CPUID AX=80000001 */
  95242. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95243. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95244. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95245. /*
  95246. * Extra stuff needed for detection of OS support for SSE on IA-32
  95247. */
  95248. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95249. # if defined(__linux__)
  95250. /*
  95251. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95252. * modify the return address to jump over the offending SSE instruction
  95253. * and also the operation following it that indicates the instruction
  95254. * executed successfully. In this way we use no global variables and
  95255. * stay thread-safe.
  95256. *
  95257. * 3 + 3 + 6:
  95258. * 3 bytes for "xorps xmm0,xmm0"
  95259. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95260. * 6 bytes extra in case our estimate is wrong
  95261. * 12 bytes puts us in the NOP "landing zone"
  95262. */
  95263. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95264. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95265. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95266. {
  95267. (void)signal;
  95268. sc.eip += 3 + 3 + 6;
  95269. }
  95270. # else
  95271. # include <sys/ucontext.h>
  95272. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95273. {
  95274. (void)signal, (void)si;
  95275. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95276. }
  95277. # endif
  95278. # elif defined(_MSC_VER)
  95279. # include <windows.h>
  95280. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95281. # ifdef USE_TRY_CATCH_FLAVOR
  95282. # else
  95283. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95284. {
  95285. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95286. ep->ContextRecord->Eip += 3 + 3 + 6;
  95287. return EXCEPTION_CONTINUE_EXECUTION;
  95288. }
  95289. return EXCEPTION_CONTINUE_SEARCH;
  95290. }
  95291. # endif
  95292. # endif
  95293. #endif
  95294. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95295. {
  95296. /*
  95297. * IA32-specific
  95298. */
  95299. #ifdef FLAC__CPU_IA32
  95300. info->type = FLAC__CPUINFO_TYPE_IA32;
  95301. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95302. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95303. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95304. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95305. info->data.ia32.cmov = false;
  95306. info->data.ia32.mmx = false;
  95307. info->data.ia32.fxsr = false;
  95308. info->data.ia32.sse = false;
  95309. info->data.ia32.sse2 = false;
  95310. info->data.ia32.sse3 = false;
  95311. info->data.ia32.ssse3 = false;
  95312. info->data.ia32._3dnow = false;
  95313. info->data.ia32.ext3dnow = false;
  95314. info->data.ia32.extmmx = false;
  95315. if(info->data.ia32.cpuid) {
  95316. /* http://www.sandpile.org/ia32/cpuid.htm */
  95317. FLAC__uint32 flags_edx, flags_ecx;
  95318. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95319. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95320. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95321. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95322. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95323. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95324. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95325. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95326. #ifdef FLAC__USE_3DNOW
  95327. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95328. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95329. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95330. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95331. #else
  95332. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95333. #endif
  95334. #ifdef DEBUG
  95335. fprintf(stderr, "CPU info (IA-32):\n");
  95336. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95337. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95338. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95339. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95340. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95341. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95342. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95343. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95344. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95345. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95346. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95347. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95348. #endif
  95349. /*
  95350. * now have to check for OS support of SSE/SSE2
  95351. */
  95352. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95353. #if defined FLAC__NO_SSE_OS
  95354. /* assume user knows better than us; turn it off */
  95355. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95356. #elif defined FLAC__SSE_OS
  95357. /* assume user knows better than us; leave as detected above */
  95358. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95359. int sse = 0;
  95360. size_t len;
  95361. /* at least one of these must work: */
  95362. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95363. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95364. if(!sse)
  95365. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95366. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95367. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95368. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95369. size_t len = sizeof(val);
  95370. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95371. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95372. else { /* double-check SSE2 */
  95373. mib[1] = CPU_SSE2;
  95374. len = sizeof(val);
  95375. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95376. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95377. }
  95378. # else
  95379. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95380. # endif
  95381. #elif defined(__linux__)
  95382. int sse = 0;
  95383. struct sigaction sigill_save;
  95384. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95385. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95386. #else
  95387. struct sigaction sigill_sse;
  95388. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95389. __sigemptyset(&sigill_sse.sa_mask);
  95390. 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 */
  95391. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95392. #endif
  95393. {
  95394. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95395. /* see sigill_handler_sse_os() for an explanation of the following: */
  95396. asm volatile (
  95397. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95398. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95399. "incl %0\n\t" /* SIGILL handler will jump over this */
  95400. /* landing zone */
  95401. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95402. "nop\n\t"
  95403. "nop\n\t"
  95404. "nop\n\t"
  95405. "nop\n\t"
  95406. "nop\n\t"
  95407. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95408. "nop\n\t"
  95409. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95410. : "=r"(sse)
  95411. : "r"(sse)
  95412. );
  95413. sigaction(SIGILL, &sigill_save, NULL);
  95414. }
  95415. if(!sse)
  95416. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95417. #elif defined(_MSC_VER)
  95418. # ifdef USE_TRY_CATCH_FLAVOR
  95419. _try {
  95420. __asm {
  95421. # if _MSC_VER <= 1200
  95422. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95423. _emit 0x0F
  95424. _emit 0x57
  95425. _emit 0xC0
  95426. # else
  95427. xorps xmm0,xmm0
  95428. # endif
  95429. }
  95430. }
  95431. _except(EXCEPTION_EXECUTE_HANDLER) {
  95432. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95433. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95434. }
  95435. # else
  95436. int sse = 0;
  95437. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95438. /* see GCC version above for explanation */
  95439. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95440. /* http://www.codeproject.com/cpp/gccasm.asp */
  95441. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95442. __asm {
  95443. # if _MSC_VER <= 1200
  95444. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95445. _emit 0x0F
  95446. _emit 0x57
  95447. _emit 0xC0
  95448. # else
  95449. xorps xmm0,xmm0
  95450. # endif
  95451. inc sse
  95452. nop
  95453. nop
  95454. nop
  95455. nop
  95456. nop
  95457. nop
  95458. nop
  95459. nop
  95460. nop
  95461. }
  95462. SetUnhandledExceptionFilter(save);
  95463. if(!sse)
  95464. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95465. # endif
  95466. #else
  95467. /* no way to test, disable to be safe */
  95468. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95469. #endif
  95470. #ifdef DEBUG
  95471. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95472. #endif
  95473. }
  95474. }
  95475. #else
  95476. info->use_asm = false;
  95477. #endif
  95478. /*
  95479. * PPC-specific
  95480. */
  95481. #elif defined FLAC__CPU_PPC
  95482. info->type = FLAC__CPUINFO_TYPE_PPC;
  95483. # if !defined FLAC__NO_ASM
  95484. info->use_asm = true;
  95485. # ifdef FLAC__USE_ALTIVEC
  95486. # if defined FLAC__SYS_DARWIN
  95487. {
  95488. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95489. size_t len = sizeof(val);
  95490. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95491. }
  95492. {
  95493. host_basic_info_data_t hostInfo;
  95494. mach_msg_type_number_t infoCount;
  95495. infoCount = HOST_BASIC_INFO_COUNT;
  95496. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95497. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95498. }
  95499. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95500. {
  95501. /* no Darwin, do it the brute-force way */
  95502. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95503. info->data.ppc.altivec = 0;
  95504. info->data.ppc.ppc64 = 0;
  95505. signal (SIGILL, sigill_handler);
  95506. canjump = 0;
  95507. if (!sigsetjmp (jmpbuf, 1)) {
  95508. canjump = 1;
  95509. asm volatile (
  95510. "mtspr 256, %0\n\t"
  95511. "vand %%v0, %%v0, %%v0"
  95512. :
  95513. : "r" (-1)
  95514. );
  95515. info->data.ppc.altivec = 1;
  95516. }
  95517. canjump = 0;
  95518. if (!sigsetjmp (jmpbuf, 1)) {
  95519. int x = 0;
  95520. canjump = 1;
  95521. /* PPC64 hardware implements the cntlzd instruction */
  95522. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95523. info->data.ppc.ppc64 = 1;
  95524. }
  95525. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95526. }
  95527. # endif
  95528. # else /* !FLAC__USE_ALTIVEC */
  95529. info->data.ppc.altivec = 0;
  95530. info->data.ppc.ppc64 = 0;
  95531. # endif
  95532. # else
  95533. info->use_asm = false;
  95534. # endif
  95535. /*
  95536. * unknown CPI
  95537. */
  95538. #else
  95539. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95540. info->use_asm = false;
  95541. #endif
  95542. }
  95543. #endif
  95544. /*** End of inlined file: cpu.c ***/
  95545. /*** Start of inlined file: crc.c ***/
  95546. /*** Start of inlined file: juce_FlacHeader.h ***/
  95547. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95548. // tasks..
  95549. #define VERSION "1.2.1"
  95550. #define FLAC__NO_DLL 1
  95551. #if JUCE_MSVC
  95552. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95553. #endif
  95554. #if JUCE_MAC
  95555. #define FLAC__SYS_DARWIN 1
  95556. #endif
  95557. /*** End of inlined file: juce_FlacHeader.h ***/
  95558. #if JUCE_USE_FLAC
  95559. #if HAVE_CONFIG_H
  95560. # include <config.h>
  95561. #endif
  95562. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95563. FLAC__byte const FLAC__crc8_table[256] = {
  95564. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95565. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95566. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95567. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95568. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95569. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95570. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95571. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95572. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95573. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95574. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95575. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95576. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95577. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95578. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95579. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95580. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95581. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95582. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95583. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95584. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95585. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95586. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95587. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95588. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95589. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95590. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95591. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95592. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95593. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95594. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95595. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95596. };
  95597. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95598. unsigned FLAC__crc16_table[256] = {
  95599. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95600. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95601. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95602. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95603. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95604. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95605. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95606. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95607. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95608. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95609. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95610. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95611. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95612. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95613. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95614. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95615. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95616. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95617. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95618. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95619. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95620. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95621. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95622. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95623. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95624. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95625. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95626. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95627. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95628. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95629. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95630. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95631. };
  95632. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95633. {
  95634. *crc = FLAC__crc8_table[*crc ^ data];
  95635. }
  95636. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95637. {
  95638. while(len--)
  95639. *crc = FLAC__crc8_table[*crc ^ *data++];
  95640. }
  95641. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95642. {
  95643. FLAC__uint8 crc = 0;
  95644. while(len--)
  95645. crc = FLAC__crc8_table[crc ^ *data++];
  95646. return crc;
  95647. }
  95648. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95649. {
  95650. unsigned crc = 0;
  95651. while(len--)
  95652. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95653. return crc;
  95654. }
  95655. #endif
  95656. /*** End of inlined file: crc.c ***/
  95657. /*** Start of inlined file: fixed.c ***/
  95658. /*** Start of inlined file: juce_FlacHeader.h ***/
  95659. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95660. // tasks..
  95661. #define VERSION "1.2.1"
  95662. #define FLAC__NO_DLL 1
  95663. #if JUCE_MSVC
  95664. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95665. #endif
  95666. #if JUCE_MAC
  95667. #define FLAC__SYS_DARWIN 1
  95668. #endif
  95669. /*** End of inlined file: juce_FlacHeader.h ***/
  95670. #if JUCE_USE_FLAC
  95671. #if HAVE_CONFIG_H
  95672. # include <config.h>
  95673. #endif
  95674. #include <math.h>
  95675. #include <string.h>
  95676. /*** Start of inlined file: fixed.h ***/
  95677. #ifndef FLAC__PRIVATE__FIXED_H
  95678. #define FLAC__PRIVATE__FIXED_H
  95679. #ifdef HAVE_CONFIG_H
  95680. #include <config.h>
  95681. #endif
  95682. /*** Start of inlined file: float.h ***/
  95683. #ifndef FLAC__PRIVATE__FLOAT_H
  95684. #define FLAC__PRIVATE__FLOAT_H
  95685. #ifdef HAVE_CONFIG_H
  95686. #include <config.h>
  95687. #endif
  95688. /*
  95689. * These typedefs make it easier to ensure that integer versions of
  95690. * the library really only contain integer operations. All the code
  95691. * in libFLAC should use FLAC__float and FLAC__double in place of
  95692. * float and double, and be protected by checks of the macro
  95693. * FLAC__INTEGER_ONLY_LIBRARY.
  95694. *
  95695. * FLAC__real is the basic floating point type used in LPC analysis.
  95696. */
  95697. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95698. typedef double FLAC__double;
  95699. typedef float FLAC__float;
  95700. /*
  95701. * WATCHOUT: changing FLAC__real will change the signatures of many
  95702. * functions that have assembly language equivalents and break them.
  95703. */
  95704. typedef float FLAC__real;
  95705. #else
  95706. /*
  95707. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95708. * for the integer part and lower 16 bits for the fractional part.
  95709. */
  95710. typedef FLAC__int32 FLAC__fixedpoint;
  95711. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95712. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95713. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95714. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95715. extern const FLAC__fixedpoint FLAC__FP_E;
  95716. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95717. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95718. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95719. /*
  95720. * FLAC__fixedpoint_log2()
  95721. * --------------------------------------------------------------------
  95722. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95723. * algorithm by Knuth for x >= 1.0
  95724. *
  95725. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95726. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95727. *
  95728. * 'precision' roughly limits the number of iterations that are done;
  95729. * use (unsigned)(-1) for maximum precision.
  95730. *
  95731. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95732. * function will punt and return 0.
  95733. *
  95734. * The return value will also have 'fracbits' fractional bits.
  95735. */
  95736. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95737. #endif
  95738. #endif
  95739. /*** End of inlined file: float.h ***/
  95740. /*** Start of inlined file: format.h ***/
  95741. #ifndef FLAC__PRIVATE__FORMAT_H
  95742. #define FLAC__PRIVATE__FORMAT_H
  95743. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95744. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95745. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95746. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95747. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95748. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95749. #endif
  95750. /*** End of inlined file: format.h ***/
  95751. /*
  95752. * FLAC__fixed_compute_best_predictor()
  95753. * --------------------------------------------------------------------
  95754. * Compute the best fixed predictor and the expected bits-per-sample
  95755. * of the residual signal for each order. The _wide() version uses
  95756. * 64-bit integers which is statistically necessary when bits-per-
  95757. * sample + log2(blocksize) > 30
  95758. *
  95759. * IN data[0,data_len-1]
  95760. * IN data_len
  95761. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95762. */
  95763. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95764. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95765. # ifndef FLAC__NO_ASM
  95766. # ifdef FLAC__CPU_IA32
  95767. # ifdef FLAC__HAS_NASM
  95768. 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]);
  95769. # endif
  95770. # endif
  95771. # endif
  95772. 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]);
  95773. #else
  95774. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95775. 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]);
  95776. #endif
  95777. /*
  95778. * FLAC__fixed_compute_residual()
  95779. * --------------------------------------------------------------------
  95780. * Compute the residual signal obtained from sutracting the predicted
  95781. * signal from the original.
  95782. *
  95783. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95784. * IN data_len length of original signal
  95785. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95786. * OUT residual[0,data_len-1] residual signal
  95787. */
  95788. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95789. /*
  95790. * FLAC__fixed_restore_signal()
  95791. * --------------------------------------------------------------------
  95792. * Restore the original signal by summing the residual and the
  95793. * predictor.
  95794. *
  95795. * IN residual[0,data_len-1] residual signal
  95796. * IN data_len length of original signal
  95797. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95798. * *** IMPORTANT: the caller must pass in the historical samples:
  95799. * IN data[-order,-1] previously-reconstructed historical samples
  95800. * OUT data[0,data_len-1] original signal
  95801. */
  95802. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95803. #endif
  95804. /*** End of inlined file: fixed.h ***/
  95805. #ifndef M_LN2
  95806. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95807. #define M_LN2 0.69314718055994530942
  95808. #endif
  95809. #ifdef min
  95810. #undef min
  95811. #endif
  95812. #define min(x,y) ((x) < (y)? (x) : (y))
  95813. #ifdef local_abs
  95814. #undef local_abs
  95815. #endif
  95816. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95817. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95818. /* rbps stands for residual bits per sample
  95819. *
  95820. * (ln(2) * err)
  95821. * rbps = log (-----------)
  95822. * 2 ( n )
  95823. */
  95824. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95825. {
  95826. FLAC__uint32 rbps;
  95827. unsigned bits; /* the number of bits required to represent a number */
  95828. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95829. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95830. FLAC__ASSERT(err > 0);
  95831. FLAC__ASSERT(n > 0);
  95832. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95833. if(err <= n)
  95834. return 0;
  95835. /*
  95836. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95837. * These allow us later to know we won't lose too much precision in the
  95838. * fixed-point division (err<<fracbits)/n.
  95839. */
  95840. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95841. err <<= fracbits;
  95842. err /= n;
  95843. /* err now holds err/n with fracbits fractional bits */
  95844. /*
  95845. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95846. * our purposes.
  95847. */
  95848. FLAC__ASSERT(err > 0);
  95849. bits = FLAC__bitmath_ilog2(err)+1;
  95850. if(bits > 16) {
  95851. err >>= (bits-16);
  95852. fracbits -= (bits-16);
  95853. }
  95854. rbps = (FLAC__uint32)err;
  95855. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95856. rbps *= FLAC__FP_LN2;
  95857. fracbits += 16;
  95858. FLAC__ASSERT(fracbits >= 0);
  95859. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95860. {
  95861. const int f = fracbits & 3;
  95862. if(f) {
  95863. rbps >>= f;
  95864. fracbits -= f;
  95865. }
  95866. }
  95867. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95868. if(rbps == 0)
  95869. return 0;
  95870. /*
  95871. * The return value must have 16 fractional bits. Since the whole part
  95872. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95873. * must be >= -3, these assertion allows us to be able to shift rbps
  95874. * left if necessary to get 16 fracbits without losing any bits of the
  95875. * whole part of rbps.
  95876. *
  95877. * There is a slight chance due to accumulated error that the whole part
  95878. * will require 6 bits, so we use 6 in the assertion. Really though as
  95879. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95880. */
  95881. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95882. FLAC__ASSERT(fracbits >= -3);
  95883. /* now shift the decimal point into place */
  95884. if(fracbits < 16)
  95885. return rbps << (16-fracbits);
  95886. else if(fracbits > 16)
  95887. return rbps >> (fracbits-16);
  95888. else
  95889. return rbps;
  95890. }
  95891. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95892. {
  95893. FLAC__uint32 rbps;
  95894. unsigned bits; /* the number of bits required to represent a number */
  95895. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95896. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95897. FLAC__ASSERT(err > 0);
  95898. FLAC__ASSERT(n > 0);
  95899. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95900. if(err <= n)
  95901. return 0;
  95902. /*
  95903. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95904. * These allow us later to know we won't lose too much precision in the
  95905. * fixed-point division (err<<fracbits)/n.
  95906. */
  95907. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95908. err <<= fracbits;
  95909. err /= n;
  95910. /* err now holds err/n with fracbits fractional bits */
  95911. /*
  95912. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95913. * our purposes.
  95914. */
  95915. FLAC__ASSERT(err > 0);
  95916. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95917. if(bits > 16) {
  95918. err >>= (bits-16);
  95919. fracbits -= (bits-16);
  95920. }
  95921. rbps = (FLAC__uint32)err;
  95922. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95923. rbps *= FLAC__FP_LN2;
  95924. fracbits += 16;
  95925. FLAC__ASSERT(fracbits >= 0);
  95926. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95927. {
  95928. const int f = fracbits & 3;
  95929. if(f) {
  95930. rbps >>= f;
  95931. fracbits -= f;
  95932. }
  95933. }
  95934. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95935. if(rbps == 0)
  95936. return 0;
  95937. /*
  95938. * The return value must have 16 fractional bits. Since the whole part
  95939. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95940. * must be >= -3, these assertion allows us to be able to shift rbps
  95941. * left if necessary to get 16 fracbits without losing any bits of the
  95942. * whole part of rbps.
  95943. *
  95944. * There is a slight chance due to accumulated error that the whole part
  95945. * will require 6 bits, so we use 6 in the assertion. Really though as
  95946. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95947. */
  95948. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95949. FLAC__ASSERT(fracbits >= -3);
  95950. /* now shift the decimal point into place */
  95951. if(fracbits < 16)
  95952. return rbps << (16-fracbits);
  95953. else if(fracbits > 16)
  95954. return rbps >> (fracbits-16);
  95955. else
  95956. return rbps;
  95957. }
  95958. #endif
  95959. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95960. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95961. #else
  95962. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95963. #endif
  95964. {
  95965. FLAC__int32 last_error_0 = data[-1];
  95966. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95967. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95968. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95969. FLAC__int32 error, save;
  95970. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95971. unsigned i, order;
  95972. for(i = 0; i < data_len; i++) {
  95973. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95974. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95975. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95976. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95977. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95978. }
  95979. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95980. order = 0;
  95981. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95982. order = 1;
  95983. else if(total_error_2 < min(total_error_3, total_error_4))
  95984. order = 2;
  95985. else if(total_error_3 < total_error_4)
  95986. order = 3;
  95987. else
  95988. order = 4;
  95989. /* Estimate the expected number of bits per residual signal sample. */
  95990. /* 'total_error*' is linearly related to the variance of the residual */
  95991. /* signal, so we use it directly to compute E(|x|) */
  95992. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95993. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95994. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95995. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95996. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95998. 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);
  95999. 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);
  96000. 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);
  96001. 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);
  96002. 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);
  96003. #else
  96004. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96005. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96006. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96007. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96008. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96009. #endif
  96010. return order;
  96011. }
  96012. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96013. 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])
  96014. #else
  96015. 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])
  96016. #endif
  96017. {
  96018. FLAC__int32 last_error_0 = data[-1];
  96019. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96020. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96021. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96022. FLAC__int32 error, save;
  96023. /* total_error_* are 64-bits to avoid overflow when encoding
  96024. * erratic signals when the bits-per-sample and blocksize are
  96025. * large.
  96026. */
  96027. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96028. unsigned i, order;
  96029. for(i = 0; i < data_len; i++) {
  96030. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96031. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96032. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96033. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96034. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96035. }
  96036. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96037. order = 0;
  96038. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96039. order = 1;
  96040. else if(total_error_2 < min(total_error_3, total_error_4))
  96041. order = 2;
  96042. else if(total_error_3 < total_error_4)
  96043. order = 3;
  96044. else
  96045. order = 4;
  96046. /* Estimate the expected number of bits per residual signal sample. */
  96047. /* 'total_error*' is linearly related to the variance of the residual */
  96048. /* signal, so we use it directly to compute E(|x|) */
  96049. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96050. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96051. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96052. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96053. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96054. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96055. #if defined _MSC_VER || defined __MINGW32__
  96056. /* with MSVC you have to spoon feed it the casting */
  96057. 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);
  96058. 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);
  96059. 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);
  96060. 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);
  96061. 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);
  96062. #else
  96063. 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);
  96064. 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);
  96065. 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);
  96066. 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);
  96067. 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);
  96068. #endif
  96069. #else
  96070. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96071. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96072. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96073. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96074. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96075. #endif
  96076. return order;
  96077. }
  96078. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96079. {
  96080. const int idata_len = (int)data_len;
  96081. int i;
  96082. switch(order) {
  96083. case 0:
  96084. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96085. memcpy(residual, data, sizeof(residual[0])*data_len);
  96086. break;
  96087. case 1:
  96088. for(i = 0; i < idata_len; i++)
  96089. residual[i] = data[i] - data[i-1];
  96090. break;
  96091. case 2:
  96092. for(i = 0; i < idata_len; i++)
  96093. #if 1 /* OPT: may be faster with some compilers on some systems */
  96094. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96095. #else
  96096. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96097. #endif
  96098. break;
  96099. case 3:
  96100. for(i = 0; i < idata_len; i++)
  96101. #if 1 /* OPT: may be faster with some compilers on some systems */
  96102. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96103. #else
  96104. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96105. #endif
  96106. break;
  96107. case 4:
  96108. for(i = 0; i < idata_len; i++)
  96109. #if 1 /* OPT: may be faster with some compilers on some systems */
  96110. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96111. #else
  96112. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96113. #endif
  96114. break;
  96115. default:
  96116. FLAC__ASSERT(0);
  96117. }
  96118. }
  96119. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96120. {
  96121. int i, idata_len = (int)data_len;
  96122. switch(order) {
  96123. case 0:
  96124. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96125. memcpy(data, residual, sizeof(residual[0])*data_len);
  96126. break;
  96127. case 1:
  96128. for(i = 0; i < idata_len; i++)
  96129. data[i] = residual[i] + data[i-1];
  96130. break;
  96131. case 2:
  96132. for(i = 0; i < idata_len; i++)
  96133. #if 1 /* OPT: may be faster with some compilers on some systems */
  96134. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96135. #else
  96136. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96137. #endif
  96138. break;
  96139. case 3:
  96140. for(i = 0; i < idata_len; i++)
  96141. #if 1 /* OPT: may be faster with some compilers on some systems */
  96142. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96143. #else
  96144. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96145. #endif
  96146. break;
  96147. case 4:
  96148. for(i = 0; i < idata_len; i++)
  96149. #if 1 /* OPT: may be faster with some compilers on some systems */
  96150. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96151. #else
  96152. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96153. #endif
  96154. break;
  96155. default:
  96156. FLAC__ASSERT(0);
  96157. }
  96158. }
  96159. #endif
  96160. /*** End of inlined file: fixed.c ***/
  96161. /*** Start of inlined file: float.c ***/
  96162. /*** Start of inlined file: juce_FlacHeader.h ***/
  96163. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96164. // tasks..
  96165. #define VERSION "1.2.1"
  96166. #define FLAC__NO_DLL 1
  96167. #if JUCE_MSVC
  96168. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96169. #endif
  96170. #if JUCE_MAC
  96171. #define FLAC__SYS_DARWIN 1
  96172. #endif
  96173. /*** End of inlined file: juce_FlacHeader.h ***/
  96174. #if JUCE_USE_FLAC
  96175. #if HAVE_CONFIG_H
  96176. # include <config.h>
  96177. #endif
  96178. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96179. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96180. #ifdef _MSC_VER
  96181. #define FLAC__U64L(x) x
  96182. #else
  96183. #define FLAC__U64L(x) x##LLU
  96184. #endif
  96185. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96186. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96187. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96188. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96189. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96190. /* Lookup tables for Knuth's logarithm algorithm */
  96191. #define LOG2_LOOKUP_PRECISION 16
  96192. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96193. {
  96194. /*
  96195. * 0 fraction bits
  96196. */
  96197. /* undefined */ 0x00000000,
  96198. /* lg(2/1) = */ 0x00000001,
  96199. /* lg(4/3) = */ 0x00000000,
  96200. /* lg(8/7) = */ 0x00000000,
  96201. /* lg(16/15) = */ 0x00000000,
  96202. /* lg(32/31) = */ 0x00000000,
  96203. /* lg(64/63) = */ 0x00000000,
  96204. /* lg(128/127) = */ 0x00000000,
  96205. /* lg(256/255) = */ 0x00000000,
  96206. /* lg(512/511) = */ 0x00000000,
  96207. /* lg(1024/1023) = */ 0x00000000,
  96208. /* lg(2048/2047) = */ 0x00000000,
  96209. /* lg(4096/4095) = */ 0x00000000,
  96210. /* lg(8192/8191) = */ 0x00000000,
  96211. /* lg(16384/16383) = */ 0x00000000,
  96212. /* lg(32768/32767) = */ 0x00000000
  96213. },
  96214. {
  96215. /*
  96216. * 4 fraction bits
  96217. */
  96218. /* undefined */ 0x00000000,
  96219. /* lg(2/1) = */ 0x00000010,
  96220. /* lg(4/3) = */ 0x00000007,
  96221. /* lg(8/7) = */ 0x00000003,
  96222. /* lg(16/15) = */ 0x00000001,
  96223. /* lg(32/31) = */ 0x00000001,
  96224. /* lg(64/63) = */ 0x00000000,
  96225. /* lg(128/127) = */ 0x00000000,
  96226. /* lg(256/255) = */ 0x00000000,
  96227. /* lg(512/511) = */ 0x00000000,
  96228. /* lg(1024/1023) = */ 0x00000000,
  96229. /* lg(2048/2047) = */ 0x00000000,
  96230. /* lg(4096/4095) = */ 0x00000000,
  96231. /* lg(8192/8191) = */ 0x00000000,
  96232. /* lg(16384/16383) = */ 0x00000000,
  96233. /* lg(32768/32767) = */ 0x00000000
  96234. },
  96235. {
  96236. /*
  96237. * 8 fraction bits
  96238. */
  96239. /* undefined */ 0x00000000,
  96240. /* lg(2/1) = */ 0x00000100,
  96241. /* lg(4/3) = */ 0x0000006a,
  96242. /* lg(8/7) = */ 0x00000031,
  96243. /* lg(16/15) = */ 0x00000018,
  96244. /* lg(32/31) = */ 0x0000000c,
  96245. /* lg(64/63) = */ 0x00000006,
  96246. /* lg(128/127) = */ 0x00000003,
  96247. /* lg(256/255) = */ 0x00000001,
  96248. /* lg(512/511) = */ 0x00000001,
  96249. /* lg(1024/1023) = */ 0x00000000,
  96250. /* lg(2048/2047) = */ 0x00000000,
  96251. /* lg(4096/4095) = */ 0x00000000,
  96252. /* lg(8192/8191) = */ 0x00000000,
  96253. /* lg(16384/16383) = */ 0x00000000,
  96254. /* lg(32768/32767) = */ 0x00000000
  96255. },
  96256. {
  96257. /*
  96258. * 12 fraction bits
  96259. */
  96260. /* undefined */ 0x00000000,
  96261. /* lg(2/1) = */ 0x00001000,
  96262. /* lg(4/3) = */ 0x000006a4,
  96263. /* lg(8/7) = */ 0x00000315,
  96264. /* lg(16/15) = */ 0x0000017d,
  96265. /* lg(32/31) = */ 0x000000bc,
  96266. /* lg(64/63) = */ 0x0000005d,
  96267. /* lg(128/127) = */ 0x0000002e,
  96268. /* lg(256/255) = */ 0x00000017,
  96269. /* lg(512/511) = */ 0x0000000c,
  96270. /* lg(1024/1023) = */ 0x00000006,
  96271. /* lg(2048/2047) = */ 0x00000003,
  96272. /* lg(4096/4095) = */ 0x00000001,
  96273. /* lg(8192/8191) = */ 0x00000001,
  96274. /* lg(16384/16383) = */ 0x00000000,
  96275. /* lg(32768/32767) = */ 0x00000000
  96276. },
  96277. {
  96278. /*
  96279. * 16 fraction bits
  96280. */
  96281. /* undefined */ 0x00000000,
  96282. /* lg(2/1) = */ 0x00010000,
  96283. /* lg(4/3) = */ 0x00006a40,
  96284. /* lg(8/7) = */ 0x00003151,
  96285. /* lg(16/15) = */ 0x000017d6,
  96286. /* lg(32/31) = */ 0x00000bba,
  96287. /* lg(64/63) = */ 0x000005d1,
  96288. /* lg(128/127) = */ 0x000002e6,
  96289. /* lg(256/255) = */ 0x00000172,
  96290. /* lg(512/511) = */ 0x000000b9,
  96291. /* lg(1024/1023) = */ 0x0000005c,
  96292. /* lg(2048/2047) = */ 0x0000002e,
  96293. /* lg(4096/4095) = */ 0x00000017,
  96294. /* lg(8192/8191) = */ 0x0000000c,
  96295. /* lg(16384/16383) = */ 0x00000006,
  96296. /* lg(32768/32767) = */ 0x00000003
  96297. },
  96298. {
  96299. /*
  96300. * 20 fraction bits
  96301. */
  96302. /* undefined */ 0x00000000,
  96303. /* lg(2/1) = */ 0x00100000,
  96304. /* lg(4/3) = */ 0x0006a3fe,
  96305. /* lg(8/7) = */ 0x00031513,
  96306. /* lg(16/15) = */ 0x00017d60,
  96307. /* lg(32/31) = */ 0x0000bb9d,
  96308. /* lg(64/63) = */ 0x00005d10,
  96309. /* lg(128/127) = */ 0x00002e59,
  96310. /* lg(256/255) = */ 0x00001721,
  96311. /* lg(512/511) = */ 0x00000b8e,
  96312. /* lg(1024/1023) = */ 0x000005c6,
  96313. /* lg(2048/2047) = */ 0x000002e3,
  96314. /* lg(4096/4095) = */ 0x00000171,
  96315. /* lg(8192/8191) = */ 0x000000b9,
  96316. /* lg(16384/16383) = */ 0x0000005c,
  96317. /* lg(32768/32767) = */ 0x0000002e
  96318. },
  96319. {
  96320. /*
  96321. * 24 fraction bits
  96322. */
  96323. /* undefined */ 0x00000000,
  96324. /* lg(2/1) = */ 0x01000000,
  96325. /* lg(4/3) = */ 0x006a3fe6,
  96326. /* lg(8/7) = */ 0x00315130,
  96327. /* lg(16/15) = */ 0x0017d605,
  96328. /* lg(32/31) = */ 0x000bb9ca,
  96329. /* lg(64/63) = */ 0x0005d0fc,
  96330. /* lg(128/127) = */ 0x0002e58f,
  96331. /* lg(256/255) = */ 0x0001720e,
  96332. /* lg(512/511) = */ 0x0000b8d8,
  96333. /* lg(1024/1023) = */ 0x00005c61,
  96334. /* lg(2048/2047) = */ 0x00002e2d,
  96335. /* lg(4096/4095) = */ 0x00001716,
  96336. /* lg(8192/8191) = */ 0x00000b8b,
  96337. /* lg(16384/16383) = */ 0x000005c5,
  96338. /* lg(32768/32767) = */ 0x000002e3
  96339. },
  96340. {
  96341. /*
  96342. * 28 fraction bits
  96343. */
  96344. /* undefined */ 0x00000000,
  96345. /* lg(2/1) = */ 0x10000000,
  96346. /* lg(4/3) = */ 0x06a3fe5c,
  96347. /* lg(8/7) = */ 0x03151301,
  96348. /* lg(16/15) = */ 0x017d6049,
  96349. /* lg(32/31) = */ 0x00bb9ca6,
  96350. /* lg(64/63) = */ 0x005d0fba,
  96351. /* lg(128/127) = */ 0x002e58f7,
  96352. /* lg(256/255) = */ 0x001720da,
  96353. /* lg(512/511) = */ 0x000b8d87,
  96354. /* lg(1024/1023) = */ 0x0005c60b,
  96355. /* lg(2048/2047) = */ 0x0002e2d7,
  96356. /* lg(4096/4095) = */ 0x00017160,
  96357. /* lg(8192/8191) = */ 0x0000b8ad,
  96358. /* lg(16384/16383) = */ 0x00005c56,
  96359. /* lg(32768/32767) = */ 0x00002e2b
  96360. }
  96361. };
  96362. #if 0
  96363. static const FLAC__uint64 log2_lookup_wide[] = {
  96364. {
  96365. /*
  96366. * 32 fraction bits
  96367. */
  96368. /* undefined */ 0x00000000,
  96369. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96370. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96371. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96372. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96373. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96374. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96375. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96376. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96377. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96378. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96379. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96380. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96381. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96382. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96383. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96384. },
  96385. {
  96386. /*
  96387. * 48 fraction bits
  96388. */
  96389. /* undefined */ 0x00000000,
  96390. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96391. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96392. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96393. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96394. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96395. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96396. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96397. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96398. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96399. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96400. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96401. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96402. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96403. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96404. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96405. }
  96406. };
  96407. #endif
  96408. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96409. {
  96410. const FLAC__uint32 ONE = (1u << fracbits);
  96411. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96412. FLAC__ASSERT(fracbits < 32);
  96413. FLAC__ASSERT((fracbits & 0x3) == 0);
  96414. if(x < ONE)
  96415. return 0;
  96416. if(precision > LOG2_LOOKUP_PRECISION)
  96417. precision = LOG2_LOOKUP_PRECISION;
  96418. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96419. {
  96420. FLAC__uint32 y = 0;
  96421. FLAC__uint32 z = x >> 1, k = 1;
  96422. while (x > ONE && k < precision) {
  96423. if (x - z >= ONE) {
  96424. x -= z;
  96425. z = x >> k;
  96426. y += table[k];
  96427. }
  96428. else {
  96429. z >>= 1;
  96430. k++;
  96431. }
  96432. }
  96433. return y;
  96434. }
  96435. }
  96436. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96437. #endif
  96438. /*** End of inlined file: float.c ***/
  96439. /*** Start of inlined file: format.c ***/
  96440. /*** Start of inlined file: juce_FlacHeader.h ***/
  96441. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96442. // tasks..
  96443. #define VERSION "1.2.1"
  96444. #define FLAC__NO_DLL 1
  96445. #if JUCE_MSVC
  96446. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96447. #endif
  96448. #if JUCE_MAC
  96449. #define FLAC__SYS_DARWIN 1
  96450. #endif
  96451. /*** End of inlined file: juce_FlacHeader.h ***/
  96452. #if JUCE_USE_FLAC
  96453. #if HAVE_CONFIG_H
  96454. # include <config.h>
  96455. #endif
  96456. #include <stdio.h>
  96457. #include <stdlib.h> /* for qsort() */
  96458. #include <string.h> /* for memset() */
  96459. #ifndef FLaC__INLINE
  96460. #define FLaC__INLINE
  96461. #endif
  96462. #ifdef min
  96463. #undef min
  96464. #endif
  96465. #define min(a,b) ((a)<(b)?(a):(b))
  96466. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96467. #ifdef _MSC_VER
  96468. #define FLAC__U64L(x) x
  96469. #else
  96470. #define FLAC__U64L(x) x##LLU
  96471. #endif
  96472. /* VERSION should come from configure */
  96473. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96474. ;
  96475. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96476. /* yet one more hack because of MSVC6: */
  96477. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96478. #else
  96479. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96480. #endif
  96481. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96482. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96483. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96484. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96485. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96486. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96487. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96488. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96489. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96490. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96491. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96492. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96493. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96494. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96495. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96496. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96497. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96498. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96499. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96500. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96501. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96502. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96503. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96504. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96505. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96506. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96507. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96508. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96509. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96510. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96511. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96512. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96513. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96514. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96515. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96516. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96517. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96518. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96519. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96520. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96521. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96522. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96523. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96524. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96525. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96526. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96527. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96528. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96529. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96530. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96531. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96532. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96533. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96534. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96535. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96536. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96537. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96538. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96539. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96540. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96541. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96542. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96543. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96544. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96545. "PARTITIONED_RICE",
  96546. "PARTITIONED_RICE2"
  96547. };
  96548. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96549. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96550. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96551. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96552. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96553. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96554. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96555. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96556. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96557. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96558. "CONSTANT",
  96559. "VERBATIM",
  96560. "FIXED",
  96561. "LPC"
  96562. };
  96563. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96564. "INDEPENDENT",
  96565. "LEFT_SIDE",
  96566. "RIGHT_SIDE",
  96567. "MID_SIDE"
  96568. };
  96569. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96570. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96571. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96572. };
  96573. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96574. "STREAMINFO",
  96575. "PADDING",
  96576. "APPLICATION",
  96577. "SEEKTABLE",
  96578. "VORBIS_COMMENT",
  96579. "CUESHEET",
  96580. "PICTURE"
  96581. };
  96582. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96583. "Other",
  96584. "32x32 pixels 'file icon' (PNG only)",
  96585. "Other file icon",
  96586. "Cover (front)",
  96587. "Cover (back)",
  96588. "Leaflet page",
  96589. "Media (e.g. label side of CD)",
  96590. "Lead artist/lead performer/soloist",
  96591. "Artist/performer",
  96592. "Conductor",
  96593. "Band/Orchestra",
  96594. "Composer",
  96595. "Lyricist/text writer",
  96596. "Recording Location",
  96597. "During recording",
  96598. "During performance",
  96599. "Movie/video screen capture",
  96600. "A bright coloured fish",
  96601. "Illustration",
  96602. "Band/artist logotype",
  96603. "Publisher/Studio logotype"
  96604. };
  96605. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96606. {
  96607. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96608. return false;
  96609. }
  96610. else
  96611. return true;
  96612. }
  96613. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96614. {
  96615. if(
  96616. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96617. (
  96618. sample_rate >= (1u << 16) &&
  96619. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96620. )
  96621. ) {
  96622. return false;
  96623. }
  96624. else
  96625. return true;
  96626. }
  96627. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96628. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96629. {
  96630. unsigned i;
  96631. FLAC__uint64 prev_sample_number = 0;
  96632. FLAC__bool got_prev = false;
  96633. FLAC__ASSERT(0 != seek_table);
  96634. for(i = 0; i < seek_table->num_points; i++) {
  96635. if(got_prev) {
  96636. if(
  96637. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96638. seek_table->points[i].sample_number <= prev_sample_number
  96639. )
  96640. return false;
  96641. }
  96642. prev_sample_number = seek_table->points[i].sample_number;
  96643. got_prev = true;
  96644. }
  96645. return true;
  96646. }
  96647. /* used as the sort predicate for qsort() */
  96648. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96649. {
  96650. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96651. if(l->sample_number == r->sample_number)
  96652. return 0;
  96653. else if(l->sample_number < r->sample_number)
  96654. return -1;
  96655. else
  96656. return 1;
  96657. }
  96658. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96659. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96660. {
  96661. unsigned i, j;
  96662. FLAC__bool first;
  96663. FLAC__ASSERT(0 != seek_table);
  96664. /* sort the seekpoints */
  96665. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96666. /* uniquify the seekpoints */
  96667. first = true;
  96668. for(i = j = 0; i < seek_table->num_points; i++) {
  96669. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96670. if(!first) {
  96671. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96672. continue;
  96673. }
  96674. }
  96675. first = false;
  96676. seek_table->points[j++] = seek_table->points[i];
  96677. }
  96678. for(i = j; i < seek_table->num_points; i++) {
  96679. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96680. seek_table->points[i].stream_offset = 0;
  96681. seek_table->points[i].frame_samples = 0;
  96682. }
  96683. return j;
  96684. }
  96685. /*
  96686. * also disallows non-shortest-form encodings, c.f.
  96687. * http://www.unicode.org/versions/corrigendum1.html
  96688. * and a more clear explanation at the end of this section:
  96689. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96690. */
  96691. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96692. {
  96693. FLAC__ASSERT(0 != utf8);
  96694. if ((utf8[0] & 0x80) == 0) {
  96695. return 1;
  96696. }
  96697. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96698. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96699. return 0;
  96700. return 2;
  96701. }
  96702. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96703. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96704. return 0;
  96705. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96706. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96707. return 0;
  96708. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96709. return 0;
  96710. return 3;
  96711. }
  96712. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96713. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96714. return 0;
  96715. return 4;
  96716. }
  96717. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96718. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96719. return 0;
  96720. return 5;
  96721. }
  96722. 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) {
  96723. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96724. return 0;
  96725. return 6;
  96726. }
  96727. else {
  96728. return 0;
  96729. }
  96730. }
  96731. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96732. {
  96733. char c;
  96734. for(c = *name; c; c = *(++name))
  96735. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96736. return false;
  96737. return true;
  96738. }
  96739. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96740. {
  96741. if(length == (unsigned)(-1)) {
  96742. while(*value) {
  96743. unsigned n = utf8len_(value);
  96744. if(n == 0)
  96745. return false;
  96746. value += n;
  96747. }
  96748. }
  96749. else {
  96750. const FLAC__byte *end = value + length;
  96751. while(value < end) {
  96752. unsigned n = utf8len_(value);
  96753. if(n == 0)
  96754. return false;
  96755. value += n;
  96756. }
  96757. if(value != end)
  96758. return false;
  96759. }
  96760. return true;
  96761. }
  96762. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96763. {
  96764. const FLAC__byte *s, *end;
  96765. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96766. if(*s < 0x20 || *s > 0x7D)
  96767. return false;
  96768. }
  96769. if(s == end)
  96770. return false;
  96771. s++; /* skip '=' */
  96772. while(s < end) {
  96773. unsigned n = utf8len_(s);
  96774. if(n == 0)
  96775. return false;
  96776. s += n;
  96777. }
  96778. if(s != end)
  96779. return false;
  96780. return true;
  96781. }
  96782. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96783. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96784. {
  96785. unsigned i, j;
  96786. if(check_cd_da_subset) {
  96787. if(cue_sheet->lead_in < 2 * 44100) {
  96788. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96789. return false;
  96790. }
  96791. if(cue_sheet->lead_in % 588 != 0) {
  96792. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96793. return false;
  96794. }
  96795. }
  96796. if(cue_sheet->num_tracks == 0) {
  96797. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96798. return false;
  96799. }
  96800. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96801. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96802. return false;
  96803. }
  96804. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96805. if(cue_sheet->tracks[i].number == 0) {
  96806. if(violation) *violation = "cue sheet may not have a track number 0";
  96807. return false;
  96808. }
  96809. if(check_cd_da_subset) {
  96810. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96811. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96812. return false;
  96813. }
  96814. }
  96815. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96816. if(violation) {
  96817. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96818. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96819. else
  96820. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96821. }
  96822. return false;
  96823. }
  96824. if(i < cue_sheet->num_tracks - 1) {
  96825. if(cue_sheet->tracks[i].num_indices == 0) {
  96826. if(violation) *violation = "cue sheet track must have at least one index point";
  96827. return false;
  96828. }
  96829. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96830. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96831. return false;
  96832. }
  96833. }
  96834. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96835. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96836. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96837. return false;
  96838. }
  96839. if(j > 0) {
  96840. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96841. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96842. return false;
  96843. }
  96844. }
  96845. }
  96846. }
  96847. return true;
  96848. }
  96849. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96850. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96851. {
  96852. char *p;
  96853. FLAC__byte *b;
  96854. for(p = picture->mime_type; *p; p++) {
  96855. if(*p < 0x20 || *p > 0x7e) {
  96856. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96857. return false;
  96858. }
  96859. }
  96860. for(b = picture->description; *b; ) {
  96861. unsigned n = utf8len_(b);
  96862. if(n == 0) {
  96863. if(violation) *violation = "description string must be valid UTF-8";
  96864. return false;
  96865. }
  96866. b += n;
  96867. }
  96868. return true;
  96869. }
  96870. /*
  96871. * These routines are private to libFLAC
  96872. */
  96873. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96874. {
  96875. return
  96876. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96877. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96878. blocksize,
  96879. predictor_order
  96880. );
  96881. }
  96882. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96883. {
  96884. unsigned max_rice_partition_order = 0;
  96885. while(!(blocksize & 1)) {
  96886. max_rice_partition_order++;
  96887. blocksize >>= 1;
  96888. }
  96889. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96890. }
  96891. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96892. {
  96893. unsigned max_rice_partition_order = limit;
  96894. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96895. max_rice_partition_order--;
  96896. FLAC__ASSERT(
  96897. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96898. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96899. );
  96900. return max_rice_partition_order;
  96901. }
  96902. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96903. {
  96904. FLAC__ASSERT(0 != object);
  96905. object->parameters = 0;
  96906. object->raw_bits = 0;
  96907. object->capacity_by_order = 0;
  96908. }
  96909. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96910. {
  96911. FLAC__ASSERT(0 != object);
  96912. if(0 != object->parameters)
  96913. free(object->parameters);
  96914. if(0 != object->raw_bits)
  96915. free(object->raw_bits);
  96916. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96917. }
  96918. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96919. {
  96920. FLAC__ASSERT(0 != object);
  96921. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96922. if(object->capacity_by_order < max_partition_order) {
  96923. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96924. return false;
  96925. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96926. return false;
  96927. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96928. object->capacity_by_order = max_partition_order;
  96929. }
  96930. return true;
  96931. }
  96932. #endif
  96933. /*** End of inlined file: format.c ***/
  96934. /*** Start of inlined file: lpc_flac.c ***/
  96935. /*** Start of inlined file: juce_FlacHeader.h ***/
  96936. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96937. // tasks..
  96938. #define VERSION "1.2.1"
  96939. #define FLAC__NO_DLL 1
  96940. #if JUCE_MSVC
  96941. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96942. #endif
  96943. #if JUCE_MAC
  96944. #define FLAC__SYS_DARWIN 1
  96945. #endif
  96946. /*** End of inlined file: juce_FlacHeader.h ***/
  96947. #if JUCE_USE_FLAC
  96948. #if HAVE_CONFIG_H
  96949. # include <config.h>
  96950. #endif
  96951. #include <math.h>
  96952. /*** Start of inlined file: lpc.h ***/
  96953. #ifndef FLAC__PRIVATE__LPC_H
  96954. #define FLAC__PRIVATE__LPC_H
  96955. #ifdef HAVE_CONFIG_H
  96956. #include <config.h>
  96957. #endif
  96958. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96959. /*
  96960. * FLAC__lpc_window_data()
  96961. * --------------------------------------------------------------------
  96962. * Applies the given window to the data.
  96963. * OPT: asm implementation
  96964. *
  96965. * IN in[0,data_len-1]
  96966. * IN window[0,data_len-1]
  96967. * OUT out[0,lag-1]
  96968. * IN data_len
  96969. */
  96970. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96971. /*
  96972. * FLAC__lpc_compute_autocorrelation()
  96973. * --------------------------------------------------------------------
  96974. * Compute the autocorrelation for lags between 0 and lag-1.
  96975. * Assumes data[] outside of [0,data_len-1] == 0.
  96976. * Asserts that lag > 0.
  96977. *
  96978. * IN data[0,data_len-1]
  96979. * IN data_len
  96980. * IN 0 < lag <= data_len
  96981. * OUT autoc[0,lag-1]
  96982. */
  96983. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96984. #ifndef FLAC__NO_ASM
  96985. # ifdef FLAC__CPU_IA32
  96986. # ifdef FLAC__HAS_NASM
  96987. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96988. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96989. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96990. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96991. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96992. # endif
  96993. # endif
  96994. #endif
  96995. /*
  96996. * FLAC__lpc_compute_lp_coefficients()
  96997. * --------------------------------------------------------------------
  96998. * Computes LP coefficients for orders 1..max_order.
  96999. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97000. * and there is no point in calculating a predictor.
  97001. *
  97002. * IN autoc[0,max_order] autocorrelation values
  97003. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97004. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97005. * *** IMPORTANT:
  97006. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97007. * OUT error[0,max_order-1] error for each order (more
  97008. * specifically, the variance of
  97009. * the error signal times # of
  97010. * samples in the signal)
  97011. *
  97012. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97013. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97014. * in lp_coeff[7][0,7], etc.
  97015. */
  97016. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97017. /*
  97018. * FLAC__lpc_quantize_coefficients()
  97019. * --------------------------------------------------------------------
  97020. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97021. * must be less than 32 (sizeof(FLAC__int32)*8).
  97022. *
  97023. * IN lp_coeff[0,order-1] LP coefficients
  97024. * IN order LP order
  97025. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97026. * desired precision (in bits, including sign
  97027. * bit) of largest coefficient
  97028. * OUT qlp_coeff[0,order-1] quantized coefficients
  97029. * OUT shift # of bits to shift right to get approximated
  97030. * LP coefficients. NOTE: could be negative.
  97031. * RETURN 0 => quantization OK
  97032. * 1 => coefficients require too much shifting for *shift to
  97033. * fit in the LPC subframe header. 'shift' is unset.
  97034. * 2 => coefficients are all zero, which is bad. 'shift' is
  97035. * unset.
  97036. */
  97037. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97038. /*
  97039. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97040. * --------------------------------------------------------------------
  97041. * Compute the residual signal obtained from sutracting the predicted
  97042. * signal from the original.
  97043. *
  97044. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97045. * IN data_len length of original signal
  97046. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97047. * IN order > 0 LP order
  97048. * IN lp_quantization quantization of LP coefficients in bits
  97049. * OUT residual[0,data_len-1] residual signal
  97050. */
  97051. 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[]);
  97052. 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[]);
  97053. #ifndef FLAC__NO_ASM
  97054. # ifdef FLAC__CPU_IA32
  97055. # ifdef FLAC__HAS_NASM
  97056. 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[]);
  97057. 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[]);
  97058. # endif
  97059. # endif
  97060. #endif
  97061. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97062. /*
  97063. * FLAC__lpc_restore_signal()
  97064. * --------------------------------------------------------------------
  97065. * Restore the original signal by summing the residual and the
  97066. * predictor.
  97067. *
  97068. * IN residual[0,data_len-1] residual signal
  97069. * IN data_len length of original signal
  97070. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97071. * IN order > 0 LP order
  97072. * IN lp_quantization quantization of LP coefficients in bits
  97073. * *** IMPORTANT: the caller must pass in the historical samples:
  97074. * IN data[-order,-1] previously-reconstructed historical samples
  97075. * OUT data[0,data_len-1] original signal
  97076. */
  97077. 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[]);
  97078. 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[]);
  97079. #ifndef FLAC__NO_ASM
  97080. # ifdef FLAC__CPU_IA32
  97081. # ifdef FLAC__HAS_NASM
  97082. 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[]);
  97083. 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[]);
  97084. # endif /* FLAC__HAS_NASM */
  97085. # elif defined FLAC__CPU_PPC
  97086. 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[]);
  97087. 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[]);
  97088. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97089. #endif /* FLAC__NO_ASM */
  97090. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97091. /*
  97092. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97093. * --------------------------------------------------------------------
  97094. * Compute the expected number of bits per residual signal sample
  97095. * based on the LP error (which is related to the residual variance).
  97096. *
  97097. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97098. * IN total_samples > 0 # of samples in residual signal
  97099. * RETURN expected bits per sample
  97100. */
  97101. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97102. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97103. /*
  97104. * FLAC__lpc_compute_best_order()
  97105. * --------------------------------------------------------------------
  97106. * Compute the best order from the array of signal errors returned
  97107. * during coefficient computation.
  97108. *
  97109. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97110. * IN max_order > 0 max LP order
  97111. * IN total_samples > 0 # of samples in residual signal
  97112. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97113. * (includes warmup sample size and quantized LP coefficient)
  97114. * RETURN [1,max_order] best order
  97115. */
  97116. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97117. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97118. #endif
  97119. /*** End of inlined file: lpc.h ***/
  97120. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97121. #include <stdio.h>
  97122. #endif
  97123. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97124. #ifndef M_LN2
  97125. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97126. #define M_LN2 0.69314718055994530942
  97127. #endif
  97128. /* OPT: #undef'ing this may improve the speed on some architectures */
  97129. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97130. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97131. {
  97132. unsigned i;
  97133. for(i = 0; i < data_len; i++)
  97134. out[i] = in[i] * window[i];
  97135. }
  97136. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97137. {
  97138. /* a readable, but slower, version */
  97139. #if 0
  97140. FLAC__real d;
  97141. unsigned i;
  97142. FLAC__ASSERT(lag > 0);
  97143. FLAC__ASSERT(lag <= data_len);
  97144. /*
  97145. * Technically we should subtract the mean first like so:
  97146. * for(i = 0; i < data_len; i++)
  97147. * data[i] -= mean;
  97148. * but it appears not to make enough of a difference to matter, and
  97149. * most signals are already closely centered around zero
  97150. */
  97151. while(lag--) {
  97152. for(i = lag, d = 0.0; i < data_len; i++)
  97153. d += data[i] * data[i - lag];
  97154. autoc[lag] = d;
  97155. }
  97156. #endif
  97157. /*
  97158. * this version tends to run faster because of better data locality
  97159. * ('data_len' is usually much larger than 'lag')
  97160. */
  97161. FLAC__real d;
  97162. unsigned sample, coeff;
  97163. const unsigned limit = data_len - lag;
  97164. FLAC__ASSERT(lag > 0);
  97165. FLAC__ASSERT(lag <= data_len);
  97166. for(coeff = 0; coeff < lag; coeff++)
  97167. autoc[coeff] = 0.0;
  97168. for(sample = 0; sample <= limit; sample++) {
  97169. d = data[sample];
  97170. for(coeff = 0; coeff < lag; coeff++)
  97171. autoc[coeff] += d * data[sample+coeff];
  97172. }
  97173. for(; sample < data_len; sample++) {
  97174. d = data[sample];
  97175. for(coeff = 0; coeff < data_len - sample; coeff++)
  97176. autoc[coeff] += d * data[sample+coeff];
  97177. }
  97178. }
  97179. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97180. {
  97181. unsigned i, j;
  97182. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97183. FLAC__ASSERT(0 != max_order);
  97184. FLAC__ASSERT(0 < *max_order);
  97185. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97186. FLAC__ASSERT(autoc[0] != 0.0);
  97187. err = autoc[0];
  97188. for(i = 0; i < *max_order; i++) {
  97189. /* Sum up this iteration's reflection coefficient. */
  97190. r = -autoc[i+1];
  97191. for(j = 0; j < i; j++)
  97192. r -= lpc[j] * autoc[i-j];
  97193. ref[i] = (r/=err);
  97194. /* Update LPC coefficients and total error. */
  97195. lpc[i]=r;
  97196. for(j = 0; j < (i>>1); j++) {
  97197. FLAC__double tmp = lpc[j];
  97198. lpc[j] += r * lpc[i-1-j];
  97199. lpc[i-1-j] += r * tmp;
  97200. }
  97201. if(i & 1)
  97202. lpc[j] += lpc[j] * r;
  97203. err *= (1.0 - r * r);
  97204. /* save this order */
  97205. for(j = 0; j <= i; j++)
  97206. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97207. error[i] = err;
  97208. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97209. if(err == 0.0) {
  97210. *max_order = i+1;
  97211. return;
  97212. }
  97213. }
  97214. }
  97215. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97216. {
  97217. unsigned i;
  97218. FLAC__double cmax;
  97219. FLAC__int32 qmax, qmin;
  97220. FLAC__ASSERT(precision > 0);
  97221. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97222. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97223. precision--;
  97224. qmax = 1 << precision;
  97225. qmin = -qmax;
  97226. qmax--;
  97227. /* calc cmax = max( |lp_coeff[i]| ) */
  97228. cmax = 0.0;
  97229. for(i = 0; i < order; i++) {
  97230. const FLAC__double d = fabs(lp_coeff[i]);
  97231. if(d > cmax)
  97232. cmax = d;
  97233. }
  97234. if(cmax <= 0.0) {
  97235. /* => coefficients are all 0, which means our constant-detect didn't work */
  97236. return 2;
  97237. }
  97238. else {
  97239. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97240. const int min_shiftlimit = -max_shiftlimit - 1;
  97241. int log2cmax;
  97242. (void)frexp(cmax, &log2cmax);
  97243. log2cmax--;
  97244. *shift = (int)precision - log2cmax - 1;
  97245. if(*shift > max_shiftlimit)
  97246. *shift = max_shiftlimit;
  97247. else if(*shift < min_shiftlimit)
  97248. return 1;
  97249. }
  97250. if(*shift >= 0) {
  97251. FLAC__double error = 0.0;
  97252. FLAC__int32 q;
  97253. for(i = 0; i < order; i++) {
  97254. error += lp_coeff[i] * (1 << *shift);
  97255. #if 1 /* unfortunately lround() is C99 */
  97256. if(error >= 0.0)
  97257. q = (FLAC__int32)(error + 0.5);
  97258. else
  97259. q = (FLAC__int32)(error - 0.5);
  97260. #else
  97261. q = lround(error);
  97262. #endif
  97263. #ifdef FLAC__OVERFLOW_DETECT
  97264. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97265. 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]);
  97266. else if(q < qmin)
  97267. 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]);
  97268. #endif
  97269. if(q > qmax)
  97270. q = qmax;
  97271. else if(q < qmin)
  97272. q = qmin;
  97273. error -= q;
  97274. qlp_coeff[i] = q;
  97275. }
  97276. }
  97277. /* negative shift is very rare but due to design flaw, negative shift is
  97278. * a NOP in the decoder, so it must be handled specially by scaling down
  97279. * coeffs
  97280. */
  97281. else {
  97282. const int nshift = -(*shift);
  97283. FLAC__double error = 0.0;
  97284. FLAC__int32 q;
  97285. #ifdef DEBUG
  97286. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97287. #endif
  97288. for(i = 0; i < order; i++) {
  97289. error += lp_coeff[i] / (1 << nshift);
  97290. #if 1 /* unfortunately lround() is C99 */
  97291. if(error >= 0.0)
  97292. q = (FLAC__int32)(error + 0.5);
  97293. else
  97294. q = (FLAC__int32)(error - 0.5);
  97295. #else
  97296. q = lround(error);
  97297. #endif
  97298. #ifdef FLAC__OVERFLOW_DETECT
  97299. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97300. 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]);
  97301. else if(q < qmin)
  97302. 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]);
  97303. #endif
  97304. if(q > qmax)
  97305. q = qmax;
  97306. else if(q < qmin)
  97307. q = qmin;
  97308. error -= q;
  97309. qlp_coeff[i] = q;
  97310. }
  97311. *shift = 0;
  97312. }
  97313. return 0;
  97314. }
  97315. 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[])
  97316. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97317. {
  97318. FLAC__int64 sumo;
  97319. unsigned i, j;
  97320. FLAC__int32 sum;
  97321. const FLAC__int32 *history;
  97322. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97323. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97324. for(i=0;i<order;i++)
  97325. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97326. fprintf(stderr,"\n");
  97327. #endif
  97328. FLAC__ASSERT(order > 0);
  97329. for(i = 0; i < data_len; i++) {
  97330. sumo = 0;
  97331. sum = 0;
  97332. history = data;
  97333. for(j = 0; j < order; j++) {
  97334. sum += qlp_coeff[j] * (*(--history));
  97335. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97336. #if defined _MSC_VER
  97337. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97338. 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);
  97339. #else
  97340. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97341. 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);
  97342. #endif
  97343. }
  97344. *(residual++) = *(data++) - (sum >> lp_quantization);
  97345. }
  97346. /* Here's a slower but clearer version:
  97347. for(i = 0; i < data_len; i++) {
  97348. sum = 0;
  97349. for(j = 0; j < order; j++)
  97350. sum += qlp_coeff[j] * data[i-j-1];
  97351. residual[i] = data[i] - (sum >> lp_quantization);
  97352. }
  97353. */
  97354. }
  97355. #else /* fully unrolled version for normal use */
  97356. {
  97357. int i;
  97358. FLAC__int32 sum;
  97359. FLAC__ASSERT(order > 0);
  97360. FLAC__ASSERT(order <= 32);
  97361. /*
  97362. * We do unique versions up to 12th order since that's the subset limit.
  97363. * Also they are roughly ordered to match frequency of occurrence to
  97364. * minimize branching.
  97365. */
  97366. if(order <= 12) {
  97367. if(order > 8) {
  97368. if(order > 10) {
  97369. if(order == 12) {
  97370. for(i = 0; i < (int)data_len; i++) {
  97371. sum = 0;
  97372. sum += qlp_coeff[11] * data[i-12];
  97373. sum += qlp_coeff[10] * data[i-11];
  97374. sum += qlp_coeff[9] * data[i-10];
  97375. sum += qlp_coeff[8] * data[i-9];
  97376. sum += qlp_coeff[7] * data[i-8];
  97377. sum += qlp_coeff[6] * data[i-7];
  97378. sum += qlp_coeff[5] * data[i-6];
  97379. sum += qlp_coeff[4] * data[i-5];
  97380. sum += qlp_coeff[3] * data[i-4];
  97381. sum += qlp_coeff[2] * data[i-3];
  97382. sum += qlp_coeff[1] * data[i-2];
  97383. sum += qlp_coeff[0] * data[i-1];
  97384. residual[i] = data[i] - (sum >> lp_quantization);
  97385. }
  97386. }
  97387. else { /* order == 11 */
  97388. for(i = 0; i < (int)data_len; i++) {
  97389. sum = 0;
  97390. sum += qlp_coeff[10] * data[i-11];
  97391. sum += qlp_coeff[9] * data[i-10];
  97392. sum += qlp_coeff[8] * data[i-9];
  97393. sum += qlp_coeff[7] * data[i-8];
  97394. sum += qlp_coeff[6] * data[i-7];
  97395. sum += qlp_coeff[5] * data[i-6];
  97396. sum += qlp_coeff[4] * data[i-5];
  97397. sum += qlp_coeff[3] * data[i-4];
  97398. sum += qlp_coeff[2] * data[i-3];
  97399. sum += qlp_coeff[1] * data[i-2];
  97400. sum += qlp_coeff[0] * data[i-1];
  97401. residual[i] = data[i] - (sum >> lp_quantization);
  97402. }
  97403. }
  97404. }
  97405. else {
  97406. if(order == 10) {
  97407. for(i = 0; i < (int)data_len; i++) {
  97408. sum = 0;
  97409. sum += qlp_coeff[9] * data[i-10];
  97410. sum += qlp_coeff[8] * data[i-9];
  97411. sum += qlp_coeff[7] * data[i-8];
  97412. sum += qlp_coeff[6] * data[i-7];
  97413. sum += qlp_coeff[5] * data[i-6];
  97414. sum += qlp_coeff[4] * data[i-5];
  97415. sum += qlp_coeff[3] * data[i-4];
  97416. sum += qlp_coeff[2] * data[i-3];
  97417. sum += qlp_coeff[1] * data[i-2];
  97418. sum += qlp_coeff[0] * data[i-1];
  97419. residual[i] = data[i] - (sum >> lp_quantization);
  97420. }
  97421. }
  97422. else { /* order == 9 */
  97423. for(i = 0; i < (int)data_len; i++) {
  97424. sum = 0;
  97425. sum += qlp_coeff[8] * data[i-9];
  97426. sum += qlp_coeff[7] * data[i-8];
  97427. sum += qlp_coeff[6] * data[i-7];
  97428. sum += qlp_coeff[5] * data[i-6];
  97429. sum += qlp_coeff[4] * data[i-5];
  97430. sum += qlp_coeff[3] * data[i-4];
  97431. sum += qlp_coeff[2] * data[i-3];
  97432. sum += qlp_coeff[1] * data[i-2];
  97433. sum += qlp_coeff[0] * data[i-1];
  97434. residual[i] = data[i] - (sum >> lp_quantization);
  97435. }
  97436. }
  97437. }
  97438. }
  97439. else if(order > 4) {
  97440. if(order > 6) {
  97441. if(order == 8) {
  97442. for(i = 0; i < (int)data_len; i++) {
  97443. sum = 0;
  97444. sum += qlp_coeff[7] * data[i-8];
  97445. sum += qlp_coeff[6] * data[i-7];
  97446. sum += qlp_coeff[5] * data[i-6];
  97447. sum += qlp_coeff[4] * data[i-5];
  97448. sum += qlp_coeff[3] * data[i-4];
  97449. sum += qlp_coeff[2] * data[i-3];
  97450. sum += qlp_coeff[1] * data[i-2];
  97451. sum += qlp_coeff[0] * data[i-1];
  97452. residual[i] = data[i] - (sum >> lp_quantization);
  97453. }
  97454. }
  97455. else { /* order == 7 */
  97456. for(i = 0; i < (int)data_len; i++) {
  97457. sum = 0;
  97458. sum += qlp_coeff[6] * data[i-7];
  97459. sum += qlp_coeff[5] * data[i-6];
  97460. sum += qlp_coeff[4] * data[i-5];
  97461. sum += qlp_coeff[3] * data[i-4];
  97462. sum += qlp_coeff[2] * data[i-3];
  97463. sum += qlp_coeff[1] * data[i-2];
  97464. sum += qlp_coeff[0] * data[i-1];
  97465. residual[i] = data[i] - (sum >> lp_quantization);
  97466. }
  97467. }
  97468. }
  97469. else {
  97470. if(order == 6) {
  97471. for(i = 0; i < (int)data_len; i++) {
  97472. sum = 0;
  97473. sum += qlp_coeff[5] * data[i-6];
  97474. sum += qlp_coeff[4] * data[i-5];
  97475. sum += qlp_coeff[3] * data[i-4];
  97476. sum += qlp_coeff[2] * data[i-3];
  97477. sum += qlp_coeff[1] * data[i-2];
  97478. sum += qlp_coeff[0] * data[i-1];
  97479. residual[i] = data[i] - (sum >> lp_quantization);
  97480. }
  97481. }
  97482. else { /* order == 5 */
  97483. for(i = 0; i < (int)data_len; i++) {
  97484. sum = 0;
  97485. sum += qlp_coeff[4] * data[i-5];
  97486. sum += qlp_coeff[3] * data[i-4];
  97487. sum += qlp_coeff[2] * data[i-3];
  97488. sum += qlp_coeff[1] * data[i-2];
  97489. sum += qlp_coeff[0] * data[i-1];
  97490. residual[i] = data[i] - (sum >> lp_quantization);
  97491. }
  97492. }
  97493. }
  97494. }
  97495. else {
  97496. if(order > 2) {
  97497. if(order == 4) {
  97498. for(i = 0; i < (int)data_len; i++) {
  97499. sum = 0;
  97500. sum += qlp_coeff[3] * data[i-4];
  97501. sum += qlp_coeff[2] * data[i-3];
  97502. sum += qlp_coeff[1] * data[i-2];
  97503. sum += qlp_coeff[0] * data[i-1];
  97504. residual[i] = data[i] - (sum >> lp_quantization);
  97505. }
  97506. }
  97507. else { /* order == 3 */
  97508. for(i = 0; i < (int)data_len; i++) {
  97509. sum = 0;
  97510. sum += qlp_coeff[2] * data[i-3];
  97511. sum += qlp_coeff[1] * data[i-2];
  97512. sum += qlp_coeff[0] * data[i-1];
  97513. residual[i] = data[i] - (sum >> lp_quantization);
  97514. }
  97515. }
  97516. }
  97517. else {
  97518. if(order == 2) {
  97519. for(i = 0; i < (int)data_len; i++) {
  97520. sum = 0;
  97521. sum += qlp_coeff[1] * data[i-2];
  97522. sum += qlp_coeff[0] * data[i-1];
  97523. residual[i] = data[i] - (sum >> lp_quantization);
  97524. }
  97525. }
  97526. else { /* order == 1 */
  97527. for(i = 0; i < (int)data_len; i++)
  97528. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97529. }
  97530. }
  97531. }
  97532. }
  97533. else { /* order > 12 */
  97534. for(i = 0; i < (int)data_len; i++) {
  97535. sum = 0;
  97536. switch(order) {
  97537. case 32: sum += qlp_coeff[31] * data[i-32];
  97538. case 31: sum += qlp_coeff[30] * data[i-31];
  97539. case 30: sum += qlp_coeff[29] * data[i-30];
  97540. case 29: sum += qlp_coeff[28] * data[i-29];
  97541. case 28: sum += qlp_coeff[27] * data[i-28];
  97542. case 27: sum += qlp_coeff[26] * data[i-27];
  97543. case 26: sum += qlp_coeff[25] * data[i-26];
  97544. case 25: sum += qlp_coeff[24] * data[i-25];
  97545. case 24: sum += qlp_coeff[23] * data[i-24];
  97546. case 23: sum += qlp_coeff[22] * data[i-23];
  97547. case 22: sum += qlp_coeff[21] * data[i-22];
  97548. case 21: sum += qlp_coeff[20] * data[i-21];
  97549. case 20: sum += qlp_coeff[19] * data[i-20];
  97550. case 19: sum += qlp_coeff[18] * data[i-19];
  97551. case 18: sum += qlp_coeff[17] * data[i-18];
  97552. case 17: sum += qlp_coeff[16] * data[i-17];
  97553. case 16: sum += qlp_coeff[15] * data[i-16];
  97554. case 15: sum += qlp_coeff[14] * data[i-15];
  97555. case 14: sum += qlp_coeff[13] * data[i-14];
  97556. case 13: sum += qlp_coeff[12] * data[i-13];
  97557. sum += qlp_coeff[11] * data[i-12];
  97558. sum += qlp_coeff[10] * data[i-11];
  97559. sum += qlp_coeff[ 9] * data[i-10];
  97560. sum += qlp_coeff[ 8] * data[i- 9];
  97561. sum += qlp_coeff[ 7] * data[i- 8];
  97562. sum += qlp_coeff[ 6] * data[i- 7];
  97563. sum += qlp_coeff[ 5] * data[i- 6];
  97564. sum += qlp_coeff[ 4] * data[i- 5];
  97565. sum += qlp_coeff[ 3] * data[i- 4];
  97566. sum += qlp_coeff[ 2] * data[i- 3];
  97567. sum += qlp_coeff[ 1] * data[i- 2];
  97568. sum += qlp_coeff[ 0] * data[i- 1];
  97569. }
  97570. residual[i] = data[i] - (sum >> lp_quantization);
  97571. }
  97572. }
  97573. }
  97574. #endif
  97575. 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[])
  97576. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97577. {
  97578. unsigned i, j;
  97579. FLAC__int64 sum;
  97580. const FLAC__int32 *history;
  97581. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97582. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97583. for(i=0;i<order;i++)
  97584. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97585. fprintf(stderr,"\n");
  97586. #endif
  97587. FLAC__ASSERT(order > 0);
  97588. for(i = 0; i < data_len; i++) {
  97589. sum = 0;
  97590. history = data;
  97591. for(j = 0; j < order; j++)
  97592. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97593. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97594. #if defined _MSC_VER
  97595. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97596. #else
  97597. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97598. #endif
  97599. break;
  97600. }
  97601. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97602. #if defined _MSC_VER
  97603. 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));
  97604. #else
  97605. 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)));
  97606. #endif
  97607. break;
  97608. }
  97609. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97610. }
  97611. }
  97612. #else /* fully unrolled version for normal use */
  97613. {
  97614. int i;
  97615. FLAC__int64 sum;
  97616. FLAC__ASSERT(order > 0);
  97617. FLAC__ASSERT(order <= 32);
  97618. /*
  97619. * We do unique versions up to 12th order since that's the subset limit.
  97620. * Also they are roughly ordered to match frequency of occurrence to
  97621. * minimize branching.
  97622. */
  97623. if(order <= 12) {
  97624. if(order > 8) {
  97625. if(order > 10) {
  97626. if(order == 12) {
  97627. for(i = 0; i < (int)data_len; i++) {
  97628. sum = 0;
  97629. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97630. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97631. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97632. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97633. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97634. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97635. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97636. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97637. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97638. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97639. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97640. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97641. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97642. }
  97643. }
  97644. else { /* order == 11 */
  97645. for(i = 0; i < (int)data_len; i++) {
  97646. sum = 0;
  97647. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97648. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97649. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97650. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97651. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97652. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97653. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97654. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97655. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97656. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97657. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97658. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97659. }
  97660. }
  97661. }
  97662. else {
  97663. if(order == 10) {
  97664. for(i = 0; i < (int)data_len; i++) {
  97665. sum = 0;
  97666. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97667. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97668. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97669. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97670. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97671. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97672. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97673. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97674. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97675. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97676. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97677. }
  97678. }
  97679. else { /* order == 9 */
  97680. for(i = 0; i < (int)data_len; i++) {
  97681. sum = 0;
  97682. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97683. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97684. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97685. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97686. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97687. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97688. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97689. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97690. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97691. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97692. }
  97693. }
  97694. }
  97695. }
  97696. else if(order > 4) {
  97697. if(order > 6) {
  97698. if(order == 8) {
  97699. for(i = 0; i < (int)data_len; i++) {
  97700. sum = 0;
  97701. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97702. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97703. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97704. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97705. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97706. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97707. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97708. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97709. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97710. }
  97711. }
  97712. else { /* order == 7 */
  97713. for(i = 0; i < (int)data_len; i++) {
  97714. sum = 0;
  97715. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97716. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97717. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97718. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97719. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97720. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97721. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97722. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97723. }
  97724. }
  97725. }
  97726. else {
  97727. if(order == 6) {
  97728. for(i = 0; i < (int)data_len; i++) {
  97729. sum = 0;
  97730. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97731. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97732. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97733. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97734. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97735. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97736. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97737. }
  97738. }
  97739. else { /* order == 5 */
  97740. for(i = 0; i < (int)data_len; i++) {
  97741. sum = 0;
  97742. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97743. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97744. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97745. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97746. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97747. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97748. }
  97749. }
  97750. }
  97751. }
  97752. else {
  97753. if(order > 2) {
  97754. if(order == 4) {
  97755. for(i = 0; i < (int)data_len; i++) {
  97756. sum = 0;
  97757. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97758. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97759. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97760. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97761. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97762. }
  97763. }
  97764. else { /* order == 3 */
  97765. for(i = 0; i < (int)data_len; i++) {
  97766. sum = 0;
  97767. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97768. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97769. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97770. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97771. }
  97772. }
  97773. }
  97774. else {
  97775. if(order == 2) {
  97776. for(i = 0; i < (int)data_len; i++) {
  97777. sum = 0;
  97778. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97779. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97780. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97781. }
  97782. }
  97783. else { /* order == 1 */
  97784. for(i = 0; i < (int)data_len; i++)
  97785. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97786. }
  97787. }
  97788. }
  97789. }
  97790. else { /* order > 12 */
  97791. for(i = 0; i < (int)data_len; i++) {
  97792. sum = 0;
  97793. switch(order) {
  97794. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97795. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97796. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97797. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97798. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97799. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97800. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97801. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97802. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97803. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97804. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97805. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97806. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97807. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97808. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97809. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97810. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97811. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97812. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97813. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97814. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97815. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97816. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97817. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97818. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97819. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97820. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97821. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97822. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97823. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97824. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97825. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97826. }
  97827. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97828. }
  97829. }
  97830. }
  97831. #endif
  97832. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97833. 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[])
  97834. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97835. {
  97836. FLAC__int64 sumo;
  97837. unsigned i, j;
  97838. FLAC__int32 sum;
  97839. const FLAC__int32 *r = residual, *history;
  97840. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97841. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97842. for(i=0;i<order;i++)
  97843. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97844. fprintf(stderr,"\n");
  97845. #endif
  97846. FLAC__ASSERT(order > 0);
  97847. for(i = 0; i < data_len; i++) {
  97848. sumo = 0;
  97849. sum = 0;
  97850. history = data;
  97851. for(j = 0; j < order; j++) {
  97852. sum += qlp_coeff[j] * (*(--history));
  97853. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97854. #if defined _MSC_VER
  97855. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97856. 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);
  97857. #else
  97858. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97859. 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);
  97860. #endif
  97861. }
  97862. *(data++) = *(r++) + (sum >> lp_quantization);
  97863. }
  97864. /* Here's a slower but clearer version:
  97865. for(i = 0; i < data_len; i++) {
  97866. sum = 0;
  97867. for(j = 0; j < order; j++)
  97868. sum += qlp_coeff[j] * data[i-j-1];
  97869. data[i] = residual[i] + (sum >> lp_quantization);
  97870. }
  97871. */
  97872. }
  97873. #else /* fully unrolled version for normal use */
  97874. {
  97875. int i;
  97876. FLAC__int32 sum;
  97877. FLAC__ASSERT(order > 0);
  97878. FLAC__ASSERT(order <= 32);
  97879. /*
  97880. * We do unique versions up to 12th order since that's the subset limit.
  97881. * Also they are roughly ordered to match frequency of occurrence to
  97882. * minimize branching.
  97883. */
  97884. if(order <= 12) {
  97885. if(order > 8) {
  97886. if(order > 10) {
  97887. if(order == 12) {
  97888. for(i = 0; i < (int)data_len; i++) {
  97889. sum = 0;
  97890. sum += qlp_coeff[11] * data[i-12];
  97891. sum += qlp_coeff[10] * data[i-11];
  97892. sum += qlp_coeff[9] * data[i-10];
  97893. sum += qlp_coeff[8] * data[i-9];
  97894. sum += qlp_coeff[7] * data[i-8];
  97895. sum += qlp_coeff[6] * data[i-7];
  97896. sum += qlp_coeff[5] * data[i-6];
  97897. sum += qlp_coeff[4] * data[i-5];
  97898. sum += qlp_coeff[3] * data[i-4];
  97899. sum += qlp_coeff[2] * data[i-3];
  97900. sum += qlp_coeff[1] * data[i-2];
  97901. sum += qlp_coeff[0] * data[i-1];
  97902. data[i] = residual[i] + (sum >> lp_quantization);
  97903. }
  97904. }
  97905. else { /* order == 11 */
  97906. for(i = 0; i < (int)data_len; i++) {
  97907. sum = 0;
  97908. sum += qlp_coeff[10] * data[i-11];
  97909. sum += qlp_coeff[9] * data[i-10];
  97910. sum += qlp_coeff[8] * data[i-9];
  97911. sum += qlp_coeff[7] * data[i-8];
  97912. sum += qlp_coeff[6] * data[i-7];
  97913. sum += qlp_coeff[5] * data[i-6];
  97914. sum += qlp_coeff[4] * data[i-5];
  97915. sum += qlp_coeff[3] * data[i-4];
  97916. sum += qlp_coeff[2] * data[i-3];
  97917. sum += qlp_coeff[1] * data[i-2];
  97918. sum += qlp_coeff[0] * data[i-1];
  97919. data[i] = residual[i] + (sum >> lp_quantization);
  97920. }
  97921. }
  97922. }
  97923. else {
  97924. if(order == 10) {
  97925. for(i = 0; i < (int)data_len; i++) {
  97926. sum = 0;
  97927. sum += qlp_coeff[9] * data[i-10];
  97928. sum += qlp_coeff[8] * data[i-9];
  97929. sum += qlp_coeff[7] * data[i-8];
  97930. sum += qlp_coeff[6] * data[i-7];
  97931. sum += qlp_coeff[5] * data[i-6];
  97932. sum += qlp_coeff[4] * data[i-5];
  97933. sum += qlp_coeff[3] * data[i-4];
  97934. sum += qlp_coeff[2] * data[i-3];
  97935. sum += qlp_coeff[1] * data[i-2];
  97936. sum += qlp_coeff[0] * data[i-1];
  97937. data[i] = residual[i] + (sum >> lp_quantization);
  97938. }
  97939. }
  97940. else { /* order == 9 */
  97941. for(i = 0; i < (int)data_len; i++) {
  97942. sum = 0;
  97943. sum += qlp_coeff[8] * data[i-9];
  97944. sum += qlp_coeff[7] * data[i-8];
  97945. sum += qlp_coeff[6] * data[i-7];
  97946. sum += qlp_coeff[5] * data[i-6];
  97947. sum += qlp_coeff[4] * data[i-5];
  97948. sum += qlp_coeff[3] * data[i-4];
  97949. sum += qlp_coeff[2] * data[i-3];
  97950. sum += qlp_coeff[1] * data[i-2];
  97951. sum += qlp_coeff[0] * data[i-1];
  97952. data[i] = residual[i] + (sum >> lp_quantization);
  97953. }
  97954. }
  97955. }
  97956. }
  97957. else if(order > 4) {
  97958. if(order > 6) {
  97959. if(order == 8) {
  97960. for(i = 0; i < (int)data_len; i++) {
  97961. sum = 0;
  97962. sum += qlp_coeff[7] * data[i-8];
  97963. sum += qlp_coeff[6] * data[i-7];
  97964. sum += qlp_coeff[5] * data[i-6];
  97965. sum += qlp_coeff[4] * data[i-5];
  97966. sum += qlp_coeff[3] * data[i-4];
  97967. sum += qlp_coeff[2] * data[i-3];
  97968. sum += qlp_coeff[1] * data[i-2];
  97969. sum += qlp_coeff[0] * data[i-1];
  97970. data[i] = residual[i] + (sum >> lp_quantization);
  97971. }
  97972. }
  97973. else { /* order == 7 */
  97974. for(i = 0; i < (int)data_len; i++) {
  97975. sum = 0;
  97976. sum += qlp_coeff[6] * data[i-7];
  97977. sum += qlp_coeff[5] * data[i-6];
  97978. sum += qlp_coeff[4] * data[i-5];
  97979. sum += qlp_coeff[3] * data[i-4];
  97980. sum += qlp_coeff[2] * data[i-3];
  97981. sum += qlp_coeff[1] * data[i-2];
  97982. sum += qlp_coeff[0] * data[i-1];
  97983. data[i] = residual[i] + (sum >> lp_quantization);
  97984. }
  97985. }
  97986. }
  97987. else {
  97988. if(order == 6) {
  97989. for(i = 0; i < (int)data_len; i++) {
  97990. sum = 0;
  97991. sum += qlp_coeff[5] * data[i-6];
  97992. sum += qlp_coeff[4] * data[i-5];
  97993. sum += qlp_coeff[3] * data[i-4];
  97994. sum += qlp_coeff[2] * data[i-3];
  97995. sum += qlp_coeff[1] * data[i-2];
  97996. sum += qlp_coeff[0] * data[i-1];
  97997. data[i] = residual[i] + (sum >> lp_quantization);
  97998. }
  97999. }
  98000. else { /* order == 5 */
  98001. for(i = 0; i < (int)data_len; i++) {
  98002. sum = 0;
  98003. sum += qlp_coeff[4] * data[i-5];
  98004. sum += qlp_coeff[3] * data[i-4];
  98005. sum += qlp_coeff[2] * data[i-3];
  98006. sum += qlp_coeff[1] * data[i-2];
  98007. sum += qlp_coeff[0] * data[i-1];
  98008. data[i] = residual[i] + (sum >> lp_quantization);
  98009. }
  98010. }
  98011. }
  98012. }
  98013. else {
  98014. if(order > 2) {
  98015. if(order == 4) {
  98016. for(i = 0; i < (int)data_len; i++) {
  98017. sum = 0;
  98018. sum += qlp_coeff[3] * data[i-4];
  98019. sum += qlp_coeff[2] * data[i-3];
  98020. sum += qlp_coeff[1] * data[i-2];
  98021. sum += qlp_coeff[0] * data[i-1];
  98022. data[i] = residual[i] + (sum >> lp_quantization);
  98023. }
  98024. }
  98025. else { /* order == 3 */
  98026. for(i = 0; i < (int)data_len; i++) {
  98027. sum = 0;
  98028. sum += qlp_coeff[2] * data[i-3];
  98029. sum += qlp_coeff[1] * data[i-2];
  98030. sum += qlp_coeff[0] * data[i-1];
  98031. data[i] = residual[i] + (sum >> lp_quantization);
  98032. }
  98033. }
  98034. }
  98035. else {
  98036. if(order == 2) {
  98037. for(i = 0; i < (int)data_len; i++) {
  98038. sum = 0;
  98039. sum += qlp_coeff[1] * data[i-2];
  98040. sum += qlp_coeff[0] * data[i-1];
  98041. data[i] = residual[i] + (sum >> lp_quantization);
  98042. }
  98043. }
  98044. else { /* order == 1 */
  98045. for(i = 0; i < (int)data_len; i++)
  98046. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98047. }
  98048. }
  98049. }
  98050. }
  98051. else { /* order > 12 */
  98052. for(i = 0; i < (int)data_len; i++) {
  98053. sum = 0;
  98054. switch(order) {
  98055. case 32: sum += qlp_coeff[31] * data[i-32];
  98056. case 31: sum += qlp_coeff[30] * data[i-31];
  98057. case 30: sum += qlp_coeff[29] * data[i-30];
  98058. case 29: sum += qlp_coeff[28] * data[i-29];
  98059. case 28: sum += qlp_coeff[27] * data[i-28];
  98060. case 27: sum += qlp_coeff[26] * data[i-27];
  98061. case 26: sum += qlp_coeff[25] * data[i-26];
  98062. case 25: sum += qlp_coeff[24] * data[i-25];
  98063. case 24: sum += qlp_coeff[23] * data[i-24];
  98064. case 23: sum += qlp_coeff[22] * data[i-23];
  98065. case 22: sum += qlp_coeff[21] * data[i-22];
  98066. case 21: sum += qlp_coeff[20] * data[i-21];
  98067. case 20: sum += qlp_coeff[19] * data[i-20];
  98068. case 19: sum += qlp_coeff[18] * data[i-19];
  98069. case 18: sum += qlp_coeff[17] * data[i-18];
  98070. case 17: sum += qlp_coeff[16] * data[i-17];
  98071. case 16: sum += qlp_coeff[15] * data[i-16];
  98072. case 15: sum += qlp_coeff[14] * data[i-15];
  98073. case 14: sum += qlp_coeff[13] * data[i-14];
  98074. case 13: sum += qlp_coeff[12] * data[i-13];
  98075. sum += qlp_coeff[11] * data[i-12];
  98076. sum += qlp_coeff[10] * data[i-11];
  98077. sum += qlp_coeff[ 9] * data[i-10];
  98078. sum += qlp_coeff[ 8] * data[i- 9];
  98079. sum += qlp_coeff[ 7] * data[i- 8];
  98080. sum += qlp_coeff[ 6] * data[i- 7];
  98081. sum += qlp_coeff[ 5] * data[i- 6];
  98082. sum += qlp_coeff[ 4] * data[i- 5];
  98083. sum += qlp_coeff[ 3] * data[i- 4];
  98084. sum += qlp_coeff[ 2] * data[i- 3];
  98085. sum += qlp_coeff[ 1] * data[i- 2];
  98086. sum += qlp_coeff[ 0] * data[i- 1];
  98087. }
  98088. data[i] = residual[i] + (sum >> lp_quantization);
  98089. }
  98090. }
  98091. }
  98092. #endif
  98093. 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[])
  98094. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98095. {
  98096. unsigned i, j;
  98097. FLAC__int64 sum;
  98098. const FLAC__int32 *r = residual, *history;
  98099. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98100. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98101. for(i=0;i<order;i++)
  98102. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98103. fprintf(stderr,"\n");
  98104. #endif
  98105. FLAC__ASSERT(order > 0);
  98106. for(i = 0; i < data_len; i++) {
  98107. sum = 0;
  98108. history = data;
  98109. for(j = 0; j < order; j++)
  98110. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98111. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98112. #ifdef _MSC_VER
  98113. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98114. #else
  98115. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98116. #endif
  98117. break;
  98118. }
  98119. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98120. #ifdef _MSC_VER
  98121. 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));
  98122. #else
  98123. 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)));
  98124. #endif
  98125. break;
  98126. }
  98127. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98128. }
  98129. }
  98130. #else /* fully unrolled version for normal use */
  98131. {
  98132. int i;
  98133. FLAC__int64 sum;
  98134. FLAC__ASSERT(order > 0);
  98135. FLAC__ASSERT(order <= 32);
  98136. /*
  98137. * We do unique versions up to 12th order since that's the subset limit.
  98138. * Also they are roughly ordered to match frequency of occurrence to
  98139. * minimize branching.
  98140. */
  98141. if(order <= 12) {
  98142. if(order > 8) {
  98143. if(order > 10) {
  98144. if(order == 12) {
  98145. for(i = 0; i < (int)data_len; i++) {
  98146. sum = 0;
  98147. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98148. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98149. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98150. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98151. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98152. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98153. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98154. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98155. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98156. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98157. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98158. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98159. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98160. }
  98161. }
  98162. else { /* order == 11 */
  98163. for(i = 0; i < (int)data_len; i++) {
  98164. sum = 0;
  98165. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98166. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98167. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98168. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98169. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98170. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98171. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98172. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98173. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98174. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98175. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98176. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98177. }
  98178. }
  98179. }
  98180. else {
  98181. if(order == 10) {
  98182. for(i = 0; i < (int)data_len; i++) {
  98183. sum = 0;
  98184. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98185. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98186. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98187. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98188. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98189. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98190. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98191. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98192. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98193. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98194. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98195. }
  98196. }
  98197. else { /* order == 9 */
  98198. for(i = 0; i < (int)data_len; i++) {
  98199. sum = 0;
  98200. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98201. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98202. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98203. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98204. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98205. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98206. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98207. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98208. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98209. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98210. }
  98211. }
  98212. }
  98213. }
  98214. else if(order > 4) {
  98215. if(order > 6) {
  98216. if(order == 8) {
  98217. for(i = 0; i < (int)data_len; i++) {
  98218. sum = 0;
  98219. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98220. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98221. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98222. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98223. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98224. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98225. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98226. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98227. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98228. }
  98229. }
  98230. else { /* order == 7 */
  98231. for(i = 0; i < (int)data_len; i++) {
  98232. sum = 0;
  98233. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98234. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98235. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98236. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98237. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98238. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98239. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98240. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98241. }
  98242. }
  98243. }
  98244. else {
  98245. if(order == 6) {
  98246. for(i = 0; i < (int)data_len; i++) {
  98247. sum = 0;
  98248. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98249. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98250. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98251. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98252. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98253. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98254. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98255. }
  98256. }
  98257. else { /* order == 5 */
  98258. for(i = 0; i < (int)data_len; i++) {
  98259. sum = 0;
  98260. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98261. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98262. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98263. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98264. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98265. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98266. }
  98267. }
  98268. }
  98269. }
  98270. else {
  98271. if(order > 2) {
  98272. if(order == 4) {
  98273. for(i = 0; i < (int)data_len; i++) {
  98274. sum = 0;
  98275. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98276. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98277. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98278. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98279. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98280. }
  98281. }
  98282. else { /* order == 3 */
  98283. for(i = 0; i < (int)data_len; i++) {
  98284. sum = 0;
  98285. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98286. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98287. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98288. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98289. }
  98290. }
  98291. }
  98292. else {
  98293. if(order == 2) {
  98294. for(i = 0; i < (int)data_len; i++) {
  98295. sum = 0;
  98296. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98297. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98298. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98299. }
  98300. }
  98301. else { /* order == 1 */
  98302. for(i = 0; i < (int)data_len; i++)
  98303. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98304. }
  98305. }
  98306. }
  98307. }
  98308. else { /* order > 12 */
  98309. for(i = 0; i < (int)data_len; i++) {
  98310. sum = 0;
  98311. switch(order) {
  98312. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98313. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98314. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98315. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98316. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98317. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98318. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98319. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98320. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98321. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98322. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98323. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98324. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98325. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98326. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98327. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98328. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98329. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98330. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98331. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98332. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98333. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98334. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98335. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98336. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98337. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98338. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98339. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98340. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98341. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98342. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98343. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98344. }
  98345. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98346. }
  98347. }
  98348. }
  98349. #endif
  98350. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98351. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98352. {
  98353. FLAC__double error_scale;
  98354. FLAC__ASSERT(total_samples > 0);
  98355. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98356. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98357. }
  98358. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98359. {
  98360. if(lpc_error > 0.0) {
  98361. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98362. if(bps >= 0.0)
  98363. return bps;
  98364. else
  98365. return 0.0;
  98366. }
  98367. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98368. return 1e32;
  98369. }
  98370. else {
  98371. return 0.0;
  98372. }
  98373. }
  98374. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98375. {
  98376. 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 */
  98377. FLAC__double bits, best_bits, error_scale;
  98378. FLAC__ASSERT(max_order > 0);
  98379. FLAC__ASSERT(total_samples > 0);
  98380. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98381. best_index = 0;
  98382. best_bits = (unsigned)(-1);
  98383. for(index = 0, order = 1; index < max_order; index++, order++) {
  98384. 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);
  98385. if(bits < best_bits) {
  98386. best_index = index;
  98387. best_bits = bits;
  98388. }
  98389. }
  98390. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98391. }
  98392. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98393. #endif
  98394. /*** End of inlined file: lpc_flac.c ***/
  98395. /*** Start of inlined file: md5.c ***/
  98396. /*** Start of inlined file: juce_FlacHeader.h ***/
  98397. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98398. // tasks..
  98399. #define VERSION "1.2.1"
  98400. #define FLAC__NO_DLL 1
  98401. #if JUCE_MSVC
  98402. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98403. #endif
  98404. #if JUCE_MAC
  98405. #define FLAC__SYS_DARWIN 1
  98406. #endif
  98407. /*** End of inlined file: juce_FlacHeader.h ***/
  98408. #if JUCE_USE_FLAC
  98409. #if HAVE_CONFIG_H
  98410. # include <config.h>
  98411. #endif
  98412. #include <stdlib.h> /* for malloc() */
  98413. #include <string.h> /* for memcpy() */
  98414. /*** Start of inlined file: md5.h ***/
  98415. #ifndef FLAC__PRIVATE__MD5_H
  98416. #define FLAC__PRIVATE__MD5_H
  98417. /*
  98418. * This is the header file for the MD5 message-digest algorithm.
  98419. * The algorithm is due to Ron Rivest. This code was
  98420. * written by Colin Plumb in 1993, no copyright is claimed.
  98421. * This code is in the public domain; do with it what you wish.
  98422. *
  98423. * Equivalent code is available from RSA Data Security, Inc.
  98424. * This code has been tested against that, and is equivalent,
  98425. * except that you don't need to include two pages of legalese
  98426. * with every copy.
  98427. *
  98428. * To compute the message digest of a chunk of bytes, declare an
  98429. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98430. * needed on buffers full of bytes, and then call MD5Final, which
  98431. * will fill a supplied 16-byte array with the digest.
  98432. *
  98433. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98434. * header definitions; now uses stuff from dpkg's config.h
  98435. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98436. * Still in the public domain.
  98437. *
  98438. * Josh Coalson: made some changes to integrate with libFLAC.
  98439. * Still in the public domain, with no warranty.
  98440. */
  98441. typedef struct {
  98442. FLAC__uint32 in[16];
  98443. FLAC__uint32 buf[4];
  98444. FLAC__uint32 bytes[2];
  98445. FLAC__byte *internal_buf;
  98446. size_t capacity;
  98447. } FLAC__MD5Context;
  98448. void FLAC__MD5Init(FLAC__MD5Context *context);
  98449. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98450. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98451. #endif
  98452. /*** End of inlined file: md5.h ***/
  98453. #ifndef FLaC__INLINE
  98454. #define FLaC__INLINE
  98455. #endif
  98456. /*
  98457. * This code implements the MD5 message-digest algorithm.
  98458. * The algorithm is due to Ron Rivest. This code was
  98459. * written by Colin Plumb in 1993, no copyright is claimed.
  98460. * This code is in the public domain; do with it what you wish.
  98461. *
  98462. * Equivalent code is available from RSA Data Security, Inc.
  98463. * This code has been tested against that, and is equivalent,
  98464. * except that you don't need to include two pages of legalese
  98465. * with every copy.
  98466. *
  98467. * To compute the message digest of a chunk of bytes, declare an
  98468. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98469. * needed on buffers full of bytes, and then call MD5Final, which
  98470. * will fill a supplied 16-byte array with the digest.
  98471. *
  98472. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98473. * definitions; now uses stuff from dpkg's config.h.
  98474. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98475. * Still in the public domain.
  98476. *
  98477. * Josh Coalson: made some changes to integrate with libFLAC.
  98478. * Still in the public domain.
  98479. */
  98480. /* The four core functions - F1 is optimized somewhat */
  98481. /* #define F1(x, y, z) (x & y | ~x & z) */
  98482. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98483. #define F2(x, y, z) F1(z, x, y)
  98484. #define F3(x, y, z) (x ^ y ^ z)
  98485. #define F4(x, y, z) (y ^ (x | ~z))
  98486. /* This is the central step in the MD5 algorithm. */
  98487. #define MD5STEP(f,w,x,y,z,in,s) \
  98488. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98489. /*
  98490. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98491. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98492. * the data and converts bytes into longwords for this routine.
  98493. */
  98494. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98495. {
  98496. register FLAC__uint32 a, b, c, d;
  98497. a = buf[0];
  98498. b = buf[1];
  98499. c = buf[2];
  98500. d = buf[3];
  98501. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98502. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98503. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98504. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98505. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98506. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98507. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98508. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98509. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98510. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98511. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98512. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98513. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98514. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98515. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98516. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98517. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98518. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98519. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98520. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98521. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98522. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98523. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98524. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98525. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98526. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98527. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98528. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98529. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98530. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98531. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98532. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98533. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98534. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98535. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98536. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98537. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98538. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98539. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98540. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98541. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98542. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98543. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98544. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98545. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98546. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98547. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98548. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98549. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98550. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98551. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98552. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98553. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98554. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98555. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98556. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98557. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98558. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98559. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98560. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98561. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98562. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98563. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98564. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98565. buf[0] += a;
  98566. buf[1] += b;
  98567. buf[2] += c;
  98568. buf[3] += d;
  98569. }
  98570. #if WORDS_BIGENDIAN
  98571. //@@@@@@ OPT: use bswap/intrinsics
  98572. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98573. {
  98574. register FLAC__uint32 x;
  98575. do {
  98576. x = *buf;
  98577. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98578. *buf++ = (x >> 16) | (x << 16);
  98579. } while (--words);
  98580. }
  98581. static void byteSwapX16(FLAC__uint32 *buf)
  98582. {
  98583. register FLAC__uint32 x;
  98584. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98585. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98586. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98587. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98588. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98589. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98590. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98591. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98592. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98593. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98594. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98595. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98596. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98597. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98598. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98599. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98600. }
  98601. #else
  98602. #define byteSwap(buf, words)
  98603. #define byteSwapX16(buf)
  98604. #endif
  98605. /*
  98606. * Update context to reflect the concatenation of another buffer full
  98607. * of bytes.
  98608. */
  98609. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98610. {
  98611. FLAC__uint32 t;
  98612. /* Update byte count */
  98613. t = ctx->bytes[0];
  98614. if ((ctx->bytes[0] = t + len) < t)
  98615. ctx->bytes[1]++; /* Carry from low to high */
  98616. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98617. if (t > len) {
  98618. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98619. return;
  98620. }
  98621. /* First chunk is an odd size */
  98622. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98623. byteSwapX16(ctx->in);
  98624. FLAC__MD5Transform(ctx->buf, ctx->in);
  98625. buf += t;
  98626. len -= t;
  98627. /* Process data in 64-byte chunks */
  98628. while (len >= 64) {
  98629. memcpy(ctx->in, buf, 64);
  98630. byteSwapX16(ctx->in);
  98631. FLAC__MD5Transform(ctx->buf, ctx->in);
  98632. buf += 64;
  98633. len -= 64;
  98634. }
  98635. /* Handle any remaining bytes of data. */
  98636. memcpy(ctx->in, buf, len);
  98637. }
  98638. /*
  98639. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98640. * initialization constants.
  98641. */
  98642. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98643. {
  98644. ctx->buf[0] = 0x67452301;
  98645. ctx->buf[1] = 0xefcdab89;
  98646. ctx->buf[2] = 0x98badcfe;
  98647. ctx->buf[3] = 0x10325476;
  98648. ctx->bytes[0] = 0;
  98649. ctx->bytes[1] = 0;
  98650. ctx->internal_buf = 0;
  98651. ctx->capacity = 0;
  98652. }
  98653. /*
  98654. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98655. * 1 0* (64-bit count of bits processed, MSB-first)
  98656. */
  98657. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98658. {
  98659. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98660. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98661. /* Set the first char of padding to 0x80. There is always room. */
  98662. *p++ = 0x80;
  98663. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98664. count = 56 - 1 - count;
  98665. if (count < 0) { /* Padding forces an extra block */
  98666. memset(p, 0, count + 8);
  98667. byteSwapX16(ctx->in);
  98668. FLAC__MD5Transform(ctx->buf, ctx->in);
  98669. p = (FLAC__byte *)ctx->in;
  98670. count = 56;
  98671. }
  98672. memset(p, 0, count);
  98673. byteSwap(ctx->in, 14);
  98674. /* Append length in bits and transform */
  98675. ctx->in[14] = ctx->bytes[0] << 3;
  98676. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98677. FLAC__MD5Transform(ctx->buf, ctx->in);
  98678. byteSwap(ctx->buf, 4);
  98679. memcpy(digest, ctx->buf, 16);
  98680. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98681. if(0 != ctx->internal_buf) {
  98682. free(ctx->internal_buf);
  98683. ctx->internal_buf = 0;
  98684. ctx->capacity = 0;
  98685. }
  98686. }
  98687. /*
  98688. * Convert the incoming audio signal to a byte stream
  98689. */
  98690. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98691. {
  98692. unsigned channel, sample;
  98693. register FLAC__int32 a_word;
  98694. register FLAC__byte *buf_ = buf;
  98695. #if WORDS_BIGENDIAN
  98696. #else
  98697. if(channels == 2 && bytes_per_sample == 2) {
  98698. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98699. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98700. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98701. *buf1_ = (FLAC__int16)signal[1][sample];
  98702. }
  98703. else if(channels == 1 && bytes_per_sample == 2) {
  98704. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98705. for(sample = 0; sample < samples; sample++)
  98706. *buf1_++ = (FLAC__int16)signal[0][sample];
  98707. }
  98708. else
  98709. #endif
  98710. if(bytes_per_sample == 2) {
  98711. if(channels == 2) {
  98712. for(sample = 0; sample < samples; sample++) {
  98713. a_word = signal[0][sample];
  98714. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98715. *buf_++ = (FLAC__byte)a_word;
  98716. a_word = signal[1][sample];
  98717. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98718. *buf_++ = (FLAC__byte)a_word;
  98719. }
  98720. }
  98721. else if(channels == 1) {
  98722. for(sample = 0; sample < samples; sample++) {
  98723. a_word = signal[0][sample];
  98724. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98725. *buf_++ = (FLAC__byte)a_word;
  98726. }
  98727. }
  98728. else {
  98729. for(sample = 0; sample < samples; sample++) {
  98730. for(channel = 0; channel < channels; channel++) {
  98731. a_word = signal[channel][sample];
  98732. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98733. *buf_++ = (FLAC__byte)a_word;
  98734. }
  98735. }
  98736. }
  98737. }
  98738. else if(bytes_per_sample == 3) {
  98739. if(channels == 2) {
  98740. for(sample = 0; sample < samples; sample++) {
  98741. a_word = signal[0][sample];
  98742. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98743. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98744. *buf_++ = (FLAC__byte)a_word;
  98745. a_word = signal[1][sample];
  98746. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98747. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98748. *buf_++ = (FLAC__byte)a_word;
  98749. }
  98750. }
  98751. else if(channels == 1) {
  98752. for(sample = 0; sample < samples; sample++) {
  98753. a_word = signal[0][sample];
  98754. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98755. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98756. *buf_++ = (FLAC__byte)a_word;
  98757. }
  98758. }
  98759. else {
  98760. for(sample = 0; sample < samples; sample++) {
  98761. for(channel = 0; channel < channels; channel++) {
  98762. a_word = signal[channel][sample];
  98763. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98764. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98765. *buf_++ = (FLAC__byte)a_word;
  98766. }
  98767. }
  98768. }
  98769. }
  98770. else if(bytes_per_sample == 1) {
  98771. if(channels == 2) {
  98772. for(sample = 0; sample < samples; sample++) {
  98773. a_word = signal[0][sample];
  98774. *buf_++ = (FLAC__byte)a_word;
  98775. a_word = signal[1][sample];
  98776. *buf_++ = (FLAC__byte)a_word;
  98777. }
  98778. }
  98779. else if(channels == 1) {
  98780. for(sample = 0; sample < samples; sample++) {
  98781. a_word = signal[0][sample];
  98782. *buf_++ = (FLAC__byte)a_word;
  98783. }
  98784. }
  98785. else {
  98786. for(sample = 0; sample < samples; sample++) {
  98787. for(channel = 0; channel < channels; channel++) {
  98788. a_word = signal[channel][sample];
  98789. *buf_++ = (FLAC__byte)a_word;
  98790. }
  98791. }
  98792. }
  98793. }
  98794. else { /* bytes_per_sample == 4, maybe optimize more later */
  98795. for(sample = 0; sample < samples; sample++) {
  98796. for(channel = 0; channel < channels; channel++) {
  98797. a_word = signal[channel][sample];
  98798. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98799. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98800. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98801. *buf_++ = (FLAC__byte)a_word;
  98802. }
  98803. }
  98804. }
  98805. }
  98806. /*
  98807. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98808. */
  98809. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98810. {
  98811. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98812. /* overflow check */
  98813. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98814. return false;
  98815. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98816. return false;
  98817. if(ctx->capacity < bytes_needed) {
  98818. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98819. if(0 == tmp) {
  98820. free(ctx->internal_buf);
  98821. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98822. return false;
  98823. }
  98824. ctx->internal_buf = tmp;
  98825. ctx->capacity = bytes_needed;
  98826. }
  98827. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98828. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98829. return true;
  98830. }
  98831. #endif
  98832. /*** End of inlined file: md5.c ***/
  98833. /*** Start of inlined file: memory.c ***/
  98834. /*** Start of inlined file: juce_FlacHeader.h ***/
  98835. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98836. // tasks..
  98837. #define VERSION "1.2.1"
  98838. #define FLAC__NO_DLL 1
  98839. #if JUCE_MSVC
  98840. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98841. #endif
  98842. #if JUCE_MAC
  98843. #define FLAC__SYS_DARWIN 1
  98844. #endif
  98845. /*** End of inlined file: juce_FlacHeader.h ***/
  98846. #if JUCE_USE_FLAC
  98847. #if HAVE_CONFIG_H
  98848. # include <config.h>
  98849. #endif
  98850. /*** Start of inlined file: memory.h ***/
  98851. #ifndef FLAC__PRIVATE__MEMORY_H
  98852. #define FLAC__PRIVATE__MEMORY_H
  98853. #ifdef HAVE_CONFIG_H
  98854. #include <config.h>
  98855. #endif
  98856. #include <stdlib.h> /* for size_t */
  98857. /* Returns the unaligned address returned by malloc.
  98858. * Use free() on this address to deallocate.
  98859. */
  98860. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98861. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98862. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98863. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98864. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98865. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98866. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98867. #endif
  98868. #endif
  98869. /*** End of inlined file: memory.h ***/
  98870. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98871. {
  98872. void *x;
  98873. FLAC__ASSERT(0 != aligned_address);
  98874. #ifdef FLAC__ALIGN_MALLOC_DATA
  98875. /* align on 32-byte (256-bit) boundary */
  98876. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98877. #ifdef SIZEOF_VOIDP
  98878. #if SIZEOF_VOIDP == 4
  98879. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98880. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98881. #elif SIZEOF_VOIDP == 8
  98882. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98883. #else
  98884. # error Unsupported sizeof(void*)
  98885. #endif
  98886. #else
  98887. /* there's got to be a better way to do this right for all archs */
  98888. if(sizeof(void*) == sizeof(unsigned))
  98889. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98890. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98891. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98892. else
  98893. return 0;
  98894. #endif
  98895. #else
  98896. x = safe_malloc_(bytes);
  98897. *aligned_address = x;
  98898. #endif
  98899. return x;
  98900. }
  98901. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98902. {
  98903. FLAC__int32 *pu; /* unaligned pointer */
  98904. union { /* union needed to comply with C99 pointer aliasing rules */
  98905. FLAC__int32 *pa; /* aligned pointer */
  98906. void *pv; /* aligned pointer alias */
  98907. } u;
  98908. FLAC__ASSERT(elements > 0);
  98909. FLAC__ASSERT(0 != unaligned_pointer);
  98910. FLAC__ASSERT(0 != aligned_pointer);
  98911. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98912. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98913. if(0 == pu) {
  98914. return false;
  98915. }
  98916. else {
  98917. if(*unaligned_pointer != 0)
  98918. free(*unaligned_pointer);
  98919. *unaligned_pointer = pu;
  98920. *aligned_pointer = u.pa;
  98921. return true;
  98922. }
  98923. }
  98924. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98925. {
  98926. FLAC__uint32 *pu; /* unaligned pointer */
  98927. union { /* union needed to comply with C99 pointer aliasing rules */
  98928. FLAC__uint32 *pa; /* aligned pointer */
  98929. void *pv; /* aligned pointer alias */
  98930. } u;
  98931. FLAC__ASSERT(elements > 0);
  98932. FLAC__ASSERT(0 != unaligned_pointer);
  98933. FLAC__ASSERT(0 != aligned_pointer);
  98934. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98935. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98936. if(0 == pu) {
  98937. return false;
  98938. }
  98939. else {
  98940. if(*unaligned_pointer != 0)
  98941. free(*unaligned_pointer);
  98942. *unaligned_pointer = pu;
  98943. *aligned_pointer = u.pa;
  98944. return true;
  98945. }
  98946. }
  98947. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98948. {
  98949. FLAC__uint64 *pu; /* unaligned pointer */
  98950. union { /* union needed to comply with C99 pointer aliasing rules */
  98951. FLAC__uint64 *pa; /* aligned pointer */
  98952. void *pv; /* aligned pointer alias */
  98953. } u;
  98954. FLAC__ASSERT(elements > 0);
  98955. FLAC__ASSERT(0 != unaligned_pointer);
  98956. FLAC__ASSERT(0 != aligned_pointer);
  98957. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98958. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98959. if(0 == pu) {
  98960. return false;
  98961. }
  98962. else {
  98963. if(*unaligned_pointer != 0)
  98964. free(*unaligned_pointer);
  98965. *unaligned_pointer = pu;
  98966. *aligned_pointer = u.pa;
  98967. return true;
  98968. }
  98969. }
  98970. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98971. {
  98972. unsigned *pu; /* unaligned pointer */
  98973. union { /* union needed to comply with C99 pointer aliasing rules */
  98974. unsigned *pa; /* aligned pointer */
  98975. void *pv; /* aligned pointer alias */
  98976. } u;
  98977. FLAC__ASSERT(elements > 0);
  98978. FLAC__ASSERT(0 != unaligned_pointer);
  98979. FLAC__ASSERT(0 != aligned_pointer);
  98980. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98981. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98982. if(0 == pu) {
  98983. return false;
  98984. }
  98985. else {
  98986. if(*unaligned_pointer != 0)
  98987. free(*unaligned_pointer);
  98988. *unaligned_pointer = pu;
  98989. *aligned_pointer = u.pa;
  98990. return true;
  98991. }
  98992. }
  98993. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98994. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98995. {
  98996. FLAC__real *pu; /* unaligned pointer */
  98997. union { /* union needed to comply with C99 pointer aliasing rules */
  98998. FLAC__real *pa; /* aligned pointer */
  98999. void *pv; /* aligned pointer alias */
  99000. } u;
  99001. FLAC__ASSERT(elements > 0);
  99002. FLAC__ASSERT(0 != unaligned_pointer);
  99003. FLAC__ASSERT(0 != aligned_pointer);
  99004. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99005. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99006. if(0 == pu) {
  99007. return false;
  99008. }
  99009. else {
  99010. if(*unaligned_pointer != 0)
  99011. free(*unaligned_pointer);
  99012. *unaligned_pointer = pu;
  99013. *aligned_pointer = u.pa;
  99014. return true;
  99015. }
  99016. }
  99017. #endif
  99018. #endif
  99019. /*** End of inlined file: memory.c ***/
  99020. /*** Start of inlined file: stream_decoder.c ***/
  99021. /*** Start of inlined file: juce_FlacHeader.h ***/
  99022. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99023. // tasks..
  99024. #define VERSION "1.2.1"
  99025. #define FLAC__NO_DLL 1
  99026. #if JUCE_MSVC
  99027. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99028. #endif
  99029. #if JUCE_MAC
  99030. #define FLAC__SYS_DARWIN 1
  99031. #endif
  99032. /*** End of inlined file: juce_FlacHeader.h ***/
  99033. #if JUCE_USE_FLAC
  99034. #if HAVE_CONFIG_H
  99035. # include <config.h>
  99036. #endif
  99037. #if defined _MSC_VER || defined __MINGW32__
  99038. #include <io.h> /* for _setmode() */
  99039. #include <fcntl.h> /* for _O_BINARY */
  99040. #endif
  99041. #if defined __CYGWIN__ || defined __EMX__
  99042. #include <io.h> /* for setmode(), O_BINARY */
  99043. #include <fcntl.h> /* for _O_BINARY */
  99044. #endif
  99045. #include <stdio.h>
  99046. #include <stdlib.h> /* for malloc() */
  99047. #include <string.h> /* for memset/memcpy() */
  99048. #include <sys/stat.h> /* for stat() */
  99049. #include <sys/types.h> /* for off_t */
  99050. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99051. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99052. #define fseeko fseek
  99053. #define ftello ftell
  99054. #endif
  99055. #endif
  99056. /*** Start of inlined file: stream_decoder.h ***/
  99057. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99058. #define FLAC__PROTECTED__STREAM_DECODER_H
  99059. #if FLAC__HAS_OGG
  99060. #include "include/private/ogg_decoder_aspect.h"
  99061. #endif
  99062. typedef struct FLAC__StreamDecoderProtected {
  99063. FLAC__StreamDecoderState state;
  99064. unsigned channels;
  99065. FLAC__ChannelAssignment channel_assignment;
  99066. unsigned bits_per_sample;
  99067. unsigned sample_rate; /* in Hz */
  99068. unsigned blocksize; /* in samples (per channel) */
  99069. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99070. #if FLAC__HAS_OGG
  99071. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99072. #endif
  99073. } FLAC__StreamDecoderProtected;
  99074. /*
  99075. * return the number of input bytes consumed
  99076. */
  99077. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99078. #endif
  99079. /*** End of inlined file: stream_decoder.h ***/
  99080. #ifdef max
  99081. #undef max
  99082. #endif
  99083. #define max(a,b) ((a)>(b)?(a):(b))
  99084. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99085. #ifdef _MSC_VER
  99086. #define FLAC__U64L(x) x
  99087. #else
  99088. #define FLAC__U64L(x) x##LLU
  99089. #endif
  99090. /* technically this should be in an "export.c" but this is convenient enough */
  99091. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99092. #if FLAC__HAS_OGG
  99093. 1
  99094. #else
  99095. 0
  99096. #endif
  99097. ;
  99098. /***********************************************************************
  99099. *
  99100. * Private static data
  99101. *
  99102. ***********************************************************************/
  99103. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99104. /***********************************************************************
  99105. *
  99106. * Private class method prototypes
  99107. *
  99108. ***********************************************************************/
  99109. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99110. static FILE *get_binary_stdin_(void);
  99111. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99112. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99113. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99114. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99115. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99116. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99117. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99118. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99119. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99120. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99121. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99122. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99123. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99124. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99125. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99126. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99127. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99128. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99129. 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);
  99130. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99131. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99132. #if FLAC__HAS_OGG
  99133. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99134. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99135. #endif
  99136. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99137. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99138. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99139. #if FLAC__HAS_OGG
  99140. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99141. #endif
  99142. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99143. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99144. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99145. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99146. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99147. /***********************************************************************
  99148. *
  99149. * Private class data
  99150. *
  99151. ***********************************************************************/
  99152. typedef struct FLAC__StreamDecoderPrivate {
  99153. #if FLAC__HAS_OGG
  99154. FLAC__bool is_ogg;
  99155. #endif
  99156. FLAC__StreamDecoderReadCallback read_callback;
  99157. FLAC__StreamDecoderSeekCallback seek_callback;
  99158. FLAC__StreamDecoderTellCallback tell_callback;
  99159. FLAC__StreamDecoderLengthCallback length_callback;
  99160. FLAC__StreamDecoderEofCallback eof_callback;
  99161. FLAC__StreamDecoderWriteCallback write_callback;
  99162. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99163. FLAC__StreamDecoderErrorCallback error_callback;
  99164. /* generic 32-bit datapath: */
  99165. 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[]);
  99166. /* generic 64-bit datapath: */
  99167. 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[]);
  99168. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99169. 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[]);
  99170. /* 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: */
  99171. 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[]);
  99172. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99173. void *client_data;
  99174. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99175. FLAC__BitReader *input;
  99176. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99177. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99178. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99179. unsigned output_capacity, output_channels;
  99180. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99181. FLAC__uint64 samples_decoded;
  99182. FLAC__bool has_stream_info, has_seek_table;
  99183. FLAC__StreamMetadata stream_info;
  99184. FLAC__StreamMetadata seek_table;
  99185. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99186. FLAC__byte *metadata_filter_ids;
  99187. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99188. FLAC__Frame frame;
  99189. FLAC__bool cached; /* true if there is a byte in lookahead */
  99190. FLAC__CPUInfo cpuinfo;
  99191. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99192. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99193. /* unaligned (original) pointers to allocated data */
  99194. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99195. 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 */
  99196. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99197. FLAC__bool is_seeking;
  99198. FLAC__MD5Context md5context;
  99199. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99200. /* (the rest of these are only used for seeking) */
  99201. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99202. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99203. FLAC__uint64 target_sample;
  99204. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99205. #if FLAC__HAS_OGG
  99206. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99207. #endif
  99208. } FLAC__StreamDecoderPrivate;
  99209. /***********************************************************************
  99210. *
  99211. * Public static class data
  99212. *
  99213. ***********************************************************************/
  99214. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99215. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99216. "FLAC__STREAM_DECODER_READ_METADATA",
  99217. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99218. "FLAC__STREAM_DECODER_READ_FRAME",
  99219. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99220. "FLAC__STREAM_DECODER_OGG_ERROR",
  99221. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99222. "FLAC__STREAM_DECODER_ABORTED",
  99223. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99224. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99225. };
  99226. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99227. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99228. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99229. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99230. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99231. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99232. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99233. };
  99234. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99235. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99236. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99237. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99238. };
  99239. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99240. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99241. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99242. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99243. };
  99244. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99245. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99246. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99247. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99248. };
  99249. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99250. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99251. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99252. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99253. };
  99254. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99255. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99256. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99257. };
  99258. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99259. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99260. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99261. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99262. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99263. };
  99264. /***********************************************************************
  99265. *
  99266. * Class constructor/destructor
  99267. *
  99268. ***********************************************************************/
  99269. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99270. {
  99271. FLAC__StreamDecoder *decoder;
  99272. unsigned i;
  99273. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99274. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99275. if(decoder == 0) {
  99276. return 0;
  99277. }
  99278. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99279. if(decoder->protected_ == 0) {
  99280. free(decoder);
  99281. return 0;
  99282. }
  99283. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99284. if(decoder->private_ == 0) {
  99285. free(decoder->protected_);
  99286. free(decoder);
  99287. return 0;
  99288. }
  99289. decoder->private_->input = FLAC__bitreader_new();
  99290. if(decoder->private_->input == 0) {
  99291. free(decoder->private_);
  99292. free(decoder->protected_);
  99293. free(decoder);
  99294. return 0;
  99295. }
  99296. decoder->private_->metadata_filter_ids_capacity = 16;
  99297. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99298. FLAC__bitreader_delete(decoder->private_->input);
  99299. free(decoder->private_);
  99300. free(decoder->protected_);
  99301. free(decoder);
  99302. return 0;
  99303. }
  99304. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99305. decoder->private_->output[i] = 0;
  99306. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99307. }
  99308. decoder->private_->output_capacity = 0;
  99309. decoder->private_->output_channels = 0;
  99310. decoder->private_->has_seek_table = false;
  99311. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99312. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99313. decoder->private_->file = 0;
  99314. set_defaults_dec(decoder);
  99315. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99316. return decoder;
  99317. }
  99318. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99319. {
  99320. unsigned i;
  99321. FLAC__ASSERT(0 != decoder);
  99322. FLAC__ASSERT(0 != decoder->protected_);
  99323. FLAC__ASSERT(0 != decoder->private_);
  99324. FLAC__ASSERT(0 != decoder->private_->input);
  99325. (void)FLAC__stream_decoder_finish(decoder);
  99326. if(0 != decoder->private_->metadata_filter_ids)
  99327. free(decoder->private_->metadata_filter_ids);
  99328. FLAC__bitreader_delete(decoder->private_->input);
  99329. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99330. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99331. free(decoder->private_);
  99332. free(decoder->protected_);
  99333. free(decoder);
  99334. }
  99335. /***********************************************************************
  99336. *
  99337. * Public class methods
  99338. *
  99339. ***********************************************************************/
  99340. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99341. FLAC__StreamDecoder *decoder,
  99342. FLAC__StreamDecoderReadCallback read_callback,
  99343. FLAC__StreamDecoderSeekCallback seek_callback,
  99344. FLAC__StreamDecoderTellCallback tell_callback,
  99345. FLAC__StreamDecoderLengthCallback length_callback,
  99346. FLAC__StreamDecoderEofCallback eof_callback,
  99347. FLAC__StreamDecoderWriteCallback write_callback,
  99348. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99349. FLAC__StreamDecoderErrorCallback error_callback,
  99350. void *client_data,
  99351. FLAC__bool is_ogg
  99352. )
  99353. {
  99354. FLAC__ASSERT(0 != decoder);
  99355. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99356. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99357. #if !FLAC__HAS_OGG
  99358. if(is_ogg)
  99359. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99360. #endif
  99361. if(
  99362. 0 == read_callback ||
  99363. 0 == write_callback ||
  99364. 0 == error_callback ||
  99365. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99366. )
  99367. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99368. #if FLAC__HAS_OGG
  99369. decoder->private_->is_ogg = is_ogg;
  99370. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99371. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99372. #endif
  99373. /*
  99374. * get the CPU info and set the function pointers
  99375. */
  99376. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99377. /* first default to the non-asm routines */
  99378. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99379. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99380. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99381. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99382. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99383. /* now override with asm where appropriate */
  99384. #ifndef FLAC__NO_ASM
  99385. if(decoder->private_->cpuinfo.use_asm) {
  99386. #ifdef FLAC__CPU_IA32
  99387. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99388. #ifdef FLAC__HAS_NASM
  99389. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99390. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99391. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99392. #endif
  99393. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99394. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99395. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99396. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99397. }
  99398. else {
  99399. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99400. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99401. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99402. }
  99403. #endif
  99404. #elif defined FLAC__CPU_PPC
  99405. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99406. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99407. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99408. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99409. }
  99410. #endif
  99411. }
  99412. #endif
  99413. /* from here on, errors are fatal */
  99414. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99415. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99416. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99417. }
  99418. decoder->private_->read_callback = read_callback;
  99419. decoder->private_->seek_callback = seek_callback;
  99420. decoder->private_->tell_callback = tell_callback;
  99421. decoder->private_->length_callback = length_callback;
  99422. decoder->private_->eof_callback = eof_callback;
  99423. decoder->private_->write_callback = write_callback;
  99424. decoder->private_->metadata_callback = metadata_callback;
  99425. decoder->private_->error_callback = error_callback;
  99426. decoder->private_->client_data = client_data;
  99427. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99428. decoder->private_->samples_decoded = 0;
  99429. decoder->private_->has_stream_info = false;
  99430. decoder->private_->cached = false;
  99431. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99432. decoder->private_->is_seeking = false;
  99433. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99434. if(!FLAC__stream_decoder_reset(decoder)) {
  99435. /* above call sets the state for us */
  99436. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99437. }
  99438. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99439. }
  99440. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99441. FLAC__StreamDecoder *decoder,
  99442. FLAC__StreamDecoderReadCallback read_callback,
  99443. FLAC__StreamDecoderSeekCallback seek_callback,
  99444. FLAC__StreamDecoderTellCallback tell_callback,
  99445. FLAC__StreamDecoderLengthCallback length_callback,
  99446. FLAC__StreamDecoderEofCallback eof_callback,
  99447. FLAC__StreamDecoderWriteCallback write_callback,
  99448. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99449. FLAC__StreamDecoderErrorCallback error_callback,
  99450. void *client_data
  99451. )
  99452. {
  99453. return init_stream_internal_dec(
  99454. decoder,
  99455. read_callback,
  99456. seek_callback,
  99457. tell_callback,
  99458. length_callback,
  99459. eof_callback,
  99460. write_callback,
  99461. metadata_callback,
  99462. error_callback,
  99463. client_data,
  99464. /*is_ogg=*/false
  99465. );
  99466. }
  99467. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99468. FLAC__StreamDecoder *decoder,
  99469. FLAC__StreamDecoderReadCallback read_callback,
  99470. FLAC__StreamDecoderSeekCallback seek_callback,
  99471. FLAC__StreamDecoderTellCallback tell_callback,
  99472. FLAC__StreamDecoderLengthCallback length_callback,
  99473. FLAC__StreamDecoderEofCallback eof_callback,
  99474. FLAC__StreamDecoderWriteCallback write_callback,
  99475. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99476. FLAC__StreamDecoderErrorCallback error_callback,
  99477. void *client_data
  99478. )
  99479. {
  99480. return init_stream_internal_dec(
  99481. decoder,
  99482. read_callback,
  99483. seek_callback,
  99484. tell_callback,
  99485. length_callback,
  99486. eof_callback,
  99487. write_callback,
  99488. metadata_callback,
  99489. error_callback,
  99490. client_data,
  99491. /*is_ogg=*/true
  99492. );
  99493. }
  99494. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99495. FLAC__StreamDecoder *decoder,
  99496. FILE *file,
  99497. FLAC__StreamDecoderWriteCallback write_callback,
  99498. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99499. FLAC__StreamDecoderErrorCallback error_callback,
  99500. void *client_data,
  99501. FLAC__bool is_ogg
  99502. )
  99503. {
  99504. FLAC__ASSERT(0 != decoder);
  99505. FLAC__ASSERT(0 != file);
  99506. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99507. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99508. if(0 == write_callback || 0 == error_callback)
  99509. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99510. /*
  99511. * To make sure that our file does not go unclosed after an error, we
  99512. * must assign the FILE pointer before any further error can occur in
  99513. * this routine.
  99514. */
  99515. if(file == stdin)
  99516. file = get_binary_stdin_(); /* just to be safe */
  99517. decoder->private_->file = file;
  99518. return init_stream_internal_dec(
  99519. decoder,
  99520. file_read_callback_dec,
  99521. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99522. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99523. decoder->private_->file == stdin? 0: file_length_callback_,
  99524. file_eof_callback_,
  99525. write_callback,
  99526. metadata_callback,
  99527. error_callback,
  99528. client_data,
  99529. is_ogg
  99530. );
  99531. }
  99532. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99533. FLAC__StreamDecoder *decoder,
  99534. FILE *file,
  99535. FLAC__StreamDecoderWriteCallback write_callback,
  99536. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99537. FLAC__StreamDecoderErrorCallback error_callback,
  99538. void *client_data
  99539. )
  99540. {
  99541. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99542. }
  99543. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99544. FLAC__StreamDecoder *decoder,
  99545. FILE *file,
  99546. FLAC__StreamDecoderWriteCallback write_callback,
  99547. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99548. FLAC__StreamDecoderErrorCallback error_callback,
  99549. void *client_data
  99550. )
  99551. {
  99552. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99553. }
  99554. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99555. FLAC__StreamDecoder *decoder,
  99556. const char *filename,
  99557. FLAC__StreamDecoderWriteCallback write_callback,
  99558. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99559. FLAC__StreamDecoderErrorCallback error_callback,
  99560. void *client_data,
  99561. FLAC__bool is_ogg
  99562. )
  99563. {
  99564. FILE *file;
  99565. FLAC__ASSERT(0 != decoder);
  99566. /*
  99567. * To make sure that our file does not go unclosed after an error, we
  99568. * have to do the same entrance checks here that are later performed
  99569. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99570. */
  99571. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99572. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99573. if(0 == write_callback || 0 == error_callback)
  99574. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99575. file = filename? fopen(filename, "rb") : stdin;
  99576. if(0 == file)
  99577. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99578. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99579. }
  99580. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99581. FLAC__StreamDecoder *decoder,
  99582. const char *filename,
  99583. FLAC__StreamDecoderWriteCallback write_callback,
  99584. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99585. FLAC__StreamDecoderErrorCallback error_callback,
  99586. void *client_data
  99587. )
  99588. {
  99589. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99590. }
  99591. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99592. FLAC__StreamDecoder *decoder,
  99593. const char *filename,
  99594. FLAC__StreamDecoderWriteCallback write_callback,
  99595. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99596. FLAC__StreamDecoderErrorCallback error_callback,
  99597. void *client_data
  99598. )
  99599. {
  99600. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99601. }
  99602. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99603. {
  99604. FLAC__bool md5_failed = false;
  99605. unsigned i;
  99606. FLAC__ASSERT(0 != decoder);
  99607. FLAC__ASSERT(0 != decoder->private_);
  99608. FLAC__ASSERT(0 != decoder->protected_);
  99609. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99610. return true;
  99611. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99612. * always call FLAC__MD5Final()
  99613. */
  99614. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99615. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99616. free(decoder->private_->seek_table.data.seek_table.points);
  99617. decoder->private_->seek_table.data.seek_table.points = 0;
  99618. decoder->private_->has_seek_table = false;
  99619. }
  99620. FLAC__bitreader_free(decoder->private_->input);
  99621. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99622. /* WATCHOUT:
  99623. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99624. * output arrays have a buffer of up to 3 zeroes in front
  99625. * (at negative indices) for alignment purposes; we use 4
  99626. * to keep the data well-aligned.
  99627. */
  99628. if(0 != decoder->private_->output[i]) {
  99629. free(decoder->private_->output[i]-4);
  99630. decoder->private_->output[i] = 0;
  99631. }
  99632. if(0 != decoder->private_->residual_unaligned[i]) {
  99633. free(decoder->private_->residual_unaligned[i]);
  99634. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99635. }
  99636. }
  99637. decoder->private_->output_capacity = 0;
  99638. decoder->private_->output_channels = 0;
  99639. #if FLAC__HAS_OGG
  99640. if(decoder->private_->is_ogg)
  99641. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99642. #endif
  99643. if(0 != decoder->private_->file) {
  99644. if(decoder->private_->file != stdin)
  99645. fclose(decoder->private_->file);
  99646. decoder->private_->file = 0;
  99647. }
  99648. if(decoder->private_->do_md5_checking) {
  99649. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99650. md5_failed = true;
  99651. }
  99652. decoder->private_->is_seeking = false;
  99653. set_defaults_dec(decoder);
  99654. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99655. return !md5_failed;
  99656. }
  99657. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99658. {
  99659. FLAC__ASSERT(0 != decoder);
  99660. FLAC__ASSERT(0 != decoder->private_);
  99661. FLAC__ASSERT(0 != decoder->protected_);
  99662. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99663. return false;
  99664. #if FLAC__HAS_OGG
  99665. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99666. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99667. return true;
  99668. #else
  99669. (void)value;
  99670. return false;
  99671. #endif
  99672. }
  99673. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99674. {
  99675. FLAC__ASSERT(0 != decoder);
  99676. FLAC__ASSERT(0 != decoder->protected_);
  99677. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99678. return false;
  99679. decoder->protected_->md5_checking = value;
  99680. return true;
  99681. }
  99682. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99683. {
  99684. FLAC__ASSERT(0 != decoder);
  99685. FLAC__ASSERT(0 != decoder->private_);
  99686. FLAC__ASSERT(0 != decoder->protected_);
  99687. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99688. /* double protection */
  99689. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99690. return false;
  99691. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99692. return false;
  99693. decoder->private_->metadata_filter[type] = true;
  99694. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99695. decoder->private_->metadata_filter_ids_count = 0;
  99696. return true;
  99697. }
  99698. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99699. {
  99700. FLAC__ASSERT(0 != decoder);
  99701. FLAC__ASSERT(0 != decoder->private_);
  99702. FLAC__ASSERT(0 != decoder->protected_);
  99703. FLAC__ASSERT(0 != id);
  99704. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99705. return false;
  99706. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99707. return true;
  99708. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99709. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99710. 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))) {
  99711. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99712. return false;
  99713. }
  99714. decoder->private_->metadata_filter_ids_capacity *= 2;
  99715. }
  99716. 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));
  99717. decoder->private_->metadata_filter_ids_count++;
  99718. return true;
  99719. }
  99720. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99721. {
  99722. unsigned i;
  99723. FLAC__ASSERT(0 != decoder);
  99724. FLAC__ASSERT(0 != decoder->private_);
  99725. FLAC__ASSERT(0 != decoder->protected_);
  99726. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99727. return false;
  99728. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99729. decoder->private_->metadata_filter[i] = true;
  99730. decoder->private_->metadata_filter_ids_count = 0;
  99731. return true;
  99732. }
  99733. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99734. {
  99735. FLAC__ASSERT(0 != decoder);
  99736. FLAC__ASSERT(0 != decoder->private_);
  99737. FLAC__ASSERT(0 != decoder->protected_);
  99738. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99739. /* double protection */
  99740. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99741. return false;
  99742. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99743. return false;
  99744. decoder->private_->metadata_filter[type] = false;
  99745. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99746. decoder->private_->metadata_filter_ids_count = 0;
  99747. return true;
  99748. }
  99749. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99750. {
  99751. FLAC__ASSERT(0 != decoder);
  99752. FLAC__ASSERT(0 != decoder->private_);
  99753. FLAC__ASSERT(0 != decoder->protected_);
  99754. FLAC__ASSERT(0 != id);
  99755. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99756. return false;
  99757. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99758. return true;
  99759. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99760. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99761. 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))) {
  99762. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99763. return false;
  99764. }
  99765. decoder->private_->metadata_filter_ids_capacity *= 2;
  99766. }
  99767. 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));
  99768. decoder->private_->metadata_filter_ids_count++;
  99769. return true;
  99770. }
  99771. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99772. {
  99773. FLAC__ASSERT(0 != decoder);
  99774. FLAC__ASSERT(0 != decoder->private_);
  99775. FLAC__ASSERT(0 != decoder->protected_);
  99776. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99777. return false;
  99778. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99779. decoder->private_->metadata_filter_ids_count = 0;
  99780. return true;
  99781. }
  99782. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99783. {
  99784. FLAC__ASSERT(0 != decoder);
  99785. FLAC__ASSERT(0 != decoder->protected_);
  99786. return decoder->protected_->state;
  99787. }
  99788. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99789. {
  99790. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99791. }
  99792. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99793. {
  99794. FLAC__ASSERT(0 != decoder);
  99795. FLAC__ASSERT(0 != decoder->protected_);
  99796. return decoder->protected_->md5_checking;
  99797. }
  99798. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99799. {
  99800. FLAC__ASSERT(0 != decoder);
  99801. FLAC__ASSERT(0 != decoder->protected_);
  99802. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99803. }
  99804. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99805. {
  99806. FLAC__ASSERT(0 != decoder);
  99807. FLAC__ASSERT(0 != decoder->protected_);
  99808. return decoder->protected_->channels;
  99809. }
  99810. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99811. {
  99812. FLAC__ASSERT(0 != decoder);
  99813. FLAC__ASSERT(0 != decoder->protected_);
  99814. return decoder->protected_->channel_assignment;
  99815. }
  99816. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99817. {
  99818. FLAC__ASSERT(0 != decoder);
  99819. FLAC__ASSERT(0 != decoder->protected_);
  99820. return decoder->protected_->bits_per_sample;
  99821. }
  99822. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99823. {
  99824. FLAC__ASSERT(0 != decoder);
  99825. FLAC__ASSERT(0 != decoder->protected_);
  99826. return decoder->protected_->sample_rate;
  99827. }
  99828. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99829. {
  99830. FLAC__ASSERT(0 != decoder);
  99831. FLAC__ASSERT(0 != decoder->protected_);
  99832. return decoder->protected_->blocksize;
  99833. }
  99834. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99835. {
  99836. FLAC__ASSERT(0 != decoder);
  99837. FLAC__ASSERT(0 != decoder->private_);
  99838. FLAC__ASSERT(0 != position);
  99839. #if FLAC__HAS_OGG
  99840. if(decoder->private_->is_ogg)
  99841. return false;
  99842. #endif
  99843. if(0 == decoder->private_->tell_callback)
  99844. return false;
  99845. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99846. return false;
  99847. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99848. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99849. return false;
  99850. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99851. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99852. return true;
  99853. }
  99854. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99855. {
  99856. FLAC__ASSERT(0 != decoder);
  99857. FLAC__ASSERT(0 != decoder->private_);
  99858. FLAC__ASSERT(0 != decoder->protected_);
  99859. decoder->private_->samples_decoded = 0;
  99860. decoder->private_->do_md5_checking = false;
  99861. #if FLAC__HAS_OGG
  99862. if(decoder->private_->is_ogg)
  99863. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99864. #endif
  99865. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99866. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99867. return false;
  99868. }
  99869. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99870. return true;
  99871. }
  99872. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99873. {
  99874. FLAC__ASSERT(0 != decoder);
  99875. FLAC__ASSERT(0 != decoder->private_);
  99876. FLAC__ASSERT(0 != decoder->protected_);
  99877. if(!FLAC__stream_decoder_flush(decoder)) {
  99878. /* above call sets the state for us */
  99879. return false;
  99880. }
  99881. #if FLAC__HAS_OGG
  99882. /*@@@ could go in !internal_reset_hack block below */
  99883. if(decoder->private_->is_ogg)
  99884. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99885. #endif
  99886. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99887. * (internal_reset_hack) don't try to rewind since we are already at
  99888. * the beginning of the stream and don't want to fail if the input is
  99889. * not seekable.
  99890. */
  99891. if(!decoder->private_->internal_reset_hack) {
  99892. if(decoder->private_->file == stdin)
  99893. return false; /* can't rewind stdin, reset fails */
  99894. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99895. return false; /* seekable and seek fails, reset fails */
  99896. }
  99897. else
  99898. decoder->private_->internal_reset_hack = false;
  99899. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99900. decoder->private_->has_stream_info = false;
  99901. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99902. free(decoder->private_->seek_table.data.seek_table.points);
  99903. decoder->private_->seek_table.data.seek_table.points = 0;
  99904. decoder->private_->has_seek_table = false;
  99905. }
  99906. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99907. /*
  99908. * This goes in reset() and not flush() because according to the spec, a
  99909. * fixed-blocksize stream must stay that way through the whole stream.
  99910. */
  99911. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99912. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99913. * is because md5 checking may be turned on to start and then turned off if
  99914. * a seek occurs. So we init the context here and finalize it in
  99915. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99916. * properly.
  99917. */
  99918. FLAC__MD5Init(&decoder->private_->md5context);
  99919. decoder->private_->first_frame_offset = 0;
  99920. decoder->private_->unparseable_frame_count = 0;
  99921. return true;
  99922. }
  99923. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99924. {
  99925. FLAC__bool got_a_frame;
  99926. FLAC__ASSERT(0 != decoder);
  99927. FLAC__ASSERT(0 != decoder->protected_);
  99928. while(1) {
  99929. switch(decoder->protected_->state) {
  99930. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99931. if(!find_metadata_(decoder))
  99932. return false; /* above function sets the status for us */
  99933. break;
  99934. case FLAC__STREAM_DECODER_READ_METADATA:
  99935. if(!read_metadata_(decoder))
  99936. return false; /* above function sets the status for us */
  99937. else
  99938. return true;
  99939. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99940. if(!frame_sync_(decoder))
  99941. return true; /* above function sets the status for us */
  99942. break;
  99943. case FLAC__STREAM_DECODER_READ_FRAME:
  99944. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99945. return false; /* above function sets the status for us */
  99946. if(got_a_frame)
  99947. return true; /* above function sets the status for us */
  99948. break;
  99949. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99950. case FLAC__STREAM_DECODER_ABORTED:
  99951. return true;
  99952. default:
  99953. FLAC__ASSERT(0);
  99954. return false;
  99955. }
  99956. }
  99957. }
  99958. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99959. {
  99960. FLAC__ASSERT(0 != decoder);
  99961. FLAC__ASSERT(0 != decoder->protected_);
  99962. while(1) {
  99963. switch(decoder->protected_->state) {
  99964. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99965. if(!find_metadata_(decoder))
  99966. return false; /* above function sets the status for us */
  99967. break;
  99968. case FLAC__STREAM_DECODER_READ_METADATA:
  99969. if(!read_metadata_(decoder))
  99970. return false; /* above function sets the status for us */
  99971. break;
  99972. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99973. case FLAC__STREAM_DECODER_READ_FRAME:
  99974. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99975. case FLAC__STREAM_DECODER_ABORTED:
  99976. return true;
  99977. default:
  99978. FLAC__ASSERT(0);
  99979. return false;
  99980. }
  99981. }
  99982. }
  99983. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99984. {
  99985. FLAC__bool dummy;
  99986. FLAC__ASSERT(0 != decoder);
  99987. FLAC__ASSERT(0 != decoder->protected_);
  99988. while(1) {
  99989. switch(decoder->protected_->state) {
  99990. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99991. if(!find_metadata_(decoder))
  99992. return false; /* above function sets the status for us */
  99993. break;
  99994. case FLAC__STREAM_DECODER_READ_METADATA:
  99995. if(!read_metadata_(decoder))
  99996. return false; /* above function sets the status for us */
  99997. break;
  99998. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99999. if(!frame_sync_(decoder))
  100000. return true; /* above function sets the status for us */
  100001. break;
  100002. case FLAC__STREAM_DECODER_READ_FRAME:
  100003. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100004. return false; /* above function sets the status for us */
  100005. break;
  100006. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100007. case FLAC__STREAM_DECODER_ABORTED:
  100008. return true;
  100009. default:
  100010. FLAC__ASSERT(0);
  100011. return false;
  100012. }
  100013. }
  100014. }
  100015. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100016. {
  100017. FLAC__bool got_a_frame;
  100018. FLAC__ASSERT(0 != decoder);
  100019. FLAC__ASSERT(0 != decoder->protected_);
  100020. while(1) {
  100021. switch(decoder->protected_->state) {
  100022. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100023. case FLAC__STREAM_DECODER_READ_METADATA:
  100024. return false; /* above function sets the status for us */
  100025. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100026. if(!frame_sync_(decoder))
  100027. return true; /* above function sets the status for us */
  100028. break;
  100029. case FLAC__STREAM_DECODER_READ_FRAME:
  100030. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100031. return false; /* above function sets the status for us */
  100032. if(got_a_frame)
  100033. return true; /* above function sets the status for us */
  100034. break;
  100035. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100036. case FLAC__STREAM_DECODER_ABORTED:
  100037. return true;
  100038. default:
  100039. FLAC__ASSERT(0);
  100040. return false;
  100041. }
  100042. }
  100043. }
  100044. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100045. {
  100046. FLAC__uint64 length;
  100047. FLAC__ASSERT(0 != decoder);
  100048. if(
  100049. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100050. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100051. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100052. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100053. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100054. )
  100055. return false;
  100056. if(0 == decoder->private_->seek_callback)
  100057. return false;
  100058. FLAC__ASSERT(decoder->private_->seek_callback);
  100059. FLAC__ASSERT(decoder->private_->tell_callback);
  100060. FLAC__ASSERT(decoder->private_->length_callback);
  100061. FLAC__ASSERT(decoder->private_->eof_callback);
  100062. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100063. return false;
  100064. decoder->private_->is_seeking = true;
  100065. /* turn off md5 checking if a seek is attempted */
  100066. decoder->private_->do_md5_checking = false;
  100067. /* 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) */
  100068. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100069. decoder->private_->is_seeking = false;
  100070. return false;
  100071. }
  100072. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100073. if(
  100074. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100075. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100076. ) {
  100077. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100078. /* above call sets the state for us */
  100079. decoder->private_->is_seeking = false;
  100080. return false;
  100081. }
  100082. /* check this again in case we didn't know total_samples the first time */
  100083. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100084. decoder->private_->is_seeking = false;
  100085. return false;
  100086. }
  100087. }
  100088. {
  100089. const FLAC__bool ok =
  100090. #if FLAC__HAS_OGG
  100091. decoder->private_->is_ogg?
  100092. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100093. #endif
  100094. seek_to_absolute_sample_(decoder, length, sample)
  100095. ;
  100096. decoder->private_->is_seeking = false;
  100097. return ok;
  100098. }
  100099. }
  100100. /***********************************************************************
  100101. *
  100102. * Protected class methods
  100103. *
  100104. ***********************************************************************/
  100105. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100106. {
  100107. FLAC__ASSERT(0 != decoder);
  100108. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100109. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100110. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100111. }
  100112. /***********************************************************************
  100113. *
  100114. * Private class methods
  100115. *
  100116. ***********************************************************************/
  100117. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100118. {
  100119. #if FLAC__HAS_OGG
  100120. decoder->private_->is_ogg = false;
  100121. #endif
  100122. decoder->private_->read_callback = 0;
  100123. decoder->private_->seek_callback = 0;
  100124. decoder->private_->tell_callback = 0;
  100125. decoder->private_->length_callback = 0;
  100126. decoder->private_->eof_callback = 0;
  100127. decoder->private_->write_callback = 0;
  100128. decoder->private_->metadata_callback = 0;
  100129. decoder->private_->error_callback = 0;
  100130. decoder->private_->client_data = 0;
  100131. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100132. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100133. decoder->private_->metadata_filter_ids_count = 0;
  100134. decoder->protected_->md5_checking = false;
  100135. #if FLAC__HAS_OGG
  100136. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100137. #endif
  100138. }
  100139. /*
  100140. * This will forcibly set stdin to binary mode (for OSes that require it)
  100141. */
  100142. FILE *get_binary_stdin_(void)
  100143. {
  100144. /* if something breaks here it is probably due to the presence or
  100145. * absence of an underscore before the identifiers 'setmode',
  100146. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100147. */
  100148. #if defined _MSC_VER || defined __MINGW32__
  100149. _setmode(_fileno(stdin), _O_BINARY);
  100150. #elif defined __CYGWIN__
  100151. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100152. setmode(_fileno(stdin), _O_BINARY);
  100153. #elif defined __EMX__
  100154. setmode(fileno(stdin), O_BINARY);
  100155. #endif
  100156. return stdin;
  100157. }
  100158. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100159. {
  100160. unsigned i;
  100161. FLAC__int32 *tmp;
  100162. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100163. return true;
  100164. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100165. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100166. if(0 != decoder->private_->output[i]) {
  100167. free(decoder->private_->output[i]-4);
  100168. decoder->private_->output[i] = 0;
  100169. }
  100170. if(0 != decoder->private_->residual_unaligned[i]) {
  100171. free(decoder->private_->residual_unaligned[i]);
  100172. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100173. }
  100174. }
  100175. for(i = 0; i < channels; i++) {
  100176. /* WATCHOUT:
  100177. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100178. * output arrays have a buffer of up to 3 zeroes in front
  100179. * (at negative indices) for alignment purposes; we use 4
  100180. * to keep the data well-aligned.
  100181. */
  100182. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100183. if(tmp == 0) {
  100184. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100185. return false;
  100186. }
  100187. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100188. decoder->private_->output[i] = tmp + 4;
  100189. /* WATCHOUT:
  100190. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100191. */
  100192. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100193. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100194. return false;
  100195. }
  100196. }
  100197. decoder->private_->output_capacity = size;
  100198. decoder->private_->output_channels = channels;
  100199. return true;
  100200. }
  100201. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100202. {
  100203. size_t i;
  100204. FLAC__ASSERT(0 != decoder);
  100205. FLAC__ASSERT(0 != decoder->private_);
  100206. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100207. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100208. return true;
  100209. return false;
  100210. }
  100211. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100212. {
  100213. FLAC__uint32 x;
  100214. unsigned i, id_;
  100215. FLAC__bool first = true;
  100216. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100217. for(i = id_ = 0; i < 4; ) {
  100218. if(decoder->private_->cached) {
  100219. x = (FLAC__uint32)decoder->private_->lookahead;
  100220. decoder->private_->cached = false;
  100221. }
  100222. else {
  100223. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100224. return false; /* read_callback_ sets the state for us */
  100225. }
  100226. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100227. first = true;
  100228. i++;
  100229. id_ = 0;
  100230. continue;
  100231. }
  100232. if(x == ID3V2_TAG_[id_]) {
  100233. id_++;
  100234. i = 0;
  100235. if(id_ == 3) {
  100236. if(!skip_id3v2_tag_(decoder))
  100237. return false; /* skip_id3v2_tag_ sets the state for us */
  100238. }
  100239. continue;
  100240. }
  100241. id_ = 0;
  100242. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100243. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100244. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100245. return false; /* read_callback_ sets the state for us */
  100246. /* 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 */
  100247. /* else we have to check if the second byte is the end of a sync code */
  100248. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100249. decoder->private_->lookahead = (FLAC__byte)x;
  100250. decoder->private_->cached = true;
  100251. }
  100252. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100253. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100254. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100255. return true;
  100256. }
  100257. }
  100258. i = 0;
  100259. if(first) {
  100260. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100261. first = false;
  100262. }
  100263. }
  100264. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100265. return true;
  100266. }
  100267. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100268. {
  100269. FLAC__bool is_last;
  100270. FLAC__uint32 i, x, type, length;
  100271. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100273. return false; /* read_callback_ sets the state for us */
  100274. is_last = x? true : false;
  100275. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100276. return false; /* read_callback_ sets the state for us */
  100277. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100278. return false; /* read_callback_ sets the state for us */
  100279. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100280. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100281. return false;
  100282. decoder->private_->has_stream_info = true;
  100283. 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))
  100284. decoder->private_->do_md5_checking = false;
  100285. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100286. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100287. }
  100288. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100289. if(!read_metadata_seektable_(decoder, is_last, length))
  100290. return false;
  100291. decoder->private_->has_seek_table = true;
  100292. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100293. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100294. }
  100295. else {
  100296. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100297. unsigned real_length = length;
  100298. FLAC__StreamMetadata block;
  100299. block.is_last = is_last;
  100300. block.type = (FLAC__MetadataType)type;
  100301. block.length = length;
  100302. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100303. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100304. return false; /* read_callback_ sets the state for us */
  100305. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100306. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100307. return false;
  100308. }
  100309. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100310. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100311. skip_it = !skip_it;
  100312. }
  100313. if(skip_it) {
  100314. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100315. return false; /* read_callback_ sets the state for us */
  100316. }
  100317. else {
  100318. switch(type) {
  100319. case FLAC__METADATA_TYPE_PADDING:
  100320. /* skip the padding bytes */
  100321. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100322. return false; /* read_callback_ sets the state for us */
  100323. break;
  100324. case FLAC__METADATA_TYPE_APPLICATION:
  100325. /* remember, we read the ID already */
  100326. if(real_length > 0) {
  100327. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100328. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100329. return false;
  100330. }
  100331. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100332. return false; /* read_callback_ sets the state for us */
  100333. }
  100334. else
  100335. block.data.application.data = 0;
  100336. break;
  100337. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100338. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100339. return false;
  100340. break;
  100341. case FLAC__METADATA_TYPE_CUESHEET:
  100342. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100343. return false;
  100344. break;
  100345. case FLAC__METADATA_TYPE_PICTURE:
  100346. if(!read_metadata_picture_(decoder, &block.data.picture))
  100347. return false;
  100348. break;
  100349. case FLAC__METADATA_TYPE_STREAMINFO:
  100350. case FLAC__METADATA_TYPE_SEEKTABLE:
  100351. FLAC__ASSERT(0);
  100352. break;
  100353. default:
  100354. if(real_length > 0) {
  100355. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100356. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100357. return false;
  100358. }
  100359. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100360. return false; /* read_callback_ sets the state for us */
  100361. }
  100362. else
  100363. block.data.unknown.data = 0;
  100364. break;
  100365. }
  100366. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100367. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100368. /* now we have to free any malloc()ed data in the block */
  100369. switch(type) {
  100370. case FLAC__METADATA_TYPE_PADDING:
  100371. break;
  100372. case FLAC__METADATA_TYPE_APPLICATION:
  100373. if(0 != block.data.application.data)
  100374. free(block.data.application.data);
  100375. break;
  100376. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100377. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100378. free(block.data.vorbis_comment.vendor_string.entry);
  100379. if(block.data.vorbis_comment.num_comments > 0)
  100380. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100381. if(0 != block.data.vorbis_comment.comments[i].entry)
  100382. free(block.data.vorbis_comment.comments[i].entry);
  100383. if(0 != block.data.vorbis_comment.comments)
  100384. free(block.data.vorbis_comment.comments);
  100385. break;
  100386. case FLAC__METADATA_TYPE_CUESHEET:
  100387. if(block.data.cue_sheet.num_tracks > 0)
  100388. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100389. if(0 != block.data.cue_sheet.tracks[i].indices)
  100390. free(block.data.cue_sheet.tracks[i].indices);
  100391. if(0 != block.data.cue_sheet.tracks)
  100392. free(block.data.cue_sheet.tracks);
  100393. break;
  100394. case FLAC__METADATA_TYPE_PICTURE:
  100395. if(0 != block.data.picture.mime_type)
  100396. free(block.data.picture.mime_type);
  100397. if(0 != block.data.picture.description)
  100398. free(block.data.picture.description);
  100399. if(0 != block.data.picture.data)
  100400. free(block.data.picture.data);
  100401. break;
  100402. case FLAC__METADATA_TYPE_STREAMINFO:
  100403. case FLAC__METADATA_TYPE_SEEKTABLE:
  100404. FLAC__ASSERT(0);
  100405. default:
  100406. if(0 != block.data.unknown.data)
  100407. free(block.data.unknown.data);
  100408. break;
  100409. }
  100410. }
  100411. }
  100412. if(is_last) {
  100413. /* if this fails, it's OK, it's just a hint for the seek routine */
  100414. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100415. decoder->private_->first_frame_offset = 0;
  100416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100417. }
  100418. return true;
  100419. }
  100420. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100421. {
  100422. FLAC__uint32 x;
  100423. unsigned bits, used_bits = 0;
  100424. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100425. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100426. decoder->private_->stream_info.is_last = is_last;
  100427. decoder->private_->stream_info.length = length;
  100428. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100429. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100430. return false; /* read_callback_ sets the state for us */
  100431. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100432. used_bits += bits;
  100433. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100434. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100435. return false; /* read_callback_ sets the state for us */
  100436. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100437. used_bits += bits;
  100438. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100439. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100440. return false; /* read_callback_ sets the state for us */
  100441. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100442. used_bits += bits;
  100443. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100444. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100445. return false; /* read_callback_ sets the state for us */
  100446. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100447. used_bits += bits;
  100448. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100449. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100450. return false; /* read_callback_ sets the state for us */
  100451. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100452. used_bits += bits;
  100453. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100454. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100455. return false; /* read_callback_ sets the state for us */
  100456. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100457. used_bits += bits;
  100458. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100459. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100460. return false; /* read_callback_ sets the state for us */
  100461. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100462. used_bits += bits;
  100463. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100464. 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))
  100465. return false; /* read_callback_ sets the state for us */
  100466. used_bits += bits;
  100467. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100468. return false; /* read_callback_ sets the state for us */
  100469. used_bits += 16*8;
  100470. /* skip the rest of the block */
  100471. FLAC__ASSERT(used_bits % 8 == 0);
  100472. length -= (used_bits / 8);
  100473. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100474. return false; /* read_callback_ sets the state for us */
  100475. return true;
  100476. }
  100477. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100478. {
  100479. FLAC__uint32 i, x;
  100480. FLAC__uint64 xx;
  100481. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100482. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100483. decoder->private_->seek_table.is_last = is_last;
  100484. decoder->private_->seek_table.length = length;
  100485. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100486. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100487. 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)))) {
  100488. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100489. return false;
  100490. }
  100491. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100492. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100493. return false; /* read_callback_ sets the state for us */
  100494. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100495. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100496. return false; /* read_callback_ sets the state for us */
  100497. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100498. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100499. return false; /* read_callback_ sets the state for us */
  100500. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100501. }
  100502. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100503. /* if there is a partial point left, skip over it */
  100504. if(length > 0) {
  100505. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100506. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100507. return false; /* read_callback_ sets the state for us */
  100508. }
  100509. return true;
  100510. }
  100511. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100512. {
  100513. FLAC__uint32 i;
  100514. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100515. /* read vendor string */
  100516. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100517. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100518. return false; /* read_callback_ sets the state for us */
  100519. if(obj->vendor_string.length > 0) {
  100520. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100521. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100522. return false;
  100523. }
  100524. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100525. return false; /* read_callback_ sets the state for us */
  100526. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100527. }
  100528. else
  100529. obj->vendor_string.entry = 0;
  100530. /* read num comments */
  100531. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100532. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100533. return false; /* read_callback_ sets the state for us */
  100534. /* read comments */
  100535. if(obj->num_comments > 0) {
  100536. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100537. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100538. return false;
  100539. }
  100540. for(i = 0; i < obj->num_comments; i++) {
  100541. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100542. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100543. return false; /* read_callback_ sets the state for us */
  100544. if(obj->comments[i].length > 0) {
  100545. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100546. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100547. return false;
  100548. }
  100549. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100550. return false; /* read_callback_ sets the state for us */
  100551. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100552. }
  100553. else
  100554. obj->comments[i].entry = 0;
  100555. }
  100556. }
  100557. else {
  100558. obj->comments = 0;
  100559. }
  100560. return true;
  100561. }
  100562. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100563. {
  100564. FLAC__uint32 i, j, x;
  100565. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100566. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100567. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100568. 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))
  100569. return false; /* read_callback_ sets the state for us */
  100570. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100571. return false; /* read_callback_ sets the state for us */
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100573. return false; /* read_callback_ sets the state for us */
  100574. obj->is_cd = x? true : false;
  100575. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100576. return false; /* read_callback_ sets the state for us */
  100577. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100578. return false; /* read_callback_ sets the state for us */
  100579. obj->num_tracks = x;
  100580. if(obj->num_tracks > 0) {
  100581. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100582. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100583. return false;
  100584. }
  100585. for(i = 0; i < obj->num_tracks; i++) {
  100586. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100587. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100588. return false; /* read_callback_ sets the state for us */
  100589. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100590. return false; /* read_callback_ sets the state for us */
  100591. track->number = (FLAC__byte)x;
  100592. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100593. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100594. return false; /* read_callback_ sets the state for us */
  100595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100596. return false; /* read_callback_ sets the state for us */
  100597. track->type = x;
  100598. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100599. return false; /* read_callback_ sets the state for us */
  100600. track->pre_emphasis = x;
  100601. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100602. return false; /* read_callback_ sets the state for us */
  100603. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100604. return false; /* read_callback_ sets the state for us */
  100605. track->num_indices = (FLAC__byte)x;
  100606. if(track->num_indices > 0) {
  100607. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100608. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100609. return false;
  100610. }
  100611. for(j = 0; j < track->num_indices; j++) {
  100612. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100613. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100614. return false; /* read_callback_ sets the state for us */
  100615. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100616. return false; /* read_callback_ sets the state for us */
  100617. index->number = (FLAC__byte)x;
  100618. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100619. return false; /* read_callback_ sets the state for us */
  100620. }
  100621. }
  100622. }
  100623. }
  100624. return true;
  100625. }
  100626. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100627. {
  100628. FLAC__uint32 x;
  100629. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100630. /* read type */
  100631. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100632. return false; /* read_callback_ sets the state for us */
  100633. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100634. /* read MIME type */
  100635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100636. return false; /* read_callback_ sets the state for us */
  100637. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100638. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100639. return false;
  100640. }
  100641. if(x > 0) {
  100642. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100643. return false; /* read_callback_ sets the state for us */
  100644. }
  100645. obj->mime_type[x] = '\0';
  100646. /* read description */
  100647. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100648. return false; /* read_callback_ sets the state for us */
  100649. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100650. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100651. return false;
  100652. }
  100653. if(x > 0) {
  100654. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100655. return false; /* read_callback_ sets the state for us */
  100656. }
  100657. obj->description[x] = '\0';
  100658. /* read width */
  100659. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100660. return false; /* read_callback_ sets the state for us */
  100661. /* read height */
  100662. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100663. return false; /* read_callback_ sets the state for us */
  100664. /* read depth */
  100665. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100666. return false; /* read_callback_ sets the state for us */
  100667. /* read colors */
  100668. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100669. return false; /* read_callback_ sets the state for us */
  100670. /* read data */
  100671. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100672. return false; /* read_callback_ sets the state for us */
  100673. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100674. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100675. return false;
  100676. }
  100677. if(obj->data_length > 0) {
  100678. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100679. return false; /* read_callback_ sets the state for us */
  100680. }
  100681. return true;
  100682. }
  100683. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100684. {
  100685. FLAC__uint32 x;
  100686. unsigned i, skip;
  100687. /* skip the version and flags bytes */
  100688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100689. return false; /* read_callback_ sets the state for us */
  100690. /* get the size (in bytes) to skip */
  100691. skip = 0;
  100692. for(i = 0; i < 4; i++) {
  100693. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100694. return false; /* read_callback_ sets the state for us */
  100695. skip <<= 7;
  100696. skip |= (x & 0x7f);
  100697. }
  100698. /* skip the rest of the tag */
  100699. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100700. return false; /* read_callback_ sets the state for us */
  100701. return true;
  100702. }
  100703. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100704. {
  100705. FLAC__uint32 x;
  100706. FLAC__bool first = true;
  100707. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100708. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100709. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100710. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100711. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100712. return true;
  100713. }
  100714. }
  100715. /* make sure we're byte aligned */
  100716. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100717. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100718. return false; /* read_callback_ sets the state for us */
  100719. }
  100720. while(1) {
  100721. if(decoder->private_->cached) {
  100722. x = (FLAC__uint32)decoder->private_->lookahead;
  100723. decoder->private_->cached = false;
  100724. }
  100725. else {
  100726. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100727. return false; /* read_callback_ sets the state for us */
  100728. }
  100729. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100730. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100731. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100732. return false; /* read_callback_ sets the state for us */
  100733. /* 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 */
  100734. /* else we have to check if the second byte is the end of a sync code */
  100735. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100736. decoder->private_->lookahead = (FLAC__byte)x;
  100737. decoder->private_->cached = true;
  100738. }
  100739. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100740. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100741. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100742. return true;
  100743. }
  100744. }
  100745. if(first) {
  100746. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100747. first = false;
  100748. }
  100749. }
  100750. return true;
  100751. }
  100752. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100753. {
  100754. unsigned channel;
  100755. unsigned i;
  100756. FLAC__int32 mid, side;
  100757. unsigned frame_crc; /* the one we calculate from the input stream */
  100758. FLAC__uint32 x;
  100759. *got_a_frame = false;
  100760. /* init the CRC */
  100761. frame_crc = 0;
  100762. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100763. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100764. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100765. if(!read_frame_header_(decoder))
  100766. return false;
  100767. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100768. return true;
  100769. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100770. return false;
  100771. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100772. /*
  100773. * first figure the correct bits-per-sample of the subframe
  100774. */
  100775. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100776. switch(decoder->private_->frame.header.channel_assignment) {
  100777. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100778. /* no adjustment needed */
  100779. break;
  100780. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100781. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100782. if(channel == 1)
  100783. bps++;
  100784. break;
  100785. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100786. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100787. if(channel == 0)
  100788. bps++;
  100789. break;
  100790. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100791. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100792. if(channel == 1)
  100793. bps++;
  100794. break;
  100795. default:
  100796. FLAC__ASSERT(0);
  100797. }
  100798. /*
  100799. * now read it
  100800. */
  100801. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100802. return false;
  100803. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100804. return true;
  100805. }
  100806. if(!read_zero_padding_(decoder))
  100807. return false;
  100808. 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) */
  100809. return true;
  100810. /*
  100811. * Read the frame CRC-16 from the footer and check
  100812. */
  100813. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100814. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100815. return false; /* read_callback_ sets the state for us */
  100816. if(frame_crc == x) {
  100817. if(do_full_decode) {
  100818. /* Undo any special channel coding */
  100819. switch(decoder->private_->frame.header.channel_assignment) {
  100820. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100821. /* do nothing */
  100822. break;
  100823. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100824. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100825. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100826. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100827. break;
  100828. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100829. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100830. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100831. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100832. break;
  100833. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100834. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100835. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100836. #if 1
  100837. mid = decoder->private_->output[0][i];
  100838. side = decoder->private_->output[1][i];
  100839. mid <<= 1;
  100840. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100841. decoder->private_->output[0][i] = (mid + side) >> 1;
  100842. decoder->private_->output[1][i] = (mid - side) >> 1;
  100843. #else
  100844. /* OPT: without 'side' temp variable */
  100845. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100846. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100847. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100848. #endif
  100849. }
  100850. break;
  100851. default:
  100852. FLAC__ASSERT(0);
  100853. break;
  100854. }
  100855. }
  100856. }
  100857. else {
  100858. /* Bad frame, emit error and zero the output signal */
  100859. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100860. if(do_full_decode) {
  100861. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100862. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100863. }
  100864. }
  100865. }
  100866. *got_a_frame = true;
  100867. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100868. if(decoder->private_->next_fixed_block_size)
  100869. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100870. /* put the latest values into the public section of the decoder instance */
  100871. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100872. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100873. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100874. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100875. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100876. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100877. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100878. /* write it */
  100879. if(do_full_decode) {
  100880. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100881. return false;
  100882. }
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100884. return true;
  100885. }
  100886. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100887. {
  100888. FLAC__uint32 x;
  100889. FLAC__uint64 xx;
  100890. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100891. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100892. unsigned raw_header_len;
  100893. FLAC__bool is_unparseable = false;
  100894. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100895. /* init the raw header with the saved bits from synchronization */
  100896. raw_header[0] = decoder->private_->header_warmup[0];
  100897. raw_header[1] = decoder->private_->header_warmup[1];
  100898. raw_header_len = 2;
  100899. /* check to make sure that reserved bit is 0 */
  100900. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100901. is_unparseable = true;
  100902. /*
  100903. * Note that along the way as we read the header, we look for a sync
  100904. * code inside. If we find one it would indicate that our original
  100905. * sync was bad since there cannot be a sync code in a valid header.
  100906. *
  100907. * Three kinds of things can go wrong when reading the frame header:
  100908. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100909. * If we don't find a sync code, it can end up looking like we read
  100910. * a valid but unparseable header, until getting to the frame header
  100911. * CRC. Even then we could get a false positive on the CRC.
  100912. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100913. * future encoder).
  100914. * 3) We may be on a damaged frame which appears valid but unparseable.
  100915. *
  100916. * For all these reasons, we try and read a complete frame header as
  100917. * long as it seems valid, even if unparseable, up until the frame
  100918. * header CRC.
  100919. */
  100920. /*
  100921. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100922. */
  100923. for(i = 0; i < 2; i++) {
  100924. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100925. return false; /* read_callback_ sets the state for us */
  100926. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100927. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100928. decoder->private_->lookahead = (FLAC__byte)x;
  100929. decoder->private_->cached = true;
  100930. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100931. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100932. return true;
  100933. }
  100934. raw_header[raw_header_len++] = (FLAC__byte)x;
  100935. }
  100936. switch(x = raw_header[2] >> 4) {
  100937. case 0:
  100938. is_unparseable = true;
  100939. break;
  100940. case 1:
  100941. decoder->private_->frame.header.blocksize = 192;
  100942. break;
  100943. case 2:
  100944. case 3:
  100945. case 4:
  100946. case 5:
  100947. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100948. break;
  100949. case 6:
  100950. case 7:
  100951. blocksize_hint = x;
  100952. break;
  100953. case 8:
  100954. case 9:
  100955. case 10:
  100956. case 11:
  100957. case 12:
  100958. case 13:
  100959. case 14:
  100960. case 15:
  100961. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100962. break;
  100963. default:
  100964. FLAC__ASSERT(0);
  100965. break;
  100966. }
  100967. switch(x = raw_header[2] & 0x0f) {
  100968. case 0:
  100969. if(decoder->private_->has_stream_info)
  100970. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100971. else
  100972. is_unparseable = true;
  100973. break;
  100974. case 1:
  100975. decoder->private_->frame.header.sample_rate = 88200;
  100976. break;
  100977. case 2:
  100978. decoder->private_->frame.header.sample_rate = 176400;
  100979. break;
  100980. case 3:
  100981. decoder->private_->frame.header.sample_rate = 192000;
  100982. break;
  100983. case 4:
  100984. decoder->private_->frame.header.sample_rate = 8000;
  100985. break;
  100986. case 5:
  100987. decoder->private_->frame.header.sample_rate = 16000;
  100988. break;
  100989. case 6:
  100990. decoder->private_->frame.header.sample_rate = 22050;
  100991. break;
  100992. case 7:
  100993. decoder->private_->frame.header.sample_rate = 24000;
  100994. break;
  100995. case 8:
  100996. decoder->private_->frame.header.sample_rate = 32000;
  100997. break;
  100998. case 9:
  100999. decoder->private_->frame.header.sample_rate = 44100;
  101000. break;
  101001. case 10:
  101002. decoder->private_->frame.header.sample_rate = 48000;
  101003. break;
  101004. case 11:
  101005. decoder->private_->frame.header.sample_rate = 96000;
  101006. break;
  101007. case 12:
  101008. case 13:
  101009. case 14:
  101010. sample_rate_hint = x;
  101011. break;
  101012. case 15:
  101013. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101014. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101015. return true;
  101016. default:
  101017. FLAC__ASSERT(0);
  101018. }
  101019. x = (unsigned)(raw_header[3] >> 4);
  101020. if(x & 8) {
  101021. decoder->private_->frame.header.channels = 2;
  101022. switch(x & 7) {
  101023. case 0:
  101024. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101025. break;
  101026. case 1:
  101027. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101028. break;
  101029. case 2:
  101030. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101031. break;
  101032. default:
  101033. is_unparseable = true;
  101034. break;
  101035. }
  101036. }
  101037. else {
  101038. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101039. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101040. }
  101041. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101042. case 0:
  101043. if(decoder->private_->has_stream_info)
  101044. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101045. else
  101046. is_unparseable = true;
  101047. break;
  101048. case 1:
  101049. decoder->private_->frame.header.bits_per_sample = 8;
  101050. break;
  101051. case 2:
  101052. decoder->private_->frame.header.bits_per_sample = 12;
  101053. break;
  101054. case 4:
  101055. decoder->private_->frame.header.bits_per_sample = 16;
  101056. break;
  101057. case 5:
  101058. decoder->private_->frame.header.bits_per_sample = 20;
  101059. break;
  101060. case 6:
  101061. decoder->private_->frame.header.bits_per_sample = 24;
  101062. break;
  101063. case 3:
  101064. case 7:
  101065. is_unparseable = true;
  101066. break;
  101067. default:
  101068. FLAC__ASSERT(0);
  101069. break;
  101070. }
  101071. /* check to make sure that reserved bit is 0 */
  101072. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101073. is_unparseable = true;
  101074. /* read the frame's starting sample number (or frame number as the case may be) */
  101075. if(
  101076. raw_header[1] & 0x01 ||
  101077. /*@@@ 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 */
  101078. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101079. ) { /* variable blocksize */
  101080. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101081. return false; /* read_callback_ sets the state for us */
  101082. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101083. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101084. decoder->private_->cached = true;
  101085. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101086. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101087. return true;
  101088. }
  101089. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101090. decoder->private_->frame.header.number.sample_number = xx;
  101091. }
  101092. else { /* fixed blocksize */
  101093. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101094. return false; /* read_callback_ sets the state for us */
  101095. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101096. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101097. decoder->private_->cached = true;
  101098. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101099. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101100. return true;
  101101. }
  101102. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101103. decoder->private_->frame.header.number.frame_number = x;
  101104. }
  101105. if(blocksize_hint) {
  101106. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101107. return false; /* read_callback_ sets the state for us */
  101108. raw_header[raw_header_len++] = (FLAC__byte)x;
  101109. if(blocksize_hint == 7) {
  101110. FLAC__uint32 _x;
  101111. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101112. return false; /* read_callback_ sets the state for us */
  101113. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101114. x = (x << 8) | _x;
  101115. }
  101116. decoder->private_->frame.header.blocksize = x+1;
  101117. }
  101118. if(sample_rate_hint) {
  101119. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101120. return false; /* read_callback_ sets the state for us */
  101121. raw_header[raw_header_len++] = (FLAC__byte)x;
  101122. if(sample_rate_hint != 12) {
  101123. FLAC__uint32 _x;
  101124. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101125. return false; /* read_callback_ sets the state for us */
  101126. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101127. x = (x << 8) | _x;
  101128. }
  101129. if(sample_rate_hint == 12)
  101130. decoder->private_->frame.header.sample_rate = x*1000;
  101131. else if(sample_rate_hint == 13)
  101132. decoder->private_->frame.header.sample_rate = x;
  101133. else
  101134. decoder->private_->frame.header.sample_rate = x*10;
  101135. }
  101136. /* read the CRC-8 byte */
  101137. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101138. return false; /* read_callback_ sets the state for us */
  101139. crc8 = (FLAC__byte)x;
  101140. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101141. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101142. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101143. return true;
  101144. }
  101145. /* calculate the sample number from the frame number if needed */
  101146. decoder->private_->next_fixed_block_size = 0;
  101147. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101148. x = decoder->private_->frame.header.number.frame_number;
  101149. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101150. if(decoder->private_->fixed_block_size)
  101151. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101152. else if(decoder->private_->has_stream_info) {
  101153. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101154. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101155. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101156. }
  101157. else
  101158. is_unparseable = true;
  101159. }
  101160. else if(x == 0) {
  101161. decoder->private_->frame.header.number.sample_number = 0;
  101162. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101163. }
  101164. else {
  101165. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101166. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101167. }
  101168. }
  101169. if(is_unparseable) {
  101170. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101171. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101172. return true;
  101173. }
  101174. return true;
  101175. }
  101176. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101177. {
  101178. FLAC__uint32 x;
  101179. FLAC__bool wasted_bits;
  101180. unsigned i;
  101181. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101182. return false; /* read_callback_ sets the state for us */
  101183. wasted_bits = (x & 1);
  101184. x &= 0xfe;
  101185. if(wasted_bits) {
  101186. unsigned u;
  101187. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101188. return false; /* read_callback_ sets the state for us */
  101189. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101190. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101191. }
  101192. else
  101193. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101194. /*
  101195. * Lots of magic numbers here
  101196. */
  101197. if(x & 0x80) {
  101198. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101199. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101200. return true;
  101201. }
  101202. else if(x == 0) {
  101203. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101204. return false;
  101205. }
  101206. else if(x == 2) {
  101207. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101208. return false;
  101209. }
  101210. else if(x < 16) {
  101211. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101212. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101213. return true;
  101214. }
  101215. else if(x <= 24) {
  101216. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101217. return false;
  101218. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101219. return true;
  101220. }
  101221. else if(x < 64) {
  101222. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101223. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101224. return true;
  101225. }
  101226. else {
  101227. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101228. return false;
  101229. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101230. return true;
  101231. }
  101232. if(wasted_bits && do_full_decode) {
  101233. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101234. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101235. decoder->private_->output[channel][i] <<= x;
  101236. }
  101237. return true;
  101238. }
  101239. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101240. {
  101241. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101242. FLAC__int32 x;
  101243. unsigned i;
  101244. FLAC__int32 *output = decoder->private_->output[channel];
  101245. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101246. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101247. return false; /* read_callback_ sets the state for us */
  101248. subframe->value = x;
  101249. /* decode the subframe */
  101250. if(do_full_decode) {
  101251. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101252. output[i] = x;
  101253. }
  101254. return true;
  101255. }
  101256. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101257. {
  101258. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101259. FLAC__int32 i32;
  101260. FLAC__uint32 u32;
  101261. unsigned u;
  101262. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101263. subframe->residual = decoder->private_->residual[channel];
  101264. subframe->order = order;
  101265. /* read warm-up samples */
  101266. for(u = 0; u < order; u++) {
  101267. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101268. return false; /* read_callback_ sets the state for us */
  101269. subframe->warmup[u] = i32;
  101270. }
  101271. /* read entropy coding method info */
  101272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101273. return false; /* read_callback_ sets the state for us */
  101274. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101275. switch(subframe->entropy_coding_method.type) {
  101276. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101277. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101278. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101279. return false; /* read_callback_ sets the state for us */
  101280. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101281. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101282. break;
  101283. default:
  101284. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101285. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101286. return true;
  101287. }
  101288. /* read residual */
  101289. switch(subframe->entropy_coding_method.type) {
  101290. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101291. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101292. 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))
  101293. return false;
  101294. break;
  101295. default:
  101296. FLAC__ASSERT(0);
  101297. }
  101298. /* decode the subframe */
  101299. if(do_full_decode) {
  101300. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101301. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101302. }
  101303. return true;
  101304. }
  101305. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101306. {
  101307. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101308. FLAC__int32 i32;
  101309. FLAC__uint32 u32;
  101310. unsigned u;
  101311. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101312. subframe->residual = decoder->private_->residual[channel];
  101313. subframe->order = order;
  101314. /* read warm-up samples */
  101315. for(u = 0; u < order; u++) {
  101316. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101317. return false; /* read_callback_ sets the state for us */
  101318. subframe->warmup[u] = i32;
  101319. }
  101320. /* read qlp coeff precision */
  101321. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101322. return false; /* read_callback_ sets the state for us */
  101323. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101324. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101325. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101326. return true;
  101327. }
  101328. subframe->qlp_coeff_precision = u32+1;
  101329. /* read qlp shift */
  101330. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101331. return false; /* read_callback_ sets the state for us */
  101332. subframe->quantization_level = i32;
  101333. /* read quantized lp coefficiencts */
  101334. for(u = 0; u < order; u++) {
  101335. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101336. return false; /* read_callback_ sets the state for us */
  101337. subframe->qlp_coeff[u] = i32;
  101338. }
  101339. /* read entropy coding method info */
  101340. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101341. return false; /* read_callback_ sets the state for us */
  101342. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101343. switch(subframe->entropy_coding_method.type) {
  101344. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101345. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101347. return false; /* read_callback_ sets the state for us */
  101348. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101349. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101350. break;
  101351. default:
  101352. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101353. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101354. return true;
  101355. }
  101356. /* read residual */
  101357. switch(subframe->entropy_coding_method.type) {
  101358. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101359. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101360. 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))
  101361. return false;
  101362. break;
  101363. default:
  101364. FLAC__ASSERT(0);
  101365. }
  101366. /* decode the subframe */
  101367. if(do_full_decode) {
  101368. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101369. /*@@@@@@ technically not pessimistic enough, should be more like
  101370. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101371. */
  101372. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101373. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101374. if(order <= 8)
  101375. 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);
  101376. else
  101377. 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);
  101378. }
  101379. else
  101380. 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);
  101381. else
  101382. 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);
  101383. }
  101384. return true;
  101385. }
  101386. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101387. {
  101388. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101389. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101390. unsigned i;
  101391. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101392. subframe->data = residual;
  101393. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101394. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101395. return false; /* read_callback_ sets the state for us */
  101396. residual[i] = x;
  101397. }
  101398. /* decode the subframe */
  101399. if(do_full_decode)
  101400. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101401. return true;
  101402. }
  101403. 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)
  101404. {
  101405. FLAC__uint32 rice_parameter;
  101406. int i;
  101407. unsigned partition, sample, u;
  101408. const unsigned partitions = 1u << partition_order;
  101409. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101410. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101411. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101412. /* sanity checks */
  101413. if(partition_order == 0) {
  101414. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101415. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101417. return true;
  101418. }
  101419. }
  101420. else {
  101421. if(partition_samples < predictor_order) {
  101422. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101423. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101424. return true;
  101425. }
  101426. }
  101427. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101428. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101429. return false;
  101430. }
  101431. sample = 0;
  101432. for(partition = 0; partition < partitions; partition++) {
  101433. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101434. return false; /* read_callback_ sets the state for us */
  101435. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101436. if(rice_parameter < pesc) {
  101437. partitioned_rice_contents->raw_bits[partition] = 0;
  101438. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101439. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101440. return false; /* read_callback_ sets the state for us */
  101441. sample += u;
  101442. }
  101443. else {
  101444. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101445. return false; /* read_callback_ sets the state for us */
  101446. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101447. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101448. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101449. return false; /* read_callback_ sets the state for us */
  101450. residual[sample] = i;
  101451. }
  101452. }
  101453. }
  101454. return true;
  101455. }
  101456. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101457. {
  101458. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101459. FLAC__uint32 zero = 0;
  101460. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101461. return false; /* read_callback_ sets the state for us */
  101462. if(zero != 0) {
  101463. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101464. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101465. }
  101466. }
  101467. return true;
  101468. }
  101469. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101470. {
  101471. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101472. if(
  101473. #if FLAC__HAS_OGG
  101474. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101475. !decoder->private_->is_ogg &&
  101476. #endif
  101477. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101478. ) {
  101479. *bytes = 0;
  101480. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101481. return false;
  101482. }
  101483. else if(*bytes > 0) {
  101484. /* While seeking, it is possible for our seek to land in the
  101485. * middle of audio data that looks exactly like a frame header
  101486. * from a future version of an encoder. When that happens, our
  101487. * error callback will get an
  101488. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101489. * unparseable_frame_count. But there is a remote possibility
  101490. * that it is properly synced at such a "future-codec frame",
  101491. * so to make sure, we wait to see many "unparseable" errors in
  101492. * a row before bailing out.
  101493. */
  101494. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101495. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101496. return false;
  101497. }
  101498. else {
  101499. const FLAC__StreamDecoderReadStatus status =
  101500. #if FLAC__HAS_OGG
  101501. decoder->private_->is_ogg?
  101502. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101503. #endif
  101504. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101505. ;
  101506. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101507. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101508. return false;
  101509. }
  101510. else if(*bytes == 0) {
  101511. if(
  101512. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101513. (
  101514. #if FLAC__HAS_OGG
  101515. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101516. !decoder->private_->is_ogg &&
  101517. #endif
  101518. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101519. )
  101520. ) {
  101521. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101522. return false;
  101523. }
  101524. else
  101525. return true;
  101526. }
  101527. else
  101528. return true;
  101529. }
  101530. }
  101531. else {
  101532. /* abort to avoid a deadlock */
  101533. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101534. return false;
  101535. }
  101536. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101537. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101538. * and at the same time hit the end of the stream (for example, seeking
  101539. * to a point that is after the beginning of the last Ogg page). There
  101540. * is no way to report an Ogg sync loss through the callbacks (see note
  101541. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101542. * So to keep the decoder from stopping at this point we gate the call
  101543. * to the eof_callback and let the Ogg decoder aspect set the
  101544. * end-of-stream state when it is needed.
  101545. */
  101546. }
  101547. #if FLAC__HAS_OGG
  101548. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101549. {
  101550. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101551. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101552. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101553. /* we don't really have a way to handle lost sync via read
  101554. * callback so we'll let it pass and let the underlying
  101555. * FLAC decoder catch the error
  101556. */
  101557. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101558. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101559. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101560. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101561. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101562. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101563. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101564. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101565. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101566. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101567. default:
  101568. FLAC__ASSERT(0);
  101569. /* double protection */
  101570. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101571. }
  101572. }
  101573. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101574. {
  101575. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101576. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101577. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101578. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101579. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101580. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101581. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101582. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101583. default:
  101584. /* double protection: */
  101585. FLAC__ASSERT(0);
  101586. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101587. }
  101588. }
  101589. #endif
  101590. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101591. {
  101592. if(decoder->private_->is_seeking) {
  101593. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101594. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101595. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101596. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101597. #if FLAC__HAS_OGG
  101598. decoder->private_->got_a_frame = true;
  101599. #endif
  101600. decoder->private_->last_frame = *frame; /* save the frame */
  101601. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101602. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101603. /* kick out of seek mode */
  101604. decoder->private_->is_seeking = false;
  101605. /* shift out the samples before target_sample */
  101606. if(delta > 0) {
  101607. unsigned channel;
  101608. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101609. for(channel = 0; channel < frame->header.channels; channel++)
  101610. newbuffer[channel] = buffer[channel] + delta;
  101611. decoder->private_->last_frame.header.blocksize -= delta;
  101612. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101613. /* write the relevant samples */
  101614. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101615. }
  101616. else {
  101617. /* write the relevant samples */
  101618. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101619. }
  101620. }
  101621. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101622. }
  101623. /*
  101624. * If we never got STREAMINFO, turn off MD5 checking to save
  101625. * cycles since we don't have a sum to compare to anyway
  101626. */
  101627. if(!decoder->private_->has_stream_info)
  101628. decoder->private_->do_md5_checking = false;
  101629. if(decoder->private_->do_md5_checking) {
  101630. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101631. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101632. }
  101633. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101634. }
  101635. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101636. {
  101637. if(!decoder->private_->is_seeking)
  101638. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101639. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101640. decoder->private_->unparseable_frame_count++;
  101641. }
  101642. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101643. {
  101644. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101645. FLAC__int64 pos = -1;
  101646. int i;
  101647. unsigned approx_bytes_per_frame;
  101648. FLAC__bool first_seek = true;
  101649. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101650. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101651. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101652. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101653. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101654. /* take these from the current frame in case they've changed mid-stream */
  101655. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101656. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101657. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101658. /* use values from stream info if we didn't decode a frame */
  101659. if(channels == 0)
  101660. channels = decoder->private_->stream_info.data.stream_info.channels;
  101661. if(bps == 0)
  101662. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101663. /* we are just guessing here */
  101664. if(max_framesize > 0)
  101665. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101666. /*
  101667. * Check if it's a known fixed-blocksize stream. Note that though
  101668. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101669. * never get a STREAMINFO block when decoding so the value of
  101670. * min_blocksize might be zero.
  101671. */
  101672. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101673. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101674. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101675. }
  101676. else
  101677. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101678. /*
  101679. * First, we set an upper and lower bound on where in the
  101680. * stream we will search. For now we assume the worst case
  101681. * scenario, which is our best guess at the beginning of
  101682. * the first frame and end of the stream.
  101683. */
  101684. lower_bound = first_frame_offset;
  101685. lower_bound_sample = 0;
  101686. upper_bound = stream_length;
  101687. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101688. /*
  101689. * Now we refine the bounds if we have a seektable with
  101690. * suitable points. Note that according to the spec they
  101691. * must be ordered by ascending sample number.
  101692. *
  101693. * Note: to protect against invalid seek tables we will ignore points
  101694. * that have frame_samples==0 or sample_number>=total_samples
  101695. */
  101696. if(seek_table) {
  101697. FLAC__uint64 new_lower_bound = lower_bound;
  101698. FLAC__uint64 new_upper_bound = upper_bound;
  101699. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101700. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101701. /* find the closest seek point <= target_sample, if it exists */
  101702. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101703. if(
  101704. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101705. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101706. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101707. seek_table->points[i].sample_number <= target_sample
  101708. )
  101709. break;
  101710. }
  101711. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101712. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101713. new_lower_bound_sample = seek_table->points[i].sample_number;
  101714. }
  101715. /* find the closest seek point > target_sample, if it exists */
  101716. for(i = 0; i < (int)seek_table->num_points; i++) {
  101717. if(
  101718. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101719. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101720. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101721. seek_table->points[i].sample_number > target_sample
  101722. )
  101723. break;
  101724. }
  101725. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101726. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101727. new_upper_bound_sample = seek_table->points[i].sample_number;
  101728. }
  101729. /* final protection against unsorted seek tables; keep original values if bogus */
  101730. if(new_upper_bound >= new_lower_bound) {
  101731. lower_bound = new_lower_bound;
  101732. upper_bound = new_upper_bound;
  101733. lower_bound_sample = new_lower_bound_sample;
  101734. upper_bound_sample = new_upper_bound_sample;
  101735. }
  101736. }
  101737. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101738. /* there are 2 insidious ways that the following equality occurs, which
  101739. * we need to fix:
  101740. * 1) total_samples is 0 (unknown) and target_sample is 0
  101741. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101742. * exactly equal to the last seek point in the seek table; this
  101743. * means there is no seek point above it, and upper_bound_samples
  101744. * remains equal to the estimate (of target_samples) we made above
  101745. * in either case it does not hurt to move upper_bound_sample up by 1
  101746. */
  101747. if(upper_bound_sample == lower_bound_sample)
  101748. upper_bound_sample++;
  101749. decoder->private_->target_sample = target_sample;
  101750. while(1) {
  101751. /* check if the bounds are still ok */
  101752. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101753. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101754. return false;
  101755. }
  101756. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101757. #if defined _MSC_VER || defined __MINGW32__
  101758. /* with VC++ you have to spoon feed it the casting */
  101759. 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;
  101760. #else
  101761. 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;
  101762. #endif
  101763. #else
  101764. /* a little less accurate: */
  101765. if(upper_bound - lower_bound < 0xffffffff)
  101766. 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;
  101767. else /* @@@ WATCHOUT, ~2TB limit */
  101768. 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;
  101769. #endif
  101770. if(pos >= (FLAC__int64)upper_bound)
  101771. pos = (FLAC__int64)upper_bound - 1;
  101772. if(pos < (FLAC__int64)lower_bound)
  101773. pos = (FLAC__int64)lower_bound;
  101774. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101775. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101776. return false;
  101777. }
  101778. if(!FLAC__stream_decoder_flush(decoder)) {
  101779. /* above call sets the state for us */
  101780. return false;
  101781. }
  101782. /* Now we need to get a frame. First we need to reset our
  101783. * unparseable_frame_count; if we get too many unparseable
  101784. * frames in a row, the read callback will return
  101785. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101786. * FLAC__stream_decoder_process_single() to return false.
  101787. */
  101788. decoder->private_->unparseable_frame_count = 0;
  101789. if(!FLAC__stream_decoder_process_single(decoder)) {
  101790. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101791. return false;
  101792. }
  101793. /* our write callback will change the state when it gets to the target frame */
  101794. /* 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 */
  101795. #if 0
  101796. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101797. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101798. break;
  101799. #endif
  101800. if(!decoder->private_->is_seeking)
  101801. break;
  101802. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101803. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101804. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101805. if (pos == (FLAC__int64)lower_bound) {
  101806. /* can't move back any more than the first frame, something is fatally wrong */
  101807. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101808. return false;
  101809. }
  101810. /* our last move backwards wasn't big enough, try again */
  101811. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101812. continue;
  101813. }
  101814. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101815. first_seek = false;
  101816. /* make sure we are not seeking in corrupted stream */
  101817. if (this_frame_sample < lower_bound_sample) {
  101818. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101819. return false;
  101820. }
  101821. /* we need to narrow the search */
  101822. if(target_sample < this_frame_sample) {
  101823. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101824. /*@@@@@@ what will decode position be if at end of stream? */
  101825. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101826. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101827. return false;
  101828. }
  101829. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101830. }
  101831. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101832. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101833. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101834. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101835. return false;
  101836. }
  101837. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101838. }
  101839. }
  101840. return true;
  101841. }
  101842. #if FLAC__HAS_OGG
  101843. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101844. {
  101845. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101846. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101847. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101848. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101849. FLAC__bool did_a_seek;
  101850. unsigned iteration = 0;
  101851. /* In the first iterations, we will calculate the target byte position
  101852. * by the distance from the target sample to left_sample and
  101853. * right_sample (let's call it "proportional search"). After that, we
  101854. * will switch to binary search.
  101855. */
  101856. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101857. /* We will switch to a linear search once our current sample is less
  101858. * than this number of samples ahead of the target sample
  101859. */
  101860. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101861. /* If the total number of samples is unknown, use a large value, and
  101862. * force binary search immediately.
  101863. */
  101864. if(right_sample == 0) {
  101865. right_sample = (FLAC__uint64)(-1);
  101866. BINARY_SEARCH_AFTER_ITERATION = 0;
  101867. }
  101868. decoder->private_->target_sample = target_sample;
  101869. for( ; ; iteration++) {
  101870. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101871. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101872. pos = (right_pos + left_pos) / 2;
  101873. }
  101874. else {
  101875. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101876. #if defined _MSC_VER || defined __MINGW32__
  101877. /* with MSVC you have to spoon feed it the casting */
  101878. 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));
  101879. #else
  101880. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101881. #endif
  101882. #else
  101883. /* a little less accurate: */
  101884. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101885. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101886. else /* @@@ WATCHOUT, ~2TB limit */
  101887. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101888. #endif
  101889. /* @@@ TODO: might want to limit pos to some distance
  101890. * before EOF, to make sure we land before the last frame,
  101891. * thereby getting a this_frame_sample and so having a better
  101892. * estimate.
  101893. */
  101894. }
  101895. /* physical seek */
  101896. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101897. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101898. return false;
  101899. }
  101900. if(!FLAC__stream_decoder_flush(decoder)) {
  101901. /* above call sets the state for us */
  101902. return false;
  101903. }
  101904. did_a_seek = true;
  101905. }
  101906. else
  101907. did_a_seek = false;
  101908. decoder->private_->got_a_frame = false;
  101909. if(!FLAC__stream_decoder_process_single(decoder)) {
  101910. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101911. return false;
  101912. }
  101913. if(!decoder->private_->got_a_frame) {
  101914. if(did_a_seek) {
  101915. /* this can happen if we seek to a point after the last frame; we drop
  101916. * to binary search right away in this case to avoid any wasted
  101917. * iterations of proportional search.
  101918. */
  101919. right_pos = pos;
  101920. BINARY_SEARCH_AFTER_ITERATION = 0;
  101921. }
  101922. else {
  101923. /* this can probably only happen if total_samples is unknown and the
  101924. * target_sample is past the end of the stream
  101925. */
  101926. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101927. return false;
  101928. }
  101929. }
  101930. /* our write callback will change the state when it gets to the target frame */
  101931. else if(!decoder->private_->is_seeking) {
  101932. break;
  101933. }
  101934. else {
  101935. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101936. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101937. if (did_a_seek) {
  101938. if (this_frame_sample <= target_sample) {
  101939. /* The 'equal' case should not happen, since
  101940. * FLAC__stream_decoder_process_single()
  101941. * should recognize that it has hit the
  101942. * target sample and we would exit through
  101943. * the 'break' above.
  101944. */
  101945. FLAC__ASSERT(this_frame_sample != target_sample);
  101946. left_sample = this_frame_sample;
  101947. /* sanity check to avoid infinite loop */
  101948. if (left_pos == pos) {
  101949. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101950. return false;
  101951. }
  101952. left_pos = pos;
  101953. }
  101954. else if(this_frame_sample > target_sample) {
  101955. right_sample = this_frame_sample;
  101956. /* sanity check to avoid infinite loop */
  101957. if (right_pos == pos) {
  101958. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101959. return false;
  101960. }
  101961. right_pos = pos;
  101962. }
  101963. }
  101964. }
  101965. }
  101966. return true;
  101967. }
  101968. #endif
  101969. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101970. {
  101971. (void)client_data;
  101972. if(*bytes > 0) {
  101973. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101974. if(ferror(decoder->private_->file))
  101975. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101976. else if(*bytes == 0)
  101977. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101978. else
  101979. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101980. }
  101981. else
  101982. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101983. }
  101984. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101985. {
  101986. (void)client_data;
  101987. if(decoder->private_->file == stdin)
  101988. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101989. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101990. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101991. else
  101992. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101993. }
  101994. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101995. {
  101996. off_t pos;
  101997. (void)client_data;
  101998. if(decoder->private_->file == stdin)
  101999. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102000. else if((pos = ftello(decoder->private_->file)) < 0)
  102001. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102002. else {
  102003. *absolute_byte_offset = (FLAC__uint64)pos;
  102004. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102005. }
  102006. }
  102007. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102008. {
  102009. struct stat filestats;
  102010. (void)client_data;
  102011. if(decoder->private_->file == stdin)
  102012. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102013. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102014. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102015. else {
  102016. *stream_length = (FLAC__uint64)filestats.st_size;
  102017. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102018. }
  102019. }
  102020. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102021. {
  102022. (void)client_data;
  102023. return feof(decoder->private_->file)? true : false;
  102024. }
  102025. #endif
  102026. /*** End of inlined file: stream_decoder.c ***/
  102027. /*** Start of inlined file: stream_encoder.c ***/
  102028. /*** Start of inlined file: juce_FlacHeader.h ***/
  102029. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102030. // tasks..
  102031. #define VERSION "1.2.1"
  102032. #define FLAC__NO_DLL 1
  102033. #if JUCE_MSVC
  102034. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102035. #endif
  102036. #if JUCE_MAC
  102037. #define FLAC__SYS_DARWIN 1
  102038. #endif
  102039. /*** End of inlined file: juce_FlacHeader.h ***/
  102040. #if JUCE_USE_FLAC
  102041. #if HAVE_CONFIG_H
  102042. # include <config.h>
  102043. #endif
  102044. #if defined _MSC_VER || defined __MINGW32__
  102045. #include <io.h> /* for _setmode() */
  102046. #include <fcntl.h> /* for _O_BINARY */
  102047. #endif
  102048. #if defined __CYGWIN__ || defined __EMX__
  102049. #include <io.h> /* for setmode(), O_BINARY */
  102050. #include <fcntl.h> /* for _O_BINARY */
  102051. #endif
  102052. #include <limits.h>
  102053. #include <stdio.h>
  102054. #include <stdlib.h> /* for malloc() */
  102055. #include <string.h> /* for memcpy() */
  102056. #include <sys/types.h> /* for off_t */
  102057. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102058. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102059. #define fseeko fseek
  102060. #define ftello ftell
  102061. #endif
  102062. #endif
  102063. /*** Start of inlined file: stream_encoder.h ***/
  102064. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102065. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102066. #if FLAC__HAS_OGG
  102067. #include "private/ogg_encoder_aspect.h"
  102068. #endif
  102069. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102070. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102071. typedef enum {
  102072. FLAC__APODIZATION_BARTLETT,
  102073. FLAC__APODIZATION_BARTLETT_HANN,
  102074. FLAC__APODIZATION_BLACKMAN,
  102075. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102076. FLAC__APODIZATION_CONNES,
  102077. FLAC__APODIZATION_FLATTOP,
  102078. FLAC__APODIZATION_GAUSS,
  102079. FLAC__APODIZATION_HAMMING,
  102080. FLAC__APODIZATION_HANN,
  102081. FLAC__APODIZATION_KAISER_BESSEL,
  102082. FLAC__APODIZATION_NUTTALL,
  102083. FLAC__APODIZATION_RECTANGLE,
  102084. FLAC__APODIZATION_TRIANGLE,
  102085. FLAC__APODIZATION_TUKEY,
  102086. FLAC__APODIZATION_WELCH
  102087. } FLAC__ApodizationFunction;
  102088. typedef struct {
  102089. FLAC__ApodizationFunction type;
  102090. union {
  102091. struct {
  102092. FLAC__real stddev;
  102093. } gauss;
  102094. struct {
  102095. FLAC__real p;
  102096. } tukey;
  102097. } parameters;
  102098. } FLAC__ApodizationSpecification;
  102099. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102100. typedef struct FLAC__StreamEncoderProtected {
  102101. FLAC__StreamEncoderState state;
  102102. FLAC__bool verify;
  102103. FLAC__bool streamable_subset;
  102104. FLAC__bool do_md5;
  102105. FLAC__bool do_mid_side_stereo;
  102106. FLAC__bool loose_mid_side_stereo;
  102107. unsigned channels;
  102108. unsigned bits_per_sample;
  102109. unsigned sample_rate;
  102110. unsigned blocksize;
  102111. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102112. unsigned num_apodizations;
  102113. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102114. #endif
  102115. unsigned max_lpc_order;
  102116. unsigned qlp_coeff_precision;
  102117. FLAC__bool do_qlp_coeff_prec_search;
  102118. FLAC__bool do_exhaustive_model_search;
  102119. FLAC__bool do_escape_coding;
  102120. unsigned min_residual_partition_order;
  102121. unsigned max_residual_partition_order;
  102122. unsigned rice_parameter_search_dist;
  102123. FLAC__uint64 total_samples_estimate;
  102124. FLAC__StreamMetadata **metadata;
  102125. unsigned num_metadata_blocks;
  102126. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102127. #if FLAC__HAS_OGG
  102128. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102129. #endif
  102130. } FLAC__StreamEncoderProtected;
  102131. #endif
  102132. /*** End of inlined file: stream_encoder.h ***/
  102133. #if FLAC__HAS_OGG
  102134. #include "include/private/ogg_helper.h"
  102135. #include "include/private/ogg_mapping.h"
  102136. #endif
  102137. /*** Start of inlined file: stream_encoder_framing.h ***/
  102138. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102139. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102140. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102141. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102142. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102143. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102144. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102145. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102146. #endif
  102147. /*** End of inlined file: stream_encoder_framing.h ***/
  102148. /*** Start of inlined file: window.h ***/
  102149. #ifndef FLAC__PRIVATE__WINDOW_H
  102150. #define FLAC__PRIVATE__WINDOW_H
  102151. #ifdef HAVE_CONFIG_H
  102152. #include <config.h>
  102153. #endif
  102154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102155. /*
  102156. * FLAC__window_*()
  102157. * --------------------------------------------------------------------
  102158. * Calculates window coefficients according to different apodization
  102159. * functions.
  102160. *
  102161. * OUT window[0,L-1]
  102162. * IN L (number of points in window)
  102163. */
  102164. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102165. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102166. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102167. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102168. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102169. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102170. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102171. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102172. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102173. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102174. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102175. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102176. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102177. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102178. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102179. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102180. #endif
  102181. /*** End of inlined file: window.h ***/
  102182. #ifndef FLaC__INLINE
  102183. #define FLaC__INLINE
  102184. #endif
  102185. #ifdef min
  102186. #undef min
  102187. #endif
  102188. #define min(x,y) ((x)<(y)?(x):(y))
  102189. #ifdef max
  102190. #undef max
  102191. #endif
  102192. #define max(x,y) ((x)>(y)?(x):(y))
  102193. /* Exact Rice codeword length calculation is off by default. The simple
  102194. * (and fast) estimation (of how many bits a residual value will be
  102195. * encoded with) in this encoder is very good, almost always yielding
  102196. * compression within 0.1% of exact calculation.
  102197. */
  102198. #undef EXACT_RICE_BITS_CALCULATION
  102199. /* Rice parameter searching is off by default. The simple (and fast)
  102200. * parameter estimation in this encoder is very good, almost always
  102201. * yielding compression within 0.1% of the optimal parameters.
  102202. */
  102203. #undef ENABLE_RICE_PARAMETER_SEARCH
  102204. typedef struct {
  102205. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102206. unsigned size; /* of each data[] in samples */
  102207. unsigned tail;
  102208. } verify_input_fifo;
  102209. typedef struct {
  102210. const FLAC__byte *data;
  102211. unsigned capacity;
  102212. unsigned bytes;
  102213. } verify_output;
  102214. typedef enum {
  102215. ENCODER_IN_MAGIC = 0,
  102216. ENCODER_IN_METADATA = 1,
  102217. ENCODER_IN_AUDIO = 2
  102218. } EncoderStateHint;
  102219. static struct CompressionLevels {
  102220. FLAC__bool do_mid_side_stereo;
  102221. FLAC__bool loose_mid_side_stereo;
  102222. unsigned max_lpc_order;
  102223. unsigned qlp_coeff_precision;
  102224. FLAC__bool do_qlp_coeff_prec_search;
  102225. FLAC__bool do_escape_coding;
  102226. FLAC__bool do_exhaustive_model_search;
  102227. unsigned min_residual_partition_order;
  102228. unsigned max_residual_partition_order;
  102229. unsigned rice_parameter_search_dist;
  102230. } compression_levels_[] = {
  102231. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102232. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102233. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102234. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102235. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102236. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102237. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102238. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102239. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102240. };
  102241. /***********************************************************************
  102242. *
  102243. * Private class method prototypes
  102244. *
  102245. ***********************************************************************/
  102246. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102247. static void free_(FLAC__StreamEncoder *encoder);
  102248. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102249. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102250. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102251. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102252. #if FLAC__HAS_OGG
  102253. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102254. #endif
  102255. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102256. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102257. static FLAC__bool process_subframe_(
  102258. FLAC__StreamEncoder *encoder,
  102259. unsigned min_partition_order,
  102260. unsigned max_partition_order,
  102261. const FLAC__FrameHeader *frame_header,
  102262. unsigned subframe_bps,
  102263. const FLAC__int32 integer_signal[],
  102264. FLAC__Subframe *subframe[2],
  102265. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102266. FLAC__int32 *residual[2],
  102267. unsigned *best_subframe,
  102268. unsigned *best_bits
  102269. );
  102270. static FLAC__bool add_subframe_(
  102271. FLAC__StreamEncoder *encoder,
  102272. unsigned blocksize,
  102273. unsigned subframe_bps,
  102274. const FLAC__Subframe *subframe,
  102275. FLAC__BitWriter *frame
  102276. );
  102277. static unsigned evaluate_constant_subframe_(
  102278. FLAC__StreamEncoder *encoder,
  102279. const FLAC__int32 signal,
  102280. unsigned blocksize,
  102281. unsigned subframe_bps,
  102282. FLAC__Subframe *subframe
  102283. );
  102284. static unsigned evaluate_fixed_subframe_(
  102285. FLAC__StreamEncoder *encoder,
  102286. const FLAC__int32 signal[],
  102287. FLAC__int32 residual[],
  102288. FLAC__uint64 abs_residual_partition_sums[],
  102289. unsigned raw_bits_per_partition[],
  102290. unsigned blocksize,
  102291. unsigned subframe_bps,
  102292. unsigned order,
  102293. unsigned rice_parameter,
  102294. unsigned rice_parameter_limit,
  102295. unsigned min_partition_order,
  102296. unsigned max_partition_order,
  102297. FLAC__bool do_escape_coding,
  102298. unsigned rice_parameter_search_dist,
  102299. FLAC__Subframe *subframe,
  102300. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102301. );
  102302. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102303. static unsigned evaluate_lpc_subframe_(
  102304. FLAC__StreamEncoder *encoder,
  102305. const FLAC__int32 signal[],
  102306. FLAC__int32 residual[],
  102307. FLAC__uint64 abs_residual_partition_sums[],
  102308. unsigned raw_bits_per_partition[],
  102309. const FLAC__real lp_coeff[],
  102310. unsigned blocksize,
  102311. unsigned subframe_bps,
  102312. unsigned order,
  102313. unsigned qlp_coeff_precision,
  102314. unsigned rice_parameter,
  102315. unsigned rice_parameter_limit,
  102316. unsigned min_partition_order,
  102317. unsigned max_partition_order,
  102318. FLAC__bool do_escape_coding,
  102319. unsigned rice_parameter_search_dist,
  102320. FLAC__Subframe *subframe,
  102321. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102322. );
  102323. #endif
  102324. static unsigned evaluate_verbatim_subframe_(
  102325. FLAC__StreamEncoder *encoder,
  102326. const FLAC__int32 signal[],
  102327. unsigned blocksize,
  102328. unsigned subframe_bps,
  102329. FLAC__Subframe *subframe
  102330. );
  102331. static unsigned find_best_partition_order_(
  102332. struct FLAC__StreamEncoderPrivate *private_,
  102333. const FLAC__int32 residual[],
  102334. FLAC__uint64 abs_residual_partition_sums[],
  102335. unsigned raw_bits_per_partition[],
  102336. unsigned residual_samples,
  102337. unsigned predictor_order,
  102338. unsigned rice_parameter,
  102339. unsigned rice_parameter_limit,
  102340. unsigned min_partition_order,
  102341. unsigned max_partition_order,
  102342. unsigned bps,
  102343. FLAC__bool do_escape_coding,
  102344. unsigned rice_parameter_search_dist,
  102345. FLAC__EntropyCodingMethod *best_ecm
  102346. );
  102347. static void precompute_partition_info_sums_(
  102348. const FLAC__int32 residual[],
  102349. FLAC__uint64 abs_residual_partition_sums[],
  102350. unsigned residual_samples,
  102351. unsigned predictor_order,
  102352. unsigned min_partition_order,
  102353. unsigned max_partition_order,
  102354. unsigned bps
  102355. );
  102356. static void precompute_partition_info_escapes_(
  102357. const FLAC__int32 residual[],
  102358. unsigned raw_bits_per_partition[],
  102359. unsigned residual_samples,
  102360. unsigned predictor_order,
  102361. unsigned min_partition_order,
  102362. unsigned max_partition_order
  102363. );
  102364. static FLAC__bool set_partitioned_rice_(
  102365. #ifdef EXACT_RICE_BITS_CALCULATION
  102366. const FLAC__int32 residual[],
  102367. #endif
  102368. const FLAC__uint64 abs_residual_partition_sums[],
  102369. const unsigned raw_bits_per_partition[],
  102370. const unsigned residual_samples,
  102371. const unsigned predictor_order,
  102372. const unsigned suggested_rice_parameter,
  102373. const unsigned rice_parameter_limit,
  102374. const unsigned rice_parameter_search_dist,
  102375. const unsigned partition_order,
  102376. const FLAC__bool search_for_escapes,
  102377. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102378. unsigned *bits
  102379. );
  102380. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102381. /* verify-related routines: */
  102382. static void append_to_verify_fifo_(
  102383. verify_input_fifo *fifo,
  102384. const FLAC__int32 * const input[],
  102385. unsigned input_offset,
  102386. unsigned channels,
  102387. unsigned wide_samples
  102388. );
  102389. static void append_to_verify_fifo_interleaved_(
  102390. verify_input_fifo *fifo,
  102391. const FLAC__int32 input[],
  102392. unsigned input_offset,
  102393. unsigned channels,
  102394. unsigned wide_samples
  102395. );
  102396. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102397. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102398. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102399. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102400. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102401. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102402. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102403. 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);
  102404. static FILE *get_binary_stdout_(void);
  102405. /***********************************************************************
  102406. *
  102407. * Private class data
  102408. *
  102409. ***********************************************************************/
  102410. typedef struct FLAC__StreamEncoderPrivate {
  102411. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102412. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102413. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102414. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102415. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102416. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102417. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102418. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102419. #endif
  102420. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102421. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102422. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102423. FLAC__int32 *residual_workspace_mid_side[2][2];
  102424. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102425. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102426. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102427. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102428. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102429. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102430. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102431. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102432. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102433. unsigned best_subframe_mid_side[2];
  102434. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102435. unsigned best_subframe_bits_mid_side[2];
  102436. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102437. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102438. FLAC__BitWriter *frame; /* the current frame being worked on */
  102439. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102440. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102441. FLAC__ChannelAssignment last_channel_assignment;
  102442. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102443. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102444. unsigned current_sample_number;
  102445. unsigned current_frame_number;
  102446. FLAC__MD5Context md5context;
  102447. FLAC__CPUInfo cpuinfo;
  102448. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102449. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102450. #else
  102451. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102452. #endif
  102453. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102454. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102455. 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[]);
  102456. 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[]);
  102457. 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[]);
  102458. #endif
  102459. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102460. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102461. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102462. FLAC__bool disable_constant_subframes;
  102463. FLAC__bool disable_fixed_subframes;
  102464. FLAC__bool disable_verbatim_subframes;
  102465. #if FLAC__HAS_OGG
  102466. FLAC__bool is_ogg;
  102467. #endif
  102468. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102469. FLAC__StreamEncoderSeekCallback seek_callback;
  102470. FLAC__StreamEncoderTellCallback tell_callback;
  102471. FLAC__StreamEncoderWriteCallback write_callback;
  102472. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102473. FLAC__StreamEncoderProgressCallback progress_callback;
  102474. void *client_data;
  102475. unsigned first_seekpoint_to_check;
  102476. FILE *file; /* only used when encoding to a file */
  102477. FLAC__uint64 bytes_written;
  102478. FLAC__uint64 samples_written;
  102479. unsigned frames_written;
  102480. unsigned total_frames_estimate;
  102481. /* unaligned (original) pointers to allocated data */
  102482. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102483. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102484. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102485. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102486. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102487. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102488. FLAC__real *windowed_signal_unaligned;
  102489. #endif
  102490. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102491. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102492. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102493. unsigned *raw_bits_per_partition_unaligned;
  102494. /*
  102495. * These fields have been moved here from private function local
  102496. * declarations merely to save stack space during encoding.
  102497. */
  102498. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102499. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102500. #endif
  102501. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102502. /*
  102503. * The data for the verify section
  102504. */
  102505. struct {
  102506. FLAC__StreamDecoder *decoder;
  102507. EncoderStateHint state_hint;
  102508. FLAC__bool needs_magic_hack;
  102509. verify_input_fifo input_fifo;
  102510. verify_output output;
  102511. struct {
  102512. FLAC__uint64 absolute_sample;
  102513. unsigned frame_number;
  102514. unsigned channel;
  102515. unsigned sample;
  102516. FLAC__int32 expected;
  102517. FLAC__int32 got;
  102518. } error_stats;
  102519. } verify;
  102520. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102521. } FLAC__StreamEncoderPrivate;
  102522. /***********************************************************************
  102523. *
  102524. * Public static class data
  102525. *
  102526. ***********************************************************************/
  102527. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102528. "FLAC__STREAM_ENCODER_OK",
  102529. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102530. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102531. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102532. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102533. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102534. "FLAC__STREAM_ENCODER_IO_ERROR",
  102535. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102536. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102537. };
  102538. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102539. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102540. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102541. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102542. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102543. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102544. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102545. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102546. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102547. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102548. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102549. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102550. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102551. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102552. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102553. };
  102554. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102555. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102556. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102557. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102558. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102559. };
  102560. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102561. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102562. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102563. };
  102564. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102565. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102566. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102567. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102568. };
  102569. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102570. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102571. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102572. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102573. };
  102574. /* Number of samples that will be overread to watch for end of stream. By
  102575. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102576. * always try to read blocksize+1 samples before encoding a block, so that
  102577. * even if the stream has a total sample count that is an integral multiple
  102578. * of the blocksize, we will still notice when we are encoding the last
  102579. * block. This is needed, for example, to correctly set the end-of-stream
  102580. * marker in Ogg FLAC.
  102581. *
  102582. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102583. * not really any reason to change it.
  102584. */
  102585. static const unsigned OVERREAD_ = 1;
  102586. /***********************************************************************
  102587. *
  102588. * Class constructor/destructor
  102589. *
  102590. */
  102591. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102592. {
  102593. FLAC__StreamEncoder *encoder;
  102594. unsigned i;
  102595. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102596. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102597. if(encoder == 0) {
  102598. return 0;
  102599. }
  102600. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102601. if(encoder->protected_ == 0) {
  102602. free(encoder);
  102603. return 0;
  102604. }
  102605. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102606. if(encoder->private_ == 0) {
  102607. free(encoder->protected_);
  102608. free(encoder);
  102609. return 0;
  102610. }
  102611. encoder->private_->frame = FLAC__bitwriter_new();
  102612. if(encoder->private_->frame == 0) {
  102613. free(encoder->private_);
  102614. free(encoder->protected_);
  102615. free(encoder);
  102616. return 0;
  102617. }
  102618. encoder->private_->file = 0;
  102619. set_defaults_enc(encoder);
  102620. encoder->private_->is_being_deleted = false;
  102621. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102622. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102623. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102624. }
  102625. for(i = 0; i < 2; i++) {
  102626. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102627. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102628. }
  102629. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102630. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102631. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102632. }
  102633. for(i = 0; i < 2; i++) {
  102634. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102635. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102636. }
  102637. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102638. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102639. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102640. }
  102641. for(i = 0; i < 2; i++) {
  102642. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102643. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102644. }
  102645. for(i = 0; i < 2; i++)
  102646. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102647. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102648. return encoder;
  102649. }
  102650. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102651. {
  102652. unsigned i;
  102653. FLAC__ASSERT(0 != encoder);
  102654. FLAC__ASSERT(0 != encoder->protected_);
  102655. FLAC__ASSERT(0 != encoder->private_);
  102656. FLAC__ASSERT(0 != encoder->private_->frame);
  102657. encoder->private_->is_being_deleted = true;
  102658. (void)FLAC__stream_encoder_finish(encoder);
  102659. if(0 != encoder->private_->verify.decoder)
  102660. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102661. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102662. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102663. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102664. }
  102665. for(i = 0; i < 2; i++) {
  102666. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102667. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102668. }
  102669. for(i = 0; i < 2; i++)
  102670. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102671. FLAC__bitwriter_delete(encoder->private_->frame);
  102672. free(encoder->private_);
  102673. free(encoder->protected_);
  102674. free(encoder);
  102675. }
  102676. /***********************************************************************
  102677. *
  102678. * Public class methods
  102679. *
  102680. ***********************************************************************/
  102681. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102682. FLAC__StreamEncoder *encoder,
  102683. FLAC__StreamEncoderReadCallback read_callback,
  102684. FLAC__StreamEncoderWriteCallback write_callback,
  102685. FLAC__StreamEncoderSeekCallback seek_callback,
  102686. FLAC__StreamEncoderTellCallback tell_callback,
  102687. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102688. void *client_data,
  102689. FLAC__bool is_ogg
  102690. )
  102691. {
  102692. unsigned i;
  102693. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102694. FLAC__ASSERT(0 != encoder);
  102695. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102696. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102697. #if !FLAC__HAS_OGG
  102698. if(is_ogg)
  102699. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102700. #endif
  102701. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102702. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102703. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102704. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102705. if(encoder->protected_->channels != 2) {
  102706. encoder->protected_->do_mid_side_stereo = false;
  102707. encoder->protected_->loose_mid_side_stereo = false;
  102708. }
  102709. else if(!encoder->protected_->do_mid_side_stereo)
  102710. encoder->protected_->loose_mid_side_stereo = false;
  102711. if(encoder->protected_->bits_per_sample >= 32)
  102712. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102713. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102714. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102715. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102716. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102717. if(encoder->protected_->blocksize == 0) {
  102718. if(encoder->protected_->max_lpc_order == 0)
  102719. encoder->protected_->blocksize = 1152;
  102720. else
  102721. encoder->protected_->blocksize = 4096;
  102722. }
  102723. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102724. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102725. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102726. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102727. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102728. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102729. if(encoder->protected_->qlp_coeff_precision == 0) {
  102730. if(encoder->protected_->bits_per_sample < 16) {
  102731. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102732. /* @@@ until then we'll make a guess */
  102733. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102734. }
  102735. else if(encoder->protected_->bits_per_sample == 16) {
  102736. if(encoder->protected_->blocksize <= 192)
  102737. encoder->protected_->qlp_coeff_precision = 7;
  102738. else if(encoder->protected_->blocksize <= 384)
  102739. encoder->protected_->qlp_coeff_precision = 8;
  102740. else if(encoder->protected_->blocksize <= 576)
  102741. encoder->protected_->qlp_coeff_precision = 9;
  102742. else if(encoder->protected_->blocksize <= 1152)
  102743. encoder->protected_->qlp_coeff_precision = 10;
  102744. else if(encoder->protected_->blocksize <= 2304)
  102745. encoder->protected_->qlp_coeff_precision = 11;
  102746. else if(encoder->protected_->blocksize <= 4608)
  102747. encoder->protected_->qlp_coeff_precision = 12;
  102748. else
  102749. encoder->protected_->qlp_coeff_precision = 13;
  102750. }
  102751. else {
  102752. if(encoder->protected_->blocksize <= 384)
  102753. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102754. else if(encoder->protected_->blocksize <= 1152)
  102755. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102756. else
  102757. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102758. }
  102759. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102760. }
  102761. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102762. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102763. if(encoder->protected_->streamable_subset) {
  102764. if(
  102765. encoder->protected_->blocksize != 192 &&
  102766. encoder->protected_->blocksize != 576 &&
  102767. encoder->protected_->blocksize != 1152 &&
  102768. encoder->protected_->blocksize != 2304 &&
  102769. encoder->protected_->blocksize != 4608 &&
  102770. encoder->protected_->blocksize != 256 &&
  102771. encoder->protected_->blocksize != 512 &&
  102772. encoder->protected_->blocksize != 1024 &&
  102773. encoder->protected_->blocksize != 2048 &&
  102774. encoder->protected_->blocksize != 4096 &&
  102775. encoder->protected_->blocksize != 8192 &&
  102776. encoder->protected_->blocksize != 16384
  102777. )
  102778. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102779. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102780. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102781. if(
  102782. encoder->protected_->bits_per_sample != 8 &&
  102783. encoder->protected_->bits_per_sample != 12 &&
  102784. encoder->protected_->bits_per_sample != 16 &&
  102785. encoder->protected_->bits_per_sample != 20 &&
  102786. encoder->protected_->bits_per_sample != 24
  102787. )
  102788. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102789. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102790. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102791. if(
  102792. encoder->protected_->sample_rate <= 48000 &&
  102793. (
  102794. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102795. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102796. )
  102797. ) {
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102799. }
  102800. }
  102801. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102802. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102803. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102804. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102805. #if FLAC__HAS_OGG
  102806. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102807. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102808. unsigned i;
  102809. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102810. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102811. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102812. for( ; i > 0; i--)
  102813. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102814. encoder->protected_->metadata[0] = vc;
  102815. break;
  102816. }
  102817. }
  102818. }
  102819. #endif
  102820. /* keep track of any SEEKTABLE block */
  102821. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102822. unsigned i;
  102823. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102824. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102825. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102826. break; /* take only the first one */
  102827. }
  102828. }
  102829. }
  102830. /* validate metadata */
  102831. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102832. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102833. metadata_has_seektable = false;
  102834. metadata_has_vorbis_comment = false;
  102835. metadata_picture_has_type1 = false;
  102836. metadata_picture_has_type2 = false;
  102837. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102838. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102839. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102840. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102841. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102842. if(metadata_has_seektable) /* only one is allowed */
  102843. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102844. metadata_has_seektable = true;
  102845. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102846. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102847. }
  102848. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102849. if(metadata_has_vorbis_comment) /* only one is allowed */
  102850. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102851. metadata_has_vorbis_comment = true;
  102852. }
  102853. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102854. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102855. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102856. }
  102857. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102858. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102859. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102860. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102861. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102862. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102863. metadata_picture_has_type1 = true;
  102864. /* standard icon must be 32x32 pixel PNG */
  102865. if(
  102866. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102867. (
  102868. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102869. m->data.picture.width != 32 ||
  102870. m->data.picture.height != 32
  102871. )
  102872. )
  102873. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102874. }
  102875. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102876. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102877. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102878. metadata_picture_has_type2 = true;
  102879. }
  102880. }
  102881. }
  102882. encoder->private_->input_capacity = 0;
  102883. for(i = 0; i < encoder->protected_->channels; i++) {
  102884. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102885. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102886. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102887. #endif
  102888. }
  102889. for(i = 0; i < 2; i++) {
  102890. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102891. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102892. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102893. #endif
  102894. }
  102895. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102896. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102897. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102898. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102899. #endif
  102900. for(i = 0; i < encoder->protected_->channels; i++) {
  102901. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102902. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102903. encoder->private_->best_subframe[i] = 0;
  102904. }
  102905. for(i = 0; i < 2; i++) {
  102906. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102907. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102908. encoder->private_->best_subframe_mid_side[i] = 0;
  102909. }
  102910. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102911. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102912. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102913. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102914. #else
  102915. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102916. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102917. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102918. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102919. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102920. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102921. 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);
  102922. #endif
  102923. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102924. encoder->private_->loose_mid_side_stereo_frames = 1;
  102925. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102926. encoder->private_->current_sample_number = 0;
  102927. encoder->private_->current_frame_number = 0;
  102928. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102929. 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? */
  102930. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102931. /*
  102932. * get the CPU info and set the function pointers
  102933. */
  102934. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102935. /* first default to the non-asm routines */
  102936. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102937. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102938. #endif
  102939. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102940. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102941. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102942. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102943. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102944. #endif
  102945. /* now override with asm where appropriate */
  102946. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102947. # ifndef FLAC__NO_ASM
  102948. if(encoder->private_->cpuinfo.use_asm) {
  102949. # ifdef FLAC__CPU_IA32
  102950. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102951. # ifdef FLAC__HAS_NASM
  102952. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102953. if(encoder->protected_->max_lpc_order < 4)
  102954. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102955. else if(encoder->protected_->max_lpc_order < 8)
  102956. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102957. else if(encoder->protected_->max_lpc_order < 12)
  102958. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102959. else
  102960. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102961. }
  102962. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102963. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102964. else
  102965. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102966. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102967. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102968. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102969. }
  102970. else {
  102971. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102972. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102973. }
  102974. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102975. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102976. # endif /* FLAC__HAS_NASM */
  102977. # endif /* FLAC__CPU_IA32 */
  102978. }
  102979. # endif /* !FLAC__NO_ASM */
  102980. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102981. /* finally override based on wide-ness if necessary */
  102982. if(encoder->private_->use_wide_by_block) {
  102983. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102984. }
  102985. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102986. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102987. #if FLAC__HAS_OGG
  102988. encoder->private_->is_ogg = is_ogg;
  102989. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102990. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102991. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102992. }
  102993. #endif
  102994. encoder->private_->read_callback = read_callback;
  102995. encoder->private_->write_callback = write_callback;
  102996. encoder->private_->seek_callback = seek_callback;
  102997. encoder->private_->tell_callback = tell_callback;
  102998. encoder->private_->metadata_callback = metadata_callback;
  102999. encoder->private_->client_data = client_data;
  103000. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103001. /* the above function sets the state for us in case of an error */
  103002. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103003. }
  103004. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103005. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103006. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103007. }
  103008. /*
  103009. * Set up the verify stuff if necessary
  103010. */
  103011. if(encoder->protected_->verify) {
  103012. /*
  103013. * First, set up the fifo which will hold the
  103014. * original signal to compare against
  103015. */
  103016. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103017. for(i = 0; i < encoder->protected_->channels; i++) {
  103018. 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))) {
  103019. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103020. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103021. }
  103022. }
  103023. encoder->private_->verify.input_fifo.tail = 0;
  103024. /*
  103025. * Now set up a stream decoder for verification
  103026. */
  103027. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103028. if(0 == encoder->private_->verify.decoder) {
  103029. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103030. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103031. }
  103032. 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) {
  103033. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103034. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103035. }
  103036. }
  103037. encoder->private_->verify.error_stats.absolute_sample = 0;
  103038. encoder->private_->verify.error_stats.frame_number = 0;
  103039. encoder->private_->verify.error_stats.channel = 0;
  103040. encoder->private_->verify.error_stats.sample = 0;
  103041. encoder->private_->verify.error_stats.expected = 0;
  103042. encoder->private_->verify.error_stats.got = 0;
  103043. /*
  103044. * These must be done before we write any metadata, because that
  103045. * calls the write_callback, which uses these values.
  103046. */
  103047. encoder->private_->first_seekpoint_to_check = 0;
  103048. encoder->private_->samples_written = 0;
  103049. encoder->protected_->streaminfo_offset = 0;
  103050. encoder->protected_->seektable_offset = 0;
  103051. encoder->protected_->audio_offset = 0;
  103052. /*
  103053. * write the stream header
  103054. */
  103055. if(encoder->protected_->verify)
  103056. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103057. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103058. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103059. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103060. }
  103061. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103062. /* the above function sets the state for us in case of an error */
  103063. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103064. }
  103065. /*
  103066. * write the STREAMINFO metadata block
  103067. */
  103068. if(encoder->protected_->verify)
  103069. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103070. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103071. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103072. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103073. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103074. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103075. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103076. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103077. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103078. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103079. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103080. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103081. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103082. if(encoder->protected_->do_md5)
  103083. FLAC__MD5Init(&encoder->private_->md5context);
  103084. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103085. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103086. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103087. }
  103088. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103089. /* the above function sets the state for us in case of an error */
  103090. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103091. }
  103092. /*
  103093. * Now that the STREAMINFO block is written, we can init this to an
  103094. * absurdly-high value...
  103095. */
  103096. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103097. /* ... and clear this to 0 */
  103098. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103099. /*
  103100. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103101. * if not, we will write an empty one (FLAC__add_metadata_block()
  103102. * automatically supplies the vendor string).
  103103. *
  103104. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103105. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103106. * true it will have already insured that the metadata list is properly
  103107. * ordered.)
  103108. */
  103109. if(!metadata_has_vorbis_comment) {
  103110. FLAC__StreamMetadata vorbis_comment;
  103111. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103112. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103113. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103114. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103115. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103116. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103117. vorbis_comment.data.vorbis_comment.comments = 0;
  103118. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103119. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103120. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103121. }
  103122. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103123. /* the above function sets the state for us in case of an error */
  103124. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103125. }
  103126. }
  103127. /*
  103128. * write the user's metadata blocks
  103129. */
  103130. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103131. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103132. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103133. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103134. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103135. }
  103136. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103137. /* the above function sets the state for us in case of an error */
  103138. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103139. }
  103140. }
  103141. /* now that all the metadata is written, we save the stream offset */
  103142. 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 */
  103143. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103144. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103145. }
  103146. if(encoder->protected_->verify)
  103147. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103148. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103149. }
  103150. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103151. FLAC__StreamEncoder *encoder,
  103152. FLAC__StreamEncoderWriteCallback write_callback,
  103153. FLAC__StreamEncoderSeekCallback seek_callback,
  103154. FLAC__StreamEncoderTellCallback tell_callback,
  103155. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103156. void *client_data
  103157. )
  103158. {
  103159. return init_stream_internal_enc(
  103160. encoder,
  103161. /*read_callback=*/0,
  103162. write_callback,
  103163. seek_callback,
  103164. tell_callback,
  103165. metadata_callback,
  103166. client_data,
  103167. /*is_ogg=*/false
  103168. );
  103169. }
  103170. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103171. FLAC__StreamEncoder *encoder,
  103172. FLAC__StreamEncoderReadCallback read_callback,
  103173. FLAC__StreamEncoderWriteCallback write_callback,
  103174. FLAC__StreamEncoderSeekCallback seek_callback,
  103175. FLAC__StreamEncoderTellCallback tell_callback,
  103176. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103177. void *client_data
  103178. )
  103179. {
  103180. return init_stream_internal_enc(
  103181. encoder,
  103182. read_callback,
  103183. write_callback,
  103184. seek_callback,
  103185. tell_callback,
  103186. metadata_callback,
  103187. client_data,
  103188. /*is_ogg=*/true
  103189. );
  103190. }
  103191. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103192. FLAC__StreamEncoder *encoder,
  103193. FILE *file,
  103194. FLAC__StreamEncoderProgressCallback progress_callback,
  103195. void *client_data,
  103196. FLAC__bool is_ogg
  103197. )
  103198. {
  103199. FLAC__StreamEncoderInitStatus init_status;
  103200. FLAC__ASSERT(0 != encoder);
  103201. FLAC__ASSERT(0 != file);
  103202. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103203. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103204. /* double protection */
  103205. if(file == 0) {
  103206. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103207. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103208. }
  103209. /*
  103210. * To make sure that our file does not go unclosed after an error, we
  103211. * must assign the FILE pointer before any further error can occur in
  103212. * this routine.
  103213. */
  103214. if(file == stdout)
  103215. file = get_binary_stdout_(); /* just to be safe */
  103216. encoder->private_->file = file;
  103217. encoder->private_->progress_callback = progress_callback;
  103218. encoder->private_->bytes_written = 0;
  103219. encoder->private_->samples_written = 0;
  103220. encoder->private_->frames_written = 0;
  103221. init_status = init_stream_internal_enc(
  103222. encoder,
  103223. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103224. file_write_callback_,
  103225. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103226. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103227. /*metadata_callback=*/0,
  103228. client_data,
  103229. is_ogg
  103230. );
  103231. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103232. /* the above function sets the state for us in case of an error */
  103233. return init_status;
  103234. }
  103235. {
  103236. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103237. FLAC__ASSERT(blocksize != 0);
  103238. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103239. }
  103240. return init_status;
  103241. }
  103242. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103243. FLAC__StreamEncoder *encoder,
  103244. FILE *file,
  103245. FLAC__StreamEncoderProgressCallback progress_callback,
  103246. void *client_data
  103247. )
  103248. {
  103249. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103250. }
  103251. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103252. FLAC__StreamEncoder *encoder,
  103253. FILE *file,
  103254. FLAC__StreamEncoderProgressCallback progress_callback,
  103255. void *client_data
  103256. )
  103257. {
  103258. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103259. }
  103260. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103261. FLAC__StreamEncoder *encoder,
  103262. const char *filename,
  103263. FLAC__StreamEncoderProgressCallback progress_callback,
  103264. void *client_data,
  103265. FLAC__bool is_ogg
  103266. )
  103267. {
  103268. FILE *file;
  103269. FLAC__ASSERT(0 != encoder);
  103270. /*
  103271. * To make sure that our file does not go unclosed after an error, we
  103272. * have to do the same entrance checks here that are later performed
  103273. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103274. */
  103275. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103276. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103277. file = filename? fopen(filename, "w+b") : stdout;
  103278. if(file == 0) {
  103279. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103280. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103281. }
  103282. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103283. }
  103284. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103285. FLAC__StreamEncoder *encoder,
  103286. const char *filename,
  103287. FLAC__StreamEncoderProgressCallback progress_callback,
  103288. void *client_data
  103289. )
  103290. {
  103291. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103292. }
  103293. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103294. FLAC__StreamEncoder *encoder,
  103295. const char *filename,
  103296. FLAC__StreamEncoderProgressCallback progress_callback,
  103297. void *client_data
  103298. )
  103299. {
  103300. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103301. }
  103302. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103303. {
  103304. FLAC__bool error = false;
  103305. FLAC__ASSERT(0 != encoder);
  103306. FLAC__ASSERT(0 != encoder->private_);
  103307. FLAC__ASSERT(0 != encoder->protected_);
  103308. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103309. return true;
  103310. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103311. if(encoder->private_->current_sample_number != 0) {
  103312. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103313. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103314. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103315. error = true;
  103316. }
  103317. }
  103318. if(encoder->protected_->do_md5)
  103319. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103320. if(!encoder->private_->is_being_deleted) {
  103321. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103322. if(encoder->private_->seek_callback) {
  103323. #if FLAC__HAS_OGG
  103324. if(encoder->private_->is_ogg)
  103325. update_ogg_metadata_(encoder);
  103326. else
  103327. #endif
  103328. update_metadata_(encoder);
  103329. /* check if an error occurred while updating metadata */
  103330. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103331. error = true;
  103332. }
  103333. if(encoder->private_->metadata_callback)
  103334. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103335. }
  103336. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103337. if(!error)
  103338. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103339. error = true;
  103340. }
  103341. }
  103342. if(0 != encoder->private_->file) {
  103343. if(encoder->private_->file != stdout)
  103344. fclose(encoder->private_->file);
  103345. encoder->private_->file = 0;
  103346. }
  103347. #if FLAC__HAS_OGG
  103348. if(encoder->private_->is_ogg)
  103349. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103350. #endif
  103351. free_(encoder);
  103352. set_defaults_enc(encoder);
  103353. if(!error)
  103354. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103355. return !error;
  103356. }
  103357. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103358. {
  103359. FLAC__ASSERT(0 != encoder);
  103360. FLAC__ASSERT(0 != encoder->private_);
  103361. FLAC__ASSERT(0 != encoder->protected_);
  103362. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103363. return false;
  103364. #if FLAC__HAS_OGG
  103365. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103366. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103367. return true;
  103368. #else
  103369. (void)value;
  103370. return false;
  103371. #endif
  103372. }
  103373. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103374. {
  103375. FLAC__ASSERT(0 != encoder);
  103376. FLAC__ASSERT(0 != encoder->private_);
  103377. FLAC__ASSERT(0 != encoder->protected_);
  103378. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103379. return false;
  103380. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103381. encoder->protected_->verify = value;
  103382. #endif
  103383. return true;
  103384. }
  103385. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103386. {
  103387. FLAC__ASSERT(0 != encoder);
  103388. FLAC__ASSERT(0 != encoder->private_);
  103389. FLAC__ASSERT(0 != encoder->protected_);
  103390. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103391. return false;
  103392. encoder->protected_->streamable_subset = value;
  103393. return true;
  103394. }
  103395. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103396. {
  103397. FLAC__ASSERT(0 != encoder);
  103398. FLAC__ASSERT(0 != encoder->private_);
  103399. FLAC__ASSERT(0 != encoder->protected_);
  103400. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103401. return false;
  103402. encoder->protected_->do_md5 = value;
  103403. return true;
  103404. }
  103405. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103406. {
  103407. FLAC__ASSERT(0 != encoder);
  103408. FLAC__ASSERT(0 != encoder->private_);
  103409. FLAC__ASSERT(0 != encoder->protected_);
  103410. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103411. return false;
  103412. encoder->protected_->channels = value;
  103413. return true;
  103414. }
  103415. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103416. {
  103417. FLAC__ASSERT(0 != encoder);
  103418. FLAC__ASSERT(0 != encoder->private_);
  103419. FLAC__ASSERT(0 != encoder->protected_);
  103420. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103421. return false;
  103422. encoder->protected_->bits_per_sample = value;
  103423. return true;
  103424. }
  103425. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103426. {
  103427. FLAC__ASSERT(0 != encoder);
  103428. FLAC__ASSERT(0 != encoder->private_);
  103429. FLAC__ASSERT(0 != encoder->protected_);
  103430. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103431. return false;
  103432. encoder->protected_->sample_rate = value;
  103433. return true;
  103434. }
  103435. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103436. {
  103437. FLAC__bool ok = true;
  103438. FLAC__ASSERT(0 != encoder);
  103439. FLAC__ASSERT(0 != encoder->private_);
  103440. FLAC__ASSERT(0 != encoder->protected_);
  103441. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103442. return false;
  103443. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103444. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103445. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103446. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103447. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103448. #if 0
  103449. /* was: */
  103450. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103451. /* but it's too hard to specify the string in a locale-specific way */
  103452. #else
  103453. encoder->protected_->num_apodizations = 1;
  103454. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103455. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103456. #endif
  103457. #endif
  103458. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103459. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103460. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103461. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103462. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103463. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103464. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103465. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103466. return ok;
  103467. }
  103468. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103469. {
  103470. FLAC__ASSERT(0 != encoder);
  103471. FLAC__ASSERT(0 != encoder->private_);
  103472. FLAC__ASSERT(0 != encoder->protected_);
  103473. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103474. return false;
  103475. encoder->protected_->blocksize = value;
  103476. return true;
  103477. }
  103478. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103479. {
  103480. FLAC__ASSERT(0 != encoder);
  103481. FLAC__ASSERT(0 != encoder->private_);
  103482. FLAC__ASSERT(0 != encoder->protected_);
  103483. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103484. return false;
  103485. encoder->protected_->do_mid_side_stereo = value;
  103486. return true;
  103487. }
  103488. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103489. {
  103490. FLAC__ASSERT(0 != encoder);
  103491. FLAC__ASSERT(0 != encoder->private_);
  103492. FLAC__ASSERT(0 != encoder->protected_);
  103493. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103494. return false;
  103495. encoder->protected_->loose_mid_side_stereo = value;
  103496. return true;
  103497. }
  103498. /*@@@@add to tests*/
  103499. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103500. {
  103501. FLAC__ASSERT(0 != encoder);
  103502. FLAC__ASSERT(0 != encoder->private_);
  103503. FLAC__ASSERT(0 != encoder->protected_);
  103504. FLAC__ASSERT(0 != specification);
  103505. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103506. return false;
  103507. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103508. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103509. #else
  103510. encoder->protected_->num_apodizations = 0;
  103511. while(1) {
  103512. const char *s = strchr(specification, ';');
  103513. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103514. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103515. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103516. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103517. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103518. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103519. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103520. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103521. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103522. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103523. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103524. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103525. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103526. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103527. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103528. if (stddev > 0.0 && stddev <= 0.5) {
  103529. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103530. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103531. }
  103532. }
  103533. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103534. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103535. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103536. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103537. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103538. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103539. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103540. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103541. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103542. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103543. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103544. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103545. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103546. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103547. if (p >= 0.0 && p <= 1.0) {
  103548. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103549. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103550. }
  103551. }
  103552. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103553. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103554. if (encoder->protected_->num_apodizations == 32)
  103555. break;
  103556. if (s)
  103557. specification = s+1;
  103558. else
  103559. break;
  103560. }
  103561. if(encoder->protected_->num_apodizations == 0) {
  103562. encoder->protected_->num_apodizations = 1;
  103563. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103564. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103565. }
  103566. #endif
  103567. return true;
  103568. }
  103569. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103570. {
  103571. FLAC__ASSERT(0 != encoder);
  103572. FLAC__ASSERT(0 != encoder->private_);
  103573. FLAC__ASSERT(0 != encoder->protected_);
  103574. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103575. return false;
  103576. encoder->protected_->max_lpc_order = value;
  103577. return true;
  103578. }
  103579. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103580. {
  103581. FLAC__ASSERT(0 != encoder);
  103582. FLAC__ASSERT(0 != encoder->private_);
  103583. FLAC__ASSERT(0 != encoder->protected_);
  103584. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103585. return false;
  103586. encoder->protected_->qlp_coeff_precision = value;
  103587. return true;
  103588. }
  103589. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103590. {
  103591. FLAC__ASSERT(0 != encoder);
  103592. FLAC__ASSERT(0 != encoder->private_);
  103593. FLAC__ASSERT(0 != encoder->protected_);
  103594. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103595. return false;
  103596. encoder->protected_->do_qlp_coeff_prec_search = value;
  103597. return true;
  103598. }
  103599. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103600. {
  103601. FLAC__ASSERT(0 != encoder);
  103602. FLAC__ASSERT(0 != encoder->private_);
  103603. FLAC__ASSERT(0 != encoder->protected_);
  103604. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103605. return false;
  103606. #if 0
  103607. /*@@@ deprecated: */
  103608. encoder->protected_->do_escape_coding = value;
  103609. #else
  103610. (void)value;
  103611. #endif
  103612. return true;
  103613. }
  103614. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103615. {
  103616. FLAC__ASSERT(0 != encoder);
  103617. FLAC__ASSERT(0 != encoder->private_);
  103618. FLAC__ASSERT(0 != encoder->protected_);
  103619. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103620. return false;
  103621. encoder->protected_->do_exhaustive_model_search = value;
  103622. return true;
  103623. }
  103624. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103625. {
  103626. FLAC__ASSERT(0 != encoder);
  103627. FLAC__ASSERT(0 != encoder->private_);
  103628. FLAC__ASSERT(0 != encoder->protected_);
  103629. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103630. return false;
  103631. encoder->protected_->min_residual_partition_order = value;
  103632. return true;
  103633. }
  103634. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103635. {
  103636. FLAC__ASSERT(0 != encoder);
  103637. FLAC__ASSERT(0 != encoder->private_);
  103638. FLAC__ASSERT(0 != encoder->protected_);
  103639. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103640. return false;
  103641. encoder->protected_->max_residual_partition_order = value;
  103642. return true;
  103643. }
  103644. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103645. {
  103646. FLAC__ASSERT(0 != encoder);
  103647. FLAC__ASSERT(0 != encoder->private_);
  103648. FLAC__ASSERT(0 != encoder->protected_);
  103649. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103650. return false;
  103651. #if 0
  103652. /*@@@ deprecated: */
  103653. encoder->protected_->rice_parameter_search_dist = value;
  103654. #else
  103655. (void)value;
  103656. #endif
  103657. return true;
  103658. }
  103659. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103660. {
  103661. FLAC__ASSERT(0 != encoder);
  103662. FLAC__ASSERT(0 != encoder->private_);
  103663. FLAC__ASSERT(0 != encoder->protected_);
  103664. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103665. return false;
  103666. encoder->protected_->total_samples_estimate = value;
  103667. return true;
  103668. }
  103669. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103670. {
  103671. FLAC__ASSERT(0 != encoder);
  103672. FLAC__ASSERT(0 != encoder->private_);
  103673. FLAC__ASSERT(0 != encoder->protected_);
  103674. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103675. return false;
  103676. if(0 == metadata)
  103677. num_blocks = 0;
  103678. if(0 == num_blocks)
  103679. metadata = 0;
  103680. /* realloc() does not do exactly what we want so... */
  103681. if(encoder->protected_->metadata) {
  103682. free(encoder->protected_->metadata);
  103683. encoder->protected_->metadata = 0;
  103684. encoder->protected_->num_metadata_blocks = 0;
  103685. }
  103686. if(num_blocks) {
  103687. FLAC__StreamMetadata **m;
  103688. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103689. return false;
  103690. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103691. encoder->protected_->metadata = m;
  103692. encoder->protected_->num_metadata_blocks = num_blocks;
  103693. }
  103694. #if FLAC__HAS_OGG
  103695. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103696. return false;
  103697. #endif
  103698. return true;
  103699. }
  103700. /*
  103701. * These three functions are not static, but not publically exposed in
  103702. * include/FLAC/ either. They are used by the test suite.
  103703. */
  103704. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103705. {
  103706. FLAC__ASSERT(0 != encoder);
  103707. FLAC__ASSERT(0 != encoder->private_);
  103708. FLAC__ASSERT(0 != encoder->protected_);
  103709. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103710. return false;
  103711. encoder->private_->disable_constant_subframes = value;
  103712. return true;
  103713. }
  103714. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103715. {
  103716. FLAC__ASSERT(0 != encoder);
  103717. FLAC__ASSERT(0 != encoder->private_);
  103718. FLAC__ASSERT(0 != encoder->protected_);
  103719. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103720. return false;
  103721. encoder->private_->disable_fixed_subframes = value;
  103722. return true;
  103723. }
  103724. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103725. {
  103726. FLAC__ASSERT(0 != encoder);
  103727. FLAC__ASSERT(0 != encoder->private_);
  103728. FLAC__ASSERT(0 != encoder->protected_);
  103729. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103730. return false;
  103731. encoder->private_->disable_verbatim_subframes = value;
  103732. return true;
  103733. }
  103734. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103735. {
  103736. FLAC__ASSERT(0 != encoder);
  103737. FLAC__ASSERT(0 != encoder->private_);
  103738. FLAC__ASSERT(0 != encoder->protected_);
  103739. return encoder->protected_->state;
  103740. }
  103741. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103742. {
  103743. FLAC__ASSERT(0 != encoder);
  103744. FLAC__ASSERT(0 != encoder->private_);
  103745. FLAC__ASSERT(0 != encoder->protected_);
  103746. if(encoder->protected_->verify)
  103747. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103748. else
  103749. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103750. }
  103751. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103752. {
  103753. FLAC__ASSERT(0 != encoder);
  103754. FLAC__ASSERT(0 != encoder->private_);
  103755. FLAC__ASSERT(0 != encoder->protected_);
  103756. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103757. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103758. else
  103759. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103760. }
  103761. 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)
  103762. {
  103763. FLAC__ASSERT(0 != encoder);
  103764. FLAC__ASSERT(0 != encoder->private_);
  103765. FLAC__ASSERT(0 != encoder->protected_);
  103766. if(0 != absolute_sample)
  103767. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103768. if(0 != frame_number)
  103769. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103770. if(0 != channel)
  103771. *channel = encoder->private_->verify.error_stats.channel;
  103772. if(0 != sample)
  103773. *sample = encoder->private_->verify.error_stats.sample;
  103774. if(0 != expected)
  103775. *expected = encoder->private_->verify.error_stats.expected;
  103776. if(0 != got)
  103777. *got = encoder->private_->verify.error_stats.got;
  103778. }
  103779. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103780. {
  103781. FLAC__ASSERT(0 != encoder);
  103782. FLAC__ASSERT(0 != encoder->private_);
  103783. FLAC__ASSERT(0 != encoder->protected_);
  103784. return encoder->protected_->verify;
  103785. }
  103786. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103787. {
  103788. FLAC__ASSERT(0 != encoder);
  103789. FLAC__ASSERT(0 != encoder->private_);
  103790. FLAC__ASSERT(0 != encoder->protected_);
  103791. return encoder->protected_->streamable_subset;
  103792. }
  103793. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103794. {
  103795. FLAC__ASSERT(0 != encoder);
  103796. FLAC__ASSERT(0 != encoder->private_);
  103797. FLAC__ASSERT(0 != encoder->protected_);
  103798. return encoder->protected_->do_md5;
  103799. }
  103800. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103801. {
  103802. FLAC__ASSERT(0 != encoder);
  103803. FLAC__ASSERT(0 != encoder->private_);
  103804. FLAC__ASSERT(0 != encoder->protected_);
  103805. return encoder->protected_->channels;
  103806. }
  103807. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103808. {
  103809. FLAC__ASSERT(0 != encoder);
  103810. FLAC__ASSERT(0 != encoder->private_);
  103811. FLAC__ASSERT(0 != encoder->protected_);
  103812. return encoder->protected_->bits_per_sample;
  103813. }
  103814. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103815. {
  103816. FLAC__ASSERT(0 != encoder);
  103817. FLAC__ASSERT(0 != encoder->private_);
  103818. FLAC__ASSERT(0 != encoder->protected_);
  103819. return encoder->protected_->sample_rate;
  103820. }
  103821. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103822. {
  103823. FLAC__ASSERT(0 != encoder);
  103824. FLAC__ASSERT(0 != encoder->private_);
  103825. FLAC__ASSERT(0 != encoder->protected_);
  103826. return encoder->protected_->blocksize;
  103827. }
  103828. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103829. {
  103830. FLAC__ASSERT(0 != encoder);
  103831. FLAC__ASSERT(0 != encoder->private_);
  103832. FLAC__ASSERT(0 != encoder->protected_);
  103833. return encoder->protected_->do_mid_side_stereo;
  103834. }
  103835. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103836. {
  103837. FLAC__ASSERT(0 != encoder);
  103838. FLAC__ASSERT(0 != encoder->private_);
  103839. FLAC__ASSERT(0 != encoder->protected_);
  103840. return encoder->protected_->loose_mid_side_stereo;
  103841. }
  103842. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103843. {
  103844. FLAC__ASSERT(0 != encoder);
  103845. FLAC__ASSERT(0 != encoder->private_);
  103846. FLAC__ASSERT(0 != encoder->protected_);
  103847. return encoder->protected_->max_lpc_order;
  103848. }
  103849. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103850. {
  103851. FLAC__ASSERT(0 != encoder);
  103852. FLAC__ASSERT(0 != encoder->private_);
  103853. FLAC__ASSERT(0 != encoder->protected_);
  103854. return encoder->protected_->qlp_coeff_precision;
  103855. }
  103856. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103857. {
  103858. FLAC__ASSERT(0 != encoder);
  103859. FLAC__ASSERT(0 != encoder->private_);
  103860. FLAC__ASSERT(0 != encoder->protected_);
  103861. return encoder->protected_->do_qlp_coeff_prec_search;
  103862. }
  103863. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103864. {
  103865. FLAC__ASSERT(0 != encoder);
  103866. FLAC__ASSERT(0 != encoder->private_);
  103867. FLAC__ASSERT(0 != encoder->protected_);
  103868. return encoder->protected_->do_escape_coding;
  103869. }
  103870. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103871. {
  103872. FLAC__ASSERT(0 != encoder);
  103873. FLAC__ASSERT(0 != encoder->private_);
  103874. FLAC__ASSERT(0 != encoder->protected_);
  103875. return encoder->protected_->do_exhaustive_model_search;
  103876. }
  103877. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103878. {
  103879. FLAC__ASSERT(0 != encoder);
  103880. FLAC__ASSERT(0 != encoder->private_);
  103881. FLAC__ASSERT(0 != encoder->protected_);
  103882. return encoder->protected_->min_residual_partition_order;
  103883. }
  103884. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103885. {
  103886. FLAC__ASSERT(0 != encoder);
  103887. FLAC__ASSERT(0 != encoder->private_);
  103888. FLAC__ASSERT(0 != encoder->protected_);
  103889. return encoder->protected_->max_residual_partition_order;
  103890. }
  103891. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103892. {
  103893. FLAC__ASSERT(0 != encoder);
  103894. FLAC__ASSERT(0 != encoder->private_);
  103895. FLAC__ASSERT(0 != encoder->protected_);
  103896. return encoder->protected_->rice_parameter_search_dist;
  103897. }
  103898. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103899. {
  103900. FLAC__ASSERT(0 != encoder);
  103901. FLAC__ASSERT(0 != encoder->private_);
  103902. FLAC__ASSERT(0 != encoder->protected_);
  103903. return encoder->protected_->total_samples_estimate;
  103904. }
  103905. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103906. {
  103907. unsigned i, j = 0, channel;
  103908. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103909. FLAC__ASSERT(0 != encoder);
  103910. FLAC__ASSERT(0 != encoder->private_);
  103911. FLAC__ASSERT(0 != encoder->protected_);
  103912. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103913. do {
  103914. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103915. if(encoder->protected_->verify)
  103916. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103917. for(channel = 0; channel < channels; channel++)
  103918. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103919. if(encoder->protected_->do_mid_side_stereo) {
  103920. FLAC__ASSERT(channels == 2);
  103921. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103922. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103923. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103924. 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' ! */
  103925. }
  103926. }
  103927. else
  103928. j += n;
  103929. encoder->private_->current_sample_number += n;
  103930. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103931. if(encoder->private_->current_sample_number > blocksize) {
  103932. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103933. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103934. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103935. return false;
  103936. /* move unprocessed overread samples to beginnings of arrays */
  103937. for(channel = 0; channel < channels; channel++)
  103938. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103939. if(encoder->protected_->do_mid_side_stereo) {
  103940. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103941. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103942. }
  103943. encoder->private_->current_sample_number = 1;
  103944. }
  103945. } while(j < samples);
  103946. return true;
  103947. }
  103948. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103949. {
  103950. unsigned i, j, k, channel;
  103951. FLAC__int32 x, mid, side;
  103952. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103953. FLAC__ASSERT(0 != encoder);
  103954. FLAC__ASSERT(0 != encoder->private_);
  103955. FLAC__ASSERT(0 != encoder->protected_);
  103956. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103957. j = k = 0;
  103958. /*
  103959. * we have several flavors of the same basic loop, optimized for
  103960. * different conditions:
  103961. */
  103962. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103963. /*
  103964. * stereo coding: unroll channel loop
  103965. */
  103966. do {
  103967. if(encoder->protected_->verify)
  103968. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103969. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103970. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103971. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103972. x = buffer[k++];
  103973. encoder->private_->integer_signal[1][i] = x;
  103974. mid += x;
  103975. side -= x;
  103976. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103977. encoder->private_->integer_signal_mid_side[1][i] = side;
  103978. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103979. }
  103980. encoder->private_->current_sample_number = i;
  103981. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103982. if(i > blocksize) {
  103983. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103984. return false;
  103985. /* move unprocessed overread samples to beginnings of arrays */
  103986. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103987. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103988. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103989. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103990. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103991. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103992. encoder->private_->current_sample_number = 1;
  103993. }
  103994. } while(j < samples);
  103995. }
  103996. else {
  103997. /*
  103998. * independent channel coding: buffer each channel in inner loop
  103999. */
  104000. do {
  104001. if(encoder->protected_->verify)
  104002. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104003. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104004. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104005. for(channel = 0; channel < channels; channel++)
  104006. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104007. }
  104008. encoder->private_->current_sample_number = i;
  104009. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104010. if(i > blocksize) {
  104011. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104012. return false;
  104013. /* move unprocessed overread samples to beginnings of arrays */
  104014. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104015. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104016. for(channel = 0; channel < channels; channel++)
  104017. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104018. encoder->private_->current_sample_number = 1;
  104019. }
  104020. } while(j < samples);
  104021. }
  104022. return true;
  104023. }
  104024. /***********************************************************************
  104025. *
  104026. * Private class methods
  104027. *
  104028. ***********************************************************************/
  104029. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104030. {
  104031. FLAC__ASSERT(0 != encoder);
  104032. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104033. encoder->protected_->verify = true;
  104034. #else
  104035. encoder->protected_->verify = false;
  104036. #endif
  104037. encoder->protected_->streamable_subset = true;
  104038. encoder->protected_->do_md5 = true;
  104039. encoder->protected_->do_mid_side_stereo = false;
  104040. encoder->protected_->loose_mid_side_stereo = false;
  104041. encoder->protected_->channels = 2;
  104042. encoder->protected_->bits_per_sample = 16;
  104043. encoder->protected_->sample_rate = 44100;
  104044. encoder->protected_->blocksize = 0;
  104045. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104046. encoder->protected_->num_apodizations = 1;
  104047. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104048. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104049. #endif
  104050. encoder->protected_->max_lpc_order = 0;
  104051. encoder->protected_->qlp_coeff_precision = 0;
  104052. encoder->protected_->do_qlp_coeff_prec_search = false;
  104053. encoder->protected_->do_exhaustive_model_search = false;
  104054. encoder->protected_->do_escape_coding = false;
  104055. encoder->protected_->min_residual_partition_order = 0;
  104056. encoder->protected_->max_residual_partition_order = 0;
  104057. encoder->protected_->rice_parameter_search_dist = 0;
  104058. encoder->protected_->total_samples_estimate = 0;
  104059. encoder->protected_->metadata = 0;
  104060. encoder->protected_->num_metadata_blocks = 0;
  104061. encoder->private_->seek_table = 0;
  104062. encoder->private_->disable_constant_subframes = false;
  104063. encoder->private_->disable_fixed_subframes = false;
  104064. encoder->private_->disable_verbatim_subframes = false;
  104065. #if FLAC__HAS_OGG
  104066. encoder->private_->is_ogg = false;
  104067. #endif
  104068. encoder->private_->read_callback = 0;
  104069. encoder->private_->write_callback = 0;
  104070. encoder->private_->seek_callback = 0;
  104071. encoder->private_->tell_callback = 0;
  104072. encoder->private_->metadata_callback = 0;
  104073. encoder->private_->progress_callback = 0;
  104074. encoder->private_->client_data = 0;
  104075. #if FLAC__HAS_OGG
  104076. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104077. #endif
  104078. }
  104079. void free_(FLAC__StreamEncoder *encoder)
  104080. {
  104081. unsigned i, channel;
  104082. FLAC__ASSERT(0 != encoder);
  104083. if(encoder->protected_->metadata) {
  104084. free(encoder->protected_->metadata);
  104085. encoder->protected_->metadata = 0;
  104086. encoder->protected_->num_metadata_blocks = 0;
  104087. }
  104088. for(i = 0; i < encoder->protected_->channels; i++) {
  104089. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104090. free(encoder->private_->integer_signal_unaligned[i]);
  104091. encoder->private_->integer_signal_unaligned[i] = 0;
  104092. }
  104093. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104094. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104095. free(encoder->private_->real_signal_unaligned[i]);
  104096. encoder->private_->real_signal_unaligned[i] = 0;
  104097. }
  104098. #endif
  104099. }
  104100. for(i = 0; i < 2; i++) {
  104101. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104102. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104103. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104104. }
  104105. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104106. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104107. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104108. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104109. }
  104110. #endif
  104111. }
  104112. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104113. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104114. if(0 != encoder->private_->window_unaligned[i]) {
  104115. free(encoder->private_->window_unaligned[i]);
  104116. encoder->private_->window_unaligned[i] = 0;
  104117. }
  104118. }
  104119. if(0 != encoder->private_->windowed_signal_unaligned) {
  104120. free(encoder->private_->windowed_signal_unaligned);
  104121. encoder->private_->windowed_signal_unaligned = 0;
  104122. }
  104123. #endif
  104124. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104125. for(i = 0; i < 2; i++) {
  104126. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104127. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104128. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104129. }
  104130. }
  104131. }
  104132. for(channel = 0; channel < 2; channel++) {
  104133. for(i = 0; i < 2; i++) {
  104134. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104135. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104136. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104137. }
  104138. }
  104139. }
  104140. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104141. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104142. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104143. }
  104144. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104145. free(encoder->private_->raw_bits_per_partition_unaligned);
  104146. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104147. }
  104148. if(encoder->protected_->verify) {
  104149. for(i = 0; i < encoder->protected_->channels; i++) {
  104150. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104151. free(encoder->private_->verify.input_fifo.data[i]);
  104152. encoder->private_->verify.input_fifo.data[i] = 0;
  104153. }
  104154. }
  104155. }
  104156. FLAC__bitwriter_free(encoder->private_->frame);
  104157. }
  104158. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104159. {
  104160. FLAC__bool ok;
  104161. unsigned i, channel;
  104162. FLAC__ASSERT(new_blocksize > 0);
  104163. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104164. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104165. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104166. if(new_blocksize <= encoder->private_->input_capacity)
  104167. return true;
  104168. ok = true;
  104169. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104170. * requires that the input arrays (in our case the integer signals)
  104171. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104172. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104173. */
  104174. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104175. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104176. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104177. encoder->private_->integer_signal[i] += 4;
  104178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104179. #if 0 /* @@@ currently unused */
  104180. if(encoder->protected_->max_lpc_order > 0)
  104181. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104182. #endif
  104183. #endif
  104184. }
  104185. for(i = 0; ok && i < 2; i++) {
  104186. 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]);
  104187. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104188. encoder->private_->integer_signal_mid_side[i] += 4;
  104189. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104190. #if 0 /* @@@ currently unused */
  104191. if(encoder->protected_->max_lpc_order > 0)
  104192. 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]);
  104193. #endif
  104194. #endif
  104195. }
  104196. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104197. if(ok && encoder->protected_->max_lpc_order > 0) {
  104198. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104199. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104200. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104201. }
  104202. #endif
  104203. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104204. for(i = 0; ok && i < 2; i++) {
  104205. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104206. }
  104207. }
  104208. for(channel = 0; ok && channel < 2; channel++) {
  104209. for(i = 0; ok && i < 2; i++) {
  104210. 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]);
  104211. }
  104212. }
  104213. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104214. /*@@@ 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) */
  104215. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104216. if(encoder->protected_->do_escape_coding)
  104217. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104218. /* now adjust the windows if the blocksize has changed */
  104219. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104220. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104221. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104222. switch(encoder->protected_->apodizations[i].type) {
  104223. case FLAC__APODIZATION_BARTLETT:
  104224. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104225. break;
  104226. case FLAC__APODIZATION_BARTLETT_HANN:
  104227. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104228. break;
  104229. case FLAC__APODIZATION_BLACKMAN:
  104230. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104231. break;
  104232. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104233. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104234. break;
  104235. case FLAC__APODIZATION_CONNES:
  104236. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104237. break;
  104238. case FLAC__APODIZATION_FLATTOP:
  104239. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104240. break;
  104241. case FLAC__APODIZATION_GAUSS:
  104242. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104243. break;
  104244. case FLAC__APODIZATION_HAMMING:
  104245. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104246. break;
  104247. case FLAC__APODIZATION_HANN:
  104248. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104249. break;
  104250. case FLAC__APODIZATION_KAISER_BESSEL:
  104251. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104252. break;
  104253. case FLAC__APODIZATION_NUTTALL:
  104254. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104255. break;
  104256. case FLAC__APODIZATION_RECTANGLE:
  104257. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104258. break;
  104259. case FLAC__APODIZATION_TRIANGLE:
  104260. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104261. break;
  104262. case FLAC__APODIZATION_TUKEY:
  104263. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104264. break;
  104265. case FLAC__APODIZATION_WELCH:
  104266. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104267. break;
  104268. default:
  104269. FLAC__ASSERT(0);
  104270. /* double protection */
  104271. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104272. break;
  104273. }
  104274. }
  104275. }
  104276. #endif
  104277. if(ok)
  104278. encoder->private_->input_capacity = new_blocksize;
  104279. else
  104280. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104281. return ok;
  104282. }
  104283. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104284. {
  104285. const FLAC__byte *buffer;
  104286. size_t bytes;
  104287. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104288. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104289. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104290. return false;
  104291. }
  104292. if(encoder->protected_->verify) {
  104293. encoder->private_->verify.output.data = buffer;
  104294. encoder->private_->verify.output.bytes = bytes;
  104295. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104296. encoder->private_->verify.needs_magic_hack = true;
  104297. }
  104298. else {
  104299. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104300. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104301. FLAC__bitwriter_clear(encoder->private_->frame);
  104302. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104303. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104304. return false;
  104305. }
  104306. }
  104307. }
  104308. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104309. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104310. FLAC__bitwriter_clear(encoder->private_->frame);
  104311. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104312. return false;
  104313. }
  104314. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104315. FLAC__bitwriter_clear(encoder->private_->frame);
  104316. if(samples > 0) {
  104317. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104318. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104319. }
  104320. return true;
  104321. }
  104322. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104323. {
  104324. FLAC__StreamEncoderWriteStatus status;
  104325. FLAC__uint64 output_position = 0;
  104326. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104327. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104328. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104329. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104330. }
  104331. /*
  104332. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104333. */
  104334. if(samples == 0) {
  104335. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104336. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104337. encoder->protected_->streaminfo_offset = output_position;
  104338. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104339. encoder->protected_->seektable_offset = output_position;
  104340. }
  104341. /*
  104342. * Mark the current seek point if hit (if audio_offset == 0 that
  104343. * means we're still writing metadata and haven't hit the first
  104344. * frame yet)
  104345. */
  104346. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104347. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104348. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104349. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104350. FLAC__uint64 test_sample;
  104351. unsigned i;
  104352. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104353. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104354. if(test_sample > frame_last_sample) {
  104355. break;
  104356. }
  104357. else if(test_sample >= frame_first_sample) {
  104358. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104359. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104360. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104361. encoder->private_->first_seekpoint_to_check++;
  104362. /* DO NOT: "break;" and here's why:
  104363. * The seektable template may contain more than one target
  104364. * sample for any given frame; we will keep looping, generating
  104365. * duplicate seekpoints for them, and we'll clean it up later,
  104366. * just before writing the seektable back to the metadata.
  104367. */
  104368. }
  104369. else {
  104370. encoder->private_->first_seekpoint_to_check++;
  104371. }
  104372. }
  104373. }
  104374. #if FLAC__HAS_OGG
  104375. if(encoder->private_->is_ogg) {
  104376. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104377. &encoder->protected_->ogg_encoder_aspect,
  104378. buffer,
  104379. bytes,
  104380. samples,
  104381. encoder->private_->current_frame_number,
  104382. is_last_block,
  104383. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104384. encoder,
  104385. encoder->private_->client_data
  104386. );
  104387. }
  104388. else
  104389. #endif
  104390. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104391. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104392. encoder->private_->bytes_written += bytes;
  104393. encoder->private_->samples_written += samples;
  104394. /* we keep a high watermark on the number of frames written because
  104395. * when the encoder goes back to write metadata, 'current_frame'
  104396. * will drop back to 0.
  104397. */
  104398. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104399. }
  104400. else
  104401. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104402. return status;
  104403. }
  104404. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104405. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104406. {
  104407. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104408. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104409. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104410. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104411. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104412. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104413. FLAC__StreamEncoderSeekStatus seek_status;
  104414. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104415. /* All this is based on intimate knowledge of the stream header
  104416. * layout, but a change to the header format that would break this
  104417. * would also break all streams encoded in the previous format.
  104418. */
  104419. /*
  104420. * Write MD5 signature
  104421. */
  104422. {
  104423. const unsigned md5_offset =
  104424. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104425. (
  104426. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104427. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104428. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104429. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104430. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104431. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104432. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104433. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104434. ) / 8;
  104435. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104436. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104437. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104438. return;
  104439. }
  104440. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104441. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104442. return;
  104443. }
  104444. }
  104445. /*
  104446. * Write total samples
  104447. */
  104448. {
  104449. const unsigned total_samples_byte_offset =
  104450. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104451. (
  104452. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104453. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104454. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104455. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104456. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104457. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104458. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104459. - 4
  104460. ) / 8;
  104461. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104462. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104463. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104464. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104465. b[4] = (FLAC__byte)(samples & 0xFF);
  104466. 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) {
  104467. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104468. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104469. return;
  104470. }
  104471. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104472. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104473. return;
  104474. }
  104475. }
  104476. /*
  104477. * Write min/max framesize
  104478. */
  104479. {
  104480. const unsigned min_framesize_offset =
  104481. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104482. (
  104483. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104484. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104485. ) / 8;
  104486. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104487. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104488. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104489. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104490. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104491. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104492. 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) {
  104493. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104494. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104495. return;
  104496. }
  104497. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104498. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104499. return;
  104500. }
  104501. }
  104502. /*
  104503. * Write seektable
  104504. */
  104505. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104506. unsigned i;
  104507. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104508. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104509. 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) {
  104510. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104511. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104512. return;
  104513. }
  104514. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104515. FLAC__uint64 xx;
  104516. unsigned x;
  104517. xx = encoder->private_->seek_table->points[i].sample_number;
  104518. b[7] = (FLAC__byte)xx; xx >>= 8;
  104519. b[6] = (FLAC__byte)xx; xx >>= 8;
  104520. b[5] = (FLAC__byte)xx; xx >>= 8;
  104521. b[4] = (FLAC__byte)xx; xx >>= 8;
  104522. b[3] = (FLAC__byte)xx; xx >>= 8;
  104523. b[2] = (FLAC__byte)xx; xx >>= 8;
  104524. b[1] = (FLAC__byte)xx; xx >>= 8;
  104525. b[0] = (FLAC__byte)xx; xx >>= 8;
  104526. xx = encoder->private_->seek_table->points[i].stream_offset;
  104527. b[15] = (FLAC__byte)xx; xx >>= 8;
  104528. b[14] = (FLAC__byte)xx; xx >>= 8;
  104529. b[13] = (FLAC__byte)xx; xx >>= 8;
  104530. b[12] = (FLAC__byte)xx; xx >>= 8;
  104531. b[11] = (FLAC__byte)xx; xx >>= 8;
  104532. b[10] = (FLAC__byte)xx; xx >>= 8;
  104533. b[9] = (FLAC__byte)xx; xx >>= 8;
  104534. b[8] = (FLAC__byte)xx; xx >>= 8;
  104535. x = encoder->private_->seek_table->points[i].frame_samples;
  104536. b[17] = (FLAC__byte)x; x >>= 8;
  104537. b[16] = (FLAC__byte)x; x >>= 8;
  104538. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104539. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104540. return;
  104541. }
  104542. }
  104543. }
  104544. }
  104545. #if FLAC__HAS_OGG
  104546. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104547. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104548. {
  104549. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104550. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104551. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104552. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104553. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104554. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104555. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104556. FLAC__STREAM_SYNC_LENGTH
  104557. ;
  104558. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104559. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104560. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104561. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104562. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104563. ogg_page page;
  104564. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104565. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104566. /* Pre-check that client supports seeking, since we don't want the
  104567. * ogg_helper code to ever have to deal with this condition.
  104568. */
  104569. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104570. return;
  104571. /* All this is based on intimate knowledge of the stream header
  104572. * layout, but a change to the header format that would break this
  104573. * would also break all streams encoded in the previous format.
  104574. */
  104575. /**
  104576. ** Write STREAMINFO stats
  104577. **/
  104578. simple_ogg_page__init(&page);
  104579. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104580. simple_ogg_page__clear(&page);
  104581. return; /* state already set */
  104582. }
  104583. /*
  104584. * Write MD5 signature
  104585. */
  104586. {
  104587. const unsigned md5_offset =
  104588. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104589. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104590. (
  104591. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104592. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104593. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104594. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104595. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104596. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104597. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104598. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104599. ) / 8;
  104600. if(md5_offset + 16 > (unsigned)page.body_len) {
  104601. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104602. simple_ogg_page__clear(&page);
  104603. return;
  104604. }
  104605. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104606. }
  104607. /*
  104608. * Write total samples
  104609. */
  104610. {
  104611. const unsigned total_samples_byte_offset =
  104612. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104613. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104614. (
  104615. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104616. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104617. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104618. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104619. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104620. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104621. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104622. - 4
  104623. ) / 8;
  104624. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104625. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104626. simple_ogg_page__clear(&page);
  104627. return;
  104628. }
  104629. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104630. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104631. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104632. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104633. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104634. b[4] = (FLAC__byte)(samples & 0xFF);
  104635. memcpy(page.body + total_samples_byte_offset, b, 5);
  104636. }
  104637. /*
  104638. * Write min/max framesize
  104639. */
  104640. {
  104641. const unsigned min_framesize_offset =
  104642. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104643. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104644. (
  104645. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104646. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104647. ) / 8;
  104648. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104649. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104650. simple_ogg_page__clear(&page);
  104651. return;
  104652. }
  104653. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104654. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104655. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104656. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104657. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104658. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104659. memcpy(page.body + min_framesize_offset, b, 6);
  104660. }
  104661. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104662. simple_ogg_page__clear(&page);
  104663. return; /* state already set */
  104664. }
  104665. simple_ogg_page__clear(&page);
  104666. /*
  104667. * Write seektable
  104668. */
  104669. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104670. unsigned i;
  104671. FLAC__byte *p;
  104672. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104673. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104674. simple_ogg_page__init(&page);
  104675. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104676. simple_ogg_page__clear(&page);
  104677. return; /* state already set */
  104678. }
  104679. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104680. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104681. simple_ogg_page__clear(&page);
  104682. return;
  104683. }
  104684. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104685. FLAC__uint64 xx;
  104686. unsigned x;
  104687. xx = encoder->private_->seek_table->points[i].sample_number;
  104688. b[7] = (FLAC__byte)xx; xx >>= 8;
  104689. b[6] = (FLAC__byte)xx; xx >>= 8;
  104690. b[5] = (FLAC__byte)xx; xx >>= 8;
  104691. b[4] = (FLAC__byte)xx; xx >>= 8;
  104692. b[3] = (FLAC__byte)xx; xx >>= 8;
  104693. b[2] = (FLAC__byte)xx; xx >>= 8;
  104694. b[1] = (FLAC__byte)xx; xx >>= 8;
  104695. b[0] = (FLAC__byte)xx; xx >>= 8;
  104696. xx = encoder->private_->seek_table->points[i].stream_offset;
  104697. b[15] = (FLAC__byte)xx; xx >>= 8;
  104698. b[14] = (FLAC__byte)xx; xx >>= 8;
  104699. b[13] = (FLAC__byte)xx; xx >>= 8;
  104700. b[12] = (FLAC__byte)xx; xx >>= 8;
  104701. b[11] = (FLAC__byte)xx; xx >>= 8;
  104702. b[10] = (FLAC__byte)xx; xx >>= 8;
  104703. b[9] = (FLAC__byte)xx; xx >>= 8;
  104704. b[8] = (FLAC__byte)xx; xx >>= 8;
  104705. x = encoder->private_->seek_table->points[i].frame_samples;
  104706. b[17] = (FLAC__byte)x; x >>= 8;
  104707. b[16] = (FLAC__byte)x; x >>= 8;
  104708. memcpy(p, b, 18);
  104709. }
  104710. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104711. simple_ogg_page__clear(&page);
  104712. return; /* state already set */
  104713. }
  104714. simple_ogg_page__clear(&page);
  104715. }
  104716. }
  104717. #endif
  104718. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104719. {
  104720. FLAC__uint16 crc;
  104721. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104722. /*
  104723. * Accumulate raw signal to the MD5 signature
  104724. */
  104725. 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)) {
  104726. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104727. return false;
  104728. }
  104729. /*
  104730. * Process the frame header and subframes into the frame bitbuffer
  104731. */
  104732. if(!process_subframes_(encoder, is_fractional_block)) {
  104733. /* the above function sets the state for us in case of an error */
  104734. return false;
  104735. }
  104736. /*
  104737. * Zero-pad the frame to a byte_boundary
  104738. */
  104739. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104740. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104741. return false;
  104742. }
  104743. /*
  104744. * CRC-16 the whole thing
  104745. */
  104746. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104747. if(
  104748. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104749. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104750. ) {
  104751. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104752. return false;
  104753. }
  104754. /*
  104755. * Write it
  104756. */
  104757. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104758. /* the above function sets the state for us in case of an error */
  104759. return false;
  104760. }
  104761. /*
  104762. * Get ready for the next frame
  104763. */
  104764. encoder->private_->current_sample_number = 0;
  104765. encoder->private_->current_frame_number++;
  104766. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104767. return true;
  104768. }
  104769. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104770. {
  104771. FLAC__FrameHeader frame_header;
  104772. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104773. FLAC__bool do_independent, do_mid_side;
  104774. /*
  104775. * Calculate the min,max Rice partition orders
  104776. */
  104777. if(is_fractional_block) {
  104778. max_partition_order = 0;
  104779. }
  104780. else {
  104781. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104782. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104783. }
  104784. min_partition_order = min(min_partition_order, max_partition_order);
  104785. /*
  104786. * Setup the frame
  104787. */
  104788. frame_header.blocksize = encoder->protected_->blocksize;
  104789. frame_header.sample_rate = encoder->protected_->sample_rate;
  104790. frame_header.channels = encoder->protected_->channels;
  104791. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104792. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104793. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104794. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104795. /*
  104796. * Figure out what channel assignments to try
  104797. */
  104798. if(encoder->protected_->do_mid_side_stereo) {
  104799. if(encoder->protected_->loose_mid_side_stereo) {
  104800. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104801. do_independent = true;
  104802. do_mid_side = true;
  104803. }
  104804. else {
  104805. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104806. do_mid_side = !do_independent;
  104807. }
  104808. }
  104809. else {
  104810. do_independent = true;
  104811. do_mid_side = true;
  104812. }
  104813. }
  104814. else {
  104815. do_independent = true;
  104816. do_mid_side = false;
  104817. }
  104818. FLAC__ASSERT(do_independent || do_mid_side);
  104819. /*
  104820. * Check for wasted bits; set effective bps for each subframe
  104821. */
  104822. if(do_independent) {
  104823. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104824. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104825. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104826. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104827. }
  104828. }
  104829. if(do_mid_side) {
  104830. FLAC__ASSERT(encoder->protected_->channels == 2);
  104831. for(channel = 0; channel < 2; channel++) {
  104832. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104833. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104834. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104835. }
  104836. }
  104837. /*
  104838. * First do a normal encoding pass of each independent channel
  104839. */
  104840. if(do_independent) {
  104841. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104842. if(!
  104843. process_subframe_(
  104844. encoder,
  104845. min_partition_order,
  104846. max_partition_order,
  104847. &frame_header,
  104848. encoder->private_->subframe_bps[channel],
  104849. encoder->private_->integer_signal[channel],
  104850. encoder->private_->subframe_workspace_ptr[channel],
  104851. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104852. encoder->private_->residual_workspace[channel],
  104853. encoder->private_->best_subframe+channel,
  104854. encoder->private_->best_subframe_bits+channel
  104855. )
  104856. )
  104857. return false;
  104858. }
  104859. }
  104860. /*
  104861. * Now do mid and side channels if requested
  104862. */
  104863. if(do_mid_side) {
  104864. FLAC__ASSERT(encoder->protected_->channels == 2);
  104865. for(channel = 0; channel < 2; channel++) {
  104866. if(!
  104867. process_subframe_(
  104868. encoder,
  104869. min_partition_order,
  104870. max_partition_order,
  104871. &frame_header,
  104872. encoder->private_->subframe_bps_mid_side[channel],
  104873. encoder->private_->integer_signal_mid_side[channel],
  104874. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104875. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104876. encoder->private_->residual_workspace_mid_side[channel],
  104877. encoder->private_->best_subframe_mid_side+channel,
  104878. encoder->private_->best_subframe_bits_mid_side+channel
  104879. )
  104880. )
  104881. return false;
  104882. }
  104883. }
  104884. /*
  104885. * Compose the frame bitbuffer
  104886. */
  104887. if(do_mid_side) {
  104888. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104889. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104890. FLAC__ChannelAssignment channel_assignment;
  104891. FLAC__ASSERT(encoder->protected_->channels == 2);
  104892. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104893. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104894. }
  104895. else {
  104896. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104897. unsigned min_bits;
  104898. int ca;
  104899. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104900. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104901. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104902. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104903. FLAC__ASSERT(do_independent && do_mid_side);
  104904. /* We have to figure out which channel assignent results in the smallest frame */
  104905. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104906. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104907. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104908. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104909. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104910. min_bits = bits[channel_assignment];
  104911. for(ca = 1; ca <= 3; ca++) {
  104912. if(bits[ca] < min_bits) {
  104913. min_bits = bits[ca];
  104914. channel_assignment = (FLAC__ChannelAssignment)ca;
  104915. }
  104916. }
  104917. }
  104918. frame_header.channel_assignment = channel_assignment;
  104919. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104920. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104921. return false;
  104922. }
  104923. switch(channel_assignment) {
  104924. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104925. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104926. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104927. break;
  104928. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104929. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104930. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104931. break;
  104932. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104933. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104934. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104935. break;
  104936. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104937. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104938. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104939. break;
  104940. default:
  104941. FLAC__ASSERT(0);
  104942. }
  104943. switch(channel_assignment) {
  104944. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104945. left_bps = encoder->private_->subframe_bps [0];
  104946. right_bps = encoder->private_->subframe_bps [1];
  104947. break;
  104948. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104949. left_bps = encoder->private_->subframe_bps [0];
  104950. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104951. break;
  104952. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104953. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104954. right_bps = encoder->private_->subframe_bps [1];
  104955. break;
  104956. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104957. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104958. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104959. break;
  104960. default:
  104961. FLAC__ASSERT(0);
  104962. }
  104963. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104964. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104965. return false;
  104966. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104967. return false;
  104968. }
  104969. else {
  104970. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104971. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104972. return false;
  104973. }
  104974. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104975. 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)) {
  104976. /* the above function sets the state for us in case of an error */
  104977. return false;
  104978. }
  104979. }
  104980. }
  104981. if(encoder->protected_->loose_mid_side_stereo) {
  104982. encoder->private_->loose_mid_side_stereo_frame_count++;
  104983. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104984. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104985. }
  104986. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104987. return true;
  104988. }
  104989. FLAC__bool process_subframe_(
  104990. FLAC__StreamEncoder *encoder,
  104991. unsigned min_partition_order,
  104992. unsigned max_partition_order,
  104993. const FLAC__FrameHeader *frame_header,
  104994. unsigned subframe_bps,
  104995. const FLAC__int32 integer_signal[],
  104996. FLAC__Subframe *subframe[2],
  104997. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104998. FLAC__int32 *residual[2],
  104999. unsigned *best_subframe,
  105000. unsigned *best_bits
  105001. )
  105002. {
  105003. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105004. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105005. #else
  105006. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105007. #endif
  105008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105009. FLAC__double lpc_residual_bits_per_sample;
  105010. 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 */
  105011. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105012. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105013. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105014. #endif
  105015. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105016. unsigned rice_parameter;
  105017. unsigned _candidate_bits, _best_bits;
  105018. unsigned _best_subframe;
  105019. /* only use RICE2 partitions if stream bps > 16 */
  105020. 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;
  105021. FLAC__ASSERT(frame_header->blocksize > 0);
  105022. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105023. _best_subframe = 0;
  105024. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105025. _best_bits = UINT_MAX;
  105026. else
  105027. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105028. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105029. unsigned signal_is_constant = false;
  105030. 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);
  105031. /* check for constant subframe */
  105032. if(
  105033. !encoder->private_->disable_constant_subframes &&
  105034. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105035. fixed_residual_bits_per_sample[1] == 0.0
  105036. #else
  105037. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105038. #endif
  105039. ) {
  105040. /* the above means it's possible all samples are the same value; now double-check it: */
  105041. unsigned i;
  105042. signal_is_constant = true;
  105043. for(i = 1; i < frame_header->blocksize; i++) {
  105044. if(integer_signal[0] != integer_signal[i]) {
  105045. signal_is_constant = false;
  105046. break;
  105047. }
  105048. }
  105049. }
  105050. if(signal_is_constant) {
  105051. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105052. if(_candidate_bits < _best_bits) {
  105053. _best_subframe = !_best_subframe;
  105054. _best_bits = _candidate_bits;
  105055. }
  105056. }
  105057. else {
  105058. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105059. /* encode fixed */
  105060. if(encoder->protected_->do_exhaustive_model_search) {
  105061. min_fixed_order = 0;
  105062. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105063. }
  105064. else {
  105065. min_fixed_order = max_fixed_order = guess_fixed_order;
  105066. }
  105067. if(max_fixed_order >= frame_header->blocksize)
  105068. max_fixed_order = frame_header->blocksize - 1;
  105069. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105070. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105071. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105072. continue; /* don't even try */
  105073. 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 */
  105074. #else
  105075. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105076. continue; /* don't even try */
  105077. 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 */
  105078. #endif
  105079. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105080. if(rice_parameter >= rice_parameter_limit) {
  105081. #ifdef DEBUG_VERBOSE
  105082. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105083. #endif
  105084. rice_parameter = rice_parameter_limit - 1;
  105085. }
  105086. _candidate_bits =
  105087. evaluate_fixed_subframe_(
  105088. encoder,
  105089. integer_signal,
  105090. residual[!_best_subframe],
  105091. encoder->private_->abs_residual_partition_sums,
  105092. encoder->private_->raw_bits_per_partition,
  105093. frame_header->blocksize,
  105094. subframe_bps,
  105095. fixed_order,
  105096. rice_parameter,
  105097. rice_parameter_limit,
  105098. min_partition_order,
  105099. max_partition_order,
  105100. encoder->protected_->do_escape_coding,
  105101. encoder->protected_->rice_parameter_search_dist,
  105102. subframe[!_best_subframe],
  105103. partitioned_rice_contents[!_best_subframe]
  105104. );
  105105. if(_candidate_bits < _best_bits) {
  105106. _best_subframe = !_best_subframe;
  105107. _best_bits = _candidate_bits;
  105108. }
  105109. }
  105110. }
  105111. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105112. /* encode lpc */
  105113. if(encoder->protected_->max_lpc_order > 0) {
  105114. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105115. max_lpc_order = frame_header->blocksize-1;
  105116. else
  105117. max_lpc_order = encoder->protected_->max_lpc_order;
  105118. if(max_lpc_order > 0) {
  105119. unsigned a;
  105120. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105121. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105122. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105123. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105124. if(autoc[0] != 0.0) {
  105125. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105126. if(encoder->protected_->do_exhaustive_model_search) {
  105127. min_lpc_order = 1;
  105128. }
  105129. else {
  105130. const unsigned guess_lpc_order =
  105131. FLAC__lpc_compute_best_order(
  105132. lpc_error,
  105133. max_lpc_order,
  105134. frame_header->blocksize,
  105135. subframe_bps + (
  105136. encoder->protected_->do_qlp_coeff_prec_search?
  105137. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105138. encoder->protected_->qlp_coeff_precision
  105139. )
  105140. );
  105141. min_lpc_order = max_lpc_order = guess_lpc_order;
  105142. }
  105143. if(max_lpc_order >= frame_header->blocksize)
  105144. max_lpc_order = frame_header->blocksize - 1;
  105145. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105146. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105147. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105148. continue; /* don't even try */
  105149. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105150. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105151. if(rice_parameter >= rice_parameter_limit) {
  105152. #ifdef DEBUG_VERBOSE
  105153. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105154. #endif
  105155. rice_parameter = rice_parameter_limit - 1;
  105156. }
  105157. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105158. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105159. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105160. if(subframe_bps <= 17) {
  105161. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105162. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105163. }
  105164. else
  105165. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105166. }
  105167. else {
  105168. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105169. }
  105170. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105171. _candidate_bits =
  105172. evaluate_lpc_subframe_(
  105173. encoder,
  105174. integer_signal,
  105175. residual[!_best_subframe],
  105176. encoder->private_->abs_residual_partition_sums,
  105177. encoder->private_->raw_bits_per_partition,
  105178. encoder->private_->lp_coeff[lpc_order-1],
  105179. frame_header->blocksize,
  105180. subframe_bps,
  105181. lpc_order,
  105182. qlp_coeff_precision,
  105183. rice_parameter,
  105184. rice_parameter_limit,
  105185. min_partition_order,
  105186. max_partition_order,
  105187. encoder->protected_->do_escape_coding,
  105188. encoder->protected_->rice_parameter_search_dist,
  105189. subframe[!_best_subframe],
  105190. partitioned_rice_contents[!_best_subframe]
  105191. );
  105192. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105193. if(_candidate_bits < _best_bits) {
  105194. _best_subframe = !_best_subframe;
  105195. _best_bits = _candidate_bits;
  105196. }
  105197. }
  105198. }
  105199. }
  105200. }
  105201. }
  105202. }
  105203. }
  105204. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105205. }
  105206. }
  105207. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105208. if(_best_bits == UINT_MAX) {
  105209. FLAC__ASSERT(_best_subframe == 0);
  105210. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105211. }
  105212. *best_subframe = _best_subframe;
  105213. *best_bits = _best_bits;
  105214. return true;
  105215. }
  105216. FLAC__bool add_subframe_(
  105217. FLAC__StreamEncoder *encoder,
  105218. unsigned blocksize,
  105219. unsigned subframe_bps,
  105220. const FLAC__Subframe *subframe,
  105221. FLAC__BitWriter *frame
  105222. )
  105223. {
  105224. switch(subframe->type) {
  105225. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105226. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105227. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105228. return false;
  105229. }
  105230. break;
  105231. case FLAC__SUBFRAME_TYPE_FIXED:
  105232. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105233. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105234. return false;
  105235. }
  105236. break;
  105237. case FLAC__SUBFRAME_TYPE_LPC:
  105238. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105239. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105240. return false;
  105241. }
  105242. break;
  105243. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105244. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105245. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105246. return false;
  105247. }
  105248. break;
  105249. default:
  105250. FLAC__ASSERT(0);
  105251. }
  105252. return true;
  105253. }
  105254. #define SPOTCHECK_ESTIMATE 0
  105255. #if SPOTCHECK_ESTIMATE
  105256. static void spotcheck_subframe_estimate_(
  105257. FLAC__StreamEncoder *encoder,
  105258. unsigned blocksize,
  105259. unsigned subframe_bps,
  105260. const FLAC__Subframe *subframe,
  105261. unsigned estimate
  105262. )
  105263. {
  105264. FLAC__bool ret;
  105265. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105266. if(frame == 0) {
  105267. fprintf(stderr, "EST: can't allocate frame\n");
  105268. return;
  105269. }
  105270. if(!FLAC__bitwriter_init(frame)) {
  105271. fprintf(stderr, "EST: can't init frame\n");
  105272. return;
  105273. }
  105274. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105275. FLAC__ASSERT(ret);
  105276. {
  105277. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105278. if(estimate != actual)
  105279. 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);
  105280. }
  105281. FLAC__bitwriter_delete(frame);
  105282. }
  105283. #endif
  105284. unsigned evaluate_constant_subframe_(
  105285. FLAC__StreamEncoder *encoder,
  105286. const FLAC__int32 signal,
  105287. unsigned blocksize,
  105288. unsigned subframe_bps,
  105289. FLAC__Subframe *subframe
  105290. )
  105291. {
  105292. unsigned estimate;
  105293. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105294. subframe->data.constant.value = signal;
  105295. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105296. #if SPOTCHECK_ESTIMATE
  105297. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105298. #else
  105299. (void)encoder, (void)blocksize;
  105300. #endif
  105301. return estimate;
  105302. }
  105303. unsigned evaluate_fixed_subframe_(
  105304. FLAC__StreamEncoder *encoder,
  105305. const FLAC__int32 signal[],
  105306. FLAC__int32 residual[],
  105307. FLAC__uint64 abs_residual_partition_sums[],
  105308. unsigned raw_bits_per_partition[],
  105309. unsigned blocksize,
  105310. unsigned subframe_bps,
  105311. unsigned order,
  105312. unsigned rice_parameter,
  105313. unsigned rice_parameter_limit,
  105314. unsigned min_partition_order,
  105315. unsigned max_partition_order,
  105316. FLAC__bool do_escape_coding,
  105317. unsigned rice_parameter_search_dist,
  105318. FLAC__Subframe *subframe,
  105319. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105320. )
  105321. {
  105322. unsigned i, residual_bits, estimate;
  105323. const unsigned residual_samples = blocksize - order;
  105324. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105325. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105326. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105327. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105328. subframe->data.fixed.residual = residual;
  105329. residual_bits =
  105330. find_best_partition_order_(
  105331. encoder->private_,
  105332. residual,
  105333. abs_residual_partition_sums,
  105334. raw_bits_per_partition,
  105335. residual_samples,
  105336. order,
  105337. rice_parameter,
  105338. rice_parameter_limit,
  105339. min_partition_order,
  105340. max_partition_order,
  105341. subframe_bps,
  105342. do_escape_coding,
  105343. rice_parameter_search_dist,
  105344. &subframe->data.fixed.entropy_coding_method
  105345. );
  105346. subframe->data.fixed.order = order;
  105347. for(i = 0; i < order; i++)
  105348. subframe->data.fixed.warmup[i] = signal[i];
  105349. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105350. #if SPOTCHECK_ESTIMATE
  105351. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105352. #endif
  105353. return estimate;
  105354. }
  105355. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105356. unsigned evaluate_lpc_subframe_(
  105357. FLAC__StreamEncoder *encoder,
  105358. const FLAC__int32 signal[],
  105359. FLAC__int32 residual[],
  105360. FLAC__uint64 abs_residual_partition_sums[],
  105361. unsigned raw_bits_per_partition[],
  105362. const FLAC__real lp_coeff[],
  105363. unsigned blocksize,
  105364. unsigned subframe_bps,
  105365. unsigned order,
  105366. unsigned qlp_coeff_precision,
  105367. unsigned rice_parameter,
  105368. unsigned rice_parameter_limit,
  105369. unsigned min_partition_order,
  105370. unsigned max_partition_order,
  105371. FLAC__bool do_escape_coding,
  105372. unsigned rice_parameter_search_dist,
  105373. FLAC__Subframe *subframe,
  105374. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105375. )
  105376. {
  105377. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105378. unsigned i, residual_bits, estimate;
  105379. int quantization, ret;
  105380. const unsigned residual_samples = blocksize - order;
  105381. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105382. if(subframe_bps <= 16) {
  105383. FLAC__ASSERT(order > 0);
  105384. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105385. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105386. }
  105387. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105388. if(ret != 0)
  105389. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105390. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105391. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105392. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105393. else
  105394. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105395. else
  105396. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105397. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105398. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105399. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105400. subframe->data.lpc.residual = residual;
  105401. residual_bits =
  105402. find_best_partition_order_(
  105403. encoder->private_,
  105404. residual,
  105405. abs_residual_partition_sums,
  105406. raw_bits_per_partition,
  105407. residual_samples,
  105408. order,
  105409. rice_parameter,
  105410. rice_parameter_limit,
  105411. min_partition_order,
  105412. max_partition_order,
  105413. subframe_bps,
  105414. do_escape_coding,
  105415. rice_parameter_search_dist,
  105416. &subframe->data.lpc.entropy_coding_method
  105417. );
  105418. subframe->data.lpc.order = order;
  105419. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105420. subframe->data.lpc.quantization_level = quantization;
  105421. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105422. for(i = 0; i < order; i++)
  105423. subframe->data.lpc.warmup[i] = signal[i];
  105424. 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;
  105425. #if SPOTCHECK_ESTIMATE
  105426. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105427. #endif
  105428. return estimate;
  105429. }
  105430. #endif
  105431. unsigned evaluate_verbatim_subframe_(
  105432. FLAC__StreamEncoder *encoder,
  105433. const FLAC__int32 signal[],
  105434. unsigned blocksize,
  105435. unsigned subframe_bps,
  105436. FLAC__Subframe *subframe
  105437. )
  105438. {
  105439. unsigned estimate;
  105440. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105441. subframe->data.verbatim.data = signal;
  105442. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105443. #if SPOTCHECK_ESTIMATE
  105444. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105445. #else
  105446. (void)encoder;
  105447. #endif
  105448. return estimate;
  105449. }
  105450. unsigned find_best_partition_order_(
  105451. FLAC__StreamEncoderPrivate *private_,
  105452. const FLAC__int32 residual[],
  105453. FLAC__uint64 abs_residual_partition_sums[],
  105454. unsigned raw_bits_per_partition[],
  105455. unsigned residual_samples,
  105456. unsigned predictor_order,
  105457. unsigned rice_parameter,
  105458. unsigned rice_parameter_limit,
  105459. unsigned min_partition_order,
  105460. unsigned max_partition_order,
  105461. unsigned bps,
  105462. FLAC__bool do_escape_coding,
  105463. unsigned rice_parameter_search_dist,
  105464. FLAC__EntropyCodingMethod *best_ecm
  105465. )
  105466. {
  105467. unsigned residual_bits, best_residual_bits = 0;
  105468. unsigned best_parameters_index = 0;
  105469. unsigned best_partition_order = 0;
  105470. const unsigned blocksize = residual_samples + predictor_order;
  105471. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105472. min_partition_order = min(min_partition_order, max_partition_order);
  105473. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105474. if(do_escape_coding)
  105475. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105476. {
  105477. int partition_order;
  105478. unsigned sum;
  105479. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105480. if(!
  105481. set_partitioned_rice_(
  105482. #ifdef EXACT_RICE_BITS_CALCULATION
  105483. residual,
  105484. #endif
  105485. abs_residual_partition_sums+sum,
  105486. raw_bits_per_partition+sum,
  105487. residual_samples,
  105488. predictor_order,
  105489. rice_parameter,
  105490. rice_parameter_limit,
  105491. rice_parameter_search_dist,
  105492. (unsigned)partition_order,
  105493. do_escape_coding,
  105494. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105495. &residual_bits
  105496. )
  105497. )
  105498. {
  105499. FLAC__ASSERT(best_residual_bits != 0);
  105500. break;
  105501. }
  105502. sum += 1u << partition_order;
  105503. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105504. best_residual_bits = residual_bits;
  105505. best_parameters_index = !best_parameters_index;
  105506. best_partition_order = partition_order;
  105507. }
  105508. }
  105509. }
  105510. best_ecm->data.partitioned_rice.order = best_partition_order;
  105511. {
  105512. /*
  105513. * We are allowed to de-const the pointer based on our special
  105514. * knowledge; it is const to the outside world.
  105515. */
  105516. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105517. unsigned partition;
  105518. /* save best parameters and raw_bits */
  105519. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105520. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105521. if(do_escape_coding)
  105522. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105523. /*
  105524. * Now need to check if the type should be changed to
  105525. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105526. * size of the rice parameters.
  105527. */
  105528. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105529. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105530. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105531. break;
  105532. }
  105533. }
  105534. }
  105535. return best_residual_bits;
  105536. }
  105537. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105538. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105539. const FLAC__int32 residual[],
  105540. FLAC__uint64 abs_residual_partition_sums[],
  105541. unsigned blocksize,
  105542. unsigned predictor_order,
  105543. unsigned min_partition_order,
  105544. unsigned max_partition_order
  105545. );
  105546. #endif
  105547. void precompute_partition_info_sums_(
  105548. const FLAC__int32 residual[],
  105549. FLAC__uint64 abs_residual_partition_sums[],
  105550. unsigned residual_samples,
  105551. unsigned predictor_order,
  105552. unsigned min_partition_order,
  105553. unsigned max_partition_order,
  105554. unsigned bps
  105555. )
  105556. {
  105557. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105558. unsigned partitions = 1u << max_partition_order;
  105559. FLAC__ASSERT(default_partition_samples > predictor_order);
  105560. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105561. /* slightly pessimistic but still catches all common cases */
  105562. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105563. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105564. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105565. return;
  105566. }
  105567. #endif
  105568. /* first do max_partition_order */
  105569. {
  105570. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105571. /* slightly pessimistic but still catches all common cases */
  105572. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105573. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105574. FLAC__uint32 abs_residual_partition_sum;
  105575. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105576. end += default_partition_samples;
  105577. abs_residual_partition_sum = 0;
  105578. for( ; residual_sample < end; residual_sample++)
  105579. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105580. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105581. }
  105582. }
  105583. else { /* have to pessimistically use 64 bits for accumulator */
  105584. FLAC__uint64 abs_residual_partition_sum;
  105585. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105586. end += default_partition_samples;
  105587. abs_residual_partition_sum = 0;
  105588. for( ; residual_sample < end; residual_sample++)
  105589. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105590. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105591. }
  105592. }
  105593. }
  105594. /* now merge partitions for lower orders */
  105595. {
  105596. unsigned from_partition = 0, to_partition = partitions;
  105597. int partition_order;
  105598. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105599. unsigned i;
  105600. partitions >>= 1;
  105601. for(i = 0; i < partitions; i++) {
  105602. abs_residual_partition_sums[to_partition++] =
  105603. abs_residual_partition_sums[from_partition ] +
  105604. abs_residual_partition_sums[from_partition+1];
  105605. from_partition += 2;
  105606. }
  105607. }
  105608. }
  105609. }
  105610. void precompute_partition_info_escapes_(
  105611. const FLAC__int32 residual[],
  105612. unsigned raw_bits_per_partition[],
  105613. unsigned residual_samples,
  105614. unsigned predictor_order,
  105615. unsigned min_partition_order,
  105616. unsigned max_partition_order
  105617. )
  105618. {
  105619. int partition_order;
  105620. unsigned from_partition, to_partition = 0;
  105621. const unsigned blocksize = residual_samples + predictor_order;
  105622. /* first do max_partition_order */
  105623. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105624. FLAC__int32 r;
  105625. FLAC__uint32 rmax;
  105626. unsigned partition, partition_sample, partition_samples, residual_sample;
  105627. const unsigned partitions = 1u << partition_order;
  105628. const unsigned default_partition_samples = blocksize >> partition_order;
  105629. FLAC__ASSERT(default_partition_samples > predictor_order);
  105630. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105631. partition_samples = default_partition_samples;
  105632. if(partition == 0)
  105633. partition_samples -= predictor_order;
  105634. rmax = 0;
  105635. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105636. r = residual[residual_sample++];
  105637. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105638. if(r < 0)
  105639. rmax |= ~r;
  105640. else
  105641. rmax |= r;
  105642. }
  105643. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105644. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105645. }
  105646. to_partition = partitions;
  105647. break; /*@@@ yuck, should remove the 'for' loop instead */
  105648. }
  105649. /* now merge partitions for lower orders */
  105650. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105651. unsigned m;
  105652. unsigned i;
  105653. const unsigned partitions = 1u << partition_order;
  105654. for(i = 0; i < partitions; i++) {
  105655. m = raw_bits_per_partition[from_partition];
  105656. from_partition++;
  105657. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105658. from_partition++;
  105659. to_partition++;
  105660. }
  105661. }
  105662. }
  105663. #ifdef EXACT_RICE_BITS_CALCULATION
  105664. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105665. const unsigned rice_parameter,
  105666. const unsigned partition_samples,
  105667. const FLAC__int32 *residual
  105668. )
  105669. {
  105670. unsigned i, partition_bits =
  105671. 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 */
  105672. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105673. ;
  105674. for(i = 0; i < partition_samples; i++)
  105675. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105676. return partition_bits;
  105677. }
  105678. #else
  105679. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105680. const unsigned rice_parameter,
  105681. const unsigned partition_samples,
  105682. const FLAC__uint64 abs_residual_partition_sum
  105683. )
  105684. {
  105685. return
  105686. 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 */
  105687. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105688. (
  105689. rice_parameter?
  105690. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105691. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105692. )
  105693. - (partition_samples >> 1)
  105694. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105695. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105696. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105697. * So the subtraction term tries to guess how many extra bits were contributed.
  105698. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105699. */
  105700. ;
  105701. }
  105702. #endif
  105703. FLAC__bool set_partitioned_rice_(
  105704. #ifdef EXACT_RICE_BITS_CALCULATION
  105705. const FLAC__int32 residual[],
  105706. #endif
  105707. const FLAC__uint64 abs_residual_partition_sums[],
  105708. const unsigned raw_bits_per_partition[],
  105709. const unsigned residual_samples,
  105710. const unsigned predictor_order,
  105711. const unsigned suggested_rice_parameter,
  105712. const unsigned rice_parameter_limit,
  105713. const unsigned rice_parameter_search_dist,
  105714. const unsigned partition_order,
  105715. const FLAC__bool search_for_escapes,
  105716. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105717. unsigned *bits
  105718. )
  105719. {
  105720. unsigned rice_parameter, partition_bits;
  105721. unsigned best_partition_bits, best_rice_parameter = 0;
  105722. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105723. unsigned *parameters, *raw_bits;
  105724. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105725. unsigned min_rice_parameter, max_rice_parameter;
  105726. #else
  105727. (void)rice_parameter_search_dist;
  105728. #endif
  105729. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105730. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105731. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105732. parameters = partitioned_rice_contents->parameters;
  105733. raw_bits = partitioned_rice_contents->raw_bits;
  105734. if(partition_order == 0) {
  105735. best_partition_bits = (unsigned)(-1);
  105736. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105737. if(rice_parameter_search_dist) {
  105738. if(suggested_rice_parameter < rice_parameter_search_dist)
  105739. min_rice_parameter = 0;
  105740. else
  105741. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105742. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105743. if(max_rice_parameter >= rice_parameter_limit) {
  105744. #ifdef DEBUG_VERBOSE
  105745. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105746. #endif
  105747. max_rice_parameter = rice_parameter_limit - 1;
  105748. }
  105749. }
  105750. else
  105751. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105752. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105753. #else
  105754. rice_parameter = suggested_rice_parameter;
  105755. #endif
  105756. #ifdef EXACT_RICE_BITS_CALCULATION
  105757. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105758. #else
  105759. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105760. #endif
  105761. if(partition_bits < best_partition_bits) {
  105762. best_rice_parameter = rice_parameter;
  105763. best_partition_bits = partition_bits;
  105764. }
  105765. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105766. }
  105767. #endif
  105768. if(search_for_escapes) {
  105769. 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;
  105770. if(partition_bits <= best_partition_bits) {
  105771. raw_bits[0] = raw_bits_per_partition[0];
  105772. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105773. best_partition_bits = partition_bits;
  105774. }
  105775. else
  105776. raw_bits[0] = 0;
  105777. }
  105778. parameters[0] = best_rice_parameter;
  105779. bits_ += best_partition_bits;
  105780. }
  105781. else {
  105782. unsigned partition, residual_sample;
  105783. unsigned partition_samples;
  105784. FLAC__uint64 mean, k;
  105785. const unsigned partitions = 1u << partition_order;
  105786. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105787. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105788. if(partition == 0) {
  105789. if(partition_samples <= predictor_order)
  105790. return false;
  105791. else
  105792. partition_samples -= predictor_order;
  105793. }
  105794. mean = abs_residual_partition_sums[partition];
  105795. /* we are basically calculating the size in bits of the
  105796. * average residual magnitude in the partition:
  105797. * rice_parameter = floor(log2(mean/partition_samples))
  105798. * 'mean' is not a good name for the variable, it is
  105799. * actually the sum of magnitudes of all residual values
  105800. * in the partition, so the actual mean is
  105801. * mean/partition_samples
  105802. */
  105803. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105804. ;
  105805. if(rice_parameter >= rice_parameter_limit) {
  105806. #ifdef DEBUG_VERBOSE
  105807. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105808. #endif
  105809. rice_parameter = rice_parameter_limit - 1;
  105810. }
  105811. best_partition_bits = (unsigned)(-1);
  105812. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105813. if(rice_parameter_search_dist) {
  105814. if(rice_parameter < rice_parameter_search_dist)
  105815. min_rice_parameter = 0;
  105816. else
  105817. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105818. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105819. if(max_rice_parameter >= rice_parameter_limit) {
  105820. #ifdef DEBUG_VERBOSE
  105821. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105822. #endif
  105823. max_rice_parameter = rice_parameter_limit - 1;
  105824. }
  105825. }
  105826. else
  105827. min_rice_parameter = max_rice_parameter = rice_parameter;
  105828. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105829. #endif
  105830. #ifdef EXACT_RICE_BITS_CALCULATION
  105831. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105832. #else
  105833. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105834. #endif
  105835. if(partition_bits < best_partition_bits) {
  105836. best_rice_parameter = rice_parameter;
  105837. best_partition_bits = partition_bits;
  105838. }
  105839. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105840. }
  105841. #endif
  105842. if(search_for_escapes) {
  105843. 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;
  105844. if(partition_bits <= best_partition_bits) {
  105845. raw_bits[partition] = raw_bits_per_partition[partition];
  105846. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105847. best_partition_bits = partition_bits;
  105848. }
  105849. else
  105850. raw_bits[partition] = 0;
  105851. }
  105852. parameters[partition] = best_rice_parameter;
  105853. bits_ += best_partition_bits;
  105854. residual_sample += partition_samples;
  105855. }
  105856. }
  105857. *bits = bits_;
  105858. return true;
  105859. }
  105860. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105861. {
  105862. unsigned i, shift;
  105863. FLAC__int32 x = 0;
  105864. for(i = 0; i < samples && !(x&1); i++)
  105865. x |= signal[i];
  105866. if(x == 0) {
  105867. shift = 0;
  105868. }
  105869. else {
  105870. for(shift = 0; !(x&1); shift++)
  105871. x >>= 1;
  105872. }
  105873. if(shift > 0) {
  105874. for(i = 0; i < samples; i++)
  105875. signal[i] >>= shift;
  105876. }
  105877. return shift;
  105878. }
  105879. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105880. {
  105881. unsigned channel;
  105882. for(channel = 0; channel < channels; channel++)
  105883. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105884. fifo->tail += wide_samples;
  105885. FLAC__ASSERT(fifo->tail <= fifo->size);
  105886. }
  105887. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105888. {
  105889. unsigned channel;
  105890. unsigned sample, wide_sample;
  105891. unsigned tail = fifo->tail;
  105892. sample = input_offset * channels;
  105893. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105894. for(channel = 0; channel < channels; channel++)
  105895. fifo->data[channel][tail] = input[sample++];
  105896. tail++;
  105897. }
  105898. fifo->tail = tail;
  105899. FLAC__ASSERT(fifo->tail <= fifo->size);
  105900. }
  105901. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105902. {
  105903. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105904. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105905. (void)decoder;
  105906. if(encoder->private_->verify.needs_magic_hack) {
  105907. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105908. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105909. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105910. encoder->private_->verify.needs_magic_hack = false;
  105911. }
  105912. else {
  105913. if(encoded_bytes == 0) {
  105914. /*
  105915. * If we get here, a FIFO underflow has occurred,
  105916. * which means there is a bug somewhere.
  105917. */
  105918. FLAC__ASSERT(0);
  105919. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105920. }
  105921. else if(encoded_bytes < *bytes)
  105922. *bytes = encoded_bytes;
  105923. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105924. encoder->private_->verify.output.data += *bytes;
  105925. encoder->private_->verify.output.bytes -= *bytes;
  105926. }
  105927. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105928. }
  105929. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105930. {
  105931. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105932. unsigned channel;
  105933. const unsigned channels = frame->header.channels;
  105934. const unsigned blocksize = frame->header.blocksize;
  105935. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105936. (void)decoder;
  105937. for(channel = 0; channel < channels; channel++) {
  105938. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105939. unsigned i, sample = 0;
  105940. FLAC__int32 expect = 0, got = 0;
  105941. for(i = 0; i < blocksize; i++) {
  105942. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105943. sample = i;
  105944. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105945. got = (FLAC__int32)buffer[channel][i];
  105946. break;
  105947. }
  105948. }
  105949. FLAC__ASSERT(i < blocksize);
  105950. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105951. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105952. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105953. encoder->private_->verify.error_stats.channel = channel;
  105954. encoder->private_->verify.error_stats.sample = sample;
  105955. encoder->private_->verify.error_stats.expected = expect;
  105956. encoder->private_->verify.error_stats.got = got;
  105957. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105958. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105959. }
  105960. }
  105961. /* dequeue the frame from the fifo */
  105962. encoder->private_->verify.input_fifo.tail -= blocksize;
  105963. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105964. for(channel = 0; channel < channels; channel++)
  105965. 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]));
  105966. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105967. }
  105968. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105969. {
  105970. (void)decoder, (void)metadata, (void)client_data;
  105971. }
  105972. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105973. {
  105974. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105975. (void)decoder, (void)status;
  105976. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105977. }
  105978. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105979. {
  105980. (void)client_data;
  105981. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105982. if (*bytes == 0) {
  105983. if (feof(encoder->private_->file))
  105984. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105985. else if (ferror(encoder->private_->file))
  105986. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105987. }
  105988. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105989. }
  105990. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105991. {
  105992. (void)client_data;
  105993. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105994. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105995. else
  105996. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105997. }
  105998. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105999. {
  106000. off_t offset;
  106001. (void)client_data;
  106002. offset = ftello(encoder->private_->file);
  106003. if(offset < 0) {
  106004. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106005. }
  106006. else {
  106007. *absolute_byte_offset = (FLAC__uint64)offset;
  106008. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106009. }
  106010. }
  106011. #ifdef FLAC__VALGRIND_TESTING
  106012. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106013. {
  106014. size_t ret = fwrite(ptr, size, nmemb, stream);
  106015. if(!ferror(stream))
  106016. fflush(stream);
  106017. return ret;
  106018. }
  106019. #else
  106020. #define local__fwrite fwrite
  106021. #endif
  106022. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106023. {
  106024. (void)client_data, (void)current_frame;
  106025. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106026. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106027. #if FLAC__HAS_OGG
  106028. /* We would like to be able to use 'samples > 0' in the
  106029. * clause here but currently because of the nature of our
  106030. * Ogg writing implementation, 'samples' is always 0 (see
  106031. * ogg_encoder_aspect.c). The downside is extra progress
  106032. * callbacks.
  106033. */
  106034. encoder->private_->is_ogg? true :
  106035. #endif
  106036. samples > 0
  106037. );
  106038. if(call_it) {
  106039. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106040. * because at this point in the callback chain, the stats
  106041. * have not been updated. Only after we return and control
  106042. * gets back to write_frame_() are the stats updated
  106043. */
  106044. 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);
  106045. }
  106046. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106047. }
  106048. else
  106049. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106050. }
  106051. /*
  106052. * This will forcibly set stdout to binary mode (for OSes that require it)
  106053. */
  106054. FILE *get_binary_stdout_(void)
  106055. {
  106056. /* if something breaks here it is probably due to the presence or
  106057. * absence of an underscore before the identifiers 'setmode',
  106058. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106059. */
  106060. #if defined _MSC_VER || defined __MINGW32__
  106061. _setmode(_fileno(stdout), _O_BINARY);
  106062. #elif defined __CYGWIN__
  106063. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106064. setmode(_fileno(stdout), _O_BINARY);
  106065. #elif defined __EMX__
  106066. setmode(fileno(stdout), O_BINARY);
  106067. #endif
  106068. return stdout;
  106069. }
  106070. #endif
  106071. /*** End of inlined file: stream_encoder.c ***/
  106072. /*** Start of inlined file: stream_encoder_framing.c ***/
  106073. /*** Start of inlined file: juce_FlacHeader.h ***/
  106074. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106075. // tasks..
  106076. #define VERSION "1.2.1"
  106077. #define FLAC__NO_DLL 1
  106078. #if JUCE_MSVC
  106079. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106080. #endif
  106081. #if JUCE_MAC
  106082. #define FLAC__SYS_DARWIN 1
  106083. #endif
  106084. /*** End of inlined file: juce_FlacHeader.h ***/
  106085. #if JUCE_USE_FLAC
  106086. #if HAVE_CONFIG_H
  106087. # include <config.h>
  106088. #endif
  106089. #include <stdio.h>
  106090. #include <string.h> /* for strlen() */
  106091. #ifdef max
  106092. #undef max
  106093. #endif
  106094. #define max(x,y) ((x)>(y)?(x):(y))
  106095. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106096. 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);
  106097. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106098. {
  106099. unsigned i, j;
  106100. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106101. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106102. return false;
  106103. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106104. return false;
  106105. /*
  106106. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106107. */
  106108. i = metadata->length;
  106109. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106110. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106111. i -= metadata->data.vorbis_comment.vendor_string.length;
  106112. i += vendor_string_length;
  106113. }
  106114. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106115. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106116. return false;
  106117. switch(metadata->type) {
  106118. case FLAC__METADATA_TYPE_STREAMINFO:
  106119. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106120. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106121. return false;
  106122. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106123. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106124. return false;
  106125. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106126. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106127. return false;
  106128. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106129. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106130. return false;
  106131. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106132. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106133. return false;
  106134. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106135. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106136. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106137. return false;
  106138. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106139. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106140. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106141. return false;
  106142. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106143. return false;
  106144. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106145. return false;
  106146. break;
  106147. case FLAC__METADATA_TYPE_PADDING:
  106148. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106149. return false;
  106150. break;
  106151. case FLAC__METADATA_TYPE_APPLICATION:
  106152. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106153. return false;
  106154. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106155. return false;
  106156. break;
  106157. case FLAC__METADATA_TYPE_SEEKTABLE:
  106158. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106159. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106160. return false;
  106161. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106162. return false;
  106163. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106164. return false;
  106165. }
  106166. break;
  106167. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106168. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106169. return false;
  106170. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106171. return false;
  106172. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106173. return false;
  106174. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106175. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106176. return false;
  106177. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106178. return false;
  106179. }
  106180. break;
  106181. case FLAC__METADATA_TYPE_CUESHEET:
  106182. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106183. 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))
  106184. return false;
  106185. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106186. return false;
  106187. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106188. return false;
  106189. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106190. return false;
  106191. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106192. return false;
  106193. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106194. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106195. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106196. return false;
  106197. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106198. return false;
  106199. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106200. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106201. return false;
  106202. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106203. return false;
  106204. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106205. return false;
  106206. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106207. return false;
  106208. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106209. return false;
  106210. for(j = 0; j < track->num_indices; j++) {
  106211. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106212. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106213. return false;
  106214. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106215. return false;
  106216. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106217. return false;
  106218. }
  106219. }
  106220. break;
  106221. case FLAC__METADATA_TYPE_PICTURE:
  106222. {
  106223. size_t len;
  106224. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106225. return false;
  106226. len = strlen(metadata->data.picture.mime_type);
  106227. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106228. return false;
  106229. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106230. return false;
  106231. len = strlen((const char *)metadata->data.picture.description);
  106232. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106233. return false;
  106234. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106235. return false;
  106236. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106237. return false;
  106238. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106239. return false;
  106240. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106241. return false;
  106242. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106243. return false;
  106244. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106245. return false;
  106246. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106247. return false;
  106248. }
  106249. break;
  106250. default:
  106251. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106252. return false;
  106253. break;
  106254. }
  106255. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106256. return true;
  106257. }
  106258. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106259. {
  106260. unsigned u, blocksize_hint, sample_rate_hint;
  106261. FLAC__byte crc;
  106262. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106263. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106264. return false;
  106265. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106266. return false;
  106267. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106268. return false;
  106269. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106270. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106271. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106272. blocksize_hint = 0;
  106273. switch(header->blocksize) {
  106274. case 192: u = 1; break;
  106275. case 576: u = 2; break;
  106276. case 1152: u = 3; break;
  106277. case 2304: u = 4; break;
  106278. case 4608: u = 5; break;
  106279. case 256: u = 8; break;
  106280. case 512: u = 9; break;
  106281. case 1024: u = 10; break;
  106282. case 2048: u = 11; break;
  106283. case 4096: u = 12; break;
  106284. case 8192: u = 13; break;
  106285. case 16384: u = 14; break;
  106286. case 32768: u = 15; break;
  106287. default:
  106288. if(header->blocksize <= 0x100)
  106289. blocksize_hint = u = 6;
  106290. else
  106291. blocksize_hint = u = 7;
  106292. break;
  106293. }
  106294. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106295. return false;
  106296. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106297. sample_rate_hint = 0;
  106298. switch(header->sample_rate) {
  106299. case 88200: u = 1; break;
  106300. case 176400: u = 2; break;
  106301. case 192000: u = 3; break;
  106302. case 8000: u = 4; break;
  106303. case 16000: u = 5; break;
  106304. case 22050: u = 6; break;
  106305. case 24000: u = 7; break;
  106306. case 32000: u = 8; break;
  106307. case 44100: u = 9; break;
  106308. case 48000: u = 10; break;
  106309. case 96000: u = 11; break;
  106310. default:
  106311. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106312. sample_rate_hint = u = 12;
  106313. else if(header->sample_rate % 10 == 0)
  106314. sample_rate_hint = u = 14;
  106315. else if(header->sample_rate <= 0xffff)
  106316. sample_rate_hint = u = 13;
  106317. else
  106318. u = 0;
  106319. break;
  106320. }
  106321. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106322. return false;
  106323. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106324. switch(header->channel_assignment) {
  106325. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106326. u = header->channels - 1;
  106327. break;
  106328. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106329. FLAC__ASSERT(header->channels == 2);
  106330. u = 8;
  106331. break;
  106332. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106333. FLAC__ASSERT(header->channels == 2);
  106334. u = 9;
  106335. break;
  106336. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106337. FLAC__ASSERT(header->channels == 2);
  106338. u = 10;
  106339. break;
  106340. default:
  106341. FLAC__ASSERT(0);
  106342. }
  106343. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106344. return false;
  106345. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106346. switch(header->bits_per_sample) {
  106347. case 8 : u = 1; break;
  106348. case 12: u = 2; break;
  106349. case 16: u = 4; break;
  106350. case 20: u = 5; break;
  106351. case 24: u = 6; break;
  106352. default: u = 0; break;
  106353. }
  106354. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106355. return false;
  106356. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106357. return false;
  106358. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106359. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106360. return false;
  106361. }
  106362. else {
  106363. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106364. return false;
  106365. }
  106366. if(blocksize_hint)
  106367. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106368. return false;
  106369. switch(sample_rate_hint) {
  106370. case 12:
  106371. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106372. return false;
  106373. break;
  106374. case 13:
  106375. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106376. return false;
  106377. break;
  106378. case 14:
  106379. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106380. return false;
  106381. break;
  106382. }
  106383. /* write the CRC */
  106384. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106385. return false;
  106386. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106387. return false;
  106388. return true;
  106389. }
  106390. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106391. {
  106392. FLAC__bool ok;
  106393. ok =
  106394. 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) &&
  106395. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106396. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106397. ;
  106398. return ok;
  106399. }
  106400. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106401. {
  106402. unsigned i;
  106403. 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))
  106404. return false;
  106405. if(wasted_bits)
  106406. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106407. return false;
  106408. for(i = 0; i < subframe->order; i++)
  106409. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106410. return false;
  106411. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106412. return false;
  106413. switch(subframe->entropy_coding_method.type) {
  106414. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106415. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106416. if(!add_residual_partitioned_rice_(
  106417. bw,
  106418. subframe->residual,
  106419. residual_samples,
  106420. subframe->order,
  106421. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106422. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106423. subframe->entropy_coding_method.data.partitioned_rice.order,
  106424. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106425. ))
  106426. return false;
  106427. break;
  106428. default:
  106429. FLAC__ASSERT(0);
  106430. }
  106431. return true;
  106432. }
  106433. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106434. {
  106435. unsigned i;
  106436. 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))
  106437. return false;
  106438. if(wasted_bits)
  106439. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106440. return false;
  106441. for(i = 0; i < subframe->order; i++)
  106442. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106443. return false;
  106444. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106445. return false;
  106446. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106447. return false;
  106448. for(i = 0; i < subframe->order; i++)
  106449. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106450. return false;
  106451. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106452. return false;
  106453. switch(subframe->entropy_coding_method.type) {
  106454. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106455. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106456. if(!add_residual_partitioned_rice_(
  106457. bw,
  106458. subframe->residual,
  106459. residual_samples,
  106460. subframe->order,
  106461. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106462. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106463. subframe->entropy_coding_method.data.partitioned_rice.order,
  106464. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106465. ))
  106466. return false;
  106467. break;
  106468. default:
  106469. FLAC__ASSERT(0);
  106470. }
  106471. return true;
  106472. }
  106473. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106474. {
  106475. unsigned i;
  106476. const FLAC__int32 *signal = subframe->data;
  106477. 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))
  106478. return false;
  106479. if(wasted_bits)
  106480. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106481. return false;
  106482. for(i = 0; i < samples; i++)
  106483. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106484. return false;
  106485. return true;
  106486. }
  106487. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106488. {
  106489. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106490. return false;
  106491. switch(method->type) {
  106492. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106493. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106494. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106495. return false;
  106496. break;
  106497. default:
  106498. FLAC__ASSERT(0);
  106499. }
  106500. return true;
  106501. }
  106502. 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)
  106503. {
  106504. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106505. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106506. if(partition_order == 0) {
  106507. unsigned i;
  106508. if(raw_bits[0] == 0) {
  106509. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106510. return false;
  106511. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106512. return false;
  106513. }
  106514. else {
  106515. FLAC__ASSERT(rice_parameters[0] == 0);
  106516. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106517. return false;
  106518. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106519. return false;
  106520. for(i = 0; i < residual_samples; i++) {
  106521. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106522. return false;
  106523. }
  106524. }
  106525. return true;
  106526. }
  106527. else {
  106528. unsigned i, j, k = 0, k_last = 0;
  106529. unsigned partition_samples;
  106530. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106531. for(i = 0; i < (1u<<partition_order); i++) {
  106532. partition_samples = default_partition_samples;
  106533. if(i == 0)
  106534. partition_samples -= predictor_order;
  106535. k += partition_samples;
  106536. if(raw_bits[i] == 0) {
  106537. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106538. return false;
  106539. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106540. return false;
  106541. }
  106542. else {
  106543. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106544. return false;
  106545. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106546. return false;
  106547. for(j = k_last; j < k; j++) {
  106548. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106549. return false;
  106550. }
  106551. }
  106552. k_last = k;
  106553. }
  106554. return true;
  106555. }
  106556. }
  106557. #endif
  106558. /*** End of inlined file: stream_encoder_framing.c ***/
  106559. /*** Start of inlined file: window_flac.c ***/
  106560. /*** Start of inlined file: juce_FlacHeader.h ***/
  106561. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106562. // tasks..
  106563. #define VERSION "1.2.1"
  106564. #define FLAC__NO_DLL 1
  106565. #if JUCE_MSVC
  106566. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106567. #endif
  106568. #if JUCE_MAC
  106569. #define FLAC__SYS_DARWIN 1
  106570. #endif
  106571. /*** End of inlined file: juce_FlacHeader.h ***/
  106572. #if JUCE_USE_FLAC
  106573. #if HAVE_CONFIG_H
  106574. # include <config.h>
  106575. #endif
  106576. #include <math.h>
  106577. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106578. #ifndef M_PI
  106579. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106580. #define M_PI 3.14159265358979323846
  106581. #endif
  106582. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106583. {
  106584. const FLAC__int32 N = L - 1;
  106585. FLAC__int32 n;
  106586. if (L & 1) {
  106587. for (n = 0; n <= N/2; n++)
  106588. window[n] = 2.0f * n / (float)N;
  106589. for (; n <= N; n++)
  106590. window[n] = 2.0f - 2.0f * n / (float)N;
  106591. }
  106592. else {
  106593. for (n = 0; n <= L/2-1; n++)
  106594. window[n] = 2.0f * n / (float)N;
  106595. for (; n <= N; n++)
  106596. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106597. }
  106598. }
  106599. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106600. {
  106601. const FLAC__int32 N = L - 1;
  106602. FLAC__int32 n;
  106603. for (n = 0; n < L; n++)
  106604. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  106605. }
  106606. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106607. {
  106608. const FLAC__int32 N = L - 1;
  106609. FLAC__int32 n;
  106610. for (n = 0; n < L; n++)
  106611. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106612. }
  106613. /* 4-term -92dB side-lobe */
  106614. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106615. {
  106616. const FLAC__int32 N = L - 1;
  106617. FLAC__int32 n;
  106618. for (n = 0; n <= N; n++)
  106619. 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));
  106620. }
  106621. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106622. {
  106623. const FLAC__int32 N = L - 1;
  106624. const double N2 = (double)N / 2.;
  106625. FLAC__int32 n;
  106626. for (n = 0; n <= N; n++) {
  106627. double k = ((double)n - N2) / N2;
  106628. k = 1.0f - k * k;
  106629. window[n] = (FLAC__real)(k * k);
  106630. }
  106631. }
  106632. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106633. {
  106634. const FLAC__int32 N = L - 1;
  106635. FLAC__int32 n;
  106636. for (n = 0; n < L; n++)
  106637. 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));
  106638. }
  106639. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106640. {
  106641. const FLAC__int32 N = L - 1;
  106642. const double N2 = (double)N / 2.;
  106643. FLAC__int32 n;
  106644. for (n = 0; n <= N; n++) {
  106645. const double k = ((double)n - N2) / (stddev * N2);
  106646. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106647. }
  106648. }
  106649. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106650. {
  106651. const FLAC__int32 N = L - 1;
  106652. FLAC__int32 n;
  106653. for (n = 0; n < L; n++)
  106654. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106655. }
  106656. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106657. {
  106658. const FLAC__int32 N = L - 1;
  106659. FLAC__int32 n;
  106660. for (n = 0; n < L; n++)
  106661. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106662. }
  106663. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106664. {
  106665. const FLAC__int32 N = L - 1;
  106666. FLAC__int32 n;
  106667. for (n = 0; n < L; n++)
  106668. 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));
  106669. }
  106670. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106671. {
  106672. const FLAC__int32 N = L - 1;
  106673. FLAC__int32 n;
  106674. for (n = 0; n < L; n++)
  106675. 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));
  106676. }
  106677. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106678. {
  106679. FLAC__int32 n;
  106680. for (n = 0; n < L; n++)
  106681. window[n] = 1.0f;
  106682. }
  106683. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106684. {
  106685. FLAC__int32 n;
  106686. if (L & 1) {
  106687. for (n = 1; n <= L+1/2; n++)
  106688. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106689. for (; n <= L; n++)
  106690. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106691. }
  106692. else {
  106693. for (n = 1; n <= L/2; n++)
  106694. window[n-1] = 2.0f * n / (float)L;
  106695. for (; n <= L; n++)
  106696. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106697. }
  106698. }
  106699. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106700. {
  106701. if (p <= 0.0)
  106702. FLAC__window_rectangle(window, L);
  106703. else if (p >= 1.0)
  106704. FLAC__window_hann(window, L);
  106705. else {
  106706. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106707. FLAC__int32 n;
  106708. /* start with rectangle... */
  106709. FLAC__window_rectangle(window, L);
  106710. /* ...replace ends with hann */
  106711. if (Np > 0) {
  106712. for (n = 0; n <= Np; n++) {
  106713. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106714. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106715. }
  106716. }
  106717. }
  106718. }
  106719. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106720. {
  106721. const FLAC__int32 N = L - 1;
  106722. const double N2 = (double)N / 2.;
  106723. FLAC__int32 n;
  106724. for (n = 0; n <= N; n++) {
  106725. const double k = ((double)n - N2) / N2;
  106726. window[n] = (FLAC__real)(1.0f - k * k);
  106727. }
  106728. }
  106729. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106730. #endif
  106731. /*** End of inlined file: window_flac.c ***/
  106732. #else
  106733. #include <FLAC/all.h>
  106734. #endif
  106735. }
  106736. #undef max
  106737. #undef min
  106738. BEGIN_JUCE_NAMESPACE
  106739. static const char* const flacFormatName = "FLAC file";
  106740. static const char* const flacExtensions[] = { ".flac", 0 };
  106741. class FlacReader : public AudioFormatReader
  106742. {
  106743. public:
  106744. FlacReader (InputStream* const in)
  106745. : AudioFormatReader (in, TRANS (flacFormatName)),
  106746. reservoir (2, 0),
  106747. reservoirStart (0),
  106748. samplesInReservoir (0),
  106749. scanningForLength (false)
  106750. {
  106751. using namespace FlacNamespace;
  106752. lengthInSamples = 0;
  106753. decoder = FLAC__stream_decoder_new();
  106754. ok = FLAC__stream_decoder_init_stream (decoder,
  106755. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106756. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106757. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106758. if (ok)
  106759. {
  106760. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106761. if (lengthInSamples == 0 && sampleRate > 0)
  106762. {
  106763. // the length hasn't been stored in the metadata, so we'll need to
  106764. // work it out the length the hard way, by scanning the whole file..
  106765. scanningForLength = true;
  106766. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106767. scanningForLength = false;
  106768. const int64 tempLength = lengthInSamples;
  106769. FLAC__stream_decoder_reset (decoder);
  106770. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106771. lengthInSamples = tempLength;
  106772. }
  106773. }
  106774. }
  106775. ~FlacReader()
  106776. {
  106777. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106778. }
  106779. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106780. {
  106781. sampleRate = info.sample_rate;
  106782. bitsPerSample = info.bits_per_sample;
  106783. lengthInSamples = (unsigned int) info.total_samples;
  106784. numChannels = info.channels;
  106785. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106786. }
  106787. // returns the number of samples read
  106788. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106789. int64 startSampleInFile, int numSamples)
  106790. {
  106791. using namespace FlacNamespace;
  106792. if (! ok)
  106793. return false;
  106794. while (numSamples > 0)
  106795. {
  106796. if (startSampleInFile >= reservoirStart
  106797. && startSampleInFile < reservoirStart + samplesInReservoir)
  106798. {
  106799. const int num = (int) jmin ((int64) numSamples,
  106800. reservoirStart + samplesInReservoir - startSampleInFile);
  106801. jassert (num > 0);
  106802. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106803. if (destSamples[i] != 0)
  106804. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106805. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106806. sizeof (int) * num);
  106807. startOffsetInDestBuffer += num;
  106808. startSampleInFile += num;
  106809. numSamples -= num;
  106810. }
  106811. else
  106812. {
  106813. if (startSampleInFile >= (int) lengthInSamples)
  106814. {
  106815. samplesInReservoir = 0;
  106816. }
  106817. else if (startSampleInFile < reservoirStart
  106818. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106819. {
  106820. // had some problems with flac crashing if the read pos is aligned more
  106821. // accurately than this. Probably fixed in newer versions of the library, though.
  106822. reservoirStart = (int) (startSampleInFile & ~511);
  106823. samplesInReservoir = 0;
  106824. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106825. }
  106826. else
  106827. {
  106828. reservoirStart += samplesInReservoir;
  106829. samplesInReservoir = 0;
  106830. FLAC__stream_decoder_process_single (decoder);
  106831. }
  106832. if (samplesInReservoir == 0)
  106833. break;
  106834. }
  106835. }
  106836. if (numSamples > 0)
  106837. {
  106838. for (int i = numDestChannels; --i >= 0;)
  106839. if (destSamples[i] != 0)
  106840. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106841. sizeof (int) * numSamples);
  106842. }
  106843. return true;
  106844. }
  106845. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106846. {
  106847. if (scanningForLength)
  106848. {
  106849. lengthInSamples += numSamples;
  106850. }
  106851. else
  106852. {
  106853. if (numSamples > reservoir.getNumSamples())
  106854. reservoir.setSize (numChannels, numSamples, false, false, true);
  106855. const int bitsToShift = 32 - bitsPerSample;
  106856. for (int i = 0; i < (int) numChannels; ++i)
  106857. {
  106858. const FlacNamespace::FLAC__int32* src = buffer[i];
  106859. int n = i;
  106860. while (src == 0 && n > 0)
  106861. src = buffer [--n];
  106862. if (src != 0)
  106863. {
  106864. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106865. for (int j = 0; j < numSamples; ++j)
  106866. dest[j] = src[j] << bitsToShift;
  106867. }
  106868. }
  106869. samplesInReservoir = numSamples;
  106870. }
  106871. }
  106872. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106873. {
  106874. using namespace FlacNamespace;
  106875. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106876. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106877. }
  106878. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106879. {
  106880. using namespace FlacNamespace;
  106881. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106882. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106883. }
  106884. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106885. {
  106886. using namespace FlacNamespace;
  106887. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106888. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106889. }
  106890. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106891. {
  106892. using namespace FlacNamespace;
  106893. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106894. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106895. }
  106896. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106897. {
  106898. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106899. }
  106900. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106901. const FlacNamespace::FLAC__Frame* frame,
  106902. const FlacNamespace::FLAC__int32* const buffer[],
  106903. void* client_data)
  106904. {
  106905. using namespace FlacNamespace;
  106906. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106907. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106908. }
  106909. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106910. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106911. void* client_data)
  106912. {
  106913. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106914. }
  106915. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106916. {
  106917. }
  106918. private:
  106919. FlacNamespace::FLAC__StreamDecoder* decoder;
  106920. AudioSampleBuffer reservoir;
  106921. int reservoirStart, samplesInReservoir;
  106922. bool ok, scanningForLength;
  106923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106924. };
  106925. class FlacWriter : public AudioFormatWriter
  106926. {
  106927. public:
  106928. FlacWriter (OutputStream* const out, double sampleRate_,
  106929. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106930. : AudioFormatWriter (out, TRANS (flacFormatName),
  106931. sampleRate_, numChannels_, bitsPerSample_)
  106932. {
  106933. using namespace FlacNamespace;
  106934. encoder = FLAC__stream_encoder_new();
  106935. if (qualityOptionIndex > 0)
  106936. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106937. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106938. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106939. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106940. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106941. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106942. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106943. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106944. ok = FLAC__stream_encoder_init_stream (encoder,
  106945. encodeWriteCallback, encodeSeekCallback,
  106946. encodeTellCallback, encodeMetadataCallback,
  106947. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106948. }
  106949. ~FlacWriter()
  106950. {
  106951. if (ok)
  106952. {
  106953. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106954. output->flush();
  106955. }
  106956. else
  106957. {
  106958. output = 0; // to stop the base class deleting this, as it needs to be returned
  106959. // to the caller of createWriter()
  106960. }
  106961. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106962. }
  106963. bool write (const int** samplesToWrite, int numSamples)
  106964. {
  106965. using namespace FlacNamespace;
  106966. if (! ok)
  106967. return false;
  106968. int* buf[3];
  106969. HeapBlock<int> temp;
  106970. const int bitsToShift = 32 - bitsPerSample;
  106971. if (bitsToShift > 0)
  106972. {
  106973. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106974. temp.malloc (numSamples * numChannelsToWrite);
  106975. buf[0] = temp.getData();
  106976. buf[1] = temp.getData() + numSamples;
  106977. buf[2] = 0;
  106978. for (int i = numChannelsToWrite; --i >= 0;)
  106979. if (samplesToWrite[i] != 0)
  106980. for (int j = 0; j < numSamples; ++j)
  106981. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106982. samplesToWrite = const_cast<const int**> (buf);
  106983. }
  106984. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106985. }
  106986. bool writeData (const void* const data, const int size) const
  106987. {
  106988. return output->write (data, size);
  106989. }
  106990. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106991. {
  106992. using namespace FlacNamespace;
  106993. b += bytes;
  106994. for (int i = 0; i < bytes; ++i)
  106995. {
  106996. *(--b) = (FLAC__byte) (val & 0xff);
  106997. val >>= 8;
  106998. }
  106999. }
  107000. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107001. {
  107002. using namespace FlacNamespace;
  107003. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107004. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107005. const unsigned int channelsMinus1 = info.channels - 1;
  107006. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107007. packUint32 (info.min_blocksize, buffer, 2);
  107008. packUint32 (info.max_blocksize, buffer + 2, 2);
  107009. packUint32 (info.min_framesize, buffer + 4, 3);
  107010. packUint32 (info.max_framesize, buffer + 7, 3);
  107011. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107012. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107013. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107014. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107015. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107016. memcpy (buffer + 18, info.md5sum, 16);
  107017. const bool seekOk = output->setPosition (4);
  107018. (void) seekOk;
  107019. // if this fails, you've given it an output stream that can't seek! It needs
  107020. // to be able to seek back to write the header
  107021. jassert (seekOk);
  107022. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107023. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107024. }
  107025. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107026. const FlacNamespace::FLAC__byte buffer[],
  107027. size_t bytes,
  107028. unsigned int /*samples*/,
  107029. unsigned int /*current_frame*/,
  107030. void* client_data)
  107031. {
  107032. using namespace FlacNamespace;
  107033. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107034. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107035. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107036. }
  107037. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107038. {
  107039. using namespace FlacNamespace;
  107040. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107041. }
  107042. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107043. {
  107044. using namespace FlacNamespace;
  107045. if (client_data == 0)
  107046. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107047. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107048. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107049. }
  107050. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107051. {
  107052. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107053. }
  107054. bool ok;
  107055. private:
  107056. FlacNamespace::FLAC__StreamEncoder* encoder;
  107057. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107058. };
  107059. FlacAudioFormat::FlacAudioFormat()
  107060. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107061. {
  107062. }
  107063. FlacAudioFormat::~FlacAudioFormat()
  107064. {
  107065. }
  107066. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107067. {
  107068. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107069. return Array <int> (rates);
  107070. }
  107071. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107072. {
  107073. const int depths[] = { 16, 24, 0 };
  107074. return Array <int> (depths);
  107075. }
  107076. bool FlacAudioFormat::canDoStereo() { return true; }
  107077. bool FlacAudioFormat::canDoMono() { return true; }
  107078. bool FlacAudioFormat::isCompressed() { return true; }
  107079. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107080. const bool deleteStreamIfOpeningFails)
  107081. {
  107082. ScopedPointer<FlacReader> r (new FlacReader (in));
  107083. if (r->sampleRate != 0)
  107084. return r.release();
  107085. if (! deleteStreamIfOpeningFails)
  107086. r->input = 0;
  107087. return 0;
  107088. }
  107089. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107090. double sampleRate,
  107091. unsigned int numberOfChannels,
  107092. int bitsPerSample,
  107093. const StringPairArray& /*metadataValues*/,
  107094. int qualityOptionIndex)
  107095. {
  107096. if (getPossibleBitDepths().contains (bitsPerSample))
  107097. {
  107098. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107099. if (w->ok)
  107100. return w.release();
  107101. }
  107102. return 0;
  107103. }
  107104. END_JUCE_NAMESPACE
  107105. #endif
  107106. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107107. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107108. #if JUCE_USE_OGGVORBIS
  107109. #if JUCE_MAC
  107110. #define __MACOSX__ 1
  107111. #endif
  107112. namespace OggVorbisNamespace
  107113. {
  107114. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107115. /*** Start of inlined file: vorbisenc.h ***/
  107116. #ifndef _OV_ENC_H_
  107117. #define _OV_ENC_H_
  107118. #ifdef __cplusplus
  107119. extern "C"
  107120. {
  107121. #endif /* __cplusplus */
  107122. /*** Start of inlined file: codec.h ***/
  107123. #ifndef _vorbis_codec_h_
  107124. #define _vorbis_codec_h_
  107125. #ifdef __cplusplus
  107126. extern "C"
  107127. {
  107128. #endif /* __cplusplus */
  107129. /*** Start of inlined file: ogg.h ***/
  107130. #ifndef _OGG_H
  107131. #define _OGG_H
  107132. #ifdef __cplusplus
  107133. extern "C" {
  107134. #endif
  107135. /*** Start of inlined file: os_types.h ***/
  107136. #ifndef _OS_TYPES_H
  107137. #define _OS_TYPES_H
  107138. /* make it easy on the folks that want to compile the libs with a
  107139. different malloc than stdlib */
  107140. #define _ogg_malloc malloc
  107141. #define _ogg_calloc calloc
  107142. #define _ogg_realloc realloc
  107143. #define _ogg_free free
  107144. #if defined(_WIN32)
  107145. # if defined(__CYGWIN__)
  107146. # include <_G_config.h>
  107147. typedef _G_int64_t ogg_int64_t;
  107148. typedef _G_int32_t ogg_int32_t;
  107149. typedef _G_uint32_t ogg_uint32_t;
  107150. typedef _G_int16_t ogg_int16_t;
  107151. typedef _G_uint16_t ogg_uint16_t;
  107152. # elif defined(__MINGW32__)
  107153. typedef short ogg_int16_t;
  107154. typedef unsigned short ogg_uint16_t;
  107155. typedef int ogg_int32_t;
  107156. typedef unsigned int ogg_uint32_t;
  107157. typedef long long ogg_int64_t;
  107158. typedef unsigned long long ogg_uint64_t;
  107159. # elif defined(__MWERKS__)
  107160. typedef long long ogg_int64_t;
  107161. typedef int ogg_int32_t;
  107162. typedef unsigned int ogg_uint32_t;
  107163. typedef short ogg_int16_t;
  107164. typedef unsigned short ogg_uint16_t;
  107165. # else
  107166. /* MSVC/Borland */
  107167. typedef __int64 ogg_int64_t;
  107168. typedef __int32 ogg_int32_t;
  107169. typedef unsigned __int32 ogg_uint32_t;
  107170. typedef __int16 ogg_int16_t;
  107171. typedef unsigned __int16 ogg_uint16_t;
  107172. # endif
  107173. #elif defined(__MACOS__)
  107174. # include <sys/types.h>
  107175. typedef SInt16 ogg_int16_t;
  107176. typedef UInt16 ogg_uint16_t;
  107177. typedef SInt32 ogg_int32_t;
  107178. typedef UInt32 ogg_uint32_t;
  107179. typedef SInt64 ogg_int64_t;
  107180. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107181. # include <sys/types.h>
  107182. typedef int16_t ogg_int16_t;
  107183. typedef u_int16_t ogg_uint16_t;
  107184. typedef int32_t ogg_int32_t;
  107185. typedef u_int32_t ogg_uint32_t;
  107186. typedef int64_t ogg_int64_t;
  107187. #elif defined(__BEOS__)
  107188. /* Be */
  107189. # include <inttypes.h>
  107190. typedef int16_t ogg_int16_t;
  107191. typedef u_int16_t ogg_uint16_t;
  107192. typedef int32_t ogg_int32_t;
  107193. typedef u_int32_t ogg_uint32_t;
  107194. typedef int64_t ogg_int64_t;
  107195. #elif defined (__EMX__)
  107196. /* OS/2 GCC */
  107197. typedef short ogg_int16_t;
  107198. typedef unsigned short ogg_uint16_t;
  107199. typedef int ogg_int32_t;
  107200. typedef unsigned int ogg_uint32_t;
  107201. typedef long long ogg_int64_t;
  107202. #elif defined (DJGPP)
  107203. /* DJGPP */
  107204. typedef short ogg_int16_t;
  107205. typedef int ogg_int32_t;
  107206. typedef unsigned int ogg_uint32_t;
  107207. typedef long long ogg_int64_t;
  107208. #elif defined(R5900)
  107209. /* PS2 EE */
  107210. typedef long ogg_int64_t;
  107211. typedef int ogg_int32_t;
  107212. typedef unsigned ogg_uint32_t;
  107213. typedef short ogg_int16_t;
  107214. #elif defined(__SYMBIAN32__)
  107215. /* Symbian GCC */
  107216. typedef signed short ogg_int16_t;
  107217. typedef unsigned short ogg_uint16_t;
  107218. typedef signed int ogg_int32_t;
  107219. typedef unsigned int ogg_uint32_t;
  107220. typedef long long int ogg_int64_t;
  107221. #else
  107222. # include <sys/types.h>
  107223. /*** Start of inlined file: config_types.h ***/
  107224. #ifndef __CONFIG_TYPES_H__
  107225. #define __CONFIG_TYPES_H__
  107226. typedef int16_t ogg_int16_t;
  107227. typedef unsigned short ogg_uint16_t;
  107228. typedef int32_t ogg_int32_t;
  107229. typedef unsigned int ogg_uint32_t;
  107230. typedef int64_t ogg_int64_t;
  107231. #endif
  107232. /*** End of inlined file: config_types.h ***/
  107233. #endif
  107234. #endif /* _OS_TYPES_H */
  107235. /*** End of inlined file: os_types.h ***/
  107236. typedef struct {
  107237. long endbyte;
  107238. int endbit;
  107239. unsigned char *buffer;
  107240. unsigned char *ptr;
  107241. long storage;
  107242. } oggpack_buffer;
  107243. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107244. typedef struct {
  107245. unsigned char *header;
  107246. long header_len;
  107247. unsigned char *body;
  107248. long body_len;
  107249. } ogg_page;
  107250. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107251. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107252. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107253. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107254. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107255. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107256. }
  107257. /* ogg_stream_state contains the current encode/decode state of a logical
  107258. Ogg bitstream **********************************************************/
  107259. typedef struct {
  107260. unsigned char *body_data; /* bytes from packet bodies */
  107261. long body_storage; /* storage elements allocated */
  107262. long body_fill; /* elements stored; fill mark */
  107263. long body_returned; /* elements of fill returned */
  107264. int *lacing_vals; /* The values that will go to the segment table */
  107265. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107266. this way, but it is simple coupled to the
  107267. lacing fifo */
  107268. long lacing_storage;
  107269. long lacing_fill;
  107270. long lacing_packet;
  107271. long lacing_returned;
  107272. unsigned char header[282]; /* working space for header encode */
  107273. int header_fill;
  107274. int e_o_s; /* set when we have buffered the last packet in the
  107275. logical bitstream */
  107276. int b_o_s; /* set after we've written the initial page
  107277. of a logical bitstream */
  107278. long serialno;
  107279. long pageno;
  107280. ogg_int64_t packetno; /* sequence number for decode; the framing
  107281. knows where there's a hole in the data,
  107282. but we need coupling so that the codec
  107283. (which is in a seperate abstraction
  107284. layer) also knows about the gap */
  107285. ogg_int64_t granulepos;
  107286. } ogg_stream_state;
  107287. /* ogg_packet is used to encapsulate the data and metadata belonging
  107288. to a single raw Ogg/Vorbis packet *************************************/
  107289. typedef struct {
  107290. unsigned char *packet;
  107291. long bytes;
  107292. long b_o_s;
  107293. long e_o_s;
  107294. ogg_int64_t granulepos;
  107295. ogg_int64_t packetno; /* sequence number for decode; the framing
  107296. knows where there's a hole in the data,
  107297. but we need coupling so that the codec
  107298. (which is in a seperate abstraction
  107299. layer) also knows about the gap */
  107300. } ogg_packet;
  107301. typedef struct {
  107302. unsigned char *data;
  107303. int storage;
  107304. int fill;
  107305. int returned;
  107306. int unsynced;
  107307. int headerbytes;
  107308. int bodybytes;
  107309. } ogg_sync_state;
  107310. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107311. extern void oggpack_writeinit(oggpack_buffer *b);
  107312. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107313. extern void oggpack_writealign(oggpack_buffer *b);
  107314. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107315. extern void oggpack_reset(oggpack_buffer *b);
  107316. extern void oggpack_writeclear(oggpack_buffer *b);
  107317. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107318. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107319. extern long oggpack_look(oggpack_buffer *b,int bits);
  107320. extern long oggpack_look1(oggpack_buffer *b);
  107321. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107322. extern void oggpack_adv1(oggpack_buffer *b);
  107323. extern long oggpack_read(oggpack_buffer *b,int bits);
  107324. extern long oggpack_read1(oggpack_buffer *b);
  107325. extern long oggpack_bytes(oggpack_buffer *b);
  107326. extern long oggpack_bits(oggpack_buffer *b);
  107327. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107328. extern void oggpackB_writeinit(oggpack_buffer *b);
  107329. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107330. extern void oggpackB_writealign(oggpack_buffer *b);
  107331. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107332. extern void oggpackB_reset(oggpack_buffer *b);
  107333. extern void oggpackB_writeclear(oggpack_buffer *b);
  107334. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107335. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107336. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107337. extern long oggpackB_look1(oggpack_buffer *b);
  107338. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107339. extern void oggpackB_adv1(oggpack_buffer *b);
  107340. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107341. extern long oggpackB_read1(oggpack_buffer *b);
  107342. extern long oggpackB_bytes(oggpack_buffer *b);
  107343. extern long oggpackB_bits(oggpack_buffer *b);
  107344. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107345. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107346. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107347. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107348. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107349. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107350. extern int ogg_sync_init(ogg_sync_state *oy);
  107351. extern int ogg_sync_clear(ogg_sync_state *oy);
  107352. extern int ogg_sync_reset(ogg_sync_state *oy);
  107353. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107354. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107355. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107356. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107357. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107358. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107359. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107360. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107361. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107362. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107363. extern int ogg_stream_clear(ogg_stream_state *os);
  107364. extern int ogg_stream_reset(ogg_stream_state *os);
  107365. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107366. extern int ogg_stream_destroy(ogg_stream_state *os);
  107367. extern int ogg_stream_eos(ogg_stream_state *os);
  107368. extern void ogg_page_checksum_set(ogg_page *og);
  107369. extern int ogg_page_version(ogg_page *og);
  107370. extern int ogg_page_continued(ogg_page *og);
  107371. extern int ogg_page_bos(ogg_page *og);
  107372. extern int ogg_page_eos(ogg_page *og);
  107373. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107374. extern int ogg_page_serialno(ogg_page *og);
  107375. extern long ogg_page_pageno(ogg_page *og);
  107376. extern int ogg_page_packets(ogg_page *og);
  107377. extern void ogg_packet_clear(ogg_packet *op);
  107378. #ifdef __cplusplus
  107379. }
  107380. #endif
  107381. #endif /* _OGG_H */
  107382. /*** End of inlined file: ogg.h ***/
  107383. typedef struct vorbis_info{
  107384. int version;
  107385. int channels;
  107386. long rate;
  107387. /* The below bitrate declarations are *hints*.
  107388. Combinations of the three values carry the following implications:
  107389. all three set to the same value:
  107390. implies a fixed rate bitstream
  107391. only nominal set:
  107392. implies a VBR stream that averages the nominal bitrate. No hard
  107393. upper/lower limit
  107394. upper and or lower set:
  107395. implies a VBR bitstream that obeys the bitrate limits. nominal
  107396. may also be set to give a nominal rate.
  107397. none set:
  107398. the coder does not care to speculate.
  107399. */
  107400. long bitrate_upper;
  107401. long bitrate_nominal;
  107402. long bitrate_lower;
  107403. long bitrate_window;
  107404. void *codec_setup;
  107405. } vorbis_info;
  107406. /* vorbis_dsp_state buffers the current vorbis audio
  107407. analysis/synthesis state. The DSP state belongs to a specific
  107408. logical bitstream ****************************************************/
  107409. typedef struct vorbis_dsp_state{
  107410. int analysisp;
  107411. vorbis_info *vi;
  107412. float **pcm;
  107413. float **pcmret;
  107414. int pcm_storage;
  107415. int pcm_current;
  107416. int pcm_returned;
  107417. int preextrapolate;
  107418. int eofflag;
  107419. long lW;
  107420. long W;
  107421. long nW;
  107422. long centerW;
  107423. ogg_int64_t granulepos;
  107424. ogg_int64_t sequence;
  107425. ogg_int64_t glue_bits;
  107426. ogg_int64_t time_bits;
  107427. ogg_int64_t floor_bits;
  107428. ogg_int64_t res_bits;
  107429. void *backend_state;
  107430. } vorbis_dsp_state;
  107431. typedef struct vorbis_block{
  107432. /* necessary stream state for linking to the framing abstraction */
  107433. float **pcm; /* this is a pointer into local storage */
  107434. oggpack_buffer opb;
  107435. long lW;
  107436. long W;
  107437. long nW;
  107438. int pcmend;
  107439. int mode;
  107440. int eofflag;
  107441. ogg_int64_t granulepos;
  107442. ogg_int64_t sequence;
  107443. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107444. /* local storage to avoid remallocing; it's up to the mapping to
  107445. structure it */
  107446. void *localstore;
  107447. long localtop;
  107448. long localalloc;
  107449. long totaluse;
  107450. struct alloc_chain *reap;
  107451. /* bitmetrics for the frame */
  107452. long glue_bits;
  107453. long time_bits;
  107454. long floor_bits;
  107455. long res_bits;
  107456. void *internal;
  107457. } vorbis_block;
  107458. /* vorbis_block is a single block of data to be processed as part of
  107459. the analysis/synthesis stream; it belongs to a specific logical
  107460. bitstream, but is independant from other vorbis_blocks belonging to
  107461. that logical bitstream. *************************************************/
  107462. struct alloc_chain{
  107463. void *ptr;
  107464. struct alloc_chain *next;
  107465. };
  107466. /* vorbis_info contains all the setup information specific to the
  107467. specific compression/decompression mode in progress (eg,
  107468. psychoacoustic settings, channel setup, options, codebook
  107469. etc). vorbis_info and substructures are in backends.h.
  107470. *********************************************************************/
  107471. /* the comments are not part of vorbis_info so that vorbis_info can be
  107472. static storage */
  107473. typedef struct vorbis_comment{
  107474. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107475. whatever vendor is set to in encode */
  107476. char **user_comments;
  107477. int *comment_lengths;
  107478. int comments;
  107479. char *vendor;
  107480. } vorbis_comment;
  107481. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107482. and produce a packet (see docs/analysis.txt). The packet is then
  107483. coded into a framed OggSquish bitstream by the second layer (see
  107484. docs/framing.txt). Decode is the reverse process; we sync/frame
  107485. the bitstream and extract individual packets, then decode the
  107486. packet back into PCM audio.
  107487. The extra framing/packetizing is used in streaming formats, such as
  107488. files. Over the net (such as with UDP), the framing and
  107489. packetization aren't necessary as they're provided by the transport
  107490. and the streaming layer is not used */
  107491. /* Vorbis PRIMITIVES: general ***************************************/
  107492. extern void vorbis_info_init(vorbis_info *vi);
  107493. extern void vorbis_info_clear(vorbis_info *vi);
  107494. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107495. extern void vorbis_comment_init(vorbis_comment *vc);
  107496. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107497. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107498. const char *tag, char *contents);
  107499. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107500. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107501. extern void vorbis_comment_clear(vorbis_comment *vc);
  107502. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107503. extern int vorbis_block_clear(vorbis_block *vb);
  107504. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107505. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107506. ogg_int64_t granulepos);
  107507. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107508. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107509. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107510. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107511. vorbis_comment *vc,
  107512. ogg_packet *op,
  107513. ogg_packet *op_comm,
  107514. ogg_packet *op_code);
  107515. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107516. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107517. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107518. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107519. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107520. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107521. ogg_packet *op);
  107522. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107523. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107524. ogg_packet *op);
  107525. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107526. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107527. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107528. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107529. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107530. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107531. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107532. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107533. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107534. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107535. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107536. /* Vorbis ERRORS and return codes ***********************************/
  107537. #define OV_FALSE -1
  107538. #define OV_EOF -2
  107539. #define OV_HOLE -3
  107540. #define OV_EREAD -128
  107541. #define OV_EFAULT -129
  107542. #define OV_EIMPL -130
  107543. #define OV_EINVAL -131
  107544. #define OV_ENOTVORBIS -132
  107545. #define OV_EBADHEADER -133
  107546. #define OV_EVERSION -134
  107547. #define OV_ENOTAUDIO -135
  107548. #define OV_EBADPACKET -136
  107549. #define OV_EBADLINK -137
  107550. #define OV_ENOSEEK -138
  107551. #ifdef __cplusplus
  107552. }
  107553. #endif /* __cplusplus */
  107554. #endif
  107555. /*** End of inlined file: codec.h ***/
  107556. extern int vorbis_encode_init(vorbis_info *vi,
  107557. long channels,
  107558. long rate,
  107559. long max_bitrate,
  107560. long nominal_bitrate,
  107561. long min_bitrate);
  107562. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107563. long channels,
  107564. long rate,
  107565. long max_bitrate,
  107566. long nominal_bitrate,
  107567. long min_bitrate);
  107568. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107569. long channels,
  107570. long rate,
  107571. float quality /* quality level from 0. (lo) to 1. (hi) */
  107572. );
  107573. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107574. long channels,
  107575. long rate,
  107576. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107577. );
  107578. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107579. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107580. /* deprecated rate management supported only for compatability */
  107581. #define OV_ECTL_RATEMANAGE_GET 0x10
  107582. #define OV_ECTL_RATEMANAGE_SET 0x11
  107583. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107584. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107585. struct ovectl_ratemanage_arg {
  107586. int management_active;
  107587. long bitrate_hard_min;
  107588. long bitrate_hard_max;
  107589. double bitrate_hard_window;
  107590. long bitrate_av_lo;
  107591. long bitrate_av_hi;
  107592. double bitrate_av_window;
  107593. double bitrate_av_window_center;
  107594. };
  107595. /* new rate setup */
  107596. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107597. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107598. struct ovectl_ratemanage2_arg {
  107599. int management_active;
  107600. long bitrate_limit_min_kbps;
  107601. long bitrate_limit_max_kbps;
  107602. long bitrate_limit_reservoir_bits;
  107603. double bitrate_limit_reservoir_bias;
  107604. long bitrate_average_kbps;
  107605. double bitrate_average_damping;
  107606. };
  107607. #define OV_ECTL_LOWPASS_GET 0x20
  107608. #define OV_ECTL_LOWPASS_SET 0x21
  107609. #define OV_ECTL_IBLOCK_GET 0x30
  107610. #define OV_ECTL_IBLOCK_SET 0x31
  107611. #ifdef __cplusplus
  107612. }
  107613. #endif /* __cplusplus */
  107614. #endif
  107615. /*** End of inlined file: vorbisenc.h ***/
  107616. /*** Start of inlined file: vorbisfile.h ***/
  107617. #ifndef _OV_FILE_H_
  107618. #define _OV_FILE_H_
  107619. #ifdef __cplusplus
  107620. extern "C"
  107621. {
  107622. #endif /* __cplusplus */
  107623. #include <stdio.h>
  107624. /* The function prototypes for the callbacks are basically the same as for
  107625. * the stdio functions fread, fseek, fclose, ftell.
  107626. * The one difference is that the FILE * arguments have been replaced with
  107627. * a void * - this is to be used as a pointer to whatever internal data these
  107628. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107629. *
  107630. * If you use other functions, check the docs for these functions and return
  107631. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107632. * unseekable
  107633. */
  107634. typedef struct {
  107635. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107636. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107637. int (*close_func) (void *datasource);
  107638. long (*tell_func) (void *datasource);
  107639. } ov_callbacks;
  107640. #define NOTOPEN 0
  107641. #define PARTOPEN 1
  107642. #define OPENED 2
  107643. #define STREAMSET 3
  107644. #define INITSET 4
  107645. typedef struct OggVorbis_File {
  107646. void *datasource; /* Pointer to a FILE *, etc. */
  107647. int seekable;
  107648. ogg_int64_t offset;
  107649. ogg_int64_t end;
  107650. ogg_sync_state oy;
  107651. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107652. stream appears */
  107653. int links;
  107654. ogg_int64_t *offsets;
  107655. ogg_int64_t *dataoffsets;
  107656. long *serialnos;
  107657. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107658. compatability; x2 size, stores both
  107659. beginning and end values */
  107660. vorbis_info *vi;
  107661. vorbis_comment *vc;
  107662. /* Decoding working state local storage */
  107663. ogg_int64_t pcm_offset;
  107664. int ready_state;
  107665. long current_serialno;
  107666. int current_link;
  107667. double bittrack;
  107668. double samptrack;
  107669. ogg_stream_state os; /* take physical pages, weld into a logical
  107670. stream of packets */
  107671. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107672. vorbis_block vb; /* local working space for packet->PCM decode */
  107673. ov_callbacks callbacks;
  107674. } OggVorbis_File;
  107675. extern int ov_clear(OggVorbis_File *vf);
  107676. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107677. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107678. char *initial, long ibytes, ov_callbacks callbacks);
  107679. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107680. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107681. char *initial, long ibytes, ov_callbacks callbacks);
  107682. extern int ov_test_open(OggVorbis_File *vf);
  107683. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107684. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107685. extern long ov_streams(OggVorbis_File *vf);
  107686. extern long ov_seekable(OggVorbis_File *vf);
  107687. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107688. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107689. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107690. extern double ov_time_total(OggVorbis_File *vf,int i);
  107691. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107692. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107693. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107694. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107695. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107696. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107697. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107698. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107699. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107700. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107701. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107702. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107703. extern double ov_time_tell(OggVorbis_File *vf);
  107704. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107705. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107706. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107707. int *bitstream);
  107708. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107709. int bigendianp,int word,int sgned,int *bitstream);
  107710. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107711. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107712. extern int ov_halfrate_p(OggVorbis_File *vf);
  107713. #ifdef __cplusplus
  107714. }
  107715. #endif /* __cplusplus */
  107716. #endif
  107717. /*** End of inlined file: vorbisfile.h ***/
  107718. /*** Start of inlined file: bitwise.c ***/
  107719. /* We're 'LSb' endian; if we write a word but read individual bits,
  107720. then we'll read the lsb first */
  107721. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107722. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107723. // tasks..
  107724. #if JUCE_MSVC
  107725. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107726. #endif
  107727. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107728. #if JUCE_USE_OGGVORBIS
  107729. #include <string.h>
  107730. #include <stdlib.h>
  107731. #define BUFFER_INCREMENT 256
  107732. static const unsigned long mask[]=
  107733. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107734. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107735. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107736. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107737. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107738. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107739. 0x3fffffff,0x7fffffff,0xffffffff };
  107740. static const unsigned int mask8B[]=
  107741. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107742. void oggpack_writeinit(oggpack_buffer *b){
  107743. memset(b,0,sizeof(*b));
  107744. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107745. b->buffer[0]='\0';
  107746. b->storage=BUFFER_INCREMENT;
  107747. }
  107748. void oggpackB_writeinit(oggpack_buffer *b){
  107749. oggpack_writeinit(b);
  107750. }
  107751. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107752. long bytes=bits>>3;
  107753. bits-=bytes*8;
  107754. b->ptr=b->buffer+bytes;
  107755. b->endbit=bits;
  107756. b->endbyte=bytes;
  107757. *b->ptr&=mask[bits];
  107758. }
  107759. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107760. long bytes=bits>>3;
  107761. bits-=bytes*8;
  107762. b->ptr=b->buffer+bytes;
  107763. b->endbit=bits;
  107764. b->endbyte=bytes;
  107765. *b->ptr&=mask8B[bits];
  107766. }
  107767. /* Takes only up to 32 bits. */
  107768. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107769. if(b->endbyte+4>=b->storage){
  107770. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107771. b->storage+=BUFFER_INCREMENT;
  107772. b->ptr=b->buffer+b->endbyte;
  107773. }
  107774. value&=mask[bits];
  107775. bits+=b->endbit;
  107776. b->ptr[0]|=value<<b->endbit;
  107777. if(bits>=8){
  107778. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107779. if(bits>=16){
  107780. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107781. if(bits>=24){
  107782. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107783. if(bits>=32){
  107784. if(b->endbit)
  107785. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107786. else
  107787. b->ptr[4]=0;
  107788. }
  107789. }
  107790. }
  107791. }
  107792. b->endbyte+=bits/8;
  107793. b->ptr+=bits/8;
  107794. b->endbit=bits&7;
  107795. }
  107796. /* Takes only up to 32 bits. */
  107797. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107798. if(b->endbyte+4>=b->storage){
  107799. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107800. b->storage+=BUFFER_INCREMENT;
  107801. b->ptr=b->buffer+b->endbyte;
  107802. }
  107803. value=(value&mask[bits])<<(32-bits);
  107804. bits+=b->endbit;
  107805. b->ptr[0]|=value>>(24+b->endbit);
  107806. if(bits>=8){
  107807. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107808. if(bits>=16){
  107809. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107810. if(bits>=24){
  107811. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107812. if(bits>=32){
  107813. if(b->endbit)
  107814. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107815. else
  107816. b->ptr[4]=0;
  107817. }
  107818. }
  107819. }
  107820. }
  107821. b->endbyte+=bits/8;
  107822. b->ptr+=bits/8;
  107823. b->endbit=bits&7;
  107824. }
  107825. void oggpack_writealign(oggpack_buffer *b){
  107826. int bits=8-b->endbit;
  107827. if(bits<8)
  107828. oggpack_write(b,0,bits);
  107829. }
  107830. void oggpackB_writealign(oggpack_buffer *b){
  107831. int bits=8-b->endbit;
  107832. if(bits<8)
  107833. oggpackB_write(b,0,bits);
  107834. }
  107835. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107836. void *source,
  107837. long bits,
  107838. void (*w)(oggpack_buffer *,
  107839. unsigned long,
  107840. int),
  107841. int msb){
  107842. unsigned char *ptr=(unsigned char *)source;
  107843. long bytes=bits/8;
  107844. bits-=bytes*8;
  107845. if(b->endbit){
  107846. int i;
  107847. /* unaligned copy. Do it the hard way. */
  107848. for(i=0;i<bytes;i++)
  107849. w(b,(unsigned long)(ptr[i]),8);
  107850. }else{
  107851. /* aligned block copy */
  107852. if(b->endbyte+bytes+1>=b->storage){
  107853. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107854. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107855. b->ptr=b->buffer+b->endbyte;
  107856. }
  107857. memmove(b->ptr,source,bytes);
  107858. b->ptr+=bytes;
  107859. b->endbyte+=bytes;
  107860. *b->ptr=0;
  107861. }
  107862. if(bits){
  107863. if(msb)
  107864. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107865. else
  107866. w(b,(unsigned long)(ptr[bytes]),bits);
  107867. }
  107868. }
  107869. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107870. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107871. }
  107872. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107873. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107874. }
  107875. void oggpack_reset(oggpack_buffer *b){
  107876. b->ptr=b->buffer;
  107877. b->buffer[0]=0;
  107878. b->endbit=b->endbyte=0;
  107879. }
  107880. void oggpackB_reset(oggpack_buffer *b){
  107881. oggpack_reset(b);
  107882. }
  107883. void oggpack_writeclear(oggpack_buffer *b){
  107884. _ogg_free(b->buffer);
  107885. memset(b,0,sizeof(*b));
  107886. }
  107887. void oggpackB_writeclear(oggpack_buffer *b){
  107888. oggpack_writeclear(b);
  107889. }
  107890. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107891. memset(b,0,sizeof(*b));
  107892. b->buffer=b->ptr=buf;
  107893. b->storage=bytes;
  107894. }
  107895. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107896. oggpack_readinit(b,buf,bytes);
  107897. }
  107898. /* Read in bits without advancing the bitptr; bits <= 32 */
  107899. long oggpack_look(oggpack_buffer *b,int bits){
  107900. unsigned long ret;
  107901. unsigned long m=mask[bits];
  107902. bits+=b->endbit;
  107903. if(b->endbyte+4>=b->storage){
  107904. /* not the main path */
  107905. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107906. }
  107907. ret=b->ptr[0]>>b->endbit;
  107908. if(bits>8){
  107909. ret|=b->ptr[1]<<(8-b->endbit);
  107910. if(bits>16){
  107911. ret|=b->ptr[2]<<(16-b->endbit);
  107912. if(bits>24){
  107913. ret|=b->ptr[3]<<(24-b->endbit);
  107914. if(bits>32 && b->endbit)
  107915. ret|=b->ptr[4]<<(32-b->endbit);
  107916. }
  107917. }
  107918. }
  107919. return(m&ret);
  107920. }
  107921. /* Read in bits without advancing the bitptr; bits <= 32 */
  107922. long oggpackB_look(oggpack_buffer *b,int bits){
  107923. unsigned long ret;
  107924. int m=32-bits;
  107925. bits+=b->endbit;
  107926. if(b->endbyte+4>=b->storage){
  107927. /* not the main path */
  107928. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107929. }
  107930. ret=b->ptr[0]<<(24+b->endbit);
  107931. if(bits>8){
  107932. ret|=b->ptr[1]<<(16+b->endbit);
  107933. if(bits>16){
  107934. ret|=b->ptr[2]<<(8+b->endbit);
  107935. if(bits>24){
  107936. ret|=b->ptr[3]<<(b->endbit);
  107937. if(bits>32 && b->endbit)
  107938. ret|=b->ptr[4]>>(8-b->endbit);
  107939. }
  107940. }
  107941. }
  107942. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107943. }
  107944. long oggpack_look1(oggpack_buffer *b){
  107945. if(b->endbyte>=b->storage)return(-1);
  107946. return((b->ptr[0]>>b->endbit)&1);
  107947. }
  107948. long oggpackB_look1(oggpack_buffer *b){
  107949. if(b->endbyte>=b->storage)return(-1);
  107950. return((b->ptr[0]>>(7-b->endbit))&1);
  107951. }
  107952. void oggpack_adv(oggpack_buffer *b,int bits){
  107953. bits+=b->endbit;
  107954. b->ptr+=bits/8;
  107955. b->endbyte+=bits/8;
  107956. b->endbit=bits&7;
  107957. }
  107958. void oggpackB_adv(oggpack_buffer *b,int bits){
  107959. oggpack_adv(b,bits);
  107960. }
  107961. void oggpack_adv1(oggpack_buffer *b){
  107962. if(++(b->endbit)>7){
  107963. b->endbit=0;
  107964. b->ptr++;
  107965. b->endbyte++;
  107966. }
  107967. }
  107968. void oggpackB_adv1(oggpack_buffer *b){
  107969. oggpack_adv1(b);
  107970. }
  107971. /* bits <= 32 */
  107972. long oggpack_read(oggpack_buffer *b,int bits){
  107973. long ret;
  107974. unsigned long m=mask[bits];
  107975. bits+=b->endbit;
  107976. if(b->endbyte+4>=b->storage){
  107977. /* not the main path */
  107978. ret=-1L;
  107979. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107980. }
  107981. ret=b->ptr[0]>>b->endbit;
  107982. if(bits>8){
  107983. ret|=b->ptr[1]<<(8-b->endbit);
  107984. if(bits>16){
  107985. ret|=b->ptr[2]<<(16-b->endbit);
  107986. if(bits>24){
  107987. ret|=b->ptr[3]<<(24-b->endbit);
  107988. if(bits>32 && b->endbit){
  107989. ret|=b->ptr[4]<<(32-b->endbit);
  107990. }
  107991. }
  107992. }
  107993. }
  107994. ret&=m;
  107995. overflow:
  107996. b->ptr+=bits/8;
  107997. b->endbyte+=bits/8;
  107998. b->endbit=bits&7;
  107999. return(ret);
  108000. }
  108001. /* bits <= 32 */
  108002. long oggpackB_read(oggpack_buffer *b,int bits){
  108003. long ret;
  108004. long m=32-bits;
  108005. bits+=b->endbit;
  108006. if(b->endbyte+4>=b->storage){
  108007. /* not the main path */
  108008. ret=-1L;
  108009. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108010. }
  108011. ret=b->ptr[0]<<(24+b->endbit);
  108012. if(bits>8){
  108013. ret|=b->ptr[1]<<(16+b->endbit);
  108014. if(bits>16){
  108015. ret|=b->ptr[2]<<(8+b->endbit);
  108016. if(bits>24){
  108017. ret|=b->ptr[3]<<(b->endbit);
  108018. if(bits>32 && b->endbit)
  108019. ret|=b->ptr[4]>>(8-b->endbit);
  108020. }
  108021. }
  108022. }
  108023. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108024. overflow:
  108025. b->ptr+=bits/8;
  108026. b->endbyte+=bits/8;
  108027. b->endbit=bits&7;
  108028. return(ret);
  108029. }
  108030. long oggpack_read1(oggpack_buffer *b){
  108031. long ret;
  108032. if(b->endbyte>=b->storage){
  108033. /* not the main path */
  108034. ret=-1L;
  108035. goto overflow;
  108036. }
  108037. ret=(b->ptr[0]>>b->endbit)&1;
  108038. overflow:
  108039. b->endbit++;
  108040. if(b->endbit>7){
  108041. b->endbit=0;
  108042. b->ptr++;
  108043. b->endbyte++;
  108044. }
  108045. return(ret);
  108046. }
  108047. long oggpackB_read1(oggpack_buffer *b){
  108048. long ret;
  108049. if(b->endbyte>=b->storage){
  108050. /* not the main path */
  108051. ret=-1L;
  108052. goto overflow;
  108053. }
  108054. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108055. overflow:
  108056. b->endbit++;
  108057. if(b->endbit>7){
  108058. b->endbit=0;
  108059. b->ptr++;
  108060. b->endbyte++;
  108061. }
  108062. return(ret);
  108063. }
  108064. long oggpack_bytes(oggpack_buffer *b){
  108065. return(b->endbyte+(b->endbit+7)/8);
  108066. }
  108067. long oggpack_bits(oggpack_buffer *b){
  108068. return(b->endbyte*8+b->endbit);
  108069. }
  108070. long oggpackB_bytes(oggpack_buffer *b){
  108071. return oggpack_bytes(b);
  108072. }
  108073. long oggpackB_bits(oggpack_buffer *b){
  108074. return oggpack_bits(b);
  108075. }
  108076. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108077. return(b->buffer);
  108078. }
  108079. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108080. return oggpack_get_buffer(b);
  108081. }
  108082. /* Self test of the bitwise routines; everything else is based on
  108083. them, so they damned well better be solid. */
  108084. #ifdef _V_SELFTEST
  108085. #include <stdio.h>
  108086. static int ilog(unsigned int v){
  108087. int ret=0;
  108088. while(v){
  108089. ret++;
  108090. v>>=1;
  108091. }
  108092. return(ret);
  108093. }
  108094. oggpack_buffer o;
  108095. oggpack_buffer r;
  108096. void report(char *in){
  108097. fprintf(stderr,"%s",in);
  108098. exit(1);
  108099. }
  108100. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108101. long bytes,i;
  108102. unsigned char *buffer;
  108103. oggpack_reset(&o);
  108104. for(i=0;i<vals;i++)
  108105. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108106. buffer=oggpack_get_buffer(&o);
  108107. bytes=oggpack_bytes(&o);
  108108. if(bytes!=compsize)report("wrong number of bytes!\n");
  108109. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108110. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108111. report("wrote incorrect value!\n");
  108112. }
  108113. oggpack_readinit(&r,buffer,bytes);
  108114. for(i=0;i<vals;i++){
  108115. int tbit=bits?bits:ilog(b[i]);
  108116. if(oggpack_look(&r,tbit)==-1)
  108117. report("out of data!\n");
  108118. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108119. report("looked at incorrect value!\n");
  108120. if(tbit==1)
  108121. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108122. report("looked at single bit incorrect value!\n");
  108123. if(tbit==1){
  108124. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108125. report("read incorrect single bit value!\n");
  108126. }else{
  108127. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108128. report("read incorrect value!\n");
  108129. }
  108130. }
  108131. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108132. }
  108133. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108134. long bytes,i;
  108135. unsigned char *buffer;
  108136. oggpackB_reset(&o);
  108137. for(i=0;i<vals;i++)
  108138. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108139. buffer=oggpackB_get_buffer(&o);
  108140. bytes=oggpackB_bytes(&o);
  108141. if(bytes!=compsize)report("wrong number of bytes!\n");
  108142. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108143. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108144. report("wrote incorrect value!\n");
  108145. }
  108146. oggpackB_readinit(&r,buffer,bytes);
  108147. for(i=0;i<vals;i++){
  108148. int tbit=bits?bits:ilog(b[i]);
  108149. if(oggpackB_look(&r,tbit)==-1)
  108150. report("out of data!\n");
  108151. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108152. report("looked at incorrect value!\n");
  108153. if(tbit==1)
  108154. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108155. report("looked at single bit incorrect value!\n");
  108156. if(tbit==1){
  108157. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108158. report("read incorrect single bit value!\n");
  108159. }else{
  108160. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108161. report("read incorrect value!\n");
  108162. }
  108163. }
  108164. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108165. }
  108166. int main(void){
  108167. unsigned char *buffer;
  108168. long bytes,i;
  108169. static unsigned long testbuffer1[]=
  108170. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108171. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108172. int test1size=43;
  108173. static unsigned long testbuffer2[]=
  108174. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108175. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108176. 85525151,0,12321,1,349528352};
  108177. int test2size=21;
  108178. static unsigned long testbuffer3[]=
  108179. {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,
  108180. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108181. int test3size=56;
  108182. static unsigned long large[]=
  108183. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108184. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108185. 85525151,0,12321,1,2146528352};
  108186. int onesize=33;
  108187. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108188. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108189. 223,4};
  108190. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108191. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108192. 245,251,128};
  108193. int twosize=6;
  108194. static int two[6]={61,255,255,251,231,29};
  108195. static int twoB[6]={247,63,255,253,249,120};
  108196. int threesize=54;
  108197. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108198. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108199. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108200. 100,52,4,14,18,86,77,1};
  108201. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108202. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108203. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108204. 200,20,254,4,58,106,176,144,0};
  108205. int foursize=38;
  108206. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108207. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108208. 28,2,133,0,1};
  108209. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108210. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108211. 129,10,4,32};
  108212. int fivesize=45;
  108213. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108214. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108215. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108216. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108217. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108218. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108219. int sixsize=7;
  108220. static int six[7]={17,177,170,242,169,19,148};
  108221. static int sixB[7]={136,141,85,79,149,200,41};
  108222. /* Test read/write together */
  108223. /* Later we test against pregenerated bitstreams */
  108224. oggpack_writeinit(&o);
  108225. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108226. cliptest(testbuffer1,test1size,0,one,onesize);
  108227. fprintf(stderr,"ok.");
  108228. fprintf(stderr,"\nNull bit call (LSb): ");
  108229. cliptest(testbuffer3,test3size,0,two,twosize);
  108230. fprintf(stderr,"ok.");
  108231. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108232. cliptest(testbuffer2,test2size,0,three,threesize);
  108233. fprintf(stderr,"ok.");
  108234. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108235. oggpack_reset(&o);
  108236. for(i=0;i<test2size;i++)
  108237. oggpack_write(&o,large[i],32);
  108238. buffer=oggpack_get_buffer(&o);
  108239. bytes=oggpack_bytes(&o);
  108240. oggpack_readinit(&r,buffer,bytes);
  108241. for(i=0;i<test2size;i++){
  108242. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108243. if(oggpack_look(&r,32)!=large[i]){
  108244. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108245. oggpack_look(&r,32),large[i]);
  108246. report("read incorrect value!\n");
  108247. }
  108248. oggpack_adv(&r,32);
  108249. }
  108250. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108251. fprintf(stderr,"ok.");
  108252. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108253. cliptest(testbuffer1,test1size,7,four,foursize);
  108254. fprintf(stderr,"ok.");
  108255. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108256. cliptest(testbuffer2,test2size,17,five,fivesize);
  108257. fprintf(stderr,"ok.");
  108258. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108259. cliptest(testbuffer3,test3size,1,six,sixsize);
  108260. fprintf(stderr,"ok.");
  108261. fprintf(stderr,"\nTesting read past end (LSb): ");
  108262. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108263. for(i=0;i<64;i++){
  108264. if(oggpack_read(&r,1)!=0){
  108265. fprintf(stderr,"failed; got -1 prematurely.\n");
  108266. exit(1);
  108267. }
  108268. }
  108269. if(oggpack_look(&r,1)!=-1 ||
  108270. oggpack_read(&r,1)!=-1){
  108271. fprintf(stderr,"failed; read past end without -1.\n");
  108272. exit(1);
  108273. }
  108274. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108275. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108276. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108277. exit(1);
  108278. }
  108279. if(oggpack_look(&r,18)!=0 ||
  108280. oggpack_look(&r,18)!=0){
  108281. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108282. exit(1);
  108283. }
  108284. if(oggpack_look(&r,19)!=-1 ||
  108285. oggpack_look(&r,19)!=-1){
  108286. fprintf(stderr,"failed; read past end without -1.\n");
  108287. exit(1);
  108288. }
  108289. if(oggpack_look(&r,32)!=-1 ||
  108290. oggpack_look(&r,32)!=-1){
  108291. fprintf(stderr,"failed; read past end without -1.\n");
  108292. exit(1);
  108293. }
  108294. oggpack_writeclear(&o);
  108295. fprintf(stderr,"ok.\n");
  108296. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108297. /* Test read/write together */
  108298. /* Later we test against pregenerated bitstreams */
  108299. oggpackB_writeinit(&o);
  108300. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108301. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108302. fprintf(stderr,"ok.");
  108303. fprintf(stderr,"\nNull bit call (MSb): ");
  108304. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108305. fprintf(stderr,"ok.");
  108306. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108307. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108308. fprintf(stderr,"ok.");
  108309. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108310. oggpackB_reset(&o);
  108311. for(i=0;i<test2size;i++)
  108312. oggpackB_write(&o,large[i],32);
  108313. buffer=oggpackB_get_buffer(&o);
  108314. bytes=oggpackB_bytes(&o);
  108315. oggpackB_readinit(&r,buffer,bytes);
  108316. for(i=0;i<test2size;i++){
  108317. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108318. if(oggpackB_look(&r,32)!=large[i]){
  108319. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108320. oggpackB_look(&r,32),large[i]);
  108321. report("read incorrect value!\n");
  108322. }
  108323. oggpackB_adv(&r,32);
  108324. }
  108325. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108326. fprintf(stderr,"ok.");
  108327. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108328. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108329. fprintf(stderr,"ok.");
  108330. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108331. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108332. fprintf(stderr,"ok.");
  108333. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108334. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108335. fprintf(stderr,"ok.");
  108336. fprintf(stderr,"\nTesting read past end (MSb): ");
  108337. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108338. for(i=0;i<64;i++){
  108339. if(oggpackB_read(&r,1)!=0){
  108340. fprintf(stderr,"failed; got -1 prematurely.\n");
  108341. exit(1);
  108342. }
  108343. }
  108344. if(oggpackB_look(&r,1)!=-1 ||
  108345. oggpackB_read(&r,1)!=-1){
  108346. fprintf(stderr,"failed; read past end without -1.\n");
  108347. exit(1);
  108348. }
  108349. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108350. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108351. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108352. exit(1);
  108353. }
  108354. if(oggpackB_look(&r,18)!=0 ||
  108355. oggpackB_look(&r,18)!=0){
  108356. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108357. exit(1);
  108358. }
  108359. if(oggpackB_look(&r,19)!=-1 ||
  108360. oggpackB_look(&r,19)!=-1){
  108361. fprintf(stderr,"failed; read past end without -1.\n");
  108362. exit(1);
  108363. }
  108364. if(oggpackB_look(&r,32)!=-1 ||
  108365. oggpackB_look(&r,32)!=-1){
  108366. fprintf(stderr,"failed; read past end without -1.\n");
  108367. exit(1);
  108368. }
  108369. oggpackB_writeclear(&o);
  108370. fprintf(stderr,"ok.\n\n");
  108371. return(0);
  108372. }
  108373. #endif /* _V_SELFTEST */
  108374. #undef BUFFER_INCREMENT
  108375. #endif
  108376. /*** End of inlined file: bitwise.c ***/
  108377. /*** Start of inlined file: framing.c ***/
  108378. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108379. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108380. // tasks..
  108381. #if JUCE_MSVC
  108382. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108383. #endif
  108384. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108385. #if JUCE_USE_OGGVORBIS
  108386. #include <stdlib.h>
  108387. #include <string.h>
  108388. /* A complete description of Ogg framing exists in docs/framing.html */
  108389. int ogg_page_version(ogg_page *og){
  108390. return((int)(og->header[4]));
  108391. }
  108392. int ogg_page_continued(ogg_page *og){
  108393. return((int)(og->header[5]&0x01));
  108394. }
  108395. int ogg_page_bos(ogg_page *og){
  108396. return((int)(og->header[5]&0x02));
  108397. }
  108398. int ogg_page_eos(ogg_page *og){
  108399. return((int)(og->header[5]&0x04));
  108400. }
  108401. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108402. unsigned char *page=og->header;
  108403. ogg_int64_t granulepos=page[13]&(0xff);
  108404. granulepos= (granulepos<<8)|(page[12]&0xff);
  108405. granulepos= (granulepos<<8)|(page[11]&0xff);
  108406. granulepos= (granulepos<<8)|(page[10]&0xff);
  108407. granulepos= (granulepos<<8)|(page[9]&0xff);
  108408. granulepos= (granulepos<<8)|(page[8]&0xff);
  108409. granulepos= (granulepos<<8)|(page[7]&0xff);
  108410. granulepos= (granulepos<<8)|(page[6]&0xff);
  108411. return(granulepos);
  108412. }
  108413. int ogg_page_serialno(ogg_page *og){
  108414. return(og->header[14] |
  108415. (og->header[15]<<8) |
  108416. (og->header[16]<<16) |
  108417. (og->header[17]<<24));
  108418. }
  108419. long ogg_page_pageno(ogg_page *og){
  108420. return(og->header[18] |
  108421. (og->header[19]<<8) |
  108422. (og->header[20]<<16) |
  108423. (og->header[21]<<24));
  108424. }
  108425. /* returns the number of packets that are completed on this page (if
  108426. the leading packet is begun on a previous page, but ends on this
  108427. page, it's counted */
  108428. /* NOTE:
  108429. If a page consists of a packet begun on a previous page, and a new
  108430. packet begun (but not completed) on this page, the return will be:
  108431. ogg_page_packets(page) ==1,
  108432. ogg_page_continued(page) !=0
  108433. If a page happens to be a single packet that was begun on a
  108434. previous page, and spans to the next page (in the case of a three or
  108435. more page packet), the return will be:
  108436. ogg_page_packets(page) ==0,
  108437. ogg_page_continued(page) !=0
  108438. */
  108439. int ogg_page_packets(ogg_page *og){
  108440. int i,n=og->header[26],count=0;
  108441. for(i=0;i<n;i++)
  108442. if(og->header[27+i]<255)count++;
  108443. return(count);
  108444. }
  108445. #if 0
  108446. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108447. use the static init below) */
  108448. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108449. int i;
  108450. unsigned long r;
  108451. r = index << 24;
  108452. for (i=0; i<8; i++)
  108453. if (r & 0x80000000UL)
  108454. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108455. polynomial, although we use an
  108456. unreflected alg and an init/final
  108457. of 0, not 0xffffffff */
  108458. else
  108459. r<<=1;
  108460. return (r & 0xffffffffUL);
  108461. }
  108462. #endif
  108463. static const ogg_uint32_t crc_lookup[256]={
  108464. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108465. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108466. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108467. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108468. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108469. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108470. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108471. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108472. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108473. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108474. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108475. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108476. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108477. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108478. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108479. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108480. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108481. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108482. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108483. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108484. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108485. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108486. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108487. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108488. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108489. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108490. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108491. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108492. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108493. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108494. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108495. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108496. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108497. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108498. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108499. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108500. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108501. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108502. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108503. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108504. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108505. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108506. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108507. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108508. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108509. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108510. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108511. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108512. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108513. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108514. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108515. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108516. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108517. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108518. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108519. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108520. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108521. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108522. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108523. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108524. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108525. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108526. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108527. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108528. /* init the encode/decode logical stream state */
  108529. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108530. if(os){
  108531. memset(os,0,sizeof(*os));
  108532. os->body_storage=16*1024;
  108533. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108534. os->lacing_storage=1024;
  108535. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108536. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108537. os->serialno=serialno;
  108538. return(0);
  108539. }
  108540. return(-1);
  108541. }
  108542. /* _clear does not free os, only the non-flat storage within */
  108543. int ogg_stream_clear(ogg_stream_state *os){
  108544. if(os){
  108545. if(os->body_data)_ogg_free(os->body_data);
  108546. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108547. if(os->granule_vals)_ogg_free(os->granule_vals);
  108548. memset(os,0,sizeof(*os));
  108549. }
  108550. return(0);
  108551. }
  108552. int ogg_stream_destroy(ogg_stream_state *os){
  108553. if(os){
  108554. ogg_stream_clear(os);
  108555. _ogg_free(os);
  108556. }
  108557. return(0);
  108558. }
  108559. /* Helpers for ogg_stream_encode; this keeps the structure and
  108560. what's happening fairly clear */
  108561. static void _os_body_expand(ogg_stream_state *os,int needed){
  108562. if(os->body_storage<=os->body_fill+needed){
  108563. os->body_storage+=(needed+1024);
  108564. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108565. }
  108566. }
  108567. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108568. if(os->lacing_storage<=os->lacing_fill+needed){
  108569. os->lacing_storage+=(needed+32);
  108570. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108571. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108572. }
  108573. }
  108574. /* checksum the page */
  108575. /* Direct table CRC; note that this will be faster in the future if we
  108576. perform the checksum silmultaneously with other copies */
  108577. void ogg_page_checksum_set(ogg_page *og){
  108578. if(og){
  108579. ogg_uint32_t crc_reg=0;
  108580. int i;
  108581. /* safety; needed for API behavior, but not framing code */
  108582. og->header[22]=0;
  108583. og->header[23]=0;
  108584. og->header[24]=0;
  108585. og->header[25]=0;
  108586. for(i=0;i<og->header_len;i++)
  108587. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108588. for(i=0;i<og->body_len;i++)
  108589. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108590. og->header[22]=(unsigned char)(crc_reg&0xff);
  108591. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108592. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108593. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108594. }
  108595. }
  108596. /* submit data to the internal buffer of the framing engine */
  108597. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108598. int lacing_vals=op->bytes/255+1,i;
  108599. if(os->body_returned){
  108600. /* advance packet data according to the body_returned pointer. We
  108601. had to keep it around to return a pointer into the buffer last
  108602. call */
  108603. os->body_fill-=os->body_returned;
  108604. if(os->body_fill)
  108605. memmove(os->body_data,os->body_data+os->body_returned,
  108606. os->body_fill);
  108607. os->body_returned=0;
  108608. }
  108609. /* make sure we have the buffer storage */
  108610. _os_body_expand(os,op->bytes);
  108611. _os_lacing_expand(os,lacing_vals);
  108612. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108613. the liability of overly clean abstraction for the time being. It
  108614. will actually be fairly easy to eliminate the extra copy in the
  108615. future */
  108616. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108617. os->body_fill+=op->bytes;
  108618. /* Store lacing vals for this packet */
  108619. for(i=0;i<lacing_vals-1;i++){
  108620. os->lacing_vals[os->lacing_fill+i]=255;
  108621. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108622. }
  108623. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108624. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108625. /* flag the first segment as the beginning of the packet */
  108626. os->lacing_vals[os->lacing_fill]|= 0x100;
  108627. os->lacing_fill+=lacing_vals;
  108628. /* for the sake of completeness */
  108629. os->packetno++;
  108630. if(op->e_o_s)os->e_o_s=1;
  108631. return(0);
  108632. }
  108633. /* This will flush remaining packets into a page (returning nonzero),
  108634. even if there is not enough data to trigger a flush normally
  108635. (undersized page). If there are no packets or partial packets to
  108636. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108637. try to flush a normal sized page like ogg_stream_pageout; a call to
  108638. ogg_stream_flush does not guarantee that all packets have flushed.
  108639. Only a return value of 0 from ogg_stream_flush indicates all packet
  108640. data is flushed into pages.
  108641. since ogg_stream_flush will flush the last page in a stream even if
  108642. it's undersized, you almost certainly want to use ogg_stream_pageout
  108643. (and *not* ogg_stream_flush) unless you specifically need to flush
  108644. an page regardless of size in the middle of a stream. */
  108645. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108646. int i;
  108647. int vals=0;
  108648. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108649. int bytes=0;
  108650. long acc=0;
  108651. ogg_int64_t granule_pos=-1;
  108652. if(maxvals==0)return(0);
  108653. /* construct a page */
  108654. /* decide how many segments to include */
  108655. /* If this is the initial header case, the first page must only include
  108656. the initial header packet */
  108657. if(os->b_o_s==0){ /* 'initial header page' case */
  108658. granule_pos=0;
  108659. for(vals=0;vals<maxvals;vals++){
  108660. if((os->lacing_vals[vals]&0x0ff)<255){
  108661. vals++;
  108662. break;
  108663. }
  108664. }
  108665. }else{
  108666. for(vals=0;vals<maxvals;vals++){
  108667. if(acc>4096)break;
  108668. acc+=os->lacing_vals[vals]&0x0ff;
  108669. if((os->lacing_vals[vals]&0xff)<255)
  108670. granule_pos=os->granule_vals[vals];
  108671. }
  108672. }
  108673. /* construct the header in temp storage */
  108674. memcpy(os->header,"OggS",4);
  108675. /* stream structure version */
  108676. os->header[4]=0x00;
  108677. /* continued packet flag? */
  108678. os->header[5]=0x00;
  108679. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108680. /* first page flag? */
  108681. if(os->b_o_s==0)os->header[5]|=0x02;
  108682. /* last page flag? */
  108683. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108684. os->b_o_s=1;
  108685. /* 64 bits of PCM position */
  108686. for(i=6;i<14;i++){
  108687. os->header[i]=(unsigned char)(granule_pos&0xff);
  108688. granule_pos>>=8;
  108689. }
  108690. /* 32 bits of stream serial number */
  108691. {
  108692. long serialno=os->serialno;
  108693. for(i=14;i<18;i++){
  108694. os->header[i]=(unsigned char)(serialno&0xff);
  108695. serialno>>=8;
  108696. }
  108697. }
  108698. /* 32 bits of page counter (we have both counter and page header
  108699. because this val can roll over) */
  108700. if(os->pageno==-1)os->pageno=0; /* because someone called
  108701. stream_reset; this would be a
  108702. strange thing to do in an
  108703. encode stream, but it has
  108704. plausible uses */
  108705. {
  108706. long pageno=os->pageno++;
  108707. for(i=18;i<22;i++){
  108708. os->header[i]=(unsigned char)(pageno&0xff);
  108709. pageno>>=8;
  108710. }
  108711. }
  108712. /* zero for computation; filled in later */
  108713. os->header[22]=0;
  108714. os->header[23]=0;
  108715. os->header[24]=0;
  108716. os->header[25]=0;
  108717. /* segment table */
  108718. os->header[26]=(unsigned char)(vals&0xff);
  108719. for(i=0;i<vals;i++)
  108720. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108721. /* set pointers in the ogg_page struct */
  108722. og->header=os->header;
  108723. og->header_len=os->header_fill=vals+27;
  108724. og->body=os->body_data+os->body_returned;
  108725. og->body_len=bytes;
  108726. /* advance the lacing data and set the body_returned pointer */
  108727. os->lacing_fill-=vals;
  108728. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108729. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108730. os->body_returned+=bytes;
  108731. /* calculate the checksum */
  108732. ogg_page_checksum_set(og);
  108733. /* done */
  108734. return(1);
  108735. }
  108736. /* This constructs pages from buffered packet segments. The pointers
  108737. returned are to static buffers; do not free. The returned buffers are
  108738. good only until the next call (using the same ogg_stream_state) */
  108739. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108740. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108741. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108742. os->lacing_fill>=255 || /* 'segment table full' case */
  108743. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108744. return(ogg_stream_flush(os,og));
  108745. }
  108746. /* not enough data to construct a page and not end of stream */
  108747. return(0);
  108748. }
  108749. int ogg_stream_eos(ogg_stream_state *os){
  108750. return os->e_o_s;
  108751. }
  108752. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108753. /* This has two layers to place more of the multi-serialno and paging
  108754. control in the application's hands. First, we expose a data buffer
  108755. using ogg_sync_buffer(). The app either copies into the
  108756. buffer, or passes it directly to read(), etc. We then call
  108757. ogg_sync_wrote() to tell how many bytes we just added.
  108758. Pages are returned (pointers into the buffer in ogg_sync_state)
  108759. by ogg_sync_pageout(). The page is then submitted to
  108760. ogg_stream_pagein() along with the appropriate
  108761. ogg_stream_state* (ie, matching serialno). We then get raw
  108762. packets out calling ogg_stream_packetout() with a
  108763. ogg_stream_state. */
  108764. /* initialize the struct to a known state */
  108765. int ogg_sync_init(ogg_sync_state *oy){
  108766. if(oy){
  108767. memset(oy,0,sizeof(*oy));
  108768. }
  108769. return(0);
  108770. }
  108771. /* clear non-flat storage within */
  108772. int ogg_sync_clear(ogg_sync_state *oy){
  108773. if(oy){
  108774. if(oy->data)_ogg_free(oy->data);
  108775. ogg_sync_init(oy);
  108776. }
  108777. return(0);
  108778. }
  108779. int ogg_sync_destroy(ogg_sync_state *oy){
  108780. if(oy){
  108781. ogg_sync_clear(oy);
  108782. _ogg_free(oy);
  108783. }
  108784. return(0);
  108785. }
  108786. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108787. /* first, clear out any space that has been previously returned */
  108788. if(oy->returned){
  108789. oy->fill-=oy->returned;
  108790. if(oy->fill>0)
  108791. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108792. oy->returned=0;
  108793. }
  108794. if(size>oy->storage-oy->fill){
  108795. /* We need to extend the internal buffer */
  108796. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108797. if(oy->data)
  108798. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108799. else
  108800. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108801. oy->storage=newsize;
  108802. }
  108803. /* expose a segment at least as large as requested at the fill mark */
  108804. return((char *)oy->data+oy->fill);
  108805. }
  108806. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108807. if(oy->fill+bytes>oy->storage)return(-1);
  108808. oy->fill+=bytes;
  108809. return(0);
  108810. }
  108811. /* sync the stream. This is meant to be useful for finding page
  108812. boundaries.
  108813. return values for this:
  108814. -n) skipped n bytes
  108815. 0) page not ready; more data (no bytes skipped)
  108816. n) page synced at current location; page length n bytes
  108817. */
  108818. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108819. unsigned char *page=oy->data+oy->returned;
  108820. unsigned char *next;
  108821. long bytes=oy->fill-oy->returned;
  108822. if(oy->headerbytes==0){
  108823. int headerbytes,i;
  108824. if(bytes<27)return(0); /* not enough for a header */
  108825. /* verify capture pattern */
  108826. if(memcmp(page,"OggS",4))goto sync_fail;
  108827. headerbytes=page[26]+27;
  108828. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108829. /* count up body length in the segment table */
  108830. for(i=0;i<page[26];i++)
  108831. oy->bodybytes+=page[27+i];
  108832. oy->headerbytes=headerbytes;
  108833. }
  108834. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108835. /* The whole test page is buffered. Verify the checksum */
  108836. {
  108837. /* Grab the checksum bytes, set the header field to zero */
  108838. char chksum[4];
  108839. ogg_page log;
  108840. memcpy(chksum,page+22,4);
  108841. memset(page+22,0,4);
  108842. /* set up a temp page struct and recompute the checksum */
  108843. log.header=page;
  108844. log.header_len=oy->headerbytes;
  108845. log.body=page+oy->headerbytes;
  108846. log.body_len=oy->bodybytes;
  108847. ogg_page_checksum_set(&log);
  108848. /* Compare */
  108849. if(memcmp(chksum,page+22,4)){
  108850. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108851. at all) */
  108852. /* replace the computed checksum with the one actually read in */
  108853. memcpy(page+22,chksum,4);
  108854. /* Bad checksum. Lose sync */
  108855. goto sync_fail;
  108856. }
  108857. }
  108858. /* yes, have a whole page all ready to go */
  108859. {
  108860. unsigned char *page=oy->data+oy->returned;
  108861. long bytes;
  108862. if(og){
  108863. og->header=page;
  108864. og->header_len=oy->headerbytes;
  108865. og->body=page+oy->headerbytes;
  108866. og->body_len=oy->bodybytes;
  108867. }
  108868. oy->unsynced=0;
  108869. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108870. oy->headerbytes=0;
  108871. oy->bodybytes=0;
  108872. return(bytes);
  108873. }
  108874. sync_fail:
  108875. oy->headerbytes=0;
  108876. oy->bodybytes=0;
  108877. /* search for possible capture */
  108878. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108879. if(!next)
  108880. next=oy->data+oy->fill;
  108881. oy->returned=next-oy->data;
  108882. return(-(next-page));
  108883. }
  108884. /* sync the stream and get a page. Keep trying until we find a page.
  108885. Supress 'sync errors' after reporting the first.
  108886. return values:
  108887. -1) recapture (hole in data)
  108888. 0) need more data
  108889. 1) page returned
  108890. Returns pointers into buffered data; invalidated by next call to
  108891. _stream, _clear, _init, or _buffer */
  108892. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108893. /* all we need to do is verify a page at the head of the stream
  108894. buffer. If it doesn't verify, we look for the next potential
  108895. frame */
  108896. for(;;){
  108897. long ret=ogg_sync_pageseek(oy,og);
  108898. if(ret>0){
  108899. /* have a page */
  108900. return(1);
  108901. }
  108902. if(ret==0){
  108903. /* need more data */
  108904. return(0);
  108905. }
  108906. /* head did not start a synced page... skipped some bytes */
  108907. if(!oy->unsynced){
  108908. oy->unsynced=1;
  108909. return(-1);
  108910. }
  108911. /* loop. keep looking */
  108912. }
  108913. }
  108914. /* add the incoming page to the stream state; we decompose the page
  108915. into packet segments here as well. */
  108916. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108917. unsigned char *header=og->header;
  108918. unsigned char *body=og->body;
  108919. long bodysize=og->body_len;
  108920. int segptr=0;
  108921. int version=ogg_page_version(og);
  108922. int continued=ogg_page_continued(og);
  108923. int bos=ogg_page_bos(og);
  108924. int eos=ogg_page_eos(og);
  108925. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108926. int serialno=ogg_page_serialno(og);
  108927. long pageno=ogg_page_pageno(og);
  108928. int segments=header[26];
  108929. /* clean up 'returned data' */
  108930. {
  108931. long lr=os->lacing_returned;
  108932. long br=os->body_returned;
  108933. /* body data */
  108934. if(br){
  108935. os->body_fill-=br;
  108936. if(os->body_fill)
  108937. memmove(os->body_data,os->body_data+br,os->body_fill);
  108938. os->body_returned=0;
  108939. }
  108940. if(lr){
  108941. /* segment table */
  108942. if(os->lacing_fill-lr){
  108943. memmove(os->lacing_vals,os->lacing_vals+lr,
  108944. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108945. memmove(os->granule_vals,os->granule_vals+lr,
  108946. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108947. }
  108948. os->lacing_fill-=lr;
  108949. os->lacing_packet-=lr;
  108950. os->lacing_returned=0;
  108951. }
  108952. }
  108953. /* check the serial number */
  108954. if(serialno!=os->serialno)return(-1);
  108955. if(version>0)return(-1);
  108956. _os_lacing_expand(os,segments+1);
  108957. /* are we in sequence? */
  108958. if(pageno!=os->pageno){
  108959. int i;
  108960. /* unroll previous partial packet (if any) */
  108961. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108962. os->body_fill-=os->lacing_vals[i]&0xff;
  108963. os->lacing_fill=os->lacing_packet;
  108964. /* make a note of dropped data in segment table */
  108965. if(os->pageno!=-1){
  108966. os->lacing_vals[os->lacing_fill++]=0x400;
  108967. os->lacing_packet++;
  108968. }
  108969. }
  108970. /* are we a 'continued packet' page? If so, we may need to skip
  108971. some segments */
  108972. if(continued){
  108973. if(os->lacing_fill<1 ||
  108974. os->lacing_vals[os->lacing_fill-1]==0x400){
  108975. bos=0;
  108976. for(;segptr<segments;segptr++){
  108977. int val=header[27+segptr];
  108978. body+=val;
  108979. bodysize-=val;
  108980. if(val<255){
  108981. segptr++;
  108982. break;
  108983. }
  108984. }
  108985. }
  108986. }
  108987. if(bodysize){
  108988. _os_body_expand(os,bodysize);
  108989. memcpy(os->body_data+os->body_fill,body,bodysize);
  108990. os->body_fill+=bodysize;
  108991. }
  108992. {
  108993. int saved=-1;
  108994. while(segptr<segments){
  108995. int val=header[27+segptr];
  108996. os->lacing_vals[os->lacing_fill]=val;
  108997. os->granule_vals[os->lacing_fill]=-1;
  108998. if(bos){
  108999. os->lacing_vals[os->lacing_fill]|=0x100;
  109000. bos=0;
  109001. }
  109002. if(val<255)saved=os->lacing_fill;
  109003. os->lacing_fill++;
  109004. segptr++;
  109005. if(val<255)os->lacing_packet=os->lacing_fill;
  109006. }
  109007. /* set the granulepos on the last granuleval of the last full packet */
  109008. if(saved!=-1){
  109009. os->granule_vals[saved]=granulepos;
  109010. }
  109011. }
  109012. if(eos){
  109013. os->e_o_s=1;
  109014. if(os->lacing_fill>0)
  109015. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109016. }
  109017. os->pageno=pageno+1;
  109018. return(0);
  109019. }
  109020. /* clear things to an initial state. Good to call, eg, before seeking */
  109021. int ogg_sync_reset(ogg_sync_state *oy){
  109022. oy->fill=0;
  109023. oy->returned=0;
  109024. oy->unsynced=0;
  109025. oy->headerbytes=0;
  109026. oy->bodybytes=0;
  109027. return(0);
  109028. }
  109029. int ogg_stream_reset(ogg_stream_state *os){
  109030. os->body_fill=0;
  109031. os->body_returned=0;
  109032. os->lacing_fill=0;
  109033. os->lacing_packet=0;
  109034. os->lacing_returned=0;
  109035. os->header_fill=0;
  109036. os->e_o_s=0;
  109037. os->b_o_s=0;
  109038. os->pageno=-1;
  109039. os->packetno=0;
  109040. os->granulepos=0;
  109041. return(0);
  109042. }
  109043. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109044. ogg_stream_reset(os);
  109045. os->serialno=serialno;
  109046. return(0);
  109047. }
  109048. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109049. /* The last part of decode. We have the stream broken into packet
  109050. segments. Now we need to group them into packets (or return the
  109051. out of sync markers) */
  109052. int ptr=os->lacing_returned;
  109053. if(os->lacing_packet<=ptr)return(0);
  109054. if(os->lacing_vals[ptr]&0x400){
  109055. /* we need to tell the codec there's a gap; it might need to
  109056. handle previous packet dependencies. */
  109057. os->lacing_returned++;
  109058. os->packetno++;
  109059. return(-1);
  109060. }
  109061. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109062. to ask if there's a whole packet
  109063. waiting */
  109064. /* Gather the whole packet. We'll have no holes or a partial packet */
  109065. {
  109066. int size=os->lacing_vals[ptr]&0xff;
  109067. int bytes=size;
  109068. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109069. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109070. while(size==255){
  109071. int val=os->lacing_vals[++ptr];
  109072. size=val&0xff;
  109073. if(val&0x200)eos=0x200;
  109074. bytes+=size;
  109075. }
  109076. if(op){
  109077. op->e_o_s=eos;
  109078. op->b_o_s=bos;
  109079. op->packet=os->body_data+os->body_returned;
  109080. op->packetno=os->packetno;
  109081. op->granulepos=os->granule_vals[ptr];
  109082. op->bytes=bytes;
  109083. }
  109084. if(adv){
  109085. os->body_returned+=bytes;
  109086. os->lacing_returned=ptr+1;
  109087. os->packetno++;
  109088. }
  109089. }
  109090. return(1);
  109091. }
  109092. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109093. return _packetout(os,op,1);
  109094. }
  109095. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109096. return _packetout(os,op,0);
  109097. }
  109098. void ogg_packet_clear(ogg_packet *op) {
  109099. _ogg_free(op->packet);
  109100. memset(op, 0, sizeof(*op));
  109101. }
  109102. #ifdef _V_SELFTEST
  109103. #include <stdio.h>
  109104. ogg_stream_state os_en, os_de;
  109105. ogg_sync_state oy;
  109106. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109107. long j;
  109108. static int sequence=0;
  109109. static int lastno=0;
  109110. if(op->bytes!=len){
  109111. fprintf(stderr,"incorrect packet length!\n");
  109112. exit(1);
  109113. }
  109114. if(op->granulepos!=pos){
  109115. fprintf(stderr,"incorrect packet position!\n");
  109116. exit(1);
  109117. }
  109118. /* packet number just follows sequence/gap; adjust the input number
  109119. for that */
  109120. if(no==0){
  109121. sequence=0;
  109122. }else{
  109123. sequence++;
  109124. if(no>lastno+1)
  109125. sequence++;
  109126. }
  109127. lastno=no;
  109128. if(op->packetno!=sequence){
  109129. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109130. (long)(op->packetno),sequence);
  109131. exit(1);
  109132. }
  109133. /* Test data */
  109134. for(j=0;j<op->bytes;j++)
  109135. if(op->packet[j]!=((j+no)&0xff)){
  109136. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109137. j,op->packet[j],(j+no)&0xff);
  109138. exit(1);
  109139. }
  109140. }
  109141. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109142. long j;
  109143. /* Test data */
  109144. for(j=0;j<og->body_len;j++)
  109145. if(og->body[j]!=data[j]){
  109146. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109147. j,data[j],og->body[j]);
  109148. exit(1);
  109149. }
  109150. /* Test header */
  109151. for(j=0;j<og->header_len;j++){
  109152. if(og->header[j]!=header[j]){
  109153. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109154. for(j=0;j<header[26]+27;j++)
  109155. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109156. fprintf(stderr,"\n");
  109157. exit(1);
  109158. }
  109159. }
  109160. if(og->header_len!=header[26]+27){
  109161. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109162. og->header_len,header[26]+27);
  109163. exit(1);
  109164. }
  109165. }
  109166. void print_header(ogg_page *og){
  109167. int j;
  109168. fprintf(stderr,"\nHEADER:\n");
  109169. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109170. og->header[0],og->header[1],og->header[2],og->header[3],
  109171. (int)og->header[4],(int)og->header[5]);
  109172. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109173. (og->header[9]<<24)|(og->header[8]<<16)|
  109174. (og->header[7]<<8)|og->header[6],
  109175. (og->header[17]<<24)|(og->header[16]<<16)|
  109176. (og->header[15]<<8)|og->header[14],
  109177. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109178. (og->header[19]<<8)|og->header[18]);
  109179. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109180. (int)og->header[22],(int)og->header[23],
  109181. (int)og->header[24],(int)og->header[25],
  109182. (int)og->header[26]);
  109183. for(j=27;j<og->header_len;j++)
  109184. fprintf(stderr,"%d ",(int)og->header[j]);
  109185. fprintf(stderr,")\n\n");
  109186. }
  109187. void copy_page(ogg_page *og){
  109188. unsigned char *temp=_ogg_malloc(og->header_len);
  109189. memcpy(temp,og->header,og->header_len);
  109190. og->header=temp;
  109191. temp=_ogg_malloc(og->body_len);
  109192. memcpy(temp,og->body,og->body_len);
  109193. og->body=temp;
  109194. }
  109195. void free_page(ogg_page *og){
  109196. _ogg_free (og->header);
  109197. _ogg_free (og->body);
  109198. }
  109199. void error(void){
  109200. fprintf(stderr,"error!\n");
  109201. exit(1);
  109202. }
  109203. /* 17 only */
  109204. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109205. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109206. 0x01,0x02,0x03,0x04,0,0,0,0,
  109207. 0x15,0xed,0xec,0x91,
  109208. 1,
  109209. 17};
  109210. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109211. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109212. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109213. 0x01,0x02,0x03,0x04,0,0,0,0,
  109214. 0x59,0x10,0x6c,0x2c,
  109215. 1,
  109216. 17};
  109217. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109218. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109219. 0x01,0x02,0x03,0x04,1,0,0,0,
  109220. 0x89,0x33,0x85,0xce,
  109221. 13,
  109222. 254,255,0,255,1,255,245,255,255,0,
  109223. 255,255,90};
  109224. /* nil packets; beginning,middle,end */
  109225. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109226. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109227. 0x01,0x02,0x03,0x04,0,0,0,0,
  109228. 0xff,0x7b,0x23,0x17,
  109229. 1,
  109230. 0};
  109231. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109232. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109233. 0x01,0x02,0x03,0x04,1,0,0,0,
  109234. 0x5c,0x3f,0x66,0xcb,
  109235. 17,
  109236. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109237. 255,255,90,0};
  109238. /* large initial packet */
  109239. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109240. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109241. 0x01,0x02,0x03,0x04,0,0,0,0,
  109242. 0x01,0x27,0x31,0xaa,
  109243. 18,
  109244. 255,255,255,255,255,255,255,255,
  109245. 255,255,255,255,255,255,255,255,255,10};
  109246. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109247. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109248. 0x01,0x02,0x03,0x04,1,0,0,0,
  109249. 0x7f,0x4e,0x8a,0xd2,
  109250. 4,
  109251. 255,4,255,0};
  109252. /* continuing packet test */
  109253. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109254. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109255. 0x01,0x02,0x03,0x04,0,0,0,0,
  109256. 0xff,0x7b,0x23,0x17,
  109257. 1,
  109258. 0};
  109259. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109260. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109261. 0x01,0x02,0x03,0x04,1,0,0,0,
  109262. 0x54,0x05,0x51,0xc8,
  109263. 17,
  109264. 255,255,255,255,255,255,255,255,
  109265. 255,255,255,255,255,255,255,255,255};
  109266. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109267. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109268. 0x01,0x02,0x03,0x04,2,0,0,0,
  109269. 0xc8,0xc3,0xcb,0xed,
  109270. 5,
  109271. 10,255,4,255,0};
  109272. /* page with the 255 segment limit */
  109273. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109274. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109275. 0x01,0x02,0x03,0x04,0,0,0,0,
  109276. 0xff,0x7b,0x23,0x17,
  109277. 1,
  109278. 0};
  109279. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109280. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109281. 0x01,0x02,0x03,0x04,1,0,0,0,
  109282. 0xed,0x2a,0x2e,0xa7,
  109283. 255,
  109284. 10,10,10,10,10,10,10,10,
  109285. 10,10,10,10,10,10,10,10,
  109286. 10,10,10,10,10,10,10,10,
  109287. 10,10,10,10,10,10,10,10,
  109288. 10,10,10,10,10,10,10,10,
  109289. 10,10,10,10,10,10,10,10,
  109290. 10,10,10,10,10,10,10,10,
  109291. 10,10,10,10,10,10,10,10,
  109292. 10,10,10,10,10,10,10,10,
  109293. 10,10,10,10,10,10,10,10,
  109294. 10,10,10,10,10,10,10,10,
  109295. 10,10,10,10,10,10,10,10,
  109296. 10,10,10,10,10,10,10,10,
  109297. 10,10,10,10,10,10,10,10,
  109298. 10,10,10,10,10,10,10,10,
  109299. 10,10,10,10,10,10,10,10,
  109300. 10,10,10,10,10,10,10,10,
  109301. 10,10,10,10,10,10,10,10,
  109302. 10,10,10,10,10,10,10,10,
  109303. 10,10,10,10,10,10,10,10,
  109304. 10,10,10,10,10,10,10,10,
  109305. 10,10,10,10,10,10,10,10,
  109306. 10,10,10,10,10,10,10,10,
  109307. 10,10,10,10,10,10,10,10,
  109308. 10,10,10,10,10,10,10,10,
  109309. 10,10,10,10,10,10,10,10,
  109310. 10,10,10,10,10,10,10,10,
  109311. 10,10,10,10,10,10,10,10,
  109312. 10,10,10,10,10,10,10,10,
  109313. 10,10,10,10,10,10,10,10,
  109314. 10,10,10,10,10,10,10,10,
  109315. 10,10,10,10,10,10,10};
  109316. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109317. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109318. 0x01,0x02,0x03,0x04,2,0,0,0,
  109319. 0x6c,0x3b,0x82,0x3d,
  109320. 1,
  109321. 50};
  109322. /* packet that overspans over an entire page */
  109323. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109324. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109325. 0x01,0x02,0x03,0x04,0,0,0,0,
  109326. 0xff,0x7b,0x23,0x17,
  109327. 1,
  109328. 0};
  109329. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109330. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109331. 0x01,0x02,0x03,0x04,1,0,0,0,
  109332. 0x3c,0xd9,0x4d,0x3f,
  109333. 17,
  109334. 100,255,255,255,255,255,255,255,255,
  109335. 255,255,255,255,255,255,255,255};
  109336. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109337. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109338. 0x01,0x02,0x03,0x04,2,0,0,0,
  109339. 0x01,0xd2,0xe5,0xe5,
  109340. 17,
  109341. 255,255,255,255,255,255,255,255,
  109342. 255,255,255,255,255,255,255,255,255};
  109343. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109344. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109345. 0x01,0x02,0x03,0x04,3,0,0,0,
  109346. 0xef,0xdd,0x88,0xde,
  109347. 7,
  109348. 255,255,75,255,4,255,0};
  109349. /* packet that overspans over an entire page */
  109350. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109351. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109352. 0x01,0x02,0x03,0x04,0,0,0,0,
  109353. 0xff,0x7b,0x23,0x17,
  109354. 1,
  109355. 0};
  109356. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109357. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109358. 0x01,0x02,0x03,0x04,1,0,0,0,
  109359. 0x3c,0xd9,0x4d,0x3f,
  109360. 17,
  109361. 100,255,255,255,255,255,255,255,255,
  109362. 255,255,255,255,255,255,255,255};
  109363. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109364. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109365. 0x01,0x02,0x03,0x04,2,0,0,0,
  109366. 0xd4,0xe0,0x60,0xe5,
  109367. 1,0};
  109368. void test_pack(const int *pl, const int **headers, int byteskip,
  109369. int pageskip, int packetskip){
  109370. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109371. long inptr=0;
  109372. long outptr=0;
  109373. long deptr=0;
  109374. long depacket=0;
  109375. long granule_pos=7,pageno=0;
  109376. int i,j,packets,pageout=pageskip;
  109377. int eosflag=0;
  109378. int bosflag=0;
  109379. int byteskipcount=0;
  109380. ogg_stream_reset(&os_en);
  109381. ogg_stream_reset(&os_de);
  109382. ogg_sync_reset(&oy);
  109383. for(packets=0;packets<packetskip;packets++)
  109384. depacket+=pl[packets];
  109385. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109386. for(i=0;i<packets;i++){
  109387. /* construct a test packet */
  109388. ogg_packet op;
  109389. int len=pl[i];
  109390. op.packet=data+inptr;
  109391. op.bytes=len;
  109392. op.e_o_s=(pl[i+1]<0?1:0);
  109393. op.granulepos=granule_pos;
  109394. granule_pos+=1024;
  109395. for(j=0;j<len;j++)data[inptr++]=i+j;
  109396. /* submit the test packet */
  109397. ogg_stream_packetin(&os_en,&op);
  109398. /* retrieve any finished pages */
  109399. {
  109400. ogg_page og;
  109401. while(ogg_stream_pageout(&os_en,&og)){
  109402. /* We have a page. Check it carefully */
  109403. fprintf(stderr,"%ld, ",pageno);
  109404. if(headers[pageno]==NULL){
  109405. fprintf(stderr,"coded too many pages!\n");
  109406. exit(1);
  109407. }
  109408. check_page(data+outptr,headers[pageno],&og);
  109409. outptr+=og.body_len;
  109410. pageno++;
  109411. if(pageskip){
  109412. bosflag=1;
  109413. pageskip--;
  109414. deptr+=og.body_len;
  109415. }
  109416. /* have a complete page; submit it to sync/decode */
  109417. {
  109418. ogg_page og_de;
  109419. ogg_packet op_de,op_de2;
  109420. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109421. char *next=buf;
  109422. byteskipcount+=og.header_len;
  109423. if(byteskipcount>byteskip){
  109424. memcpy(next,og.header,byteskipcount-byteskip);
  109425. next+=byteskipcount-byteskip;
  109426. byteskipcount=byteskip;
  109427. }
  109428. byteskipcount+=og.body_len;
  109429. if(byteskipcount>byteskip){
  109430. memcpy(next,og.body,byteskipcount-byteskip);
  109431. next+=byteskipcount-byteskip;
  109432. byteskipcount=byteskip;
  109433. }
  109434. ogg_sync_wrote(&oy,next-buf);
  109435. while(1){
  109436. int ret=ogg_sync_pageout(&oy,&og_de);
  109437. if(ret==0)break;
  109438. if(ret<0)continue;
  109439. /* got a page. Happy happy. Verify that it's good. */
  109440. fprintf(stderr,"(%ld), ",pageout);
  109441. check_page(data+deptr,headers[pageout],&og_de);
  109442. deptr+=og_de.body_len;
  109443. pageout++;
  109444. /* submit it to deconstitution */
  109445. ogg_stream_pagein(&os_de,&og_de);
  109446. /* packets out? */
  109447. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109448. ogg_stream_packetpeek(&os_de,NULL);
  109449. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109450. /* verify peek and out match */
  109451. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109452. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109453. depacket);
  109454. exit(1);
  109455. }
  109456. /* verify the packet! */
  109457. /* check data */
  109458. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109459. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109460. depacket);
  109461. exit(1);
  109462. }
  109463. /* check bos flag */
  109464. if(bosflag==0 && op_de.b_o_s==0){
  109465. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109466. exit(1);
  109467. }
  109468. if(bosflag && op_de.b_o_s){
  109469. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109470. exit(1);
  109471. }
  109472. bosflag=1;
  109473. depacket+=op_de.bytes;
  109474. /* check eos flag */
  109475. if(eosflag){
  109476. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109477. exit(1);
  109478. }
  109479. if(op_de.e_o_s)eosflag=1;
  109480. /* check granulepos flag */
  109481. if(op_de.granulepos!=-1){
  109482. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109483. }
  109484. }
  109485. }
  109486. }
  109487. }
  109488. }
  109489. }
  109490. _ogg_free(data);
  109491. if(headers[pageno]!=NULL){
  109492. fprintf(stderr,"did not write last page!\n");
  109493. exit(1);
  109494. }
  109495. if(headers[pageout]!=NULL){
  109496. fprintf(stderr,"did not decode last page!\n");
  109497. exit(1);
  109498. }
  109499. if(inptr!=outptr){
  109500. fprintf(stderr,"encoded page data incomplete!\n");
  109501. exit(1);
  109502. }
  109503. if(inptr!=deptr){
  109504. fprintf(stderr,"decoded page data incomplete!\n");
  109505. exit(1);
  109506. }
  109507. if(inptr!=depacket){
  109508. fprintf(stderr,"decoded packet data incomplete!\n");
  109509. exit(1);
  109510. }
  109511. if(!eosflag){
  109512. fprintf(stderr,"Never got a packet with EOS set!\n");
  109513. exit(1);
  109514. }
  109515. fprintf(stderr,"ok.\n");
  109516. }
  109517. int main(void){
  109518. ogg_stream_init(&os_en,0x04030201);
  109519. ogg_stream_init(&os_de,0x04030201);
  109520. ogg_sync_init(&oy);
  109521. /* Exercise each code path in the framing code. Also verify that
  109522. the checksums are working. */
  109523. {
  109524. /* 17 only */
  109525. const int packets[]={17, -1};
  109526. const int *headret[]={head1_0,NULL};
  109527. fprintf(stderr,"testing single page encoding... ");
  109528. test_pack(packets,headret,0,0,0);
  109529. }
  109530. {
  109531. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109532. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109533. const int *headret[]={head1_1,head2_1,NULL};
  109534. fprintf(stderr,"testing basic page encoding... ");
  109535. test_pack(packets,headret,0,0,0);
  109536. }
  109537. {
  109538. /* nil packets; beginning,middle,end */
  109539. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109540. const int *headret[]={head1_2,head2_2,NULL};
  109541. fprintf(stderr,"testing basic nil packets... ");
  109542. test_pack(packets,headret,0,0,0);
  109543. }
  109544. {
  109545. /* large initial packet */
  109546. const int packets[]={4345,259,255,-1};
  109547. const int *headret[]={head1_3,head2_3,NULL};
  109548. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109549. test_pack(packets,headret,0,0,0);
  109550. }
  109551. {
  109552. /* continuing packet test */
  109553. const int packets[]={0,4345,259,255,-1};
  109554. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109555. fprintf(stderr,"testing single packet page span... ");
  109556. test_pack(packets,headret,0,0,0);
  109557. }
  109558. /* page with the 255 segment limit */
  109559. {
  109560. const int packets[]={0,10,10,10,10,10,10,10,10,
  109561. 10,10,10,10,10,10,10,10,
  109562. 10,10,10,10,10,10,10,10,
  109563. 10,10,10,10,10,10,10,10,
  109564. 10,10,10,10,10,10,10,10,
  109565. 10,10,10,10,10,10,10,10,
  109566. 10,10,10,10,10,10,10,10,
  109567. 10,10,10,10,10,10,10,10,
  109568. 10,10,10,10,10,10,10,10,
  109569. 10,10,10,10,10,10,10,10,
  109570. 10,10,10,10,10,10,10,10,
  109571. 10,10,10,10,10,10,10,10,
  109572. 10,10,10,10,10,10,10,10,
  109573. 10,10,10,10,10,10,10,10,
  109574. 10,10,10,10,10,10,10,10,
  109575. 10,10,10,10,10,10,10,10,
  109576. 10,10,10,10,10,10,10,10,
  109577. 10,10,10,10,10,10,10,10,
  109578. 10,10,10,10,10,10,10,10,
  109579. 10,10,10,10,10,10,10,10,
  109580. 10,10,10,10,10,10,10,10,
  109581. 10,10,10,10,10,10,10,10,
  109582. 10,10,10,10,10,10,10,10,
  109583. 10,10,10,10,10,10,10,10,
  109584. 10,10,10,10,10,10,10,10,
  109585. 10,10,10,10,10,10,10,10,
  109586. 10,10,10,10,10,10,10,10,
  109587. 10,10,10,10,10,10,10,10,
  109588. 10,10,10,10,10,10,10,10,
  109589. 10,10,10,10,10,10,10,10,
  109590. 10,10,10,10,10,10,10,10,
  109591. 10,10,10,10,10,10,10,50,-1};
  109592. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109593. fprintf(stderr,"testing max packet segments... ");
  109594. test_pack(packets,headret,0,0,0);
  109595. }
  109596. {
  109597. /* packet that overspans over an entire page */
  109598. const int packets[]={0,100,9000,259,255,-1};
  109599. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109600. fprintf(stderr,"testing very large packets... ");
  109601. test_pack(packets,headret,0,0,0);
  109602. }
  109603. {
  109604. /* test for the libogg 1.1.1 resync in large continuation bug
  109605. found by Josh Coalson) */
  109606. const int packets[]={0,100,9000,259,255,-1};
  109607. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109608. fprintf(stderr,"testing continuation resync in very large packets... ");
  109609. test_pack(packets,headret,100,2,3);
  109610. }
  109611. {
  109612. /* term only page. why not? */
  109613. const int packets[]={0,100,4080,-1};
  109614. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109615. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109616. test_pack(packets,headret,0,0,0);
  109617. }
  109618. {
  109619. /* build a bunch of pages for testing */
  109620. unsigned char *data=_ogg_malloc(1024*1024);
  109621. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109622. int inptr=0,i,j;
  109623. ogg_page og[5];
  109624. ogg_stream_reset(&os_en);
  109625. for(i=0;pl[i]!=-1;i++){
  109626. ogg_packet op;
  109627. int len=pl[i];
  109628. op.packet=data+inptr;
  109629. op.bytes=len;
  109630. op.e_o_s=(pl[i+1]<0?1:0);
  109631. op.granulepos=(i+1)*1000;
  109632. for(j=0;j<len;j++)data[inptr++]=i+j;
  109633. ogg_stream_packetin(&os_en,&op);
  109634. }
  109635. _ogg_free(data);
  109636. /* retrieve finished pages */
  109637. for(i=0;i<5;i++){
  109638. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109639. fprintf(stderr,"Too few pages output building sync tests!\n");
  109640. exit(1);
  109641. }
  109642. copy_page(&og[i]);
  109643. }
  109644. /* Test lost pages on pagein/packetout: no rollback */
  109645. {
  109646. ogg_page temp;
  109647. ogg_packet test;
  109648. fprintf(stderr,"Testing loss of pages... ");
  109649. ogg_sync_reset(&oy);
  109650. ogg_stream_reset(&os_de);
  109651. for(i=0;i<5;i++){
  109652. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109653. og[i].header_len);
  109654. ogg_sync_wrote(&oy,og[i].header_len);
  109655. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109656. ogg_sync_wrote(&oy,og[i].body_len);
  109657. }
  109658. ogg_sync_pageout(&oy,&temp);
  109659. ogg_stream_pagein(&os_de,&temp);
  109660. ogg_sync_pageout(&oy,&temp);
  109661. ogg_stream_pagein(&os_de,&temp);
  109662. ogg_sync_pageout(&oy,&temp);
  109663. /* skip */
  109664. ogg_sync_pageout(&oy,&temp);
  109665. ogg_stream_pagein(&os_de,&temp);
  109666. /* do we get the expected results/packets? */
  109667. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109668. checkpacket(&test,0,0,0);
  109669. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109670. checkpacket(&test,100,1,-1);
  109671. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109672. checkpacket(&test,4079,2,3000);
  109673. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109674. fprintf(stderr,"Error: loss of page did not return error\n");
  109675. exit(1);
  109676. }
  109677. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109678. checkpacket(&test,76,5,-1);
  109679. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109680. checkpacket(&test,34,6,-1);
  109681. fprintf(stderr,"ok.\n");
  109682. }
  109683. /* Test lost pages on pagein/packetout: rollback with continuation */
  109684. {
  109685. ogg_page temp;
  109686. ogg_packet test;
  109687. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109688. ogg_sync_reset(&oy);
  109689. ogg_stream_reset(&os_de);
  109690. for(i=0;i<5;i++){
  109691. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109692. og[i].header_len);
  109693. ogg_sync_wrote(&oy,og[i].header_len);
  109694. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109695. ogg_sync_wrote(&oy,og[i].body_len);
  109696. }
  109697. ogg_sync_pageout(&oy,&temp);
  109698. ogg_stream_pagein(&os_de,&temp);
  109699. ogg_sync_pageout(&oy,&temp);
  109700. ogg_stream_pagein(&os_de,&temp);
  109701. ogg_sync_pageout(&oy,&temp);
  109702. ogg_stream_pagein(&os_de,&temp);
  109703. ogg_sync_pageout(&oy,&temp);
  109704. /* skip */
  109705. ogg_sync_pageout(&oy,&temp);
  109706. ogg_stream_pagein(&os_de,&temp);
  109707. /* do we get the expected results/packets? */
  109708. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109709. checkpacket(&test,0,0,0);
  109710. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109711. checkpacket(&test,100,1,-1);
  109712. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109713. checkpacket(&test,4079,2,3000);
  109714. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109715. checkpacket(&test,2956,3,4000);
  109716. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109717. fprintf(stderr,"Error: loss of page did not return error\n");
  109718. exit(1);
  109719. }
  109720. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109721. checkpacket(&test,300,13,14000);
  109722. fprintf(stderr,"ok.\n");
  109723. }
  109724. /* the rest only test sync */
  109725. {
  109726. ogg_page og_de;
  109727. /* Test fractional page inputs: incomplete capture */
  109728. fprintf(stderr,"Testing sync on partial inputs... ");
  109729. ogg_sync_reset(&oy);
  109730. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109731. 3);
  109732. ogg_sync_wrote(&oy,3);
  109733. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109734. /* Test fractional page inputs: incomplete fixed header */
  109735. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109736. 20);
  109737. ogg_sync_wrote(&oy,20);
  109738. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109739. /* Test fractional page inputs: incomplete header */
  109740. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109741. 5);
  109742. ogg_sync_wrote(&oy,5);
  109743. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109744. /* Test fractional page inputs: incomplete body */
  109745. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109746. og[1].header_len-28);
  109747. ogg_sync_wrote(&oy,og[1].header_len-28);
  109748. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109749. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109750. ogg_sync_wrote(&oy,1000);
  109751. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109752. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109753. og[1].body_len-1000);
  109754. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109755. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109756. fprintf(stderr,"ok.\n");
  109757. }
  109758. /* Test fractional page inputs: page + incomplete capture */
  109759. {
  109760. ogg_page og_de;
  109761. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109762. ogg_sync_reset(&oy);
  109763. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109764. og[1].header_len);
  109765. ogg_sync_wrote(&oy,og[1].header_len);
  109766. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109767. og[1].body_len);
  109768. ogg_sync_wrote(&oy,og[1].body_len);
  109769. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109770. 20);
  109771. ogg_sync_wrote(&oy,20);
  109772. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109773. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109774. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109775. og[1].header_len-20);
  109776. ogg_sync_wrote(&oy,og[1].header_len-20);
  109777. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109778. og[1].body_len);
  109779. ogg_sync_wrote(&oy,og[1].body_len);
  109780. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109781. fprintf(stderr,"ok.\n");
  109782. }
  109783. /* Test recapture: garbage + page */
  109784. {
  109785. ogg_page og_de;
  109786. fprintf(stderr,"Testing search for capture... ");
  109787. ogg_sync_reset(&oy);
  109788. /* 'garbage' */
  109789. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109790. og[1].body_len);
  109791. ogg_sync_wrote(&oy,og[1].body_len);
  109792. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109793. og[1].header_len);
  109794. ogg_sync_wrote(&oy,og[1].header_len);
  109795. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109796. og[1].body_len);
  109797. ogg_sync_wrote(&oy,og[1].body_len);
  109798. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109799. 20);
  109800. ogg_sync_wrote(&oy,20);
  109801. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109802. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109803. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109804. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109805. og[2].header_len-20);
  109806. ogg_sync_wrote(&oy,og[2].header_len-20);
  109807. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109808. og[2].body_len);
  109809. ogg_sync_wrote(&oy,og[2].body_len);
  109810. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109811. fprintf(stderr,"ok.\n");
  109812. }
  109813. /* Test recapture: page + garbage + page */
  109814. {
  109815. ogg_page og_de;
  109816. fprintf(stderr,"Testing recapture... ");
  109817. ogg_sync_reset(&oy);
  109818. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109819. og[1].header_len);
  109820. ogg_sync_wrote(&oy,og[1].header_len);
  109821. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109822. og[1].body_len);
  109823. ogg_sync_wrote(&oy,og[1].body_len);
  109824. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109825. og[2].header_len);
  109826. ogg_sync_wrote(&oy,og[2].header_len);
  109827. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109828. og[2].header_len);
  109829. ogg_sync_wrote(&oy,og[2].header_len);
  109830. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109831. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109832. og[2].body_len-5);
  109833. ogg_sync_wrote(&oy,og[2].body_len-5);
  109834. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109835. og[3].header_len);
  109836. ogg_sync_wrote(&oy,og[3].header_len);
  109837. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109838. og[3].body_len);
  109839. ogg_sync_wrote(&oy,og[3].body_len);
  109840. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109841. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109842. fprintf(stderr,"ok.\n");
  109843. }
  109844. /* Free page data that was previously copied */
  109845. {
  109846. for(i=0;i<5;i++){
  109847. free_page(&og[i]);
  109848. }
  109849. }
  109850. }
  109851. return(0);
  109852. }
  109853. #endif
  109854. #endif
  109855. /*** End of inlined file: framing.c ***/
  109856. /*** Start of inlined file: analysis.c ***/
  109857. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109858. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109859. // tasks..
  109860. #if JUCE_MSVC
  109861. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109862. #endif
  109863. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109864. #if JUCE_USE_OGGVORBIS
  109865. #include <stdio.h>
  109866. #include <string.h>
  109867. #include <math.h>
  109868. /*** Start of inlined file: codec_internal.h ***/
  109869. #ifndef _V_CODECI_H_
  109870. #define _V_CODECI_H_
  109871. /*** Start of inlined file: envelope.h ***/
  109872. #ifndef _V_ENVELOPE_
  109873. #define _V_ENVELOPE_
  109874. /*** Start of inlined file: mdct.h ***/
  109875. #ifndef _OGG_mdct_H_
  109876. #define _OGG_mdct_H_
  109877. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109878. #ifdef MDCT_INTEGERIZED
  109879. #define DATA_TYPE int
  109880. #define REG_TYPE register int
  109881. #define TRIGBITS 14
  109882. #define cPI3_8 6270
  109883. #define cPI2_8 11585
  109884. #define cPI1_8 15137
  109885. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109886. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109887. #define HALVE(x) ((x)>>1)
  109888. #else
  109889. #define DATA_TYPE float
  109890. #define REG_TYPE float
  109891. #define cPI3_8 .38268343236508977175F
  109892. #define cPI2_8 .70710678118654752441F
  109893. #define cPI1_8 .92387953251128675613F
  109894. #define FLOAT_CONV(x) (x)
  109895. #define MULT_NORM(x) (x)
  109896. #define HALVE(x) ((x)*.5f)
  109897. #endif
  109898. typedef struct {
  109899. int n;
  109900. int log2n;
  109901. DATA_TYPE *trig;
  109902. int *bitrev;
  109903. DATA_TYPE scale;
  109904. } mdct_lookup;
  109905. extern void mdct_init(mdct_lookup *lookup,int n);
  109906. extern void mdct_clear(mdct_lookup *l);
  109907. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109908. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109909. #endif
  109910. /*** End of inlined file: mdct.h ***/
  109911. #define VE_PRE 16
  109912. #define VE_WIN 4
  109913. #define VE_POST 2
  109914. #define VE_AMP (VE_PRE+VE_POST-1)
  109915. #define VE_BANDS 7
  109916. #define VE_NEARDC 15
  109917. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109918. #define VE_MAXSTRETCH 12 /* one-third full block */
  109919. typedef struct {
  109920. float ampbuf[VE_AMP];
  109921. int ampptr;
  109922. float nearDC[VE_NEARDC];
  109923. float nearDC_acc;
  109924. float nearDC_partialacc;
  109925. int nearptr;
  109926. } envelope_filter_state;
  109927. typedef struct {
  109928. int begin;
  109929. int end;
  109930. float *window;
  109931. float total;
  109932. } envelope_band;
  109933. typedef struct {
  109934. int ch;
  109935. int winlength;
  109936. int searchstep;
  109937. float minenergy;
  109938. mdct_lookup mdct;
  109939. float *mdct_win;
  109940. envelope_band band[VE_BANDS];
  109941. envelope_filter_state *filter;
  109942. int stretch;
  109943. int *mark;
  109944. long storage;
  109945. long current;
  109946. long curmark;
  109947. long cursor;
  109948. } envelope_lookup;
  109949. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109950. extern void _ve_envelope_clear(envelope_lookup *e);
  109951. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109952. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109953. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109954. #endif
  109955. /*** End of inlined file: envelope.h ***/
  109956. /*** Start of inlined file: codebook.h ***/
  109957. #ifndef _V_CODEBOOK_H_
  109958. #define _V_CODEBOOK_H_
  109959. /* This structure encapsulates huffman and VQ style encoding books; it
  109960. doesn't do anything specific to either.
  109961. valuelist/quantlist are nonNULL (and q_* significant) only if
  109962. there's entry->value mapping to be done.
  109963. If encode-side mapping must be done (and thus the entry needs to be
  109964. hunted), the auxiliary encode pointer will point to a decision
  109965. tree. This is true of both VQ and huffman, but is mostly useful
  109966. with VQ.
  109967. */
  109968. typedef struct static_codebook{
  109969. long dim; /* codebook dimensions (elements per vector) */
  109970. long entries; /* codebook entries */
  109971. long *lengthlist; /* codeword lengths in bits */
  109972. /* mapping ***************************************************************/
  109973. int maptype; /* 0=none
  109974. 1=implicitly populated values from map column
  109975. 2=listed arbitrary values */
  109976. /* The below does a linear, single monotonic sequence mapping. */
  109977. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109978. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109979. int q_quant; /* bits: 0 < quant <= 16 */
  109980. int q_sequencep; /* bitflag */
  109981. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109982. map == 2: list of dim*entries quantized entry vals
  109983. */
  109984. /* encode helpers ********************************************************/
  109985. struct encode_aux_nearestmatch *nearest_tree;
  109986. struct encode_aux_threshmatch *thresh_tree;
  109987. struct encode_aux_pigeonhole *pigeon_tree;
  109988. int allocedp;
  109989. } static_codebook;
  109990. /* this structures an arbitrary trained book to quickly find the
  109991. nearest cell match */
  109992. typedef struct encode_aux_nearestmatch{
  109993. /* pre-calculated partitioning tree */
  109994. long *ptr0;
  109995. long *ptr1;
  109996. long *p; /* decision points (each is an entry) */
  109997. long *q; /* decision points (each is an entry) */
  109998. long aux; /* number of tree entries */
  109999. long alloc;
  110000. } encode_aux_nearestmatch;
  110001. /* assumes a maptype of 1; encode side only, so that's OK */
  110002. typedef struct encode_aux_threshmatch{
  110003. float *quantthresh;
  110004. long *quantmap;
  110005. int quantvals;
  110006. int threshvals;
  110007. } encode_aux_threshmatch;
  110008. typedef struct encode_aux_pigeonhole{
  110009. float min;
  110010. float del;
  110011. int mapentries;
  110012. int quantvals;
  110013. long *pigeonmap;
  110014. long fittotal;
  110015. long *fitlist;
  110016. long *fitmap;
  110017. long *fitlength;
  110018. } encode_aux_pigeonhole;
  110019. typedef struct codebook{
  110020. long dim; /* codebook dimensions (elements per vector) */
  110021. long entries; /* codebook entries */
  110022. long used_entries; /* populated codebook entries */
  110023. const static_codebook *c;
  110024. /* for encode, the below are entry-ordered, fully populated */
  110025. /* for decode, the below are ordered by bitreversed codeword and only
  110026. used entries are populated */
  110027. float *valuelist; /* list of dim*entries actual entry values */
  110028. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110029. int *dec_index; /* only used if sparseness collapsed */
  110030. char *dec_codelengths;
  110031. ogg_uint32_t *dec_firsttable;
  110032. int dec_firsttablen;
  110033. int dec_maxlength;
  110034. } codebook;
  110035. extern void vorbis_staticbook_clear(static_codebook *b);
  110036. extern void vorbis_staticbook_destroy(static_codebook *b);
  110037. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110038. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110039. extern void vorbis_book_clear(codebook *b);
  110040. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110041. extern float *_book_logdist(const static_codebook *b,float *vals);
  110042. extern float _float32_unpack(long val);
  110043. extern long _float32_pack(float val);
  110044. extern int _best(codebook *book, float *a, int step);
  110045. extern int _ilog(unsigned int v);
  110046. extern long _book_maptype1_quantvals(const static_codebook *b);
  110047. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110048. extern long vorbis_book_codeword(codebook *book,int entry);
  110049. extern long vorbis_book_codelen(codebook *book,int entry);
  110050. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110051. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110052. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110053. extern int vorbis_book_errorv(codebook *book, float *a);
  110054. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110055. oggpack_buffer *b);
  110056. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110057. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110058. oggpack_buffer *b,int n);
  110059. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110060. oggpack_buffer *b,int n);
  110061. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110062. oggpack_buffer *b,int n);
  110063. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110064. long off,int ch,
  110065. oggpack_buffer *b,int n);
  110066. #endif
  110067. /*** End of inlined file: codebook.h ***/
  110068. #define BLOCKTYPE_IMPULSE 0
  110069. #define BLOCKTYPE_PADDING 1
  110070. #define BLOCKTYPE_TRANSITION 0
  110071. #define BLOCKTYPE_LONG 1
  110072. #define PACKETBLOBS 15
  110073. typedef struct vorbis_block_internal{
  110074. float **pcmdelay; /* this is a pointer into local storage */
  110075. float ampmax;
  110076. int blocktype;
  110077. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110078. blob [PACKETBLOBS/2] points to
  110079. the oggpack_buffer in the
  110080. main vorbis_block */
  110081. } vorbis_block_internal;
  110082. typedef void vorbis_look_floor;
  110083. typedef void vorbis_look_residue;
  110084. typedef void vorbis_look_transform;
  110085. /* mode ************************************************************/
  110086. typedef struct {
  110087. int blockflag;
  110088. int windowtype;
  110089. int transformtype;
  110090. int mapping;
  110091. } vorbis_info_mode;
  110092. typedef void vorbis_info_floor;
  110093. typedef void vorbis_info_residue;
  110094. typedef void vorbis_info_mapping;
  110095. /*** Start of inlined file: psy.h ***/
  110096. #ifndef _V_PSY_H_
  110097. #define _V_PSY_H_
  110098. /*** Start of inlined file: smallft.h ***/
  110099. #ifndef _V_SMFT_H_
  110100. #define _V_SMFT_H_
  110101. typedef struct {
  110102. int n;
  110103. float *trigcache;
  110104. int *splitcache;
  110105. } drft_lookup;
  110106. extern void drft_forward(drft_lookup *l,float *data);
  110107. extern void drft_backward(drft_lookup *l,float *data);
  110108. extern void drft_init(drft_lookup *l,int n);
  110109. extern void drft_clear(drft_lookup *l);
  110110. #endif
  110111. /*** End of inlined file: smallft.h ***/
  110112. /*** Start of inlined file: backends.h ***/
  110113. /* this is exposed up here because we need it for static modes.
  110114. Lookups for each backend aren't exposed because there's no reason
  110115. to do so */
  110116. #ifndef _vorbis_backend_h_
  110117. #define _vorbis_backend_h_
  110118. /* this would all be simpler/shorter with templates, but.... */
  110119. /* Floor backend generic *****************************************/
  110120. typedef struct{
  110121. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110122. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110123. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110124. void (*free_info) (vorbis_info_floor *);
  110125. void (*free_look) (vorbis_look_floor *);
  110126. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110127. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110128. void *buffer,float *);
  110129. } vorbis_func_floor;
  110130. typedef struct{
  110131. int order;
  110132. long rate;
  110133. long barkmap;
  110134. int ampbits;
  110135. int ampdB;
  110136. int numbooks; /* <= 16 */
  110137. int books[16];
  110138. float lessthan; /* encode-only config setting hacks for libvorbis */
  110139. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110140. } vorbis_info_floor0;
  110141. #define VIF_POSIT 63
  110142. #define VIF_CLASS 16
  110143. #define VIF_PARTS 31
  110144. typedef struct{
  110145. int partitions; /* 0 to 31 */
  110146. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110147. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110148. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110149. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110150. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110151. int mult; /* 1 2 3 or 4 */
  110152. int postlist[VIF_POSIT+2]; /* first two implicit */
  110153. /* encode side analysis parameters */
  110154. float maxover;
  110155. float maxunder;
  110156. float maxerr;
  110157. float twofitweight;
  110158. float twofitatten;
  110159. int n;
  110160. } vorbis_info_floor1;
  110161. /* Residue backend generic *****************************************/
  110162. typedef struct{
  110163. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110164. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110165. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110166. vorbis_info_residue *);
  110167. void (*free_info) (vorbis_info_residue *);
  110168. void (*free_look) (vorbis_look_residue *);
  110169. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110170. float **,int *,int);
  110171. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110172. vorbis_look_residue *,
  110173. float **,float **,int *,int,long **);
  110174. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110175. float **,int *,int);
  110176. } vorbis_func_residue;
  110177. typedef struct vorbis_info_residue0{
  110178. /* block-partitioned VQ coded straight residue */
  110179. long begin;
  110180. long end;
  110181. /* first stage (lossless partitioning) */
  110182. int grouping; /* group n vectors per partition */
  110183. int partitions; /* possible codebooks for a partition */
  110184. int groupbook; /* huffbook for partitioning */
  110185. int secondstages[64]; /* expanded out to pointers in lookup */
  110186. int booklist[256]; /* list of second stage books */
  110187. float classmetric1[64];
  110188. float classmetric2[64];
  110189. } vorbis_info_residue0;
  110190. /* Mapping backend generic *****************************************/
  110191. typedef struct{
  110192. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110193. oggpack_buffer *);
  110194. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110195. void (*free_info) (vorbis_info_mapping *);
  110196. int (*forward) (struct vorbis_block *vb);
  110197. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110198. } vorbis_func_mapping;
  110199. typedef struct vorbis_info_mapping0{
  110200. int submaps; /* <= 16 */
  110201. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110202. int floorsubmap[16]; /* [mux] submap to floors */
  110203. int residuesubmap[16]; /* [mux] submap to residue */
  110204. int coupling_steps;
  110205. int coupling_mag[256];
  110206. int coupling_ang[256];
  110207. } vorbis_info_mapping0;
  110208. #endif
  110209. /*** End of inlined file: backends.h ***/
  110210. #ifndef EHMER_MAX
  110211. #define EHMER_MAX 56
  110212. #endif
  110213. /* psychoacoustic setup ********************************************/
  110214. #define P_BANDS 17 /* 62Hz to 16kHz */
  110215. #define P_LEVELS 8 /* 30dB to 100dB */
  110216. #define P_LEVEL_0 30. /* 30 dB */
  110217. #define P_NOISECURVES 3
  110218. #define NOISE_COMPAND_LEVELS 40
  110219. typedef struct vorbis_info_psy{
  110220. int blockflag;
  110221. float ath_adjatt;
  110222. float ath_maxatt;
  110223. float tone_masteratt[P_NOISECURVES];
  110224. float tone_centerboost;
  110225. float tone_decay;
  110226. float tone_abs_limit;
  110227. float toneatt[P_BANDS];
  110228. int noisemaskp;
  110229. float noisemaxsupp;
  110230. float noisewindowlo;
  110231. float noisewindowhi;
  110232. int noisewindowlomin;
  110233. int noisewindowhimin;
  110234. int noisewindowfixed;
  110235. float noiseoff[P_NOISECURVES][P_BANDS];
  110236. float noisecompand[NOISE_COMPAND_LEVELS];
  110237. float max_curve_dB;
  110238. int normal_channel_p;
  110239. int normal_point_p;
  110240. int normal_start;
  110241. int normal_partition;
  110242. double normal_thresh;
  110243. } vorbis_info_psy;
  110244. typedef struct{
  110245. int eighth_octave_lines;
  110246. /* for block long/short tuning; encode only */
  110247. float preecho_thresh[VE_BANDS];
  110248. float postecho_thresh[VE_BANDS];
  110249. float stretch_penalty;
  110250. float preecho_minenergy;
  110251. float ampmax_att_per_sec;
  110252. /* channel coupling config */
  110253. int coupling_pkHz[PACKETBLOBS];
  110254. int coupling_pointlimit[2][PACKETBLOBS];
  110255. int coupling_prepointamp[PACKETBLOBS];
  110256. int coupling_postpointamp[PACKETBLOBS];
  110257. int sliding_lowpass[2][PACKETBLOBS];
  110258. } vorbis_info_psy_global;
  110259. typedef struct {
  110260. float ampmax;
  110261. int channels;
  110262. vorbis_info_psy_global *gi;
  110263. int coupling_pointlimit[2][P_NOISECURVES];
  110264. } vorbis_look_psy_global;
  110265. typedef struct {
  110266. int n;
  110267. struct vorbis_info_psy *vi;
  110268. float ***tonecurves;
  110269. float **noiseoffset;
  110270. float *ath;
  110271. long *octave; /* in n.ocshift format */
  110272. long *bark;
  110273. long firstoc;
  110274. long shiftoc;
  110275. int eighth_octave_lines; /* power of two, please */
  110276. int total_octave_lines;
  110277. long rate; /* cache it */
  110278. float m_val; /* Masking compensation value */
  110279. } vorbis_look_psy;
  110280. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110281. vorbis_info_psy_global *gi,int n,long rate);
  110282. extern void _vp_psy_clear(vorbis_look_psy *p);
  110283. extern void *_vi_psy_dup(void *source);
  110284. extern void _vi_psy_free(vorbis_info_psy *i);
  110285. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110286. extern void _vp_remove_floor(vorbis_look_psy *p,
  110287. float *mdct,
  110288. int *icodedflr,
  110289. float *residue,
  110290. int sliding_lowpass);
  110291. extern void _vp_noisemask(vorbis_look_psy *p,
  110292. float *logmdct,
  110293. float *logmask);
  110294. extern void _vp_tonemask(vorbis_look_psy *p,
  110295. float *logfft,
  110296. float *logmask,
  110297. float global_specmax,
  110298. float local_specmax);
  110299. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110300. float *noise,
  110301. float *tone,
  110302. int offset_select,
  110303. float *logmask,
  110304. float *mdct,
  110305. float *logmdct);
  110306. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110307. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110308. vorbis_info_psy_global *g,
  110309. vorbis_look_psy *p,
  110310. vorbis_info_mapping0 *vi,
  110311. float **mdct);
  110312. extern void _vp_couple(int blobno,
  110313. vorbis_info_psy_global *g,
  110314. vorbis_look_psy *p,
  110315. vorbis_info_mapping0 *vi,
  110316. float **res,
  110317. float **mag_memo,
  110318. int **mag_sort,
  110319. int **ifloor,
  110320. int *nonzero,
  110321. int sliding_lowpass);
  110322. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110323. float *in,float *out,int *sortedindex);
  110324. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110325. float *magnitudes,int *sortedindex);
  110326. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110327. vorbis_look_psy *p,
  110328. vorbis_info_mapping0 *vi,
  110329. float **mags);
  110330. extern void hf_reduction(vorbis_info_psy_global *g,
  110331. vorbis_look_psy *p,
  110332. vorbis_info_mapping0 *vi,
  110333. float **mdct);
  110334. #endif
  110335. /*** End of inlined file: psy.h ***/
  110336. /*** Start of inlined file: bitrate.h ***/
  110337. #ifndef _V_BITRATE_H_
  110338. #define _V_BITRATE_H_
  110339. /*** Start of inlined file: os.h ***/
  110340. #ifndef _OS_H
  110341. #define _OS_H
  110342. /********************************************************************
  110343. * *
  110344. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110345. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110346. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110347. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110348. * *
  110349. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110350. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110351. * *
  110352. ********************************************************************
  110353. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110354. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110355. ********************************************************************/
  110356. #ifdef HAVE_CONFIG_H
  110357. #include "config.h"
  110358. #endif
  110359. #include <math.h>
  110360. /*** Start of inlined file: misc.h ***/
  110361. #ifndef _V_RANDOM_H_
  110362. #define _V_RANDOM_H_
  110363. extern int analysis_noisy;
  110364. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110365. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110366. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110367. ogg_int64_t off);
  110368. #ifdef DEBUG_MALLOC
  110369. #define _VDBG_GRAPHFILE "malloc.m"
  110370. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110371. extern void _VDBG_free(void *ptr,char *file,long line);
  110372. #ifndef MISC_C
  110373. #undef _ogg_malloc
  110374. #undef _ogg_calloc
  110375. #undef _ogg_realloc
  110376. #undef _ogg_free
  110377. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110378. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110379. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110380. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110381. #endif
  110382. #endif
  110383. #endif
  110384. /*** End of inlined file: misc.h ***/
  110385. #ifndef _V_IFDEFJAIL_H_
  110386. # define _V_IFDEFJAIL_H_
  110387. # ifdef __GNUC__
  110388. # define STIN static __inline__
  110389. # elif _WIN32
  110390. # define STIN static __inline
  110391. # else
  110392. # define STIN static
  110393. # endif
  110394. #ifdef DJGPP
  110395. # define rint(x) (floor((x)+0.5f))
  110396. #endif
  110397. #ifndef M_PI
  110398. # define M_PI (3.1415926536f)
  110399. #endif
  110400. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110401. # include <malloc.h>
  110402. # define rint(x) (floor((x)+0.5f))
  110403. # define NO_FLOAT_MATH_LIB
  110404. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110405. #endif
  110406. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110407. void *_alloca(size_t size);
  110408. # define alloca _alloca
  110409. #endif
  110410. #ifndef FAST_HYPOT
  110411. # define FAST_HYPOT hypot
  110412. #endif
  110413. #endif
  110414. #ifdef HAVE_ALLOCA_H
  110415. # include <alloca.h>
  110416. #endif
  110417. #ifdef USE_MEMORY_H
  110418. # include <memory.h>
  110419. #endif
  110420. #ifndef min
  110421. # define min(x,y) ((x)>(y)?(y):(x))
  110422. #endif
  110423. #ifndef max
  110424. # define max(x,y) ((x)<(y)?(y):(x))
  110425. #endif
  110426. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110427. # define VORBIS_FPU_CONTROL
  110428. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110429. Because of encapsulation constraints (GCC can't see inside the asm
  110430. block and so we end up doing stupid things like a store/load that
  110431. is collectively a noop), we do it this way */
  110432. /* we must set up the fpu before this works!! */
  110433. typedef ogg_int16_t vorbis_fpu_control;
  110434. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110435. ogg_int16_t ret;
  110436. ogg_int16_t temp;
  110437. __asm__ __volatile__("fnstcw %0\n\t"
  110438. "movw %0,%%dx\n\t"
  110439. "orw $62463,%%dx\n\t"
  110440. "movw %%dx,%1\n\t"
  110441. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110442. *fpu=ret;
  110443. }
  110444. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110445. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110446. }
  110447. /* assumes the FPU is in round mode! */
  110448. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110449. we get extra fst/fld to
  110450. truncate precision */
  110451. int i;
  110452. __asm__("fistl %0": "=m"(i) : "t"(f));
  110453. return(i);
  110454. }
  110455. #endif
  110456. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110457. # define VORBIS_FPU_CONTROL
  110458. typedef ogg_int16_t vorbis_fpu_control;
  110459. static __inline int vorbis_ftoi(double f){
  110460. int i;
  110461. __asm{
  110462. fld f
  110463. fistp i
  110464. }
  110465. return i;
  110466. }
  110467. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110468. }
  110469. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110470. }
  110471. #endif
  110472. #ifndef VORBIS_FPU_CONTROL
  110473. typedef int vorbis_fpu_control;
  110474. static int vorbis_ftoi(double f){
  110475. return (int)(f+.5);
  110476. }
  110477. /* We don't have special code for this compiler/arch, so do it the slow way */
  110478. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110479. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110480. #endif
  110481. #endif /* _OS_H */
  110482. /*** End of inlined file: os.h ***/
  110483. /* encode side bitrate tracking */
  110484. typedef struct bitrate_manager_state {
  110485. int managed;
  110486. long avg_reservoir;
  110487. long minmax_reservoir;
  110488. long avg_bitsper;
  110489. long min_bitsper;
  110490. long max_bitsper;
  110491. long short_per_long;
  110492. double avgfloat;
  110493. vorbis_block *vb;
  110494. int choice;
  110495. } bitrate_manager_state;
  110496. typedef struct bitrate_manager_info{
  110497. long avg_rate;
  110498. long min_rate;
  110499. long max_rate;
  110500. long reservoir_bits;
  110501. double reservoir_bias;
  110502. double slew_damp;
  110503. } bitrate_manager_info;
  110504. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110505. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110506. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110507. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110508. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110509. #endif
  110510. /*** End of inlined file: bitrate.h ***/
  110511. static int ilog(unsigned int v){
  110512. int ret=0;
  110513. while(v){
  110514. ret++;
  110515. v>>=1;
  110516. }
  110517. return(ret);
  110518. }
  110519. static int ilog2(unsigned int v){
  110520. int ret=0;
  110521. if(v)--v;
  110522. while(v){
  110523. ret++;
  110524. v>>=1;
  110525. }
  110526. return(ret);
  110527. }
  110528. typedef struct private_state {
  110529. /* local lookup storage */
  110530. envelope_lookup *ve; /* envelope lookup */
  110531. int window[2];
  110532. vorbis_look_transform **transform[2]; /* block, type */
  110533. drft_lookup fft_look[2];
  110534. int modebits;
  110535. vorbis_look_floor **flr;
  110536. vorbis_look_residue **residue;
  110537. vorbis_look_psy *psy;
  110538. vorbis_look_psy_global *psy_g_look;
  110539. /* local storage, only used on the encoding side. This way the
  110540. application does not need to worry about freeing some packets'
  110541. memory and not others'; packet storage is always tracked.
  110542. Cleared next call to a _dsp_ function */
  110543. unsigned char *header;
  110544. unsigned char *header1;
  110545. unsigned char *header2;
  110546. bitrate_manager_state bms;
  110547. ogg_int64_t sample_count;
  110548. } private_state;
  110549. /* codec_setup_info contains all the setup information specific to the
  110550. specific compression/decompression mode in progress (eg,
  110551. psychoacoustic settings, channel setup, options, codebook
  110552. etc).
  110553. *********************************************************************/
  110554. /*** Start of inlined file: highlevel.h ***/
  110555. typedef struct highlevel_byblocktype {
  110556. double tone_mask_setting;
  110557. double tone_peaklimit_setting;
  110558. double noise_bias_setting;
  110559. double noise_compand_setting;
  110560. } highlevel_byblocktype;
  110561. typedef struct highlevel_encode_setup {
  110562. void *setup;
  110563. int set_in_stone;
  110564. double base_setting;
  110565. double long_setting;
  110566. double short_setting;
  110567. double impulse_noisetune;
  110568. int managed;
  110569. long bitrate_min;
  110570. long bitrate_av;
  110571. double bitrate_av_damp;
  110572. long bitrate_max;
  110573. long bitrate_reservoir;
  110574. double bitrate_reservoir_bias;
  110575. int impulse_block_p;
  110576. int noise_normalize_p;
  110577. double stereo_point_setting;
  110578. double lowpass_kHz;
  110579. double ath_floating_dB;
  110580. double ath_absolute_dB;
  110581. double amplitude_track_dBpersec;
  110582. double trigger_setting;
  110583. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110584. } highlevel_encode_setup;
  110585. /*** End of inlined file: highlevel.h ***/
  110586. typedef struct codec_setup_info {
  110587. /* Vorbis supports only short and long blocks, but allows the
  110588. encoder to choose the sizes */
  110589. long blocksizes[2];
  110590. /* modes are the primary means of supporting on-the-fly different
  110591. blocksizes, different channel mappings (LR or M/A),
  110592. different residue backends, etc. Each mode consists of a
  110593. blocksize flag and a mapping (along with the mapping setup */
  110594. int modes;
  110595. int maps;
  110596. int floors;
  110597. int residues;
  110598. int books;
  110599. int psys; /* encode only */
  110600. vorbis_info_mode *mode_param[64];
  110601. int map_type[64];
  110602. vorbis_info_mapping *map_param[64];
  110603. int floor_type[64];
  110604. vorbis_info_floor *floor_param[64];
  110605. int residue_type[64];
  110606. vorbis_info_residue *residue_param[64];
  110607. static_codebook *book_param[256];
  110608. codebook *fullbooks;
  110609. vorbis_info_psy *psy_param[4]; /* encode only */
  110610. vorbis_info_psy_global psy_g_param;
  110611. bitrate_manager_info bi;
  110612. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110613. highly redundant structure, but
  110614. improves clarity of program flow. */
  110615. int halfrate_flag; /* painless downsample for decode */
  110616. } codec_setup_info;
  110617. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110618. extern void _vp_global_free(vorbis_look_psy_global *look);
  110619. #endif
  110620. /*** End of inlined file: codec_internal.h ***/
  110621. /*** Start of inlined file: registry.h ***/
  110622. #ifndef _V_REG_H_
  110623. #define _V_REG_H_
  110624. #define VI_TRANSFORMB 1
  110625. #define VI_WINDOWB 1
  110626. #define VI_TIMEB 1
  110627. #define VI_FLOORB 2
  110628. #define VI_RESB 3
  110629. #define VI_MAPB 1
  110630. extern vorbis_func_floor *_floor_P[];
  110631. extern vorbis_func_residue *_residue_P[];
  110632. extern vorbis_func_mapping *_mapping_P[];
  110633. #endif
  110634. /*** End of inlined file: registry.h ***/
  110635. /*** Start of inlined file: scales.h ***/
  110636. #ifndef _V_SCALES_H_
  110637. #define _V_SCALES_H_
  110638. #include <math.h>
  110639. /* 20log10(x) */
  110640. #define VORBIS_IEEE_FLOAT32 1
  110641. #ifdef VORBIS_IEEE_FLOAT32
  110642. static float unitnorm(float x){
  110643. union {
  110644. ogg_uint32_t i;
  110645. float f;
  110646. } ix;
  110647. ix.f = x;
  110648. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110649. return ix.f;
  110650. }
  110651. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110652. static float todB(const float *x){
  110653. union {
  110654. ogg_uint32_t i;
  110655. float f;
  110656. } ix;
  110657. ix.f = *x;
  110658. ix.i = ix.i&0x7fffffff;
  110659. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110660. }
  110661. #define todB_nn(x) todB(x)
  110662. #else
  110663. static float unitnorm(float x){
  110664. if(x<0)return(-1.f);
  110665. return(1.f);
  110666. }
  110667. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110668. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110669. #endif
  110670. #define fromdB(x) (exp((x)*.11512925f))
  110671. /* The bark scale equations are approximations, since the original
  110672. table was somewhat hand rolled. The below are chosen to have the
  110673. best possible fit to the rolled tables, thus their somewhat odd
  110674. appearance (these are more accurate and over a longer range than
  110675. the oft-quoted bark equations found in the texts I have). The
  110676. approximations are valid from 0 - 30kHz (nyquist) or so.
  110677. all f in Hz, z in Bark */
  110678. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110679. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110680. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110681. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110682. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110683. 0.0 */
  110684. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110685. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110686. #endif
  110687. /*** End of inlined file: scales.h ***/
  110688. int analysis_noisy=1;
  110689. /* decides between modes, dispatches to the appropriate mapping. */
  110690. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110691. int ret,i;
  110692. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110693. vb->glue_bits=0;
  110694. vb->time_bits=0;
  110695. vb->floor_bits=0;
  110696. vb->res_bits=0;
  110697. /* first things first. Make sure encode is ready */
  110698. for(i=0;i<PACKETBLOBS;i++)
  110699. oggpack_reset(vbi->packetblob[i]);
  110700. /* we only have one mapping type (0), and we let the mapping code
  110701. itself figure out what soft mode to use. This allows easier
  110702. bitrate management */
  110703. if((ret=_mapping_P[0]->forward(vb)))
  110704. return(ret);
  110705. if(op){
  110706. if(vorbis_bitrate_managed(vb))
  110707. /* The app is using a bitmanaged mode... but not using the
  110708. bitrate management interface. */
  110709. return(OV_EINVAL);
  110710. op->packet=oggpack_get_buffer(&vb->opb);
  110711. op->bytes=oggpack_bytes(&vb->opb);
  110712. op->b_o_s=0;
  110713. op->e_o_s=vb->eofflag;
  110714. op->granulepos=vb->granulepos;
  110715. op->packetno=vb->sequence; /* for sake of completeness */
  110716. }
  110717. return(0);
  110718. }
  110719. /* there was no great place to put this.... */
  110720. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110721. int j;
  110722. FILE *of;
  110723. char buffer[80];
  110724. /* if(i==5870){*/
  110725. sprintf(buffer,"%s_%d.m",base,i);
  110726. of=fopen(buffer,"w");
  110727. if(!of)perror("failed to open data dump file");
  110728. for(j=0;j<n;j++){
  110729. if(bark){
  110730. float b=toBARK((4000.f*j/n)+.25);
  110731. fprintf(of,"%f ",b);
  110732. }else
  110733. if(off!=0)
  110734. fprintf(of,"%f ",(double)(j+off)/8000.);
  110735. else
  110736. fprintf(of,"%f ",(double)j);
  110737. if(dB){
  110738. float val;
  110739. if(v[j]==0.)
  110740. val=-140.;
  110741. else
  110742. val=todB(v+j);
  110743. fprintf(of,"%f\n",val);
  110744. }else{
  110745. fprintf(of,"%f\n",v[j]);
  110746. }
  110747. }
  110748. fclose(of);
  110749. /* } */
  110750. }
  110751. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110752. ogg_int64_t off){
  110753. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110754. }
  110755. #endif
  110756. /*** End of inlined file: analysis.c ***/
  110757. /*** Start of inlined file: bitrate.c ***/
  110758. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110759. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110760. // tasks..
  110761. #if JUCE_MSVC
  110762. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110763. #endif
  110764. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110765. #if JUCE_USE_OGGVORBIS
  110766. #include <stdlib.h>
  110767. #include <string.h>
  110768. #include <math.h>
  110769. /* compute bitrate tracking setup */
  110770. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110771. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110772. bitrate_manager_info *bi=&ci->bi;
  110773. memset(bm,0,sizeof(*bm));
  110774. if(bi && (bi->reservoir_bits>0)){
  110775. long ratesamples=vi->rate;
  110776. int halfsamples=ci->blocksizes[0]>>1;
  110777. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110778. bm->managed=1;
  110779. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110780. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110781. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110782. bm->avgfloat=PACKETBLOBS/2;
  110783. /* not a necessary fix, but one that leads to a more balanced
  110784. typical initialization */
  110785. {
  110786. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110787. bm->minmax_reservoir=desired_fill;
  110788. bm->avg_reservoir=desired_fill;
  110789. }
  110790. }
  110791. }
  110792. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110793. memset(bm,0,sizeof(*bm));
  110794. return;
  110795. }
  110796. int vorbis_bitrate_managed(vorbis_block *vb){
  110797. vorbis_dsp_state *vd=vb->vd;
  110798. private_state *b=(private_state*)vd->backend_state;
  110799. bitrate_manager_state *bm=&b->bms;
  110800. if(bm && bm->managed)return(1);
  110801. return(0);
  110802. }
  110803. /* finish taking in the block we just processed */
  110804. int vorbis_bitrate_addblock(vorbis_block *vb){
  110805. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110806. vorbis_dsp_state *vd=vb->vd;
  110807. private_state *b=(private_state*)vd->backend_state;
  110808. bitrate_manager_state *bm=&b->bms;
  110809. vorbis_info *vi=vd->vi;
  110810. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110811. bitrate_manager_info *bi=&ci->bi;
  110812. int choice=rint(bm->avgfloat);
  110813. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110814. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110815. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110816. int samples=ci->blocksizes[vb->W]>>1;
  110817. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110818. if(!bm->managed){
  110819. /* not a bitrate managed stream, but for API simplicity, we'll
  110820. buffer the packet to keep the code path clean */
  110821. if(bm->vb)return(-1); /* one has been submitted without
  110822. being claimed */
  110823. bm->vb=vb;
  110824. return(0);
  110825. }
  110826. bm->vb=vb;
  110827. /* look ahead for avg floater */
  110828. if(bm->avg_bitsper>0){
  110829. double slew=0.;
  110830. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110831. double slewlimit= 15./bi->slew_damp;
  110832. /* choosing a new floater:
  110833. if we're over target, we slew down
  110834. if we're under target, we slew up
  110835. choose slew as follows: look through packetblobs of this frame
  110836. and set slew as the first in the appropriate direction that
  110837. gives us the slew we want. This may mean no slew if delta is
  110838. already favorable.
  110839. Then limit slew to slew max */
  110840. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110841. while(choice>0 && this_bits>avg_target_bits &&
  110842. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110843. choice--;
  110844. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110845. }
  110846. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110847. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110848. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110849. choice++;
  110850. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110851. }
  110852. }
  110853. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110854. if(slew<-slewlimit)slew=-slewlimit;
  110855. if(slew>slewlimit)slew=slewlimit;
  110856. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110857. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110858. }
  110859. /* enforce min(if used) on the current floater (if used) */
  110860. if(bm->min_bitsper>0){
  110861. /* do we need to force the bitrate up? */
  110862. if(this_bits<min_target_bits){
  110863. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110864. choice++;
  110865. if(choice>=PACKETBLOBS)break;
  110866. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110867. }
  110868. }
  110869. }
  110870. /* enforce max (if used) on the current floater (if used) */
  110871. if(bm->max_bitsper>0){
  110872. /* do we need to force the bitrate down? */
  110873. if(this_bits>max_target_bits){
  110874. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110875. choice--;
  110876. if(choice<0)break;
  110877. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110878. }
  110879. }
  110880. }
  110881. /* Choice of packetblobs now made based on floater, and min/max
  110882. requirements. Now boundary check extreme choices */
  110883. if(choice<0){
  110884. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110885. frame will need to be truncated */
  110886. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110887. bm->choice=choice=0;
  110888. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110889. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110890. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110891. }
  110892. }else{
  110893. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110894. if(choice>=PACKETBLOBS)
  110895. choice=PACKETBLOBS-1;
  110896. bm->choice=choice;
  110897. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110898. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110899. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110900. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110901. }
  110902. /* now we have the final packet and the final packet size. Update statistics */
  110903. /* min and max reservoir */
  110904. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110905. if(max_target_bits>0 && this_bits>max_target_bits){
  110906. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110907. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110908. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110909. }else{
  110910. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110911. if(bm->minmax_reservoir>desired_fill){
  110912. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110913. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110914. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110915. }else{
  110916. bm->minmax_reservoir=desired_fill;
  110917. }
  110918. }else{
  110919. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110920. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110921. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110922. }else{
  110923. bm->minmax_reservoir=desired_fill;
  110924. }
  110925. }
  110926. }
  110927. }
  110928. /* avg reservoir */
  110929. if(bm->avg_bitsper>0){
  110930. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110931. bm->avg_reservoir+=this_bits-avg_target_bits;
  110932. }
  110933. return(0);
  110934. }
  110935. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110936. private_state *b=(private_state*)vd->backend_state;
  110937. bitrate_manager_state *bm=&b->bms;
  110938. vorbis_block *vb=bm->vb;
  110939. int choice=PACKETBLOBS/2;
  110940. if(!vb)return 0;
  110941. if(op){
  110942. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110943. if(vorbis_bitrate_managed(vb))
  110944. choice=bm->choice;
  110945. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110946. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110947. op->b_o_s=0;
  110948. op->e_o_s=vb->eofflag;
  110949. op->granulepos=vb->granulepos;
  110950. op->packetno=vb->sequence; /* for sake of completeness */
  110951. }
  110952. bm->vb=0;
  110953. return(1);
  110954. }
  110955. #endif
  110956. /*** End of inlined file: bitrate.c ***/
  110957. /*** Start of inlined file: block.c ***/
  110958. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110959. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110960. // tasks..
  110961. #if JUCE_MSVC
  110962. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110963. #endif
  110964. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110965. #if JUCE_USE_OGGVORBIS
  110966. #include <stdio.h>
  110967. #include <stdlib.h>
  110968. #include <string.h>
  110969. /*** Start of inlined file: window.h ***/
  110970. #ifndef _V_WINDOW_
  110971. #define _V_WINDOW_
  110972. extern float *_vorbis_window_get(int n);
  110973. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110974. int lW,int W,int nW);
  110975. #endif
  110976. /*** End of inlined file: window.h ***/
  110977. /*** Start of inlined file: lpc.h ***/
  110978. #ifndef _V_LPC_H_
  110979. #define _V_LPC_H_
  110980. /* simple linear scale LPC code */
  110981. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110982. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110983. float *data,long n);
  110984. #endif
  110985. /*** End of inlined file: lpc.h ***/
  110986. /* pcm accumulator examples (not exhaustive):
  110987. <-------------- lW ---------------->
  110988. <--------------- W ---------------->
  110989. : .....|..... _______________ |
  110990. : .''' | '''_--- | |\ |
  110991. :.....''' |_____--- '''......| | \_______|
  110992. :.................|__________________|_______|__|______|
  110993. |<------ Sl ------>| > Sr < |endW
  110994. |beginSl |endSl | |endSr
  110995. |beginW |endlW |beginSr
  110996. |< lW >|
  110997. <--------------- W ---------------->
  110998. | | .. ______________ |
  110999. | | ' `/ | ---_ |
  111000. |___.'___/`. | ---_____|
  111001. |_______|__|_______|_________________|
  111002. | >|Sl|< |<------ Sr ----->|endW
  111003. | | |endSl |beginSr |endSr
  111004. |beginW | |endlW
  111005. mult[0] |beginSl mult[n]
  111006. <-------------- lW ----------------->
  111007. |<--W-->|
  111008. : .............. ___ | |
  111009. : .''' |`/ \ | |
  111010. :.....''' |/`....\|...|
  111011. :.........................|___|___|___|
  111012. |Sl |Sr |endW
  111013. | | |endSr
  111014. | |beginSr
  111015. | |endSl
  111016. |beginSl
  111017. |beginW
  111018. */
  111019. /* block abstraction setup *********************************************/
  111020. #ifndef WORD_ALIGN
  111021. #define WORD_ALIGN 8
  111022. #endif
  111023. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111024. int i;
  111025. memset(vb,0,sizeof(*vb));
  111026. vb->vd=v;
  111027. vb->localalloc=0;
  111028. vb->localstore=NULL;
  111029. if(v->analysisp){
  111030. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111031. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111032. vbi->ampmax=-9999;
  111033. for(i=0;i<PACKETBLOBS;i++){
  111034. if(i==PACKETBLOBS/2){
  111035. vbi->packetblob[i]=&vb->opb;
  111036. }else{
  111037. vbi->packetblob[i]=
  111038. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111039. }
  111040. oggpack_writeinit(vbi->packetblob[i]);
  111041. }
  111042. }
  111043. return(0);
  111044. }
  111045. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111046. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111047. if(bytes+vb->localtop>vb->localalloc){
  111048. /* can't just _ogg_realloc... there are outstanding pointers */
  111049. if(vb->localstore){
  111050. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111051. vb->totaluse+=vb->localtop;
  111052. link->next=vb->reap;
  111053. link->ptr=vb->localstore;
  111054. vb->reap=link;
  111055. }
  111056. /* highly conservative */
  111057. vb->localalloc=bytes;
  111058. vb->localstore=_ogg_malloc(vb->localalloc);
  111059. vb->localtop=0;
  111060. }
  111061. {
  111062. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111063. vb->localtop+=bytes;
  111064. return ret;
  111065. }
  111066. }
  111067. /* reap the chain, pull the ripcord */
  111068. void _vorbis_block_ripcord(vorbis_block *vb){
  111069. /* reap the chain */
  111070. struct alloc_chain *reap=vb->reap;
  111071. while(reap){
  111072. struct alloc_chain *next=reap->next;
  111073. _ogg_free(reap->ptr);
  111074. memset(reap,0,sizeof(*reap));
  111075. _ogg_free(reap);
  111076. reap=next;
  111077. }
  111078. /* consolidate storage */
  111079. if(vb->totaluse){
  111080. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111081. vb->localalloc+=vb->totaluse;
  111082. vb->totaluse=0;
  111083. }
  111084. /* pull the ripcord */
  111085. vb->localtop=0;
  111086. vb->reap=NULL;
  111087. }
  111088. int vorbis_block_clear(vorbis_block *vb){
  111089. int i;
  111090. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111091. _vorbis_block_ripcord(vb);
  111092. if(vb->localstore)_ogg_free(vb->localstore);
  111093. if(vbi){
  111094. for(i=0;i<PACKETBLOBS;i++){
  111095. oggpack_writeclear(vbi->packetblob[i]);
  111096. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111097. }
  111098. _ogg_free(vbi);
  111099. }
  111100. memset(vb,0,sizeof(*vb));
  111101. return(0);
  111102. }
  111103. /* Analysis side code, but directly related to blocking. Thus it's
  111104. here and not in analysis.c (which is for analysis transforms only).
  111105. The init is here because some of it is shared */
  111106. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111107. int i;
  111108. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111109. private_state *b=NULL;
  111110. int hs;
  111111. if(ci==NULL) return 1;
  111112. hs=ci->halfrate_flag;
  111113. memset(v,0,sizeof(*v));
  111114. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111115. v->vi=vi;
  111116. b->modebits=ilog2(ci->modes);
  111117. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111118. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111119. /* MDCT is tranform 0 */
  111120. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111121. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111122. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111123. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111124. /* Vorbis I uses only window type 0 */
  111125. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111126. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111127. if(encp){ /* encode/decode differ here */
  111128. /* analysis always needs an fft */
  111129. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111130. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111131. /* finish the codebooks */
  111132. if(!ci->fullbooks){
  111133. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111134. for(i=0;i<ci->books;i++)
  111135. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111136. }
  111137. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111138. for(i=0;i<ci->psys;i++){
  111139. _vp_psy_init(b->psy+i,
  111140. ci->psy_param[i],
  111141. &ci->psy_g_param,
  111142. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111143. vi->rate);
  111144. }
  111145. v->analysisp=1;
  111146. }else{
  111147. /* finish the codebooks */
  111148. if(!ci->fullbooks){
  111149. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111150. for(i=0;i<ci->books;i++){
  111151. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111152. /* decode codebooks are now standalone after init */
  111153. vorbis_staticbook_destroy(ci->book_param[i]);
  111154. ci->book_param[i]=NULL;
  111155. }
  111156. }
  111157. }
  111158. /* initialize the storage vectors. blocksize[1] is small for encode,
  111159. but the correct size for decode */
  111160. v->pcm_storage=ci->blocksizes[1];
  111161. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111162. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111163. {
  111164. int i;
  111165. for(i=0;i<vi->channels;i++)
  111166. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111167. }
  111168. /* all 1 (large block) or 0 (small block) */
  111169. /* explicitly set for the sake of clarity */
  111170. v->lW=0; /* previous window size */
  111171. v->W=0; /* current window size */
  111172. /* all vector indexes */
  111173. v->centerW=ci->blocksizes[1]/2;
  111174. v->pcm_current=v->centerW;
  111175. /* initialize all the backend lookups */
  111176. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111177. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111178. for(i=0;i<ci->floors;i++)
  111179. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111180. look(v,ci->floor_param[i]);
  111181. for(i=0;i<ci->residues;i++)
  111182. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111183. look(v,ci->residue_param[i]);
  111184. return 0;
  111185. }
  111186. /* arbitrary settings and spec-mandated numbers get filled in here */
  111187. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111188. private_state *b=NULL;
  111189. if(_vds_shared_init(v,vi,1))return 1;
  111190. b=(private_state*)v->backend_state;
  111191. b->psy_g_look=_vp_global_look(vi);
  111192. /* Initialize the envelope state storage */
  111193. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111194. _ve_envelope_init(b->ve,vi);
  111195. vorbis_bitrate_init(vi,&b->bms);
  111196. /* compressed audio packets start after the headers
  111197. with sequence number 3 */
  111198. v->sequence=3;
  111199. return(0);
  111200. }
  111201. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111202. int i;
  111203. if(v){
  111204. vorbis_info *vi=v->vi;
  111205. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111206. private_state *b=(private_state*)v->backend_state;
  111207. if(b){
  111208. if(b->ve){
  111209. _ve_envelope_clear(b->ve);
  111210. _ogg_free(b->ve);
  111211. }
  111212. if(b->transform[0]){
  111213. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111214. _ogg_free(b->transform[0][0]);
  111215. _ogg_free(b->transform[0]);
  111216. }
  111217. if(b->transform[1]){
  111218. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111219. _ogg_free(b->transform[1][0]);
  111220. _ogg_free(b->transform[1]);
  111221. }
  111222. if(b->flr){
  111223. for(i=0;i<ci->floors;i++)
  111224. _floor_P[ci->floor_type[i]]->
  111225. free_look(b->flr[i]);
  111226. _ogg_free(b->flr);
  111227. }
  111228. if(b->residue){
  111229. for(i=0;i<ci->residues;i++)
  111230. _residue_P[ci->residue_type[i]]->
  111231. free_look(b->residue[i]);
  111232. _ogg_free(b->residue);
  111233. }
  111234. if(b->psy){
  111235. for(i=0;i<ci->psys;i++)
  111236. _vp_psy_clear(b->psy+i);
  111237. _ogg_free(b->psy);
  111238. }
  111239. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111240. vorbis_bitrate_clear(&b->bms);
  111241. drft_clear(&b->fft_look[0]);
  111242. drft_clear(&b->fft_look[1]);
  111243. }
  111244. if(v->pcm){
  111245. for(i=0;i<vi->channels;i++)
  111246. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111247. _ogg_free(v->pcm);
  111248. if(v->pcmret)_ogg_free(v->pcmret);
  111249. }
  111250. if(b){
  111251. /* free header, header1, header2 */
  111252. if(b->header)_ogg_free(b->header);
  111253. if(b->header1)_ogg_free(b->header1);
  111254. if(b->header2)_ogg_free(b->header2);
  111255. _ogg_free(b);
  111256. }
  111257. memset(v,0,sizeof(*v));
  111258. }
  111259. }
  111260. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111261. int i;
  111262. vorbis_info *vi=v->vi;
  111263. private_state *b=(private_state*)v->backend_state;
  111264. /* free header, header1, header2 */
  111265. if(b->header)_ogg_free(b->header);b->header=NULL;
  111266. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111267. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111268. /* Do we have enough storage space for the requested buffer? If not,
  111269. expand the PCM (and envelope) storage */
  111270. if(v->pcm_current+vals>=v->pcm_storage){
  111271. v->pcm_storage=v->pcm_current+vals*2;
  111272. for(i=0;i<vi->channels;i++){
  111273. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111274. }
  111275. }
  111276. for(i=0;i<vi->channels;i++)
  111277. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111278. return(v->pcmret);
  111279. }
  111280. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111281. int i;
  111282. int order=32;
  111283. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111284. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111285. long j;
  111286. v->preextrapolate=1;
  111287. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111288. for(i=0;i<v->vi->channels;i++){
  111289. /* need to run the extrapolation in reverse! */
  111290. for(j=0;j<v->pcm_current;j++)
  111291. work[j]=v->pcm[i][v->pcm_current-j-1];
  111292. /* prime as above */
  111293. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111294. /* run the predictor filter */
  111295. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111296. order,
  111297. work+v->pcm_current-v->centerW,
  111298. v->centerW);
  111299. for(j=0;j<v->pcm_current;j++)
  111300. v->pcm[i][v->pcm_current-j-1]=work[j];
  111301. }
  111302. }
  111303. }
  111304. /* call with val<=0 to set eof */
  111305. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111306. vorbis_info *vi=v->vi;
  111307. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111308. if(vals<=0){
  111309. int order=32;
  111310. int i;
  111311. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111312. /* if it wasn't done earlier (very short sample) */
  111313. if(!v->preextrapolate)
  111314. _preextrapolate_helper(v);
  111315. /* We're encoding the end of the stream. Just make sure we have
  111316. [at least] a few full blocks of zeroes at the end. */
  111317. /* actually, we don't want zeroes; that could drop a large
  111318. amplitude off a cliff, creating spread spectrum noise that will
  111319. suck to encode. Extrapolate for the sake of cleanliness. */
  111320. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111321. v->eofflag=v->pcm_current;
  111322. v->pcm_current+=ci->blocksizes[1]*3;
  111323. for(i=0;i<vi->channels;i++){
  111324. if(v->eofflag>order*2){
  111325. /* extrapolate with LPC to fill in */
  111326. long n;
  111327. /* make a predictor filter */
  111328. n=v->eofflag;
  111329. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111330. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111331. /* run the predictor filter */
  111332. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111333. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111334. }else{
  111335. /* not enough data to extrapolate (unlikely to happen due to
  111336. guarding the overlap, but bulletproof in case that
  111337. assumtion goes away). zeroes will do. */
  111338. memset(v->pcm[i]+v->eofflag,0,
  111339. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111340. }
  111341. }
  111342. }else{
  111343. if(v->pcm_current+vals>v->pcm_storage)
  111344. return(OV_EINVAL);
  111345. v->pcm_current+=vals;
  111346. /* we may want to reverse extrapolate the beginning of a stream
  111347. too... in case we're beginning on a cliff! */
  111348. /* clumsy, but simple. It only runs once, so simple is good. */
  111349. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111350. _preextrapolate_helper(v);
  111351. }
  111352. return(0);
  111353. }
  111354. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111355. the next block on which to continue analysis */
  111356. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111357. int i;
  111358. vorbis_info *vi=v->vi;
  111359. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111360. private_state *b=(private_state*)v->backend_state;
  111361. vorbis_look_psy_global *g=b->psy_g_look;
  111362. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111363. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111364. /* check to see if we're started... */
  111365. if(!v->preextrapolate)return(0);
  111366. /* check to see if we're done... */
  111367. if(v->eofflag==-1)return(0);
  111368. /* By our invariant, we have lW, W and centerW set. Search for
  111369. the next boundary so we can determine nW (the next window size)
  111370. which lets us compute the shape of the current block's window */
  111371. /* we do an envelope search even on a single blocksize; we may still
  111372. be throwing more bits at impulses, and envelope search handles
  111373. marking impulses too. */
  111374. {
  111375. long bp=_ve_envelope_search(v);
  111376. if(bp==-1){
  111377. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111378. full long block */
  111379. v->nW=0;
  111380. }else{
  111381. if(ci->blocksizes[0]==ci->blocksizes[1])
  111382. v->nW=0;
  111383. else
  111384. v->nW=bp;
  111385. }
  111386. }
  111387. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111388. {
  111389. /* center of next block + next block maximum right side. */
  111390. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111391. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111392. although this check is
  111393. less strict that the
  111394. _ve_envelope_search,
  111395. the search is not run
  111396. if we only use one
  111397. block size */
  111398. }
  111399. /* fill in the block. Note that for a short window, lW and nW are *short*
  111400. regardless of actual settings in the stream */
  111401. _vorbis_block_ripcord(vb);
  111402. vb->lW=v->lW;
  111403. vb->W=v->W;
  111404. vb->nW=v->nW;
  111405. if(v->W){
  111406. if(!v->lW || !v->nW){
  111407. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111408. /*fprintf(stderr,"-");*/
  111409. }else{
  111410. vbi->blocktype=BLOCKTYPE_LONG;
  111411. /*fprintf(stderr,"_");*/
  111412. }
  111413. }else{
  111414. if(_ve_envelope_mark(v)){
  111415. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111416. /*fprintf(stderr,"|");*/
  111417. }else{
  111418. vbi->blocktype=BLOCKTYPE_PADDING;
  111419. /*fprintf(stderr,".");*/
  111420. }
  111421. }
  111422. vb->vd=v;
  111423. vb->sequence=v->sequence++;
  111424. vb->granulepos=v->granulepos;
  111425. vb->pcmend=ci->blocksizes[v->W];
  111426. /* copy the vectors; this uses the local storage in vb */
  111427. /* this tracks 'strongest peak' for later psychoacoustics */
  111428. /* moved to the global psy state; clean this mess up */
  111429. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111430. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111431. vbi->ampmax=g->ampmax;
  111432. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111433. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111434. for(i=0;i<vi->channels;i++){
  111435. vbi->pcmdelay[i]=
  111436. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111437. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111438. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111439. /* before we added the delay
  111440. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111441. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111442. */
  111443. }
  111444. /* handle eof detection: eof==0 means that we've not yet received EOF
  111445. eof>0 marks the last 'real' sample in pcm[]
  111446. eof<0 'no more to do'; doesn't get here */
  111447. if(v->eofflag){
  111448. if(v->centerW>=v->eofflag){
  111449. v->eofflag=-1;
  111450. vb->eofflag=1;
  111451. return(1);
  111452. }
  111453. }
  111454. /* advance storage vectors and clean up */
  111455. {
  111456. int new_centerNext=ci->blocksizes[1]/2;
  111457. int movementW=centerNext-new_centerNext;
  111458. if(movementW>0){
  111459. _ve_envelope_shift(b->ve,movementW);
  111460. v->pcm_current-=movementW;
  111461. for(i=0;i<vi->channels;i++)
  111462. memmove(v->pcm[i],v->pcm[i]+movementW,
  111463. v->pcm_current*sizeof(*v->pcm[i]));
  111464. v->lW=v->W;
  111465. v->W=v->nW;
  111466. v->centerW=new_centerNext;
  111467. if(v->eofflag){
  111468. v->eofflag-=movementW;
  111469. if(v->eofflag<=0)v->eofflag=-1;
  111470. /* do not add padding to end of stream! */
  111471. if(v->centerW>=v->eofflag){
  111472. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111473. }else{
  111474. v->granulepos+=movementW;
  111475. }
  111476. }else{
  111477. v->granulepos+=movementW;
  111478. }
  111479. }
  111480. }
  111481. /* done */
  111482. return(1);
  111483. }
  111484. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111485. vorbis_info *vi=v->vi;
  111486. codec_setup_info *ci;
  111487. int hs;
  111488. if(!v->backend_state)return -1;
  111489. if(!vi)return -1;
  111490. ci=(codec_setup_info*) vi->codec_setup;
  111491. if(!ci)return -1;
  111492. hs=ci->halfrate_flag;
  111493. v->centerW=ci->blocksizes[1]>>(hs+1);
  111494. v->pcm_current=v->centerW>>hs;
  111495. v->pcm_returned=-1;
  111496. v->granulepos=-1;
  111497. v->sequence=-1;
  111498. v->eofflag=0;
  111499. ((private_state *)(v->backend_state))->sample_count=-1;
  111500. return(0);
  111501. }
  111502. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111503. if(_vds_shared_init(v,vi,0)) return 1;
  111504. vorbis_synthesis_restart(v);
  111505. return 0;
  111506. }
  111507. /* Unlike in analysis, the window is only partially applied for each
  111508. block. The time domain envelope is not yet handled at the point of
  111509. calling (as it relies on the previous block). */
  111510. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111511. vorbis_info *vi=v->vi;
  111512. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111513. private_state *b=(private_state*)v->backend_state;
  111514. int hs=ci->halfrate_flag;
  111515. int i,j;
  111516. if(!vb)return(OV_EINVAL);
  111517. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111518. v->lW=v->W;
  111519. v->W=vb->W;
  111520. v->nW=-1;
  111521. if((v->sequence==-1)||
  111522. (v->sequence+1 != vb->sequence)){
  111523. v->granulepos=-1; /* out of sequence; lose count */
  111524. b->sample_count=-1;
  111525. }
  111526. v->sequence=vb->sequence;
  111527. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111528. was called on block */
  111529. int n=ci->blocksizes[v->W]>>(hs+1);
  111530. int n0=ci->blocksizes[0]>>(hs+1);
  111531. int n1=ci->blocksizes[1]>>(hs+1);
  111532. int thisCenter;
  111533. int prevCenter;
  111534. v->glue_bits+=vb->glue_bits;
  111535. v->time_bits+=vb->time_bits;
  111536. v->floor_bits+=vb->floor_bits;
  111537. v->res_bits+=vb->res_bits;
  111538. if(v->centerW){
  111539. thisCenter=n1;
  111540. prevCenter=0;
  111541. }else{
  111542. thisCenter=0;
  111543. prevCenter=n1;
  111544. }
  111545. /* v->pcm is now used like a two-stage double buffer. We don't want
  111546. to have to constantly shift *or* adjust memory usage. Don't
  111547. accept a new block until the old is shifted out */
  111548. for(j=0;j<vi->channels;j++){
  111549. /* the overlap/add section */
  111550. if(v->lW){
  111551. if(v->W){
  111552. /* large/large */
  111553. float *w=_vorbis_window_get(b->window[1]-hs);
  111554. float *pcm=v->pcm[j]+prevCenter;
  111555. float *p=vb->pcm[j];
  111556. for(i=0;i<n1;i++)
  111557. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111558. }else{
  111559. /* large/small */
  111560. float *w=_vorbis_window_get(b->window[0]-hs);
  111561. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111562. float *p=vb->pcm[j];
  111563. for(i=0;i<n0;i++)
  111564. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111565. }
  111566. }else{
  111567. if(v->W){
  111568. /* small/large */
  111569. float *w=_vorbis_window_get(b->window[0]-hs);
  111570. float *pcm=v->pcm[j]+prevCenter;
  111571. float *p=vb->pcm[j]+n1/2-n0/2;
  111572. for(i=0;i<n0;i++)
  111573. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111574. for(;i<n1/2+n0/2;i++)
  111575. pcm[i]=p[i];
  111576. }else{
  111577. /* small/small */
  111578. float *w=_vorbis_window_get(b->window[0]-hs);
  111579. float *pcm=v->pcm[j]+prevCenter;
  111580. float *p=vb->pcm[j];
  111581. for(i=0;i<n0;i++)
  111582. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111583. }
  111584. }
  111585. /* the copy section */
  111586. {
  111587. float *pcm=v->pcm[j]+thisCenter;
  111588. float *p=vb->pcm[j]+n;
  111589. for(i=0;i<n;i++)
  111590. pcm[i]=p[i];
  111591. }
  111592. }
  111593. if(v->centerW)
  111594. v->centerW=0;
  111595. else
  111596. v->centerW=n1;
  111597. /* deal with initial packet state; we do this using the explicit
  111598. pcm_returned==-1 flag otherwise we're sensitive to first block
  111599. being short or long */
  111600. if(v->pcm_returned==-1){
  111601. v->pcm_returned=thisCenter;
  111602. v->pcm_current=thisCenter;
  111603. }else{
  111604. v->pcm_returned=prevCenter;
  111605. v->pcm_current=prevCenter+
  111606. ((ci->blocksizes[v->lW]/4+
  111607. ci->blocksizes[v->W]/4)>>hs);
  111608. }
  111609. }
  111610. /* track the frame number... This is for convenience, but also
  111611. making sure our last packet doesn't end with added padding. If
  111612. the last packet is partial, the number of samples we'll have to
  111613. return will be past the vb->granulepos.
  111614. This is not foolproof! It will be confused if we begin
  111615. decoding at the last page after a seek or hole. In that case,
  111616. we don't have a starting point to judge where the last frame
  111617. is. For this reason, vorbisfile will always try to make sure
  111618. it reads the last two marked pages in proper sequence */
  111619. if(b->sample_count==-1){
  111620. b->sample_count=0;
  111621. }else{
  111622. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111623. }
  111624. if(v->granulepos==-1){
  111625. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111626. v->granulepos=vb->granulepos;
  111627. /* is this a short page? */
  111628. if(b->sample_count>v->granulepos){
  111629. /* corner case; if this is both the first and last audio page,
  111630. then spec says the end is cut, not beginning */
  111631. if(vb->eofflag){
  111632. /* trim the end */
  111633. /* no preceeding granulepos; assume we started at zero (we'd
  111634. have to in a short single-page stream) */
  111635. /* granulepos could be -1 due to a seek, but that would result
  111636. in a long count, not short count */
  111637. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111638. }else{
  111639. /* trim the beginning */
  111640. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111641. if(v->pcm_returned>v->pcm_current)
  111642. v->pcm_returned=v->pcm_current;
  111643. }
  111644. }
  111645. }
  111646. }else{
  111647. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111648. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111649. if(v->granulepos>vb->granulepos){
  111650. long extra=v->granulepos-vb->granulepos;
  111651. if(extra)
  111652. if(vb->eofflag){
  111653. /* partial last frame. Strip the extra samples off */
  111654. v->pcm_current-=extra>>hs;
  111655. } /* else {Shouldn't happen *unless* the bitstream is out of
  111656. spec. Either way, believe the bitstream } */
  111657. } /* else {Shouldn't happen *unless* the bitstream is out of
  111658. spec. Either way, believe the bitstream } */
  111659. v->granulepos=vb->granulepos;
  111660. }
  111661. }
  111662. /* Update, cleanup */
  111663. if(vb->eofflag)v->eofflag=1;
  111664. return(0);
  111665. }
  111666. /* pcm==NULL indicates we just want the pending samples, no more */
  111667. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111668. vorbis_info *vi=v->vi;
  111669. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111670. if(pcm){
  111671. int i;
  111672. for(i=0;i<vi->channels;i++)
  111673. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111674. *pcm=v->pcmret;
  111675. }
  111676. return(v->pcm_current-v->pcm_returned);
  111677. }
  111678. return(0);
  111679. }
  111680. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111681. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111682. v->pcm_returned+=n;
  111683. return(0);
  111684. }
  111685. /* intended for use with a specific vorbisfile feature; we want access
  111686. to the [usually synthetic/postextrapolated] buffer and lapping at
  111687. the end of a decode cycle, specifically, a half-short-block worth.
  111688. This funtion works like pcmout above, except it will also expose
  111689. this implicit buffer data not normally decoded. */
  111690. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111691. vorbis_info *vi=v->vi;
  111692. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111693. int hs=ci->halfrate_flag;
  111694. int n=ci->blocksizes[v->W]>>(hs+1);
  111695. int n0=ci->blocksizes[0]>>(hs+1);
  111696. int n1=ci->blocksizes[1]>>(hs+1);
  111697. int i,j;
  111698. if(v->pcm_returned<0)return 0;
  111699. /* our returned data ends at pcm_returned; because the synthesis pcm
  111700. buffer is a two-fragment ring, that means our data block may be
  111701. fragmented by buffering, wrapping or a short block not filling
  111702. out a buffer. To simplify things, we unfragment if it's at all
  111703. possibly needed. Otherwise, we'd need to call lapout more than
  111704. once as well as hold additional dsp state. Opt for
  111705. simplicity. */
  111706. /* centerW was advanced by blockin; it would be the center of the
  111707. *next* block */
  111708. if(v->centerW==n1){
  111709. /* the data buffer wraps; swap the halves */
  111710. /* slow, sure, small */
  111711. for(j=0;j<vi->channels;j++){
  111712. float *p=v->pcm[j];
  111713. for(i=0;i<n1;i++){
  111714. float temp=p[i];
  111715. p[i]=p[i+n1];
  111716. p[i+n1]=temp;
  111717. }
  111718. }
  111719. v->pcm_current-=n1;
  111720. v->pcm_returned-=n1;
  111721. v->centerW=0;
  111722. }
  111723. /* solidify buffer into contiguous space */
  111724. if((v->lW^v->W)==1){
  111725. /* long/short or short/long */
  111726. for(j=0;j<vi->channels;j++){
  111727. float *s=v->pcm[j];
  111728. float *d=v->pcm[j]+(n1-n0)/2;
  111729. for(i=(n1+n0)/2-1;i>=0;--i)
  111730. d[i]=s[i];
  111731. }
  111732. v->pcm_returned+=(n1-n0)/2;
  111733. v->pcm_current+=(n1-n0)/2;
  111734. }else{
  111735. if(v->lW==0){
  111736. /* short/short */
  111737. for(j=0;j<vi->channels;j++){
  111738. float *s=v->pcm[j];
  111739. float *d=v->pcm[j]+n1-n0;
  111740. for(i=n0-1;i>=0;--i)
  111741. d[i]=s[i];
  111742. }
  111743. v->pcm_returned+=n1-n0;
  111744. v->pcm_current+=n1-n0;
  111745. }
  111746. }
  111747. if(pcm){
  111748. int i;
  111749. for(i=0;i<vi->channels;i++)
  111750. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111751. *pcm=v->pcmret;
  111752. }
  111753. return(n1+n-v->pcm_returned);
  111754. }
  111755. float *vorbis_window(vorbis_dsp_state *v,int W){
  111756. vorbis_info *vi=v->vi;
  111757. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111758. int hs=ci->halfrate_flag;
  111759. private_state *b=(private_state*)v->backend_state;
  111760. if(b->window[W]-1<0)return NULL;
  111761. return _vorbis_window_get(b->window[W]-hs);
  111762. }
  111763. #endif
  111764. /*** End of inlined file: block.c ***/
  111765. /*** Start of inlined file: codebook.c ***/
  111766. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111767. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111768. // tasks..
  111769. #if JUCE_MSVC
  111770. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111771. #endif
  111772. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111773. #if JUCE_USE_OGGVORBIS
  111774. #include <stdlib.h>
  111775. #include <string.h>
  111776. #include <math.h>
  111777. /* packs the given codebook into the bitstream **************************/
  111778. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111779. long i,j;
  111780. int ordered=0;
  111781. /* first the basic parameters */
  111782. oggpack_write(opb,0x564342,24);
  111783. oggpack_write(opb,c->dim,16);
  111784. oggpack_write(opb,c->entries,24);
  111785. /* pack the codewords. There are two packings; length ordered and
  111786. length random. Decide between the two now. */
  111787. for(i=1;i<c->entries;i++)
  111788. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111789. if(i==c->entries)ordered=1;
  111790. if(ordered){
  111791. /* length ordered. We only need to say how many codewords of
  111792. each length. The actual codewords are generated
  111793. deterministically */
  111794. long count=0;
  111795. oggpack_write(opb,1,1); /* ordered */
  111796. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111797. for(i=1;i<c->entries;i++){
  111798. long thisx=c->lengthlist[i];
  111799. long last=c->lengthlist[i-1];
  111800. if(thisx>last){
  111801. for(j=last;j<thisx;j++){
  111802. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111803. count=i;
  111804. }
  111805. }
  111806. }
  111807. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111808. }else{
  111809. /* length random. Again, we don't code the codeword itself, just
  111810. the length. This time, though, we have to encode each length */
  111811. oggpack_write(opb,0,1); /* unordered */
  111812. /* algortihmic mapping has use for 'unused entries', which we tag
  111813. here. The algorithmic mapping happens as usual, but the unused
  111814. entry has no codeword. */
  111815. for(i=0;i<c->entries;i++)
  111816. if(c->lengthlist[i]==0)break;
  111817. if(i==c->entries){
  111818. oggpack_write(opb,0,1); /* no unused entries */
  111819. for(i=0;i<c->entries;i++)
  111820. oggpack_write(opb,c->lengthlist[i]-1,5);
  111821. }else{
  111822. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111823. for(i=0;i<c->entries;i++){
  111824. if(c->lengthlist[i]==0){
  111825. oggpack_write(opb,0,1);
  111826. }else{
  111827. oggpack_write(opb,1,1);
  111828. oggpack_write(opb,c->lengthlist[i]-1,5);
  111829. }
  111830. }
  111831. }
  111832. }
  111833. /* is the entry number the desired return value, or do we have a
  111834. mapping? If we have a mapping, what type? */
  111835. oggpack_write(opb,c->maptype,4);
  111836. switch(c->maptype){
  111837. case 0:
  111838. /* no mapping */
  111839. break;
  111840. case 1:case 2:
  111841. /* implicitly populated value mapping */
  111842. /* explicitly populated value mapping */
  111843. if(!c->quantlist){
  111844. /* no quantlist? error */
  111845. return(-1);
  111846. }
  111847. /* values that define the dequantization */
  111848. oggpack_write(opb,c->q_min,32);
  111849. oggpack_write(opb,c->q_delta,32);
  111850. oggpack_write(opb,c->q_quant-1,4);
  111851. oggpack_write(opb,c->q_sequencep,1);
  111852. {
  111853. int quantvals;
  111854. switch(c->maptype){
  111855. case 1:
  111856. /* a single column of (c->entries/c->dim) quantized values for
  111857. building a full value list algorithmically (square lattice) */
  111858. quantvals=_book_maptype1_quantvals(c);
  111859. break;
  111860. case 2:
  111861. /* every value (c->entries*c->dim total) specified explicitly */
  111862. quantvals=c->entries*c->dim;
  111863. break;
  111864. default: /* NOT_REACHABLE */
  111865. quantvals=-1;
  111866. }
  111867. /* quantized values */
  111868. for(i=0;i<quantvals;i++)
  111869. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111870. }
  111871. break;
  111872. default:
  111873. /* error case; we don't have any other map types now */
  111874. return(-1);
  111875. }
  111876. return(0);
  111877. }
  111878. /* unpacks a codebook from the packet buffer into the codebook struct,
  111879. readies the codebook auxiliary structures for decode *************/
  111880. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111881. long i,j;
  111882. memset(s,0,sizeof(*s));
  111883. s->allocedp=1;
  111884. /* make sure alignment is correct */
  111885. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111886. /* first the basic parameters */
  111887. s->dim=oggpack_read(opb,16);
  111888. s->entries=oggpack_read(opb,24);
  111889. if(s->entries==-1)goto _eofout;
  111890. /* codeword ordering.... length ordered or unordered? */
  111891. switch((int)oggpack_read(opb,1)){
  111892. case 0:
  111893. /* unordered */
  111894. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111895. /* allocated but unused entries? */
  111896. if(oggpack_read(opb,1)){
  111897. /* yes, unused entries */
  111898. for(i=0;i<s->entries;i++){
  111899. if(oggpack_read(opb,1)){
  111900. long num=oggpack_read(opb,5);
  111901. if(num==-1)goto _eofout;
  111902. s->lengthlist[i]=num+1;
  111903. }else
  111904. s->lengthlist[i]=0;
  111905. }
  111906. }else{
  111907. /* all entries used; no tagging */
  111908. for(i=0;i<s->entries;i++){
  111909. long num=oggpack_read(opb,5);
  111910. if(num==-1)goto _eofout;
  111911. s->lengthlist[i]=num+1;
  111912. }
  111913. }
  111914. break;
  111915. case 1:
  111916. /* ordered */
  111917. {
  111918. long length=oggpack_read(opb,5)+1;
  111919. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111920. for(i=0;i<s->entries;){
  111921. long num=oggpack_read(opb,_ilog(s->entries-i));
  111922. if(num==-1)goto _eofout;
  111923. for(j=0;j<num && i<s->entries;j++,i++)
  111924. s->lengthlist[i]=length;
  111925. length++;
  111926. }
  111927. }
  111928. break;
  111929. default:
  111930. /* EOF */
  111931. return(-1);
  111932. }
  111933. /* Do we have a mapping to unpack? */
  111934. switch((s->maptype=oggpack_read(opb,4))){
  111935. case 0:
  111936. /* no mapping */
  111937. break;
  111938. case 1: case 2:
  111939. /* implicitly populated value mapping */
  111940. /* explicitly populated value mapping */
  111941. s->q_min=oggpack_read(opb,32);
  111942. s->q_delta=oggpack_read(opb,32);
  111943. s->q_quant=oggpack_read(opb,4)+1;
  111944. s->q_sequencep=oggpack_read(opb,1);
  111945. {
  111946. int quantvals=0;
  111947. switch(s->maptype){
  111948. case 1:
  111949. quantvals=_book_maptype1_quantvals(s);
  111950. break;
  111951. case 2:
  111952. quantvals=s->entries*s->dim;
  111953. break;
  111954. }
  111955. /* quantized values */
  111956. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111957. for(i=0;i<quantvals;i++)
  111958. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111959. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111960. }
  111961. break;
  111962. default:
  111963. goto _errout;
  111964. }
  111965. /* all set */
  111966. return(0);
  111967. _errout:
  111968. _eofout:
  111969. vorbis_staticbook_clear(s);
  111970. return(-1);
  111971. }
  111972. /* returns the number of bits ************************************************/
  111973. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111974. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111975. return(book->c->lengthlist[a]);
  111976. }
  111977. /* One the encode side, our vector writers are each designed for a
  111978. specific purpose, and the encoder is not flexible without modification:
  111979. The LSP vector coder uses a single stage nearest-match with no
  111980. interleave, so no step and no error return. This is specced by floor0
  111981. and doesn't change.
  111982. Residue0 encoding interleaves, uses multiple stages, and each stage
  111983. peels of a specific amount of resolution from a lattice (thus we want
  111984. to match by threshold, not nearest match). Residue doesn't *have* to
  111985. be encoded that way, but to change it, one will need to add more
  111986. infrastructure on the encode side (decode side is specced and simpler) */
  111987. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111988. /* returns entry number and *modifies a* to the quantization value *****/
  111989. int vorbis_book_errorv(codebook *book,float *a){
  111990. int dim=book->dim,k;
  111991. int best=_best(book,a,1);
  111992. for(k=0;k<dim;k++)
  111993. a[k]=(book->valuelist+best*dim)[k];
  111994. return(best);
  111995. }
  111996. /* returns the number of bits and *modifies a* to the quantization value *****/
  111997. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111998. int k,dim=book->dim;
  111999. for(k=0;k<dim;k++)
  112000. a[k]=(book->valuelist+best*dim)[k];
  112001. return(vorbis_book_encode(book,best,b));
  112002. }
  112003. /* the 'eliminate the decode tree' optimization actually requires the
  112004. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112005. (and one of the first places where carefully thought out design
  112006. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112007. to an MSb bitpacker), but not actually the huge hit it appears to
  112008. be. The first-stage decode table catches most words so that
  112009. bitreverse is not in the main execution path. */
  112010. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112011. int read=book->dec_maxlength;
  112012. long lo,hi;
  112013. long lok = oggpack_look(b,book->dec_firsttablen);
  112014. if (lok >= 0) {
  112015. long entry = book->dec_firsttable[lok];
  112016. if(entry&0x80000000UL){
  112017. lo=(entry>>15)&0x7fff;
  112018. hi=book->used_entries-(entry&0x7fff);
  112019. }else{
  112020. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112021. return(entry-1);
  112022. }
  112023. }else{
  112024. lo=0;
  112025. hi=book->used_entries;
  112026. }
  112027. lok = oggpack_look(b, read);
  112028. while(lok<0 && read>1)
  112029. lok = oggpack_look(b, --read);
  112030. if(lok<0)return -1;
  112031. /* bisect search for the codeword in the ordered list */
  112032. {
  112033. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112034. while(hi-lo>1){
  112035. long p=(hi-lo)>>1;
  112036. long test=book->codelist[lo+p]>testword;
  112037. lo+=p&(test-1);
  112038. hi-=p&(-test);
  112039. }
  112040. if(book->dec_codelengths[lo]<=read){
  112041. oggpack_adv(b, book->dec_codelengths[lo]);
  112042. return(lo);
  112043. }
  112044. }
  112045. oggpack_adv(b, read);
  112046. return(-1);
  112047. }
  112048. /* Decode side is specced and easier, because we don't need to find
  112049. matches using different criteria; we simply read and map. There are
  112050. two things we need to do 'depending':
  112051. We may need to support interleave. We don't really, but it's
  112052. convenient to do it here rather than rebuild the vector later.
  112053. Cascades may be additive or multiplicitive; this is not inherent in
  112054. the codebook, but set in the code using the codebook. Like
  112055. interleaving, it's easiest to do it here.
  112056. addmul==0 -> declarative (set the value)
  112057. addmul==1 -> additive
  112058. addmul==2 -> multiplicitive */
  112059. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112060. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112061. long packed_entry=decode_packed_entry_number(book,b);
  112062. if(packed_entry>=0)
  112063. return(book->dec_index[packed_entry]);
  112064. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112065. return(packed_entry);
  112066. }
  112067. /* returns 0 on OK or -1 on eof *************************************/
  112068. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112069. int step=n/book->dim;
  112070. long *entry = (long*)alloca(sizeof(*entry)*step);
  112071. float **t = (float**)alloca(sizeof(*t)*step);
  112072. int i,j,o;
  112073. for (i = 0; i < step; i++) {
  112074. entry[i]=decode_packed_entry_number(book,b);
  112075. if(entry[i]==-1)return(-1);
  112076. t[i] = book->valuelist+entry[i]*book->dim;
  112077. }
  112078. for(i=0,o=0;i<book->dim;i++,o+=step)
  112079. for (j=0;j<step;j++)
  112080. a[o+j]+=t[j][i];
  112081. return(0);
  112082. }
  112083. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112084. int i,j,entry;
  112085. float *t;
  112086. if(book->dim>8){
  112087. for(i=0;i<n;){
  112088. entry = decode_packed_entry_number(book,b);
  112089. if(entry==-1)return(-1);
  112090. t = book->valuelist+entry*book->dim;
  112091. for (j=0;j<book->dim;)
  112092. a[i++]+=t[j++];
  112093. }
  112094. }else{
  112095. for(i=0;i<n;){
  112096. entry = decode_packed_entry_number(book,b);
  112097. if(entry==-1)return(-1);
  112098. t = book->valuelist+entry*book->dim;
  112099. j=0;
  112100. switch((int)book->dim){
  112101. case 8:
  112102. a[i++]+=t[j++];
  112103. case 7:
  112104. a[i++]+=t[j++];
  112105. case 6:
  112106. a[i++]+=t[j++];
  112107. case 5:
  112108. a[i++]+=t[j++];
  112109. case 4:
  112110. a[i++]+=t[j++];
  112111. case 3:
  112112. a[i++]+=t[j++];
  112113. case 2:
  112114. a[i++]+=t[j++];
  112115. case 1:
  112116. a[i++]+=t[j++];
  112117. case 0:
  112118. break;
  112119. }
  112120. }
  112121. }
  112122. return(0);
  112123. }
  112124. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112125. int i,j,entry;
  112126. float *t;
  112127. for(i=0;i<n;){
  112128. entry = decode_packed_entry_number(book,b);
  112129. if(entry==-1)return(-1);
  112130. t = book->valuelist+entry*book->dim;
  112131. for (j=0;j<book->dim;)
  112132. a[i++]=t[j++];
  112133. }
  112134. return(0);
  112135. }
  112136. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112137. oggpack_buffer *b,int n){
  112138. long i,j,entry;
  112139. int chptr=0;
  112140. for(i=offset/ch;i<(offset+n)/ch;){
  112141. entry = decode_packed_entry_number(book,b);
  112142. if(entry==-1)return(-1);
  112143. {
  112144. const float *t = book->valuelist+entry*book->dim;
  112145. for (j=0;j<book->dim;j++){
  112146. a[chptr++][i]+=t[j];
  112147. if(chptr==ch){
  112148. chptr=0;
  112149. i++;
  112150. }
  112151. }
  112152. }
  112153. }
  112154. return(0);
  112155. }
  112156. #ifdef _V_SELFTEST
  112157. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112158. number of vectors through (keeping track of the quantized values),
  112159. and decode using the unpacked book. quantized version of in should
  112160. exactly equal out */
  112161. #include <stdio.h>
  112162. #include "vorbis/book/lsp20_0.vqh"
  112163. #include "vorbis/book/res0a_13.vqh"
  112164. #define TESTSIZE 40
  112165. float test1[TESTSIZE]={
  112166. 0.105939f,
  112167. 0.215373f,
  112168. 0.429117f,
  112169. 0.587974f,
  112170. 0.181173f,
  112171. 0.296583f,
  112172. 0.515707f,
  112173. 0.715261f,
  112174. 0.162327f,
  112175. 0.263834f,
  112176. 0.342876f,
  112177. 0.406025f,
  112178. 0.103571f,
  112179. 0.223561f,
  112180. 0.368513f,
  112181. 0.540313f,
  112182. 0.136672f,
  112183. 0.395882f,
  112184. 0.587183f,
  112185. 0.652476f,
  112186. 0.114338f,
  112187. 0.417300f,
  112188. 0.525486f,
  112189. 0.698679f,
  112190. 0.147492f,
  112191. 0.324481f,
  112192. 0.643089f,
  112193. 0.757582f,
  112194. 0.139556f,
  112195. 0.215795f,
  112196. 0.324559f,
  112197. 0.399387f,
  112198. 0.120236f,
  112199. 0.267420f,
  112200. 0.446940f,
  112201. 0.608760f,
  112202. 0.115587f,
  112203. 0.287234f,
  112204. 0.571081f,
  112205. 0.708603f,
  112206. };
  112207. float test3[TESTSIZE]={
  112208. 0,1,-2,3,4,-5,6,7,8,9,
  112209. 8,-2,7,-1,4,6,8,3,1,-9,
  112210. 10,11,12,13,14,15,26,17,18,19,
  112211. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112212. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112213. &_vq_book_res0a_13,NULL};
  112214. float *testvec[]={test1,test3};
  112215. int main(){
  112216. oggpack_buffer write;
  112217. oggpack_buffer read;
  112218. long ptr=0,i;
  112219. oggpack_writeinit(&write);
  112220. fprintf(stderr,"Testing codebook abstraction...:\n");
  112221. while(testlist[ptr]){
  112222. codebook c;
  112223. static_codebook s;
  112224. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112225. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112226. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112227. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112228. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112229. /* pack the codebook, write the testvector */
  112230. oggpack_reset(&write);
  112231. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112232. we can write */
  112233. vorbis_staticbook_pack(testlist[ptr],&write);
  112234. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112235. for(i=0;i<TESTSIZE;i+=c.dim){
  112236. int best=_best(&c,qv+i,1);
  112237. vorbis_book_encodev(&c,best,qv+i,&write);
  112238. }
  112239. vorbis_book_clear(&c);
  112240. fprintf(stderr,"OK.\n");
  112241. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112242. /* transfer the write data to a read buffer and unpack/read */
  112243. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112244. if(vorbis_staticbook_unpack(&read,&s)){
  112245. fprintf(stderr,"Error unpacking codebook.\n");
  112246. exit(1);
  112247. }
  112248. if(vorbis_book_init_decode(&c,&s)){
  112249. fprintf(stderr,"Error initializing codebook.\n");
  112250. exit(1);
  112251. }
  112252. for(i=0;i<TESTSIZE;i+=c.dim)
  112253. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112254. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112255. exit(1);
  112256. }
  112257. for(i=0;i<TESTSIZE;i++)
  112258. if(fabs(qv[i]-iv[i])>.000001){
  112259. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112260. iv[i],qv[i],i);
  112261. exit(1);
  112262. }
  112263. fprintf(stderr,"OK\n");
  112264. ptr++;
  112265. }
  112266. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112267. exit(0);
  112268. }
  112269. #endif
  112270. #endif
  112271. /*** End of inlined file: codebook.c ***/
  112272. /*** Start of inlined file: envelope.c ***/
  112273. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112274. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112275. // tasks..
  112276. #if JUCE_MSVC
  112277. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112278. #endif
  112279. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112280. #if JUCE_USE_OGGVORBIS
  112281. #include <stdlib.h>
  112282. #include <string.h>
  112283. #include <stdio.h>
  112284. #include <math.h>
  112285. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112286. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112287. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112288. int ch=vi->channels;
  112289. int i,j;
  112290. int n=e->winlength=128;
  112291. e->searchstep=64; /* not random */
  112292. e->minenergy=gi->preecho_minenergy;
  112293. e->ch=ch;
  112294. e->storage=128;
  112295. e->cursor=ci->blocksizes[1]/2;
  112296. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112297. mdct_init(&e->mdct,n);
  112298. for(i=0;i<n;i++){
  112299. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112300. e->mdct_win[i]*=e->mdct_win[i];
  112301. }
  112302. /* magic follows */
  112303. e->band[0].begin=2; e->band[0].end=4;
  112304. e->band[1].begin=4; e->band[1].end=5;
  112305. e->band[2].begin=6; e->band[2].end=6;
  112306. e->band[3].begin=9; e->band[3].end=8;
  112307. e->band[4].begin=13; e->band[4].end=8;
  112308. e->band[5].begin=17; e->band[5].end=8;
  112309. e->band[6].begin=22; e->band[6].end=8;
  112310. for(j=0;j<VE_BANDS;j++){
  112311. n=e->band[j].end;
  112312. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112313. for(i=0;i<n;i++){
  112314. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112315. e->band[j].total+=e->band[j].window[i];
  112316. }
  112317. e->band[j].total=1./e->band[j].total;
  112318. }
  112319. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112320. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112321. }
  112322. void _ve_envelope_clear(envelope_lookup *e){
  112323. int i;
  112324. mdct_clear(&e->mdct);
  112325. for(i=0;i<VE_BANDS;i++)
  112326. _ogg_free(e->band[i].window);
  112327. _ogg_free(e->mdct_win);
  112328. _ogg_free(e->filter);
  112329. _ogg_free(e->mark);
  112330. memset(e,0,sizeof(*e));
  112331. }
  112332. /* fairly straight threshhold-by-band based until we find something
  112333. that works better and isn't patented. */
  112334. static int _ve_amp(envelope_lookup *ve,
  112335. vorbis_info_psy_global *gi,
  112336. float *data,
  112337. envelope_band *bands,
  112338. envelope_filter_state *filters,
  112339. long pos){
  112340. long n=ve->winlength;
  112341. int ret=0;
  112342. long i,j;
  112343. float decay;
  112344. /* we want to have a 'minimum bar' for energy, else we're just
  112345. basing blocks on quantization noise that outweighs the signal
  112346. itself (for low power signals) */
  112347. float minV=ve->minenergy;
  112348. float *vec=(float*) alloca(n*sizeof(*vec));
  112349. /* stretch is used to gradually lengthen the number of windows
  112350. considered prevoius-to-potential-trigger */
  112351. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112352. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112353. if(penalty<0.f)penalty=0.f;
  112354. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112355. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112356. totalshift+pos*ve->searchstep);*/
  112357. /* window and transform */
  112358. for(i=0;i<n;i++)
  112359. vec[i]=data[i]*ve->mdct_win[i];
  112360. mdct_forward(&ve->mdct,vec,vec);
  112361. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112362. /* near-DC spreading function; this has nothing to do with
  112363. psychoacoustics, just sidelobe leakage and window size */
  112364. {
  112365. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112366. int ptr=filters->nearptr;
  112367. /* the accumulation is regularly refreshed from scratch to avoid
  112368. floating point creep */
  112369. if(ptr==0){
  112370. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112371. filters->nearDC_partialacc=temp;
  112372. }else{
  112373. decay=filters->nearDC_acc+=temp;
  112374. filters->nearDC_partialacc+=temp;
  112375. }
  112376. filters->nearDC_acc-=filters->nearDC[ptr];
  112377. filters->nearDC[ptr]=temp;
  112378. decay*=(1./(VE_NEARDC+1));
  112379. filters->nearptr++;
  112380. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112381. decay=todB(&decay)*.5-15.f;
  112382. }
  112383. /* perform spreading and limiting, also smooth the spectrum. yes,
  112384. the MDCT results in all real coefficients, but it still *behaves*
  112385. like real/imaginary pairs */
  112386. for(i=0;i<n/2;i+=2){
  112387. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112388. val=todB(&val)*.5f;
  112389. if(val<decay)val=decay;
  112390. if(val<minV)val=minV;
  112391. vec[i>>1]=val;
  112392. decay-=8.;
  112393. }
  112394. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112395. /* perform preecho/postecho triggering by band */
  112396. for(j=0;j<VE_BANDS;j++){
  112397. float acc=0.;
  112398. float valmax,valmin;
  112399. /* accumulate amplitude */
  112400. for(i=0;i<bands[j].end;i++)
  112401. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112402. acc*=bands[j].total;
  112403. /* convert amplitude to delta */
  112404. {
  112405. int p,thisx=filters[j].ampptr;
  112406. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112407. p=thisx;
  112408. p--;
  112409. if(p<0)p+=VE_AMP;
  112410. postmax=max(acc,filters[j].ampbuf[p]);
  112411. postmin=min(acc,filters[j].ampbuf[p]);
  112412. for(i=0;i<stretch;i++){
  112413. p--;
  112414. if(p<0)p+=VE_AMP;
  112415. premax=max(premax,filters[j].ampbuf[p]);
  112416. premin=min(premin,filters[j].ampbuf[p]);
  112417. }
  112418. valmin=postmin-premin;
  112419. valmax=postmax-premax;
  112420. /*filters[j].markers[pos]=valmax;*/
  112421. filters[j].ampbuf[thisx]=acc;
  112422. filters[j].ampptr++;
  112423. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112424. }
  112425. /* look at min/max, decide trigger */
  112426. if(valmax>gi->preecho_thresh[j]+penalty){
  112427. ret|=1;
  112428. ret|=4;
  112429. }
  112430. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112431. }
  112432. return(ret);
  112433. }
  112434. #if 0
  112435. static int seq=0;
  112436. static ogg_int64_t totalshift=-1024;
  112437. #endif
  112438. long _ve_envelope_search(vorbis_dsp_state *v){
  112439. vorbis_info *vi=v->vi;
  112440. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112441. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112442. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112443. long i,j;
  112444. int first=ve->current/ve->searchstep;
  112445. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112446. if(first<0)first=0;
  112447. /* make sure we have enough storage to match the PCM */
  112448. if(last+VE_WIN+VE_POST>ve->storage){
  112449. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112450. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112451. }
  112452. for(j=first;j<last;j++){
  112453. int ret=0;
  112454. ve->stretch++;
  112455. if(ve->stretch>VE_MAXSTRETCH*2)
  112456. ve->stretch=VE_MAXSTRETCH*2;
  112457. for(i=0;i<ve->ch;i++){
  112458. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112459. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112460. }
  112461. ve->mark[j+VE_POST]=0;
  112462. if(ret&1){
  112463. ve->mark[j]=1;
  112464. ve->mark[j+1]=1;
  112465. }
  112466. if(ret&2){
  112467. ve->mark[j]=1;
  112468. if(j>0)ve->mark[j-1]=1;
  112469. }
  112470. if(ret&4)ve->stretch=-1;
  112471. }
  112472. ve->current=last*ve->searchstep;
  112473. {
  112474. long centerW=v->centerW;
  112475. long testW=
  112476. centerW+
  112477. ci->blocksizes[v->W]/4+
  112478. ci->blocksizes[1]/2+
  112479. ci->blocksizes[0]/4;
  112480. j=ve->cursor;
  112481. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112482. working back one window */
  112483. if(j>=testW)return(1);
  112484. ve->cursor=j;
  112485. if(ve->mark[j/ve->searchstep]){
  112486. if(j>centerW){
  112487. #if 0
  112488. if(j>ve->curmark){
  112489. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112490. int l,m;
  112491. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112492. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112493. seq,
  112494. (totalshift+ve->cursor)/44100.,
  112495. (totalshift+j)/44100.);
  112496. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112497. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112498. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112499. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112500. for(m=0;m<VE_BANDS;m++){
  112501. char buf[80];
  112502. sprintf(buf,"delL%d",m);
  112503. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112504. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112505. }
  112506. for(m=0;m<VE_BANDS;m++){
  112507. char buf[80];
  112508. sprintf(buf,"delR%d",m);
  112509. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112510. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112511. }
  112512. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112513. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112514. seq++;
  112515. }
  112516. #endif
  112517. ve->curmark=j;
  112518. if(j>=testW)return(1);
  112519. return(0);
  112520. }
  112521. }
  112522. j+=ve->searchstep;
  112523. }
  112524. }
  112525. return(-1);
  112526. }
  112527. int _ve_envelope_mark(vorbis_dsp_state *v){
  112528. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112529. vorbis_info *vi=v->vi;
  112530. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112531. long centerW=v->centerW;
  112532. long beginW=centerW-ci->blocksizes[v->W]/4;
  112533. long endW=centerW+ci->blocksizes[v->W]/4;
  112534. if(v->W){
  112535. beginW-=ci->blocksizes[v->lW]/4;
  112536. endW+=ci->blocksizes[v->nW]/4;
  112537. }else{
  112538. beginW-=ci->blocksizes[0]/4;
  112539. endW+=ci->blocksizes[0]/4;
  112540. }
  112541. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112542. {
  112543. long first=beginW/ve->searchstep;
  112544. long last=endW/ve->searchstep;
  112545. long i;
  112546. for(i=first;i<last;i++)
  112547. if(ve->mark[i])return(1);
  112548. }
  112549. return(0);
  112550. }
  112551. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112552. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112553. ahead of ve->current */
  112554. int smallshift=shift/e->searchstep;
  112555. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112556. #if 0
  112557. for(i=0;i<VE_BANDS*e->ch;i++)
  112558. memmove(e->filter[i].markers,
  112559. e->filter[i].markers+smallshift,
  112560. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112561. totalshift+=shift;
  112562. #endif
  112563. e->current-=shift;
  112564. if(e->curmark>=0)
  112565. e->curmark-=shift;
  112566. e->cursor-=shift;
  112567. }
  112568. #endif
  112569. /*** End of inlined file: envelope.c ***/
  112570. /*** Start of inlined file: floor0.c ***/
  112571. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112572. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112573. // tasks..
  112574. #if JUCE_MSVC
  112575. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112576. #endif
  112577. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112578. #if JUCE_USE_OGGVORBIS
  112579. #include <stdlib.h>
  112580. #include <string.h>
  112581. #include <math.h>
  112582. /*** Start of inlined file: lsp.h ***/
  112583. #ifndef _V_LSP_H_
  112584. #define _V_LSP_H_
  112585. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112586. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112587. float *lsp,int m,
  112588. float amp,float ampoffset);
  112589. #endif
  112590. /*** End of inlined file: lsp.h ***/
  112591. #include <stdio.h>
  112592. typedef struct {
  112593. int ln;
  112594. int m;
  112595. int **linearmap;
  112596. int n[2];
  112597. vorbis_info_floor0 *vi;
  112598. long bits;
  112599. long frames;
  112600. } vorbis_look_floor0;
  112601. /***********************************************/
  112602. static void floor0_free_info(vorbis_info_floor *i){
  112603. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112604. if(info){
  112605. memset(info,0,sizeof(*info));
  112606. _ogg_free(info);
  112607. }
  112608. }
  112609. static void floor0_free_look(vorbis_look_floor *i){
  112610. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112611. if(look){
  112612. if(look->linearmap){
  112613. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112614. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112615. _ogg_free(look->linearmap);
  112616. }
  112617. memset(look,0,sizeof(*look));
  112618. _ogg_free(look);
  112619. }
  112620. }
  112621. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112622. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112623. int j;
  112624. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112625. info->order=oggpack_read(opb,8);
  112626. info->rate=oggpack_read(opb,16);
  112627. info->barkmap=oggpack_read(opb,16);
  112628. info->ampbits=oggpack_read(opb,6);
  112629. info->ampdB=oggpack_read(opb,8);
  112630. info->numbooks=oggpack_read(opb,4)+1;
  112631. if(info->order<1)goto err_out;
  112632. if(info->rate<1)goto err_out;
  112633. if(info->barkmap<1)goto err_out;
  112634. if(info->numbooks<1)goto err_out;
  112635. for(j=0;j<info->numbooks;j++){
  112636. info->books[j]=oggpack_read(opb,8);
  112637. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112638. }
  112639. return(info);
  112640. err_out:
  112641. floor0_free_info(info);
  112642. return(NULL);
  112643. }
  112644. /* initialize Bark scale and normalization lookups. We could do this
  112645. with static tables, but Vorbis allows a number of possible
  112646. combinations, so it's best to do it computationally.
  112647. The below is authoritative in terms of defining scale mapping.
  112648. Note that the scale depends on the sampling rate as well as the
  112649. linear block and mapping sizes */
  112650. static void floor0_map_lazy_init(vorbis_block *vb,
  112651. vorbis_info_floor *infoX,
  112652. vorbis_look_floor0 *look){
  112653. if(!look->linearmap[vb->W]){
  112654. vorbis_dsp_state *vd=vb->vd;
  112655. vorbis_info *vi=vd->vi;
  112656. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112657. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112658. int W=vb->W;
  112659. int n=ci->blocksizes[W]/2,j;
  112660. /* we choose a scaling constant so that:
  112661. floor(bark(rate/2-1)*C)=mapped-1
  112662. floor(bark(rate/2)*C)=mapped */
  112663. float scale=look->ln/toBARK(info->rate/2.f);
  112664. /* the mapping from a linear scale to a smaller bark scale is
  112665. straightforward. We do *not* make sure that the linear mapping
  112666. does not skip bark-scale bins; the decoder simply skips them and
  112667. the encoder may do what it wishes in filling them. They're
  112668. necessary in some mapping combinations to keep the scale spacing
  112669. accurate */
  112670. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112671. for(j=0;j<n;j++){
  112672. int val=floor( toBARK((info->rate/2.f)/n*j)
  112673. *scale); /* bark numbers represent band edges */
  112674. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112675. look->linearmap[W][j]=val;
  112676. }
  112677. look->linearmap[W][j]=-1;
  112678. look->n[W]=n;
  112679. }
  112680. }
  112681. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112682. vorbis_info_floor *i){
  112683. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112684. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112685. look->m=info->order;
  112686. look->ln=info->barkmap;
  112687. look->vi=info;
  112688. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112689. return look;
  112690. }
  112691. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112692. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112693. vorbis_info_floor0 *info=look->vi;
  112694. int j,k;
  112695. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112696. if(ampraw>0){ /* also handles the -1 out of data case */
  112697. long maxval=(1<<info->ampbits)-1;
  112698. float amp=(float)ampraw/maxval*info->ampdB;
  112699. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112700. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112701. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112702. codebook *b=ci->fullbooks+info->books[booknum];
  112703. float last=0.f;
  112704. /* the additional b->dim is a guard against any possible stack
  112705. smash; b->dim is provably more than we can overflow the
  112706. vector */
  112707. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112708. for(j=0;j<look->m;j+=b->dim)
  112709. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112710. for(j=0;j<look->m;){
  112711. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112712. last=lsp[j-1];
  112713. }
  112714. lsp[look->m]=amp;
  112715. return(lsp);
  112716. }
  112717. }
  112718. eop:
  112719. return(NULL);
  112720. }
  112721. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112722. void *memo,float *out){
  112723. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112724. vorbis_info_floor0 *info=look->vi;
  112725. floor0_map_lazy_init(vb,info,look);
  112726. if(memo){
  112727. float *lsp=(float *)memo;
  112728. float amp=lsp[look->m];
  112729. /* take the coefficients back to a spectral envelope curve */
  112730. vorbis_lsp_to_curve(out,
  112731. look->linearmap[vb->W],
  112732. look->n[vb->W],
  112733. look->ln,
  112734. lsp,look->m,amp,(float)info->ampdB);
  112735. return(1);
  112736. }
  112737. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112738. return(0);
  112739. }
  112740. /* export hooks */
  112741. vorbis_func_floor floor0_exportbundle={
  112742. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112743. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112744. };
  112745. #endif
  112746. /*** End of inlined file: floor0.c ***/
  112747. /*** Start of inlined file: floor1.c ***/
  112748. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112749. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112750. // tasks..
  112751. #if JUCE_MSVC
  112752. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112753. #endif
  112754. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112755. #if JUCE_USE_OGGVORBIS
  112756. #include <stdlib.h>
  112757. #include <string.h>
  112758. #include <math.h>
  112759. #include <stdio.h>
  112760. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112761. typedef struct {
  112762. int sorted_index[VIF_POSIT+2];
  112763. int forward_index[VIF_POSIT+2];
  112764. int reverse_index[VIF_POSIT+2];
  112765. int hineighbor[VIF_POSIT];
  112766. int loneighbor[VIF_POSIT];
  112767. int posts;
  112768. int n;
  112769. int quant_q;
  112770. vorbis_info_floor1 *vi;
  112771. long phrasebits;
  112772. long postbits;
  112773. long frames;
  112774. } vorbis_look_floor1;
  112775. typedef struct lsfit_acc{
  112776. long x0;
  112777. long x1;
  112778. long xa;
  112779. long ya;
  112780. long x2a;
  112781. long y2a;
  112782. long xya;
  112783. long an;
  112784. } lsfit_acc;
  112785. /***********************************************/
  112786. static void floor1_free_info(vorbis_info_floor *i){
  112787. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112788. if(info){
  112789. memset(info,0,sizeof(*info));
  112790. _ogg_free(info);
  112791. }
  112792. }
  112793. static void floor1_free_look(vorbis_look_floor *i){
  112794. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112795. if(look){
  112796. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112797. (float)look->phrasebits/look->frames,
  112798. (float)look->postbits/look->frames,
  112799. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112800. memset(look,0,sizeof(*look));
  112801. _ogg_free(look);
  112802. }
  112803. }
  112804. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112805. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112806. int j,k;
  112807. int count=0;
  112808. int rangebits;
  112809. int maxposit=info->postlist[1];
  112810. int maxclass=-1;
  112811. /* save out partitions */
  112812. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112813. for(j=0;j<info->partitions;j++){
  112814. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112815. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112816. }
  112817. /* save out partition classes */
  112818. for(j=0;j<maxclass+1;j++){
  112819. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112820. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112821. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112822. for(k=0;k<(1<<info->class_subs[j]);k++)
  112823. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112824. }
  112825. /* save out the post list */
  112826. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112827. oggpack_write(opb,ilog2(maxposit),4);
  112828. rangebits=ilog2(maxposit);
  112829. for(j=0,k=0;j<info->partitions;j++){
  112830. count+=info->class_dim[info->partitionclass[j]];
  112831. for(;k<count;k++)
  112832. oggpack_write(opb,info->postlist[k+2],rangebits);
  112833. }
  112834. }
  112835. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112836. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112837. int j,k,count=0,maxclass=-1,rangebits;
  112838. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112839. /* read partitions */
  112840. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112841. for(j=0;j<info->partitions;j++){
  112842. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112843. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112844. }
  112845. /* read partition classes */
  112846. for(j=0;j<maxclass+1;j++){
  112847. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112848. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112849. if(info->class_subs[j]<0)
  112850. goto err_out;
  112851. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112852. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112853. goto err_out;
  112854. for(k=0;k<(1<<info->class_subs[j]);k++){
  112855. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112856. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112857. goto err_out;
  112858. }
  112859. }
  112860. /* read the post list */
  112861. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112862. rangebits=oggpack_read(opb,4);
  112863. for(j=0,k=0;j<info->partitions;j++){
  112864. count+=info->class_dim[info->partitionclass[j]];
  112865. for(;k<count;k++){
  112866. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112867. if(t<0 || t>=(1<<rangebits))
  112868. goto err_out;
  112869. }
  112870. }
  112871. info->postlist[0]=0;
  112872. info->postlist[1]=1<<rangebits;
  112873. return(info);
  112874. err_out:
  112875. floor1_free_info(info);
  112876. return(NULL);
  112877. }
  112878. static int JUCE_CDECL icomp(const void *a,const void *b){
  112879. return(**(int **)a-**(int **)b);
  112880. }
  112881. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112882. vorbis_info_floor *in){
  112883. int *sortpointer[VIF_POSIT+2];
  112884. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112885. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112886. int i,j,n=0;
  112887. look->vi=info;
  112888. look->n=info->postlist[1];
  112889. /* we drop each position value in-between already decoded values,
  112890. and use linear interpolation to predict each new value past the
  112891. edges. The positions are read in the order of the position
  112892. list... we precompute the bounding positions in the lookup. Of
  112893. course, the neighbors can change (if a position is declined), but
  112894. this is an initial mapping */
  112895. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112896. n+=2;
  112897. look->posts=n;
  112898. /* also store a sorted position index */
  112899. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112900. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112901. /* points from sort order back to range number */
  112902. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112903. /* points from range order to sorted position */
  112904. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112905. /* we actually need the post values too */
  112906. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112907. /* quantize values to multiplier spec */
  112908. switch(info->mult){
  112909. case 1: /* 1024 -> 256 */
  112910. look->quant_q=256;
  112911. break;
  112912. case 2: /* 1024 -> 128 */
  112913. look->quant_q=128;
  112914. break;
  112915. case 3: /* 1024 -> 86 */
  112916. look->quant_q=86;
  112917. break;
  112918. case 4: /* 1024 -> 64 */
  112919. look->quant_q=64;
  112920. break;
  112921. }
  112922. /* discover our neighbors for decode where we don't use fit flags
  112923. (that would push the neighbors outward) */
  112924. for(i=0;i<n-2;i++){
  112925. int lo=0;
  112926. int hi=1;
  112927. int lx=0;
  112928. int hx=look->n;
  112929. int currentx=info->postlist[i+2];
  112930. for(j=0;j<i+2;j++){
  112931. int x=info->postlist[j];
  112932. if(x>lx && x<currentx){
  112933. lo=j;
  112934. lx=x;
  112935. }
  112936. if(x<hx && x>currentx){
  112937. hi=j;
  112938. hx=x;
  112939. }
  112940. }
  112941. look->loneighbor[i]=lo;
  112942. look->hineighbor[i]=hi;
  112943. }
  112944. return(look);
  112945. }
  112946. static int render_point(int x0,int x1,int y0,int y1,int x){
  112947. y0&=0x7fff; /* mask off flag */
  112948. y1&=0x7fff;
  112949. {
  112950. int dy=y1-y0;
  112951. int adx=x1-x0;
  112952. int ady=abs(dy);
  112953. int err=ady*(x-x0);
  112954. int off=err/adx;
  112955. if(dy<0)return(y0-off);
  112956. return(y0+off);
  112957. }
  112958. }
  112959. static int vorbis_dBquant(const float *x){
  112960. int i= *x*7.3142857f+1023.5f;
  112961. if(i>1023)return(1023);
  112962. if(i<0)return(0);
  112963. return i;
  112964. }
  112965. static float FLOOR1_fromdB_LOOKUP[256]={
  112966. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112967. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112968. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112969. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112970. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112971. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112972. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112973. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112974. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112975. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112976. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112977. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112978. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112979. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112980. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112981. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112982. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112983. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112984. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112985. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112986. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112987. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112988. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112989. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112990. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112991. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112992. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112993. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112994. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112995. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112996. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112997. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112998. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112999. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113000. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113001. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113002. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113003. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113004. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113005. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113006. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113007. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113008. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113009. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113010. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113011. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113012. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113013. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113014. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113015. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113016. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113017. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113018. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113019. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113020. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113021. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113022. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113023. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113024. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113025. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113026. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113027. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113028. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113029. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113030. };
  113031. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113032. int dy=y1-y0;
  113033. int adx=x1-x0;
  113034. int ady=abs(dy);
  113035. int base=dy/adx;
  113036. int sy=(dy<0?base-1:base+1);
  113037. int x=x0;
  113038. int y=y0;
  113039. int err=0;
  113040. ady-=abs(base*adx);
  113041. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113042. while(++x<x1){
  113043. err=err+ady;
  113044. if(err>=adx){
  113045. err-=adx;
  113046. y+=sy;
  113047. }else{
  113048. y+=base;
  113049. }
  113050. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113051. }
  113052. }
  113053. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113054. int dy=y1-y0;
  113055. int adx=x1-x0;
  113056. int ady=abs(dy);
  113057. int base=dy/adx;
  113058. int sy=(dy<0?base-1:base+1);
  113059. int x=x0;
  113060. int y=y0;
  113061. int err=0;
  113062. ady-=abs(base*adx);
  113063. d[x]=y;
  113064. while(++x<x1){
  113065. err=err+ady;
  113066. if(err>=adx){
  113067. err-=adx;
  113068. y+=sy;
  113069. }else{
  113070. y+=base;
  113071. }
  113072. d[x]=y;
  113073. }
  113074. }
  113075. /* the floor has already been filtered to only include relevant sections */
  113076. static int accumulate_fit(const float *flr,const float *mdct,
  113077. int x0, int x1,lsfit_acc *a,
  113078. int n,vorbis_info_floor1 *info){
  113079. long i;
  113080. 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;
  113081. memset(a,0,sizeof(*a));
  113082. a->x0=x0;
  113083. a->x1=x1;
  113084. if(x1>=n)x1=n-1;
  113085. for(i=x0;i<=x1;i++){
  113086. int quantized=vorbis_dBquant(flr+i);
  113087. if(quantized){
  113088. if(mdct[i]+info->twofitatten>=flr[i]){
  113089. xa += i;
  113090. ya += quantized;
  113091. x2a += i*i;
  113092. y2a += quantized*quantized;
  113093. xya += i*quantized;
  113094. na++;
  113095. }else{
  113096. xb += i;
  113097. yb += quantized;
  113098. x2b += i*i;
  113099. y2b += quantized*quantized;
  113100. xyb += i*quantized;
  113101. nb++;
  113102. }
  113103. }
  113104. }
  113105. xb+=xa;
  113106. yb+=ya;
  113107. x2b+=x2a;
  113108. y2b+=y2a;
  113109. xyb+=xya;
  113110. nb+=na;
  113111. /* weight toward the actually used frequencies if we meet the threshhold */
  113112. {
  113113. int weight=nb*info->twofitweight/(na+1);
  113114. a->xa=xa*weight+xb;
  113115. a->ya=ya*weight+yb;
  113116. a->x2a=x2a*weight+x2b;
  113117. a->y2a=y2a*weight+y2b;
  113118. a->xya=xya*weight+xyb;
  113119. a->an=na*weight+nb;
  113120. }
  113121. return(na);
  113122. }
  113123. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113124. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113125. long x0=a[0].x0;
  113126. long x1=a[fits-1].x1;
  113127. for(i=0;i<fits;i++){
  113128. x+=a[i].xa;
  113129. y+=a[i].ya;
  113130. x2+=a[i].x2a;
  113131. y2+=a[i].y2a;
  113132. xy+=a[i].xya;
  113133. an+=a[i].an;
  113134. }
  113135. if(*y0>=0){
  113136. x+= x0;
  113137. y+= *y0;
  113138. x2+= x0 * x0;
  113139. y2+= *y0 * *y0;
  113140. xy+= *y0 * x0;
  113141. an++;
  113142. }
  113143. if(*y1>=0){
  113144. x+= x1;
  113145. y+= *y1;
  113146. x2+= x1 * x1;
  113147. y2+= *y1 * *y1;
  113148. xy+= *y1 * x1;
  113149. an++;
  113150. }
  113151. if(an){
  113152. /* need 64 bit multiplies, which C doesn't give portably as int */
  113153. double fx=x;
  113154. double fy=y;
  113155. double fx2=x2;
  113156. double fxy=xy;
  113157. double denom=1./(an*fx2-fx*fx);
  113158. double a=(fy*fx2-fxy*fx)*denom;
  113159. double b=(an*fxy-fx*fy)*denom;
  113160. *y0=rint(a+b*x0);
  113161. *y1=rint(a+b*x1);
  113162. /* limit to our range! */
  113163. if(*y0>1023)*y0=1023;
  113164. if(*y1>1023)*y1=1023;
  113165. if(*y0<0)*y0=0;
  113166. if(*y1<0)*y1=0;
  113167. }else{
  113168. *y0=0;
  113169. *y1=0;
  113170. }
  113171. }
  113172. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113173. long y=0;
  113174. int i;
  113175. for(i=0;i<fits && y==0;i++)
  113176. y+=a[i].ya;
  113177. *y0=*y1=y;
  113178. }*/
  113179. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113180. const float *mdct,
  113181. vorbis_info_floor1 *info){
  113182. int dy=y1-y0;
  113183. int adx=x1-x0;
  113184. int ady=abs(dy);
  113185. int base=dy/adx;
  113186. int sy=(dy<0?base-1:base+1);
  113187. int x=x0;
  113188. int y=y0;
  113189. int err=0;
  113190. int val=vorbis_dBquant(mask+x);
  113191. int mse=0;
  113192. int n=0;
  113193. ady-=abs(base*adx);
  113194. mse=(y-val);
  113195. mse*=mse;
  113196. n++;
  113197. if(mdct[x]+info->twofitatten>=mask[x]){
  113198. if(y+info->maxover<val)return(1);
  113199. if(y-info->maxunder>val)return(1);
  113200. }
  113201. while(++x<x1){
  113202. err=err+ady;
  113203. if(err>=adx){
  113204. err-=adx;
  113205. y+=sy;
  113206. }else{
  113207. y+=base;
  113208. }
  113209. val=vorbis_dBquant(mask+x);
  113210. mse+=((y-val)*(y-val));
  113211. n++;
  113212. if(mdct[x]+info->twofitatten>=mask[x]){
  113213. if(val){
  113214. if(y+info->maxover<val)return(1);
  113215. if(y-info->maxunder>val)return(1);
  113216. }
  113217. }
  113218. }
  113219. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113220. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113221. if(mse/n>info->maxerr)return(1);
  113222. return(0);
  113223. }
  113224. static int post_Y(int *A,int *B,int pos){
  113225. if(A[pos]<0)
  113226. return B[pos];
  113227. if(B[pos]<0)
  113228. return A[pos];
  113229. return (A[pos]+B[pos])>>1;
  113230. }
  113231. int *floor1_fit(vorbis_block *vb,void *look_,
  113232. const float *logmdct, /* in */
  113233. const float *logmask){
  113234. long i,j;
  113235. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113236. vorbis_info_floor1 *info=look->vi;
  113237. long n=look->n;
  113238. long posts=look->posts;
  113239. long nonzero=0;
  113240. lsfit_acc fits[VIF_POSIT+1];
  113241. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113242. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113243. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113244. int hineighbor[VIF_POSIT+2];
  113245. int *output=NULL;
  113246. int memo[VIF_POSIT+2];
  113247. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113248. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113249. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113250. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113251. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113252. /* quantize the relevant floor points and collect them into line fit
  113253. structures (one per minimal division) at the same time */
  113254. if(posts==0){
  113255. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113256. }else{
  113257. for(i=0;i<posts-1;i++)
  113258. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113259. look->sorted_index[i+1],fits+i,
  113260. n,info);
  113261. }
  113262. if(nonzero){
  113263. /* start by fitting the implicit base case.... */
  113264. int y0=-200;
  113265. int y1=-200;
  113266. fit_line(fits,posts-1,&y0,&y1);
  113267. fit_valueA[0]=y0;
  113268. fit_valueB[0]=y0;
  113269. fit_valueB[1]=y1;
  113270. fit_valueA[1]=y1;
  113271. /* Non degenerate case */
  113272. /* start progressive splitting. This is a greedy, non-optimal
  113273. algorithm, but simple and close enough to the best
  113274. answer. */
  113275. for(i=2;i<posts;i++){
  113276. int sortpos=look->reverse_index[i];
  113277. int ln=loneighbor[sortpos];
  113278. int hn=hineighbor[sortpos];
  113279. /* eliminate repeat searches of a particular range with a memo */
  113280. if(memo[ln]!=hn){
  113281. /* haven't performed this error search yet */
  113282. int lsortpos=look->reverse_index[ln];
  113283. int hsortpos=look->reverse_index[hn];
  113284. memo[ln]=hn;
  113285. {
  113286. /* A note: we want to bound/minimize *local*, not global, error */
  113287. int lx=info->postlist[ln];
  113288. int hx=info->postlist[hn];
  113289. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113290. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113291. if(ly==-1 || hy==-1){
  113292. exit(1);
  113293. }
  113294. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113295. /* outside error bounds/begin search area. Split it. */
  113296. int ly0=-200;
  113297. int ly1=-200;
  113298. int hy0=-200;
  113299. int hy1=-200;
  113300. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113301. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113302. /* store new edge values */
  113303. fit_valueB[ln]=ly0;
  113304. if(ln==0)fit_valueA[ln]=ly0;
  113305. fit_valueA[i]=ly1;
  113306. fit_valueB[i]=hy0;
  113307. fit_valueA[hn]=hy1;
  113308. if(hn==1)fit_valueB[hn]=hy1;
  113309. if(ly1>=0 || hy0>=0){
  113310. /* store new neighbor values */
  113311. for(j=sortpos-1;j>=0;j--)
  113312. if(hineighbor[j]==hn)
  113313. hineighbor[j]=i;
  113314. else
  113315. break;
  113316. for(j=sortpos+1;j<posts;j++)
  113317. if(loneighbor[j]==ln)
  113318. loneighbor[j]=i;
  113319. else
  113320. break;
  113321. }
  113322. }else{
  113323. fit_valueA[i]=-200;
  113324. fit_valueB[i]=-200;
  113325. }
  113326. }
  113327. }
  113328. }
  113329. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113330. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113331. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113332. /* fill in posts marked as not using a fit; we will zero
  113333. back out to 'unused' when encoding them so long as curve
  113334. interpolation doesn't force them into use */
  113335. for(i=2;i<posts;i++){
  113336. int ln=look->loneighbor[i-2];
  113337. int hn=look->hineighbor[i-2];
  113338. int x0=info->postlist[ln];
  113339. int x1=info->postlist[hn];
  113340. int y0=output[ln];
  113341. int y1=output[hn];
  113342. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113343. int vx=post_Y(fit_valueA,fit_valueB,i);
  113344. if(vx>=0 && predicted!=vx){
  113345. output[i]=vx;
  113346. }else{
  113347. output[i]= predicted|0x8000;
  113348. }
  113349. }
  113350. }
  113351. return(output);
  113352. }
  113353. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113354. int *A,int *B,
  113355. int del){
  113356. long i;
  113357. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113358. long posts=look->posts;
  113359. int *output=NULL;
  113360. if(A && B){
  113361. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113362. for(i=0;i<posts;i++){
  113363. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113364. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113365. }
  113366. }
  113367. return(output);
  113368. }
  113369. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113370. void*look_,
  113371. int *post,int *ilogmask){
  113372. long i,j;
  113373. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113374. vorbis_info_floor1 *info=look->vi;
  113375. long posts=look->posts;
  113376. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113377. int out[VIF_POSIT+2];
  113378. static_codebook **sbooks=ci->book_param;
  113379. codebook *books=ci->fullbooks;
  113380. static long seq=0;
  113381. /* quantize values to multiplier spec */
  113382. if(post){
  113383. for(i=0;i<posts;i++){
  113384. int val=post[i]&0x7fff;
  113385. switch(info->mult){
  113386. case 1: /* 1024 -> 256 */
  113387. val>>=2;
  113388. break;
  113389. case 2: /* 1024 -> 128 */
  113390. val>>=3;
  113391. break;
  113392. case 3: /* 1024 -> 86 */
  113393. val/=12;
  113394. break;
  113395. case 4: /* 1024 -> 64 */
  113396. val>>=4;
  113397. break;
  113398. }
  113399. post[i]=val | (post[i]&0x8000);
  113400. }
  113401. out[0]=post[0];
  113402. out[1]=post[1];
  113403. /* find prediction values for each post and subtract them */
  113404. for(i=2;i<posts;i++){
  113405. int ln=look->loneighbor[i-2];
  113406. int hn=look->hineighbor[i-2];
  113407. int x0=info->postlist[ln];
  113408. int x1=info->postlist[hn];
  113409. int y0=post[ln];
  113410. int y1=post[hn];
  113411. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113412. if((post[i]&0x8000) || (predicted==post[i])){
  113413. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113414. in interpolation */
  113415. out[i]=0;
  113416. }else{
  113417. int headroom=(look->quant_q-predicted<predicted?
  113418. look->quant_q-predicted:predicted);
  113419. int val=post[i]-predicted;
  113420. /* at this point the 'deviation' value is in the range +/- max
  113421. range, but the real, unique range can always be mapped to
  113422. only [0-maxrange). So we want to wrap the deviation into
  113423. this limited range, but do it in the way that least screws
  113424. an essentially gaussian probability distribution. */
  113425. if(val<0)
  113426. if(val<-headroom)
  113427. val=headroom-val-1;
  113428. else
  113429. val=-1-(val<<1);
  113430. else
  113431. if(val>=headroom)
  113432. val= val+headroom;
  113433. else
  113434. val<<=1;
  113435. out[i]=val;
  113436. post[ln]&=0x7fff;
  113437. post[hn]&=0x7fff;
  113438. }
  113439. }
  113440. /* we have everything we need. pack it out */
  113441. /* mark nontrivial floor */
  113442. oggpack_write(opb,1,1);
  113443. /* beginning/end post */
  113444. look->frames++;
  113445. look->postbits+=ilog(look->quant_q-1)*2;
  113446. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113447. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113448. /* partition by partition */
  113449. for(i=0,j=2;i<info->partitions;i++){
  113450. int classx=info->partitionclass[i];
  113451. int cdim=info->class_dim[classx];
  113452. int csubbits=info->class_subs[classx];
  113453. int csub=1<<csubbits;
  113454. int bookas[8]={0,0,0,0,0,0,0,0};
  113455. int cval=0;
  113456. int cshift=0;
  113457. int k,l;
  113458. /* generate the partition's first stage cascade value */
  113459. if(csubbits){
  113460. int maxval[8];
  113461. for(k=0;k<csub;k++){
  113462. int booknum=info->class_subbook[classx][k];
  113463. if(booknum<0){
  113464. maxval[k]=1;
  113465. }else{
  113466. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113467. }
  113468. }
  113469. for(k=0;k<cdim;k++){
  113470. for(l=0;l<csub;l++){
  113471. int val=out[j+k];
  113472. if(val<maxval[l]){
  113473. bookas[k]=l;
  113474. break;
  113475. }
  113476. }
  113477. cval|= bookas[k]<<cshift;
  113478. cshift+=csubbits;
  113479. }
  113480. /* write it */
  113481. look->phrasebits+=
  113482. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113483. #ifdef TRAIN_FLOOR1
  113484. {
  113485. FILE *of;
  113486. char buffer[80];
  113487. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113488. vb->pcmend/2,posts-2,class);
  113489. of=fopen(buffer,"a");
  113490. fprintf(of,"%d\n",cval);
  113491. fclose(of);
  113492. }
  113493. #endif
  113494. }
  113495. /* write post values */
  113496. for(k=0;k<cdim;k++){
  113497. int book=info->class_subbook[classx][bookas[k]];
  113498. if(book>=0){
  113499. /* hack to allow training with 'bad' books */
  113500. if(out[j+k]<(books+book)->entries)
  113501. look->postbits+=vorbis_book_encode(books+book,
  113502. out[j+k],opb);
  113503. /*else
  113504. fprintf(stderr,"+!");*/
  113505. #ifdef TRAIN_FLOOR1
  113506. {
  113507. FILE *of;
  113508. char buffer[80];
  113509. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113510. vb->pcmend/2,posts-2,class,bookas[k]);
  113511. of=fopen(buffer,"a");
  113512. fprintf(of,"%d\n",out[j+k]);
  113513. fclose(of);
  113514. }
  113515. #endif
  113516. }
  113517. }
  113518. j+=cdim;
  113519. }
  113520. {
  113521. /* generate quantized floor equivalent to what we'd unpack in decode */
  113522. /* render the lines */
  113523. int hx=0;
  113524. int lx=0;
  113525. int ly=post[0]*info->mult;
  113526. for(j=1;j<look->posts;j++){
  113527. int current=look->forward_index[j];
  113528. int hy=post[current]&0x7fff;
  113529. if(hy==post[current]){
  113530. hy*=info->mult;
  113531. hx=info->postlist[current];
  113532. render_line0(lx,hx,ly,hy,ilogmask);
  113533. lx=hx;
  113534. ly=hy;
  113535. }
  113536. }
  113537. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113538. seq++;
  113539. return(1);
  113540. }
  113541. }else{
  113542. oggpack_write(opb,0,1);
  113543. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113544. seq++;
  113545. return(0);
  113546. }
  113547. }
  113548. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113549. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113550. vorbis_info_floor1 *info=look->vi;
  113551. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113552. int i,j,k;
  113553. codebook *books=ci->fullbooks;
  113554. /* unpack wrapped/predicted values from stream */
  113555. if(oggpack_read(&vb->opb,1)==1){
  113556. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113557. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113558. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113559. /* partition by partition */
  113560. for(i=0,j=2;i<info->partitions;i++){
  113561. int classx=info->partitionclass[i];
  113562. int cdim=info->class_dim[classx];
  113563. int csubbits=info->class_subs[classx];
  113564. int csub=1<<csubbits;
  113565. int cval=0;
  113566. /* decode the partition's first stage cascade value */
  113567. if(csubbits){
  113568. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113569. if(cval==-1)goto eop;
  113570. }
  113571. for(k=0;k<cdim;k++){
  113572. int book=info->class_subbook[classx][cval&(csub-1)];
  113573. cval>>=csubbits;
  113574. if(book>=0){
  113575. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113576. goto eop;
  113577. }else{
  113578. fit_value[j+k]=0;
  113579. }
  113580. }
  113581. j+=cdim;
  113582. }
  113583. /* unwrap positive values and reconsitute via linear interpolation */
  113584. for(i=2;i<look->posts;i++){
  113585. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113586. info->postlist[look->hineighbor[i-2]],
  113587. fit_value[look->loneighbor[i-2]],
  113588. fit_value[look->hineighbor[i-2]],
  113589. info->postlist[i]);
  113590. int hiroom=look->quant_q-predicted;
  113591. int loroom=predicted;
  113592. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113593. int val=fit_value[i];
  113594. if(val){
  113595. if(val>=room){
  113596. if(hiroom>loroom){
  113597. val = val-loroom;
  113598. }else{
  113599. val = -1-(val-hiroom);
  113600. }
  113601. }else{
  113602. if(val&1){
  113603. val= -((val+1)>>1);
  113604. }else{
  113605. val>>=1;
  113606. }
  113607. }
  113608. fit_value[i]=val+predicted;
  113609. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113610. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113611. }else{
  113612. fit_value[i]=predicted|0x8000;
  113613. }
  113614. }
  113615. return(fit_value);
  113616. }
  113617. eop:
  113618. return(NULL);
  113619. }
  113620. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113621. float *out){
  113622. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113623. vorbis_info_floor1 *info=look->vi;
  113624. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113625. int n=ci->blocksizes[vb->W]/2;
  113626. int j;
  113627. if(memo){
  113628. /* render the lines */
  113629. int *fit_value=(int *)memo;
  113630. int hx=0;
  113631. int lx=0;
  113632. int ly=fit_value[0]*info->mult;
  113633. for(j=1;j<look->posts;j++){
  113634. int current=look->forward_index[j];
  113635. int hy=fit_value[current]&0x7fff;
  113636. if(hy==fit_value[current]){
  113637. hy*=info->mult;
  113638. hx=info->postlist[current];
  113639. render_line(lx,hx,ly,hy,out);
  113640. lx=hx;
  113641. ly=hy;
  113642. }
  113643. }
  113644. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113645. return(1);
  113646. }
  113647. memset(out,0,sizeof(*out)*n);
  113648. return(0);
  113649. }
  113650. /* export hooks */
  113651. vorbis_func_floor floor1_exportbundle={
  113652. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113653. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113654. };
  113655. #endif
  113656. /*** End of inlined file: floor1.c ***/
  113657. /*** Start of inlined file: info.c ***/
  113658. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113659. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113660. // tasks..
  113661. #if JUCE_MSVC
  113662. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113663. #endif
  113664. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113665. #if JUCE_USE_OGGVORBIS
  113666. /* general handling of the header and the vorbis_info structure (and
  113667. substructures) */
  113668. #include <stdlib.h>
  113669. #include <string.h>
  113670. #include <ctype.h>
  113671. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113672. while(bytes--){
  113673. oggpack_write(o,*s++,8);
  113674. }
  113675. }
  113676. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113677. while(bytes--){
  113678. *buf++=oggpack_read(o,8);
  113679. }
  113680. }
  113681. void vorbis_comment_init(vorbis_comment *vc){
  113682. memset(vc,0,sizeof(*vc));
  113683. }
  113684. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113685. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113686. (vc->comments+2)*sizeof(*vc->user_comments));
  113687. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113688. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113689. vc->comment_lengths[vc->comments]=strlen(comment);
  113690. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113691. strcpy(vc->user_comments[vc->comments], comment);
  113692. vc->comments++;
  113693. vc->user_comments[vc->comments]=NULL;
  113694. }
  113695. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113696. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113697. strcpy(comment, tag);
  113698. strcat(comment, "=");
  113699. strcat(comment, contents);
  113700. vorbis_comment_add(vc, comment);
  113701. }
  113702. /* This is more or less the same as strncasecmp - but that doesn't exist
  113703. * everywhere, and this is a fairly trivial function, so we include it */
  113704. static int tagcompare(const char *s1, const char *s2, int n){
  113705. int c=0;
  113706. while(c < n){
  113707. if(toupper(s1[c]) != toupper(s2[c]))
  113708. return !0;
  113709. c++;
  113710. }
  113711. return 0;
  113712. }
  113713. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113714. long i;
  113715. int found = 0;
  113716. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113717. char *fulltag = (char*)alloca(taglen+ 1);
  113718. strcpy(fulltag, tag);
  113719. strcat(fulltag, "=");
  113720. for(i=0;i<vc->comments;i++){
  113721. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113722. if(count == found)
  113723. /* We return a pointer to the data, not a copy */
  113724. return vc->user_comments[i] + taglen;
  113725. else
  113726. found++;
  113727. }
  113728. }
  113729. return NULL; /* didn't find anything */
  113730. }
  113731. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113732. int i,count=0;
  113733. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113734. char *fulltag = (char*)alloca(taglen+1);
  113735. strcpy(fulltag,tag);
  113736. strcat(fulltag, "=");
  113737. for(i=0;i<vc->comments;i++){
  113738. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113739. count++;
  113740. }
  113741. return count;
  113742. }
  113743. void vorbis_comment_clear(vorbis_comment *vc){
  113744. if(vc){
  113745. long i;
  113746. for(i=0;i<vc->comments;i++)
  113747. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113748. if(vc->user_comments)_ogg_free(vc->user_comments);
  113749. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113750. if(vc->vendor)_ogg_free(vc->vendor);
  113751. }
  113752. memset(vc,0,sizeof(*vc));
  113753. }
  113754. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113755. They may be equal, but short will never ge greater than long */
  113756. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113757. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113758. return ci ? ci->blocksizes[zo] : -1;
  113759. }
  113760. /* used by synthesis, which has a full, alloced vi */
  113761. void vorbis_info_init(vorbis_info *vi){
  113762. memset(vi,0,sizeof(*vi));
  113763. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113764. }
  113765. void vorbis_info_clear(vorbis_info *vi){
  113766. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113767. int i;
  113768. if(ci){
  113769. for(i=0;i<ci->modes;i++)
  113770. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113771. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113772. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113773. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113774. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113775. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113776. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113777. for(i=0;i<ci->books;i++){
  113778. if(ci->book_param[i]){
  113779. /* knows if the book was not alloced */
  113780. vorbis_staticbook_destroy(ci->book_param[i]);
  113781. }
  113782. if(ci->fullbooks)
  113783. vorbis_book_clear(ci->fullbooks+i);
  113784. }
  113785. if(ci->fullbooks)
  113786. _ogg_free(ci->fullbooks);
  113787. for(i=0;i<ci->psys;i++)
  113788. _vi_psy_free(ci->psy_param[i]);
  113789. _ogg_free(ci);
  113790. }
  113791. memset(vi,0,sizeof(*vi));
  113792. }
  113793. /* Header packing/unpacking ********************************************/
  113794. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113795. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113796. if(!ci)return(OV_EFAULT);
  113797. vi->version=oggpack_read(opb,32);
  113798. if(vi->version!=0)return(OV_EVERSION);
  113799. vi->channels=oggpack_read(opb,8);
  113800. vi->rate=oggpack_read(opb,32);
  113801. vi->bitrate_upper=oggpack_read(opb,32);
  113802. vi->bitrate_nominal=oggpack_read(opb,32);
  113803. vi->bitrate_lower=oggpack_read(opb,32);
  113804. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113805. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113806. if(vi->rate<1)goto err_out;
  113807. if(vi->channels<1)goto err_out;
  113808. if(ci->blocksizes[0]<8)goto err_out;
  113809. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113810. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113811. return(0);
  113812. err_out:
  113813. vorbis_info_clear(vi);
  113814. return(OV_EBADHEADER);
  113815. }
  113816. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113817. int i;
  113818. int vendorlen=oggpack_read(opb,32);
  113819. if(vendorlen<0)goto err_out;
  113820. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113821. _v_readstring(opb,vc->vendor,vendorlen);
  113822. vc->comments=oggpack_read(opb,32);
  113823. if(vc->comments<0)goto err_out;
  113824. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113825. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113826. for(i=0;i<vc->comments;i++){
  113827. int len=oggpack_read(opb,32);
  113828. if(len<0)goto err_out;
  113829. vc->comment_lengths[i]=len;
  113830. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113831. _v_readstring(opb,vc->user_comments[i],len);
  113832. }
  113833. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113834. return(0);
  113835. err_out:
  113836. vorbis_comment_clear(vc);
  113837. return(OV_EBADHEADER);
  113838. }
  113839. /* all of the real encoding details are here. The modes, books,
  113840. everything */
  113841. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113842. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113843. int i;
  113844. if(!ci)return(OV_EFAULT);
  113845. /* codebooks */
  113846. ci->books=oggpack_read(opb,8)+1;
  113847. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113848. for(i=0;i<ci->books;i++){
  113849. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113850. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113851. }
  113852. /* time backend settings; hooks are unused */
  113853. {
  113854. int times=oggpack_read(opb,6)+1;
  113855. for(i=0;i<times;i++){
  113856. int test=oggpack_read(opb,16);
  113857. if(test<0 || test>=VI_TIMEB)goto err_out;
  113858. }
  113859. }
  113860. /* floor backend settings */
  113861. ci->floors=oggpack_read(opb,6)+1;
  113862. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113863. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113864. for(i=0;i<ci->floors;i++){
  113865. ci->floor_type[i]=oggpack_read(opb,16);
  113866. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113867. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113868. if(!ci->floor_param[i])goto err_out;
  113869. }
  113870. /* residue backend settings */
  113871. ci->residues=oggpack_read(opb,6)+1;
  113872. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113873. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113874. for(i=0;i<ci->residues;i++){
  113875. ci->residue_type[i]=oggpack_read(opb,16);
  113876. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113877. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113878. if(!ci->residue_param[i])goto err_out;
  113879. }
  113880. /* map backend settings */
  113881. ci->maps=oggpack_read(opb,6)+1;
  113882. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113883. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113884. for(i=0;i<ci->maps;i++){
  113885. ci->map_type[i]=oggpack_read(opb,16);
  113886. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113887. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113888. if(!ci->map_param[i])goto err_out;
  113889. }
  113890. /* mode settings */
  113891. ci->modes=oggpack_read(opb,6)+1;
  113892. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113893. for(i=0;i<ci->modes;i++){
  113894. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113895. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113896. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113897. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113898. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113899. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113900. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113901. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113902. }
  113903. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113904. return(0);
  113905. err_out:
  113906. vorbis_info_clear(vi);
  113907. return(OV_EBADHEADER);
  113908. }
  113909. /* The Vorbis header is in three packets; the initial small packet in
  113910. the first page that identifies basic parameters, a second packet
  113911. with bitstream comments and a third packet that holds the
  113912. codebook. */
  113913. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113914. oggpack_buffer opb;
  113915. if(op){
  113916. oggpack_readinit(&opb,op->packet,op->bytes);
  113917. /* Which of the three types of header is this? */
  113918. /* Also verify header-ness, vorbis */
  113919. {
  113920. char buffer[6];
  113921. int packtype=oggpack_read(&opb,8);
  113922. memset(buffer,0,6);
  113923. _v_readstring(&opb,buffer,6);
  113924. if(memcmp(buffer,"vorbis",6)){
  113925. /* not a vorbis header */
  113926. return(OV_ENOTVORBIS);
  113927. }
  113928. switch(packtype){
  113929. case 0x01: /* least significant *bit* is read first */
  113930. if(!op->b_o_s){
  113931. /* Not the initial packet */
  113932. return(OV_EBADHEADER);
  113933. }
  113934. if(vi->rate!=0){
  113935. /* previously initialized info header */
  113936. return(OV_EBADHEADER);
  113937. }
  113938. return(_vorbis_unpack_info(vi,&opb));
  113939. case 0x03: /* least significant *bit* is read first */
  113940. if(vi->rate==0){
  113941. /* um... we didn't get the initial header */
  113942. return(OV_EBADHEADER);
  113943. }
  113944. return(_vorbis_unpack_comment(vc,&opb));
  113945. case 0x05: /* least significant *bit* is read first */
  113946. if(vi->rate==0 || vc->vendor==NULL){
  113947. /* um... we didn;t get the initial header or comments yet */
  113948. return(OV_EBADHEADER);
  113949. }
  113950. return(_vorbis_unpack_books(vi,&opb));
  113951. default:
  113952. /* Not a valid vorbis header type */
  113953. return(OV_EBADHEADER);
  113954. break;
  113955. }
  113956. }
  113957. }
  113958. return(OV_EBADHEADER);
  113959. }
  113960. /* pack side **********************************************************/
  113961. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113962. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113963. if(!ci)return(OV_EFAULT);
  113964. /* preamble */
  113965. oggpack_write(opb,0x01,8);
  113966. _v_writestring(opb,"vorbis", 6);
  113967. /* basic information about the stream */
  113968. oggpack_write(opb,0x00,32);
  113969. oggpack_write(opb,vi->channels,8);
  113970. oggpack_write(opb,vi->rate,32);
  113971. oggpack_write(opb,vi->bitrate_upper,32);
  113972. oggpack_write(opb,vi->bitrate_nominal,32);
  113973. oggpack_write(opb,vi->bitrate_lower,32);
  113974. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113975. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113976. oggpack_write(opb,1,1);
  113977. return(0);
  113978. }
  113979. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113980. char temp[]="Xiph.Org libVorbis I 20050304";
  113981. int bytes = strlen(temp);
  113982. /* preamble */
  113983. oggpack_write(opb,0x03,8);
  113984. _v_writestring(opb,"vorbis", 6);
  113985. /* vendor */
  113986. oggpack_write(opb,bytes,32);
  113987. _v_writestring(opb,temp, bytes);
  113988. /* comments */
  113989. oggpack_write(opb,vc->comments,32);
  113990. if(vc->comments){
  113991. int i;
  113992. for(i=0;i<vc->comments;i++){
  113993. if(vc->user_comments[i]){
  113994. oggpack_write(opb,vc->comment_lengths[i],32);
  113995. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113996. }else{
  113997. oggpack_write(opb,0,32);
  113998. }
  113999. }
  114000. }
  114001. oggpack_write(opb,1,1);
  114002. return(0);
  114003. }
  114004. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114005. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114006. int i;
  114007. if(!ci)return(OV_EFAULT);
  114008. oggpack_write(opb,0x05,8);
  114009. _v_writestring(opb,"vorbis", 6);
  114010. /* books */
  114011. oggpack_write(opb,ci->books-1,8);
  114012. for(i=0;i<ci->books;i++)
  114013. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114014. /* times; hook placeholders */
  114015. oggpack_write(opb,0,6);
  114016. oggpack_write(opb,0,16);
  114017. /* floors */
  114018. oggpack_write(opb,ci->floors-1,6);
  114019. for(i=0;i<ci->floors;i++){
  114020. oggpack_write(opb,ci->floor_type[i],16);
  114021. if(_floor_P[ci->floor_type[i]]->pack)
  114022. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114023. else
  114024. goto err_out;
  114025. }
  114026. /* residues */
  114027. oggpack_write(opb,ci->residues-1,6);
  114028. for(i=0;i<ci->residues;i++){
  114029. oggpack_write(opb,ci->residue_type[i],16);
  114030. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114031. }
  114032. /* maps */
  114033. oggpack_write(opb,ci->maps-1,6);
  114034. for(i=0;i<ci->maps;i++){
  114035. oggpack_write(opb,ci->map_type[i],16);
  114036. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114037. }
  114038. /* modes */
  114039. oggpack_write(opb,ci->modes-1,6);
  114040. for(i=0;i<ci->modes;i++){
  114041. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114042. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114043. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114044. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114045. }
  114046. oggpack_write(opb,1,1);
  114047. return(0);
  114048. err_out:
  114049. return(-1);
  114050. }
  114051. int vorbis_commentheader_out(vorbis_comment *vc,
  114052. ogg_packet *op){
  114053. oggpack_buffer opb;
  114054. oggpack_writeinit(&opb);
  114055. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114056. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114057. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114058. op->bytes=oggpack_bytes(&opb);
  114059. op->b_o_s=0;
  114060. op->e_o_s=0;
  114061. op->granulepos=0;
  114062. op->packetno=1;
  114063. return 0;
  114064. }
  114065. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114066. vorbis_comment *vc,
  114067. ogg_packet *op,
  114068. ogg_packet *op_comm,
  114069. ogg_packet *op_code){
  114070. int ret=OV_EIMPL;
  114071. vorbis_info *vi=v->vi;
  114072. oggpack_buffer opb;
  114073. private_state *b=(private_state*)v->backend_state;
  114074. if(!b){
  114075. ret=OV_EFAULT;
  114076. goto err_out;
  114077. }
  114078. /* first header packet **********************************************/
  114079. oggpack_writeinit(&opb);
  114080. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114081. /* build the packet */
  114082. if(b->header)_ogg_free(b->header);
  114083. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114084. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114085. op->packet=b->header;
  114086. op->bytes=oggpack_bytes(&opb);
  114087. op->b_o_s=1;
  114088. op->e_o_s=0;
  114089. op->granulepos=0;
  114090. op->packetno=0;
  114091. /* second header packet (comments) **********************************/
  114092. oggpack_reset(&opb);
  114093. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114094. if(b->header1)_ogg_free(b->header1);
  114095. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114096. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114097. op_comm->packet=b->header1;
  114098. op_comm->bytes=oggpack_bytes(&opb);
  114099. op_comm->b_o_s=0;
  114100. op_comm->e_o_s=0;
  114101. op_comm->granulepos=0;
  114102. op_comm->packetno=1;
  114103. /* third header packet (modes/codebooks) ****************************/
  114104. oggpack_reset(&opb);
  114105. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114106. if(b->header2)_ogg_free(b->header2);
  114107. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114108. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114109. op_code->packet=b->header2;
  114110. op_code->bytes=oggpack_bytes(&opb);
  114111. op_code->b_o_s=0;
  114112. op_code->e_o_s=0;
  114113. op_code->granulepos=0;
  114114. op_code->packetno=2;
  114115. oggpack_writeclear(&opb);
  114116. return(0);
  114117. err_out:
  114118. oggpack_writeclear(&opb);
  114119. memset(op,0,sizeof(*op));
  114120. memset(op_comm,0,sizeof(*op_comm));
  114121. memset(op_code,0,sizeof(*op_code));
  114122. if(b->header)_ogg_free(b->header);
  114123. if(b->header1)_ogg_free(b->header1);
  114124. if(b->header2)_ogg_free(b->header2);
  114125. b->header=NULL;
  114126. b->header1=NULL;
  114127. b->header2=NULL;
  114128. return(ret);
  114129. }
  114130. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114131. if(granulepos>=0)
  114132. return((double)granulepos/v->vi->rate);
  114133. return(-1);
  114134. }
  114135. #endif
  114136. /*** End of inlined file: info.c ***/
  114137. /*** Start of inlined file: lpc.c ***/
  114138. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114139. are derived from code written by Jutta Degener and Carsten Bormann;
  114140. thus we include their copyright below. The entirety of this file
  114141. is freely redistributable on the condition that both of these
  114142. copyright notices are preserved without modification. */
  114143. /* Preserved Copyright: *********************************************/
  114144. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114145. Technische Universita"t Berlin
  114146. Any use of this software is permitted provided that this notice is not
  114147. removed and that neither the authors nor the Technische Universita"t
  114148. Berlin are deemed to have made any representations as to the
  114149. suitability of this software for any purpose nor are held responsible
  114150. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114151. THIS SOFTWARE.
  114152. As a matter of courtesy, the authors request to be informed about uses
  114153. this software has found, about bugs in this software, and about any
  114154. improvements that may be of general interest.
  114155. Berlin, 28.11.1994
  114156. Jutta Degener
  114157. Carsten Bormann
  114158. *********************************************************************/
  114159. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114160. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114161. // tasks..
  114162. #if JUCE_MSVC
  114163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114164. #endif
  114165. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114166. #if JUCE_USE_OGGVORBIS
  114167. #include <stdlib.h>
  114168. #include <string.h>
  114169. #include <math.h>
  114170. /* Autocorrelation LPC coeff generation algorithm invented by
  114171. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114172. /* Input : n elements of time doamin data
  114173. Output: m lpc coefficients, excitation energy */
  114174. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114175. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114176. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114177. double error;
  114178. int i,j;
  114179. /* autocorrelation, p+1 lag coefficients */
  114180. j=m+1;
  114181. while(j--){
  114182. double d=0; /* double needed for accumulator depth */
  114183. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114184. aut[j]=d;
  114185. }
  114186. /* Generate lpc coefficients from autocorr values */
  114187. error=aut[0];
  114188. for(i=0;i<m;i++){
  114189. double r= -aut[i+1];
  114190. if(error==0){
  114191. memset(lpci,0,m*sizeof(*lpci));
  114192. return 0;
  114193. }
  114194. /* Sum up this iteration's reflection coefficient; note that in
  114195. Vorbis we don't save it. If anyone wants to recycle this code
  114196. and needs reflection coefficients, save the results of 'r' from
  114197. each iteration. */
  114198. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114199. r/=error;
  114200. /* Update LPC coefficients and total error */
  114201. lpc[i]=r;
  114202. for(j=0;j<i/2;j++){
  114203. double tmp=lpc[j];
  114204. lpc[j]+=r*lpc[i-1-j];
  114205. lpc[i-1-j]+=r*tmp;
  114206. }
  114207. if(i%2)lpc[j]+=lpc[j]*r;
  114208. error*=1.f-r*r;
  114209. }
  114210. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114211. /* we need the error value to know how big an impulse to hit the
  114212. filter with later */
  114213. return error;
  114214. }
  114215. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114216. float *data,long n){
  114217. /* in: coeff[0...m-1] LPC coefficients
  114218. prime[0...m-1] initial values (allocated size of n+m-1)
  114219. out: data[0...n-1] data samples */
  114220. long i,j,o,p;
  114221. float y;
  114222. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114223. if(!prime)
  114224. for(i=0;i<m;i++)
  114225. work[i]=0.f;
  114226. else
  114227. for(i=0;i<m;i++)
  114228. work[i]=prime[i];
  114229. for(i=0;i<n;i++){
  114230. y=0;
  114231. o=i;
  114232. p=m;
  114233. for(j=0;j<m;j++)
  114234. y-=work[o++]*coeff[--p];
  114235. data[i]=work[o]=y;
  114236. }
  114237. }
  114238. #endif
  114239. /*** End of inlined file: lpc.c ***/
  114240. /*** Start of inlined file: lsp.c ***/
  114241. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114242. an iterative root polisher (CACM algorithm 283). It *is* possible
  114243. to confuse this algorithm into not converging; that should only
  114244. happen with absurdly closely spaced roots (very sharp peaks in the
  114245. LPC f response) which in turn should be impossible in our use of
  114246. the code. If this *does* happen anyway, it's a bug in the floor
  114247. finder; find the cause of the confusion (probably a single bin
  114248. spike or accidental near-float-limit resolution problems) and
  114249. correct it. */
  114250. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114251. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114252. // tasks..
  114253. #if JUCE_MSVC
  114254. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114255. #endif
  114256. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114257. #if JUCE_USE_OGGVORBIS
  114258. #include <math.h>
  114259. #include <string.h>
  114260. #include <stdlib.h>
  114261. /*** Start of inlined file: lookup.h ***/
  114262. #ifndef _V_LOOKUP_H_
  114263. #ifdef FLOAT_LOOKUP
  114264. extern float vorbis_coslook(float a);
  114265. extern float vorbis_invsqlook(float a);
  114266. extern float vorbis_invsq2explook(int a);
  114267. extern float vorbis_fromdBlook(float a);
  114268. #endif
  114269. #ifdef INT_LOOKUP
  114270. extern long vorbis_invsqlook_i(long a,long e);
  114271. extern long vorbis_coslook_i(long a);
  114272. extern float vorbis_fromdBlook_i(long a);
  114273. #endif
  114274. #endif
  114275. /*** End of inlined file: lookup.h ***/
  114276. /* three possible LSP to f curve functions; the exact computation
  114277. (float), a lookup based float implementation, and an integer
  114278. implementation. The float lookup is likely the optimal choice on
  114279. any machine with an FPU. The integer implementation is *not* fixed
  114280. point (due to the need for a large dynamic range and thus a
  114281. seperately tracked exponent) and thus much more complex than the
  114282. relatively simple float implementations. It's mostly for future
  114283. work on a fully fixed point implementation for processors like the
  114284. ARM family. */
  114285. /* undefine both for the 'old' but more precise implementation */
  114286. #define FLOAT_LOOKUP
  114287. #undef INT_LOOKUP
  114288. #ifdef FLOAT_LOOKUP
  114289. /*** Start of inlined file: lookup.c ***/
  114290. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114291. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114292. // tasks..
  114293. #if JUCE_MSVC
  114294. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114295. #endif
  114296. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114297. #if JUCE_USE_OGGVORBIS
  114298. #include <math.h>
  114299. /*** Start of inlined file: lookup.h ***/
  114300. #ifndef _V_LOOKUP_H_
  114301. #ifdef FLOAT_LOOKUP
  114302. extern float vorbis_coslook(float a);
  114303. extern float vorbis_invsqlook(float a);
  114304. extern float vorbis_invsq2explook(int a);
  114305. extern float vorbis_fromdBlook(float a);
  114306. #endif
  114307. #ifdef INT_LOOKUP
  114308. extern long vorbis_invsqlook_i(long a,long e);
  114309. extern long vorbis_coslook_i(long a);
  114310. extern float vorbis_fromdBlook_i(long a);
  114311. #endif
  114312. #endif
  114313. /*** End of inlined file: lookup.h ***/
  114314. /*** Start of inlined file: lookup_data.h ***/
  114315. #ifndef _V_LOOKUP_DATA_H_
  114316. #ifdef FLOAT_LOOKUP
  114317. #define COS_LOOKUP_SZ 128
  114318. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114319. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114320. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114321. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114322. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114323. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114324. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114325. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114326. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114327. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114328. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114329. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114330. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114331. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114332. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114333. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114334. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114335. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114336. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114337. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114338. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114339. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114340. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114341. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114342. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114343. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114344. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114345. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114346. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114347. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114348. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114349. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114350. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114351. -1.0000000000000f,
  114352. };
  114353. #define INVSQ_LOOKUP_SZ 32
  114354. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114355. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114356. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114357. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114358. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114359. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114360. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114361. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114362. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114363. 1.000000000000f,
  114364. };
  114365. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114366. #define INVSQ2EXP_LOOKUP_MAX 32
  114367. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114368. INVSQ2EXP_LOOKUP_MIN+1]={
  114369. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114370. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114371. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114372. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114373. 256.f, 181.019336f, 128.f, 90.50966799f,
  114374. 64.f, 45.254834f, 32.f, 22.627417f,
  114375. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114376. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114377. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114378. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114379. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114380. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114381. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114382. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114383. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114384. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114385. 1.525878906e-05f,
  114386. };
  114387. #endif
  114388. #define FROMdB_LOOKUP_SZ 35
  114389. #define FROMdB2_LOOKUP_SZ 32
  114390. #define FROMdB_SHIFT 5
  114391. #define FROMdB2_SHIFT 3
  114392. #define FROMdB2_MASK 31
  114393. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114394. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114395. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114396. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114397. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114398. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114399. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114400. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114401. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114402. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114403. };
  114404. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114405. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114406. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114407. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114408. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114409. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114410. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114411. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114412. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114413. };
  114414. #ifdef INT_LOOKUP
  114415. #define INVSQ_LOOKUP_I_SHIFT 10
  114416. #define INVSQ_LOOKUP_I_MASK 1023
  114417. static long INVSQ_LOOKUP_I[64+1]={
  114418. 92682l, 91966l, 91267l, 90583l,
  114419. 89915l, 89261l, 88621l, 87995l,
  114420. 87381l, 86781l, 86192l, 85616l,
  114421. 85051l, 84497l, 83953l, 83420l,
  114422. 82897l, 82384l, 81880l, 81385l,
  114423. 80899l, 80422l, 79953l, 79492l,
  114424. 79039l, 78594l, 78156l, 77726l,
  114425. 77302l, 76885l, 76475l, 76072l,
  114426. 75674l, 75283l, 74898l, 74519l,
  114427. 74146l, 73778l, 73415l, 73058l,
  114428. 72706l, 72359l, 72016l, 71679l,
  114429. 71347l, 71019l, 70695l, 70376l,
  114430. 70061l, 69750l, 69444l, 69141l,
  114431. 68842l, 68548l, 68256l, 67969l,
  114432. 67685l, 67405l, 67128l, 66855l,
  114433. 66585l, 66318l, 66054l, 65794l,
  114434. 65536l,
  114435. };
  114436. #define COS_LOOKUP_I_SHIFT 9
  114437. #define COS_LOOKUP_I_MASK 511
  114438. #define COS_LOOKUP_I_SZ 128
  114439. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114440. 16384l, 16379l, 16364l, 16340l,
  114441. 16305l, 16261l, 16207l, 16143l,
  114442. 16069l, 15986l, 15893l, 15791l,
  114443. 15679l, 15557l, 15426l, 15286l,
  114444. 15137l, 14978l, 14811l, 14635l,
  114445. 14449l, 14256l, 14053l, 13842l,
  114446. 13623l, 13395l, 13160l, 12916l,
  114447. 12665l, 12406l, 12140l, 11866l,
  114448. 11585l, 11297l, 11003l, 10702l,
  114449. 10394l, 10080l, 9760l, 9434l,
  114450. 9102l, 8765l, 8423l, 8076l,
  114451. 7723l, 7366l, 7005l, 6639l,
  114452. 6270l, 5897l, 5520l, 5139l,
  114453. 4756l, 4370l, 3981l, 3590l,
  114454. 3196l, 2801l, 2404l, 2006l,
  114455. 1606l, 1205l, 804l, 402l,
  114456. 0l, -401l, -803l, -1204l,
  114457. -1605l, -2005l, -2403l, -2800l,
  114458. -3195l, -3589l, -3980l, -4369l,
  114459. -4755l, -5138l, -5519l, -5896l,
  114460. -6269l, -6638l, -7004l, -7365l,
  114461. -7722l, -8075l, -8422l, -8764l,
  114462. -9101l, -9433l, -9759l, -10079l,
  114463. -10393l, -10701l, -11002l, -11296l,
  114464. -11584l, -11865l, -12139l, -12405l,
  114465. -12664l, -12915l, -13159l, -13394l,
  114466. -13622l, -13841l, -14052l, -14255l,
  114467. -14448l, -14634l, -14810l, -14977l,
  114468. -15136l, -15285l, -15425l, -15556l,
  114469. -15678l, -15790l, -15892l, -15985l,
  114470. -16068l, -16142l, -16206l, -16260l,
  114471. -16304l, -16339l, -16363l, -16378l,
  114472. -16383l,
  114473. };
  114474. #endif
  114475. #endif
  114476. /*** End of inlined file: lookup_data.h ***/
  114477. #ifdef FLOAT_LOOKUP
  114478. /* interpolated lookup based cos function, domain 0 to PI only */
  114479. float vorbis_coslook(float a){
  114480. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114481. int i=vorbis_ftoi(d-.5);
  114482. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114483. }
  114484. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114485. float vorbis_invsqlook(float a){
  114486. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114487. int i=vorbis_ftoi(d-.5f);
  114488. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114489. }
  114490. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114491. float vorbis_invsq2explook(int a){
  114492. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114493. }
  114494. #include <stdio.h>
  114495. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114496. float vorbis_fromdBlook(float a){
  114497. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114498. return (i<0)?1.f:
  114499. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114500. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114501. }
  114502. #endif
  114503. #ifdef INT_LOOKUP
  114504. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114505. 16.16 format
  114506. returns in m.8 format */
  114507. long vorbis_invsqlook_i(long a,long e){
  114508. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114509. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114510. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114511. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114512. d)>>16); /* result 1.16 */
  114513. e+=32;
  114514. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114515. e=(e>>1)-8;
  114516. return(val>>e);
  114517. }
  114518. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114519. /* a is in n.12 format */
  114520. float vorbis_fromdBlook_i(long a){
  114521. int i=(-a)>>(12-FROMdB2_SHIFT);
  114522. return (i<0)?1.f:
  114523. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114524. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114525. }
  114526. /* interpolated lookup based cos function, domain 0 to PI only */
  114527. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114528. long vorbis_coslook_i(long a){
  114529. int i=a>>COS_LOOKUP_I_SHIFT;
  114530. int d=a&COS_LOOKUP_I_MASK;
  114531. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114532. COS_LOOKUP_I_SHIFT);
  114533. }
  114534. #endif
  114535. #endif
  114536. /*** End of inlined file: lookup.c ***/
  114537. /* catch this in the build system; we #include for
  114538. compilers (like gcc) that can't inline across
  114539. modules */
  114540. /* side effect: changes *lsp to cosines of lsp */
  114541. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114542. float amp,float ampoffset){
  114543. int i;
  114544. float wdel=M_PI/ln;
  114545. vorbis_fpu_control fpu;
  114546. (void) fpu; // to avoid an unused variable warning
  114547. vorbis_fpu_setround(&fpu);
  114548. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114549. i=0;
  114550. while(i<n){
  114551. int k=map[i];
  114552. int qexp;
  114553. float p=.7071067812f;
  114554. float q=.7071067812f;
  114555. float w=vorbis_coslook(wdel*k);
  114556. float *ftmp=lsp;
  114557. int c=m>>1;
  114558. do{
  114559. q*=ftmp[0]-w;
  114560. p*=ftmp[1]-w;
  114561. ftmp+=2;
  114562. }while(--c);
  114563. if(m&1){
  114564. /* odd order filter; slightly assymetric */
  114565. /* the last coefficient */
  114566. q*=ftmp[0]-w;
  114567. q*=q;
  114568. p*=p*(1.f-w*w);
  114569. }else{
  114570. /* even order filter; still symmetric */
  114571. q*=q*(1.f+w);
  114572. p*=p*(1.f-w);
  114573. }
  114574. q=frexp(p+q,&qexp);
  114575. q=vorbis_fromdBlook(amp*
  114576. vorbis_invsqlook(q)*
  114577. vorbis_invsq2explook(qexp+m)-
  114578. ampoffset);
  114579. do{
  114580. curve[i++]*=q;
  114581. }while(map[i]==k);
  114582. }
  114583. vorbis_fpu_restore(fpu);
  114584. }
  114585. #else
  114586. #ifdef INT_LOOKUP
  114587. /*** Start of inlined file: lookup.c ***/
  114588. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114589. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114590. // tasks..
  114591. #if JUCE_MSVC
  114592. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114593. #endif
  114594. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114595. #if JUCE_USE_OGGVORBIS
  114596. #include <math.h>
  114597. /*** Start of inlined file: lookup.h ***/
  114598. #ifndef _V_LOOKUP_H_
  114599. #ifdef FLOAT_LOOKUP
  114600. extern float vorbis_coslook(float a);
  114601. extern float vorbis_invsqlook(float a);
  114602. extern float vorbis_invsq2explook(int a);
  114603. extern float vorbis_fromdBlook(float a);
  114604. #endif
  114605. #ifdef INT_LOOKUP
  114606. extern long vorbis_invsqlook_i(long a,long e);
  114607. extern long vorbis_coslook_i(long a);
  114608. extern float vorbis_fromdBlook_i(long a);
  114609. #endif
  114610. #endif
  114611. /*** End of inlined file: lookup.h ***/
  114612. /*** Start of inlined file: lookup_data.h ***/
  114613. #ifndef _V_LOOKUP_DATA_H_
  114614. #ifdef FLOAT_LOOKUP
  114615. #define COS_LOOKUP_SZ 128
  114616. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114617. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114618. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114619. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114620. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114621. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114622. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114623. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114624. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114625. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114626. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114627. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114628. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114629. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114630. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114631. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114632. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114633. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114634. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114635. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114636. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114637. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114638. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114639. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114640. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114641. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114642. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114643. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114644. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114645. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114646. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114647. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114648. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114649. -1.0000000000000f,
  114650. };
  114651. #define INVSQ_LOOKUP_SZ 32
  114652. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114653. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114654. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114655. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114656. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114657. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114658. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114659. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114660. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114661. 1.000000000000f,
  114662. };
  114663. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114664. #define INVSQ2EXP_LOOKUP_MAX 32
  114665. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114666. INVSQ2EXP_LOOKUP_MIN+1]={
  114667. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114668. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114669. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114670. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114671. 256.f, 181.019336f, 128.f, 90.50966799f,
  114672. 64.f, 45.254834f, 32.f, 22.627417f,
  114673. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114674. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114675. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114676. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114677. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114678. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114679. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114680. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114681. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114682. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114683. 1.525878906e-05f,
  114684. };
  114685. #endif
  114686. #define FROMdB_LOOKUP_SZ 35
  114687. #define FROMdB2_LOOKUP_SZ 32
  114688. #define FROMdB_SHIFT 5
  114689. #define FROMdB2_SHIFT 3
  114690. #define FROMdB2_MASK 31
  114691. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114692. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114693. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114694. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114695. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114696. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114697. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114698. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114699. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114700. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114701. };
  114702. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114703. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114704. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114705. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114706. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114707. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114708. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114709. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114710. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114711. };
  114712. #ifdef INT_LOOKUP
  114713. #define INVSQ_LOOKUP_I_SHIFT 10
  114714. #define INVSQ_LOOKUP_I_MASK 1023
  114715. static long INVSQ_LOOKUP_I[64+1]={
  114716. 92682l, 91966l, 91267l, 90583l,
  114717. 89915l, 89261l, 88621l, 87995l,
  114718. 87381l, 86781l, 86192l, 85616l,
  114719. 85051l, 84497l, 83953l, 83420l,
  114720. 82897l, 82384l, 81880l, 81385l,
  114721. 80899l, 80422l, 79953l, 79492l,
  114722. 79039l, 78594l, 78156l, 77726l,
  114723. 77302l, 76885l, 76475l, 76072l,
  114724. 75674l, 75283l, 74898l, 74519l,
  114725. 74146l, 73778l, 73415l, 73058l,
  114726. 72706l, 72359l, 72016l, 71679l,
  114727. 71347l, 71019l, 70695l, 70376l,
  114728. 70061l, 69750l, 69444l, 69141l,
  114729. 68842l, 68548l, 68256l, 67969l,
  114730. 67685l, 67405l, 67128l, 66855l,
  114731. 66585l, 66318l, 66054l, 65794l,
  114732. 65536l,
  114733. };
  114734. #define COS_LOOKUP_I_SHIFT 9
  114735. #define COS_LOOKUP_I_MASK 511
  114736. #define COS_LOOKUP_I_SZ 128
  114737. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114738. 16384l, 16379l, 16364l, 16340l,
  114739. 16305l, 16261l, 16207l, 16143l,
  114740. 16069l, 15986l, 15893l, 15791l,
  114741. 15679l, 15557l, 15426l, 15286l,
  114742. 15137l, 14978l, 14811l, 14635l,
  114743. 14449l, 14256l, 14053l, 13842l,
  114744. 13623l, 13395l, 13160l, 12916l,
  114745. 12665l, 12406l, 12140l, 11866l,
  114746. 11585l, 11297l, 11003l, 10702l,
  114747. 10394l, 10080l, 9760l, 9434l,
  114748. 9102l, 8765l, 8423l, 8076l,
  114749. 7723l, 7366l, 7005l, 6639l,
  114750. 6270l, 5897l, 5520l, 5139l,
  114751. 4756l, 4370l, 3981l, 3590l,
  114752. 3196l, 2801l, 2404l, 2006l,
  114753. 1606l, 1205l, 804l, 402l,
  114754. 0l, -401l, -803l, -1204l,
  114755. -1605l, -2005l, -2403l, -2800l,
  114756. -3195l, -3589l, -3980l, -4369l,
  114757. -4755l, -5138l, -5519l, -5896l,
  114758. -6269l, -6638l, -7004l, -7365l,
  114759. -7722l, -8075l, -8422l, -8764l,
  114760. -9101l, -9433l, -9759l, -10079l,
  114761. -10393l, -10701l, -11002l, -11296l,
  114762. -11584l, -11865l, -12139l, -12405l,
  114763. -12664l, -12915l, -13159l, -13394l,
  114764. -13622l, -13841l, -14052l, -14255l,
  114765. -14448l, -14634l, -14810l, -14977l,
  114766. -15136l, -15285l, -15425l, -15556l,
  114767. -15678l, -15790l, -15892l, -15985l,
  114768. -16068l, -16142l, -16206l, -16260l,
  114769. -16304l, -16339l, -16363l, -16378l,
  114770. -16383l,
  114771. };
  114772. #endif
  114773. #endif
  114774. /*** End of inlined file: lookup_data.h ***/
  114775. #ifdef FLOAT_LOOKUP
  114776. /* interpolated lookup based cos function, domain 0 to PI only */
  114777. float vorbis_coslook(float a){
  114778. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114779. int i=vorbis_ftoi(d-.5);
  114780. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114781. }
  114782. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114783. float vorbis_invsqlook(float a){
  114784. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114785. int i=vorbis_ftoi(d-.5f);
  114786. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114787. }
  114788. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114789. float vorbis_invsq2explook(int a){
  114790. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114791. }
  114792. #include <stdio.h>
  114793. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114794. float vorbis_fromdBlook(float a){
  114795. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114796. return (i<0)?1.f:
  114797. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114798. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114799. }
  114800. #endif
  114801. #ifdef INT_LOOKUP
  114802. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114803. 16.16 format
  114804. returns in m.8 format */
  114805. long vorbis_invsqlook_i(long a,long e){
  114806. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114807. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114808. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114809. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114810. d)>>16); /* result 1.16 */
  114811. e+=32;
  114812. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114813. e=(e>>1)-8;
  114814. return(val>>e);
  114815. }
  114816. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114817. /* a is in n.12 format */
  114818. float vorbis_fromdBlook_i(long a){
  114819. int i=(-a)>>(12-FROMdB2_SHIFT);
  114820. return (i<0)?1.f:
  114821. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114822. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114823. }
  114824. /* interpolated lookup based cos function, domain 0 to PI only */
  114825. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114826. long vorbis_coslook_i(long a){
  114827. int i=a>>COS_LOOKUP_I_SHIFT;
  114828. int d=a&COS_LOOKUP_I_MASK;
  114829. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114830. COS_LOOKUP_I_SHIFT);
  114831. }
  114832. #endif
  114833. #endif
  114834. /*** End of inlined file: lookup.c ***/
  114835. /* catch this in the build system; we #include for
  114836. compilers (like gcc) that can't inline across
  114837. modules */
  114838. static int MLOOP_1[64]={
  114839. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114840. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114841. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114842. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114843. };
  114844. static int MLOOP_2[64]={
  114845. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114846. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114847. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114848. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114849. };
  114850. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114851. /* side effect: changes *lsp to cosines of lsp */
  114852. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114853. float amp,float ampoffset){
  114854. /* 0 <= m < 256 */
  114855. /* set up for using all int later */
  114856. int i;
  114857. int ampoffseti=rint(ampoffset*4096.f);
  114858. int ampi=rint(amp*16.f);
  114859. long *ilsp=alloca(m*sizeof(*ilsp));
  114860. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114861. i=0;
  114862. while(i<n){
  114863. int j,k=map[i];
  114864. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114865. unsigned long qi=46341;
  114866. int qexp=0,shift;
  114867. long wi=vorbis_coslook_i(k*65536/ln);
  114868. qi*=labs(ilsp[0]-wi);
  114869. pi*=labs(ilsp[1]-wi);
  114870. for(j=3;j<m;j+=2){
  114871. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114872. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114873. shift=MLOOP_3[(pi|qi)>>16];
  114874. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114875. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114876. qexp+=shift;
  114877. }
  114878. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114879. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114880. shift=MLOOP_3[(pi|qi)>>16];
  114881. /* pi,qi normalized collectively, both tracked using qexp */
  114882. if(m&1){
  114883. /* odd order filter; slightly assymetric */
  114884. /* the last coefficient */
  114885. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114886. pi=(pi>>shift)<<14;
  114887. qexp+=shift;
  114888. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114889. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114890. shift=MLOOP_3[(pi|qi)>>16];
  114891. pi>>=shift;
  114892. qi>>=shift;
  114893. qexp+=shift-14*((m+1)>>1);
  114894. pi=((pi*pi)>>16);
  114895. qi=((qi*qi)>>16);
  114896. qexp=qexp*2+m;
  114897. pi*=(1<<14)-((wi*wi)>>14);
  114898. qi+=pi>>14;
  114899. }else{
  114900. /* even order filter; still symmetric */
  114901. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114902. worth tracking step by step */
  114903. pi>>=shift;
  114904. qi>>=shift;
  114905. qexp+=shift-7*m;
  114906. pi=((pi*pi)>>16);
  114907. qi=((qi*qi)>>16);
  114908. qexp=qexp*2+m;
  114909. pi*=(1<<14)-wi;
  114910. qi*=(1<<14)+wi;
  114911. qi=(qi+pi)>>14;
  114912. }
  114913. /* we've let the normalization drift because it wasn't important;
  114914. however, for the lookup, things must be normalized again. We
  114915. need at most one right shift or a number of left shifts */
  114916. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114917. qi>>=1; qexp++;
  114918. }else
  114919. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114920. qi<<=1; qexp--;
  114921. }
  114922. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114923. vorbis_invsqlook_i(qi,qexp)-
  114924. /* m.8, m+n<=8 */
  114925. ampoffseti); /* 8.12[0] */
  114926. curve[i]*=amp;
  114927. while(map[++i]==k)curve[i]*=amp;
  114928. }
  114929. }
  114930. #else
  114931. /* old, nonoptimized but simple version for any poor sap who needs to
  114932. figure out what the hell this code does, or wants the other
  114933. fraction of a dB precision */
  114934. /* side effect: changes *lsp to cosines of lsp */
  114935. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114936. float amp,float ampoffset){
  114937. int i;
  114938. float wdel=M_PI/ln;
  114939. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114940. i=0;
  114941. while(i<n){
  114942. int j,k=map[i];
  114943. float p=.5f;
  114944. float q=.5f;
  114945. float w=2.f*cos(wdel*k);
  114946. for(j=1;j<m;j+=2){
  114947. q *= w-lsp[j-1];
  114948. p *= w-lsp[j];
  114949. }
  114950. if(j==m){
  114951. /* odd order filter; slightly assymetric */
  114952. /* the last coefficient */
  114953. q*=w-lsp[j-1];
  114954. p*=p*(4.f-w*w);
  114955. q*=q;
  114956. }else{
  114957. /* even order filter; still symmetric */
  114958. p*=p*(2.f-w);
  114959. q*=q*(2.f+w);
  114960. }
  114961. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114962. curve[i]*=q;
  114963. while(map[++i]==k)curve[i]*=q;
  114964. }
  114965. }
  114966. #endif
  114967. #endif
  114968. static void cheby(float *g, int ord) {
  114969. int i, j;
  114970. g[0] *= .5f;
  114971. for(i=2; i<= ord; i++) {
  114972. for(j=ord; j >= i; j--) {
  114973. g[j-2] -= g[j];
  114974. g[j] += g[j];
  114975. }
  114976. }
  114977. }
  114978. static int JUCE_CDECL comp(const void *a,const void *b){
  114979. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114980. }
  114981. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114982. but there are root sets for which it gets into limit cycles
  114983. (exacerbated by zero suppression) and fails. We can't afford to
  114984. fail, even if the failure is 1 in 100,000,000, so we now use
  114985. Laguerre and later polish with Newton-Raphson (which can then
  114986. afford to fail) */
  114987. #define EPSILON 10e-7
  114988. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114989. int i,m;
  114990. double lastdelta=0.f;
  114991. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114992. for(i=0;i<=ord;i++)defl[i]=a[i];
  114993. for(m=ord;m>0;m--){
  114994. double newx=0.f,delta;
  114995. /* iterate a root */
  114996. while(1){
  114997. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114998. /* eval the polynomial and its first two derivatives */
  114999. for(i=m;i>0;i--){
  115000. ppp = newx*ppp + pp;
  115001. pp = newx*pp + p;
  115002. p = newx*p + defl[i-1];
  115003. }
  115004. /* Laguerre's method */
  115005. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115006. if(denom<0)
  115007. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115008. if(pp>0){
  115009. denom = pp + sqrt(denom);
  115010. if(denom<EPSILON)denom=EPSILON;
  115011. }else{
  115012. denom = pp - sqrt(denom);
  115013. if(denom>-(EPSILON))denom=-(EPSILON);
  115014. }
  115015. delta = m*p/denom;
  115016. newx -= delta;
  115017. if(delta<0.f)delta*=-1;
  115018. if(fabs(delta/newx)<10e-12)break;
  115019. lastdelta=delta;
  115020. }
  115021. r[m-1]=newx;
  115022. /* forward deflation */
  115023. for(i=m;i>0;i--)
  115024. defl[i-1]+=newx*defl[i];
  115025. defl++;
  115026. }
  115027. return(0);
  115028. }
  115029. /* for spit-and-polish only */
  115030. static int Newton_Raphson(float *a,int ord,float *r){
  115031. int i, k, count=0;
  115032. double error=1.f;
  115033. double *root=(double*)alloca(ord*sizeof(*root));
  115034. for(i=0; i<ord;i++) root[i] = r[i];
  115035. while(error>1e-20){
  115036. error=0;
  115037. for(i=0; i<ord; i++) { /* Update each point. */
  115038. double pp=0.,delta;
  115039. double rooti=root[i];
  115040. double p=a[ord];
  115041. for(k=ord-1; k>= 0; k--) {
  115042. pp= pp* rooti + p;
  115043. p = p * rooti + a[k];
  115044. }
  115045. delta = p/pp;
  115046. root[i] -= delta;
  115047. error+= delta*delta;
  115048. }
  115049. if(count>40)return(-1);
  115050. count++;
  115051. }
  115052. /* Replaced the original bubble sort with a real sort. With your
  115053. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115054. for(i=0; i<ord;i++) r[i] = root[i];
  115055. return(0);
  115056. }
  115057. /* Convert lpc coefficients to lsp coefficients */
  115058. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115059. int order2=(m+1)>>1;
  115060. int g1_order,g2_order;
  115061. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115062. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115063. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115064. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115065. int i;
  115066. /* even and odd are slightly different base cases */
  115067. g1_order=(m+1)>>1;
  115068. g2_order=(m) >>1;
  115069. /* Compute the lengths of the x polynomials. */
  115070. /* Compute the first half of K & R F1 & F2 polynomials. */
  115071. /* Compute half of the symmetric and antisymmetric polynomials. */
  115072. /* Remove the roots at +1 and -1. */
  115073. g1[g1_order] = 1.f;
  115074. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115075. g2[g2_order] = 1.f;
  115076. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115077. if(g1_order>g2_order){
  115078. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115079. }else{
  115080. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115081. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115082. }
  115083. /* Convert into polynomials in cos(alpha) */
  115084. cheby(g1,g1_order);
  115085. cheby(g2,g2_order);
  115086. /* Find the roots of the 2 even polynomials.*/
  115087. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115088. Laguerre_With_Deflation(g2,g2_order,g2r))
  115089. return(-1);
  115090. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115091. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115092. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115093. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115094. for(i=0;i<g1_order;i++)
  115095. lsp[i*2] = acos(g1r[i]);
  115096. for(i=0;i<g2_order;i++)
  115097. lsp[i*2+1] = acos(g2r[i]);
  115098. return(0);
  115099. }
  115100. #endif
  115101. /*** End of inlined file: lsp.c ***/
  115102. /*** Start of inlined file: mapping0.c ***/
  115103. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115104. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115105. // tasks..
  115106. #if JUCE_MSVC
  115107. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115108. #endif
  115109. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115110. #if JUCE_USE_OGGVORBIS
  115111. #include <stdlib.h>
  115112. #include <stdio.h>
  115113. #include <string.h>
  115114. #include <math.h>
  115115. /* simplistic, wasteful way of doing this (unique lookup for each
  115116. mode/submapping); there should be a central repository for
  115117. identical lookups. That will require minor work, so I'm putting it
  115118. off as low priority.
  115119. Why a lookup for each backend in a given mode? Because the
  115120. blocksize is set by the mode, and low backend lookups may require
  115121. parameters from other areas of the mode/mapping */
  115122. static void mapping0_free_info(vorbis_info_mapping *i){
  115123. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115124. if(info){
  115125. memset(info,0,sizeof(*info));
  115126. _ogg_free(info);
  115127. }
  115128. }
  115129. static int ilog3(unsigned int v){
  115130. int ret=0;
  115131. if(v)--v;
  115132. while(v){
  115133. ret++;
  115134. v>>=1;
  115135. }
  115136. return(ret);
  115137. }
  115138. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115139. oggpack_buffer *opb){
  115140. int i;
  115141. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115142. /* another 'we meant to do it this way' hack... up to beta 4, we
  115143. packed 4 binary zeros here to signify one submapping in use. We
  115144. now redefine that to mean four bitflags that indicate use of
  115145. deeper features; bit0:submappings, bit1:coupling,
  115146. bit2,3:reserved. This is backward compatable with all actual uses
  115147. of the beta code. */
  115148. if(info->submaps>1){
  115149. oggpack_write(opb,1,1);
  115150. oggpack_write(opb,info->submaps-1,4);
  115151. }else
  115152. oggpack_write(opb,0,1);
  115153. if(info->coupling_steps>0){
  115154. oggpack_write(opb,1,1);
  115155. oggpack_write(opb,info->coupling_steps-1,8);
  115156. for(i=0;i<info->coupling_steps;i++){
  115157. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115158. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115159. }
  115160. }else
  115161. oggpack_write(opb,0,1);
  115162. oggpack_write(opb,0,2); /* 2,3:reserved */
  115163. /* we don't write the channel submappings if we only have one... */
  115164. if(info->submaps>1){
  115165. for(i=0;i<vi->channels;i++)
  115166. oggpack_write(opb,info->chmuxlist[i],4);
  115167. }
  115168. for(i=0;i<info->submaps;i++){
  115169. oggpack_write(opb,0,8); /* time submap unused */
  115170. oggpack_write(opb,info->floorsubmap[i],8);
  115171. oggpack_write(opb,info->residuesubmap[i],8);
  115172. }
  115173. }
  115174. /* also responsible for range checking */
  115175. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115176. int i;
  115177. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115178. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115179. memset(info,0,sizeof(*info));
  115180. if(oggpack_read(opb,1))
  115181. info->submaps=oggpack_read(opb,4)+1;
  115182. else
  115183. info->submaps=1;
  115184. if(oggpack_read(opb,1)){
  115185. info->coupling_steps=oggpack_read(opb,8)+1;
  115186. for(i=0;i<info->coupling_steps;i++){
  115187. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115188. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115189. if(testM<0 ||
  115190. testA<0 ||
  115191. testM==testA ||
  115192. testM>=vi->channels ||
  115193. testA>=vi->channels) goto err_out;
  115194. }
  115195. }
  115196. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115197. if(info->submaps>1){
  115198. for(i=0;i<vi->channels;i++){
  115199. info->chmuxlist[i]=oggpack_read(opb,4);
  115200. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115201. }
  115202. }
  115203. for(i=0;i<info->submaps;i++){
  115204. oggpack_read(opb,8); /* time submap unused */
  115205. info->floorsubmap[i]=oggpack_read(opb,8);
  115206. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115207. info->residuesubmap[i]=oggpack_read(opb,8);
  115208. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115209. }
  115210. return info;
  115211. err_out:
  115212. mapping0_free_info(info);
  115213. return(NULL);
  115214. }
  115215. #if 0
  115216. static long seq=0;
  115217. static ogg_int64_t total=0;
  115218. static float FLOOR1_fromdB_LOOKUP[256]={
  115219. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115220. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115221. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115222. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115223. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115224. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115225. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115226. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115227. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115228. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115229. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115230. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115231. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115232. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115233. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115234. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115235. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115236. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115237. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115238. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115239. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115240. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115241. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115242. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115243. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115244. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115245. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115246. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115247. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115248. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115249. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115250. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115251. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115252. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115253. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115254. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115255. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115256. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115257. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115258. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115259. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115260. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115261. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115262. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115263. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115264. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115265. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115266. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115267. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115268. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115269. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115270. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115271. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115272. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115273. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115274. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115275. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115276. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115277. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115278. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115279. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115280. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115281. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115282. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115283. };
  115284. #endif
  115285. extern int *floor1_fit(vorbis_block *vb,void *look,
  115286. const float *logmdct, /* in */
  115287. const float *logmask);
  115288. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115289. int *A,int *B,
  115290. int del);
  115291. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115292. void*look,
  115293. int *post,int *ilogmask);
  115294. static int mapping0_forward(vorbis_block *vb){
  115295. vorbis_dsp_state *vd=vb->vd;
  115296. vorbis_info *vi=vd->vi;
  115297. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115298. private_state *b=(private_state*)vb->vd->backend_state;
  115299. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115300. int n=vb->pcmend;
  115301. int i,j,k;
  115302. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115303. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115304. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115305. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115306. float global_ampmax=vbi->ampmax;
  115307. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115308. int blocktype=vbi->blocktype;
  115309. int modenumber=vb->W;
  115310. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115311. vorbis_look_psy *psy_look=
  115312. b->psy+blocktype+(vb->W?2:0);
  115313. vb->mode=modenumber;
  115314. for(i=0;i<vi->channels;i++){
  115315. float scale=4.f/n;
  115316. float scale_dB;
  115317. float *pcm =vb->pcm[i];
  115318. float *logfft =pcm;
  115319. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115320. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115321. todB estimation used on IEEE 754
  115322. compliant machines had a bug that
  115323. returned dB values about a third
  115324. of a decibel too high. The bug
  115325. was harmless because tunings
  115326. implicitly took that into
  115327. account. However, fixing the bug
  115328. in the estimator requires
  115329. changing all the tunings as well.
  115330. For now, it's easier to sync
  115331. things back up here, and
  115332. recalibrate the tunings in the
  115333. next major model upgrade. */
  115334. #if 0
  115335. if(vi->channels==2)
  115336. if(i==0)
  115337. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115338. else
  115339. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115340. #endif
  115341. /* window the PCM data */
  115342. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115343. #if 0
  115344. if(vi->channels==2)
  115345. if(i==0)
  115346. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115347. else
  115348. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115349. #endif
  115350. /* transform the PCM data */
  115351. /* only MDCT right now.... */
  115352. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115353. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115354. drft_forward(&b->fft_look[vb->W],pcm);
  115355. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115356. original todB estimation used on
  115357. IEEE 754 compliant machines had a
  115358. bug that returned dB values about
  115359. a third of a decibel too high.
  115360. The bug was harmless because
  115361. tunings implicitly took that into
  115362. account. However, fixing the bug
  115363. in the estimator requires
  115364. changing all the tunings as well.
  115365. For now, it's easier to sync
  115366. things back up here, and
  115367. recalibrate the tunings in the
  115368. next major model upgrade. */
  115369. local_ampmax[i]=logfft[0];
  115370. for(j=1;j<n-1;j+=2){
  115371. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115372. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115373. .345 is a hack; the original todB
  115374. estimation used on IEEE 754
  115375. compliant machines had a bug that
  115376. returned dB values about a third
  115377. of a decibel too high. The bug
  115378. was harmless because tunings
  115379. implicitly took that into
  115380. account. However, fixing the bug
  115381. in the estimator requires
  115382. changing all the tunings as well.
  115383. For now, it's easier to sync
  115384. things back up here, and
  115385. recalibrate the tunings in the
  115386. next major model upgrade. */
  115387. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115388. }
  115389. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115390. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115391. #if 0
  115392. if(vi->channels==2){
  115393. if(i==0){
  115394. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115395. }else{
  115396. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115397. }
  115398. }
  115399. #endif
  115400. }
  115401. {
  115402. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115403. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115404. for(i=0;i<vi->channels;i++){
  115405. /* the encoder setup assumes that all the modes used by any
  115406. specific bitrate tweaking use the same floor */
  115407. int submap=info->chmuxlist[i];
  115408. /* the following makes things clearer to *me* anyway */
  115409. float *mdct =gmdct[i];
  115410. float *logfft =vb->pcm[i];
  115411. float *logmdct =logfft+n/2;
  115412. float *logmask =logfft;
  115413. vb->mode=modenumber;
  115414. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115415. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115416. for(j=0;j<n/2;j++)
  115417. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115418. todB estimation used on IEEE 754
  115419. compliant machines had a bug that
  115420. returned dB values about a third
  115421. of a decibel too high. The bug
  115422. was harmless because tunings
  115423. implicitly took that into
  115424. account. However, fixing the bug
  115425. in the estimator requires
  115426. changing all the tunings as well.
  115427. For now, it's easier to sync
  115428. things back up here, and
  115429. recalibrate the tunings in the
  115430. next major model upgrade. */
  115431. #if 0
  115432. if(vi->channels==2){
  115433. if(i==0)
  115434. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115435. else
  115436. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115437. }else{
  115438. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115439. }
  115440. #endif
  115441. /* first step; noise masking. Not only does 'noise masking'
  115442. give us curves from which we can decide how much resolution
  115443. to give noise parts of the spectrum, it also implicitly hands
  115444. us a tonality estimate (the larger the value in the
  115445. 'noise_depth' vector, the more tonal that area is) */
  115446. _vp_noisemask(psy_look,
  115447. logmdct,
  115448. noise); /* noise does not have by-frequency offset
  115449. bias applied yet */
  115450. #if 0
  115451. if(vi->channels==2){
  115452. if(i==0)
  115453. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115454. else
  115455. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115456. }
  115457. #endif
  115458. /* second step: 'all the other crap'; all the stuff that isn't
  115459. computed/fit for bitrate management goes in the second psy
  115460. vector. This includes tone masking, peak limiting and ATH */
  115461. _vp_tonemask(psy_look,
  115462. logfft,
  115463. tone,
  115464. global_ampmax,
  115465. local_ampmax[i]);
  115466. #if 0
  115467. if(vi->channels==2){
  115468. if(i==0)
  115469. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115470. else
  115471. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115472. }
  115473. #endif
  115474. /* third step; we offset the noise vectors, overlay tone
  115475. masking. We then do a floor1-specific line fit. If we're
  115476. performing bitrate management, the line fit is performed
  115477. multiple times for up/down tweakage on demand. */
  115478. #if 0
  115479. {
  115480. float aotuv[psy_look->n];
  115481. #endif
  115482. _vp_offset_and_mix(psy_look,
  115483. noise,
  115484. tone,
  115485. 1,
  115486. logmask,
  115487. mdct,
  115488. logmdct);
  115489. #if 0
  115490. if(vi->channels==2){
  115491. if(i==0)
  115492. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115493. else
  115494. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115495. }
  115496. }
  115497. #endif
  115498. #if 0
  115499. if(vi->channels==2){
  115500. if(i==0)
  115501. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115502. else
  115503. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115504. }
  115505. #endif
  115506. /* this algorithm is hardwired to floor 1 for now; abort out if
  115507. we're *not* floor1. This won't happen unless someone has
  115508. broken the encode setup lib. Guard it anyway. */
  115509. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115510. floor_posts[i][PACKETBLOBS/2]=
  115511. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115512. logmdct,
  115513. logmask);
  115514. /* are we managing bitrate? If so, perform two more fits for
  115515. later rate tweaking (fits represent hi/lo) */
  115516. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115517. /* higher rate by way of lower noise curve */
  115518. _vp_offset_and_mix(psy_look,
  115519. noise,
  115520. tone,
  115521. 2,
  115522. logmask,
  115523. mdct,
  115524. logmdct);
  115525. #if 0
  115526. if(vi->channels==2){
  115527. if(i==0)
  115528. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115529. else
  115530. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115531. }
  115532. #endif
  115533. floor_posts[i][PACKETBLOBS-1]=
  115534. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115535. logmdct,
  115536. logmask);
  115537. /* lower rate by way of higher noise curve */
  115538. _vp_offset_and_mix(psy_look,
  115539. noise,
  115540. tone,
  115541. 0,
  115542. logmask,
  115543. mdct,
  115544. logmdct);
  115545. #if 0
  115546. if(vi->channels==2)
  115547. if(i==0)
  115548. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115549. else
  115550. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115551. #endif
  115552. floor_posts[i][0]=
  115553. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115554. logmdct,
  115555. logmask);
  115556. /* we also interpolate a range of intermediate curves for
  115557. intermediate rates */
  115558. for(k=1;k<PACKETBLOBS/2;k++)
  115559. floor_posts[i][k]=
  115560. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115561. floor_posts[i][0],
  115562. floor_posts[i][PACKETBLOBS/2],
  115563. k*65536/(PACKETBLOBS/2));
  115564. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115565. floor_posts[i][k]=
  115566. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115567. floor_posts[i][PACKETBLOBS/2],
  115568. floor_posts[i][PACKETBLOBS-1],
  115569. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115570. }
  115571. }
  115572. }
  115573. vbi->ampmax=global_ampmax;
  115574. /*
  115575. the next phases are performed once for vbr-only and PACKETBLOB
  115576. times for bitrate managed modes.
  115577. 1) encode actual mode being used
  115578. 2) encode the floor for each channel, compute coded mask curve/res
  115579. 3) normalize and couple.
  115580. 4) encode residue
  115581. 5) save packet bytes to the packetblob vector
  115582. */
  115583. /* iterate over the many masking curve fits we've created */
  115584. {
  115585. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115586. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115587. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115588. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115589. float **mag_memo;
  115590. int **mag_sort;
  115591. if(info->coupling_steps){
  115592. mag_memo=_vp_quantize_couple_memo(vb,
  115593. &ci->psy_g_param,
  115594. psy_look,
  115595. info,
  115596. gmdct);
  115597. mag_sort=_vp_quantize_couple_sort(vb,
  115598. psy_look,
  115599. info,
  115600. mag_memo);
  115601. hf_reduction(&ci->psy_g_param,
  115602. psy_look,
  115603. info,
  115604. mag_memo);
  115605. }
  115606. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115607. if(psy_look->vi->normal_channel_p){
  115608. for(i=0;i<vi->channels;i++){
  115609. float *mdct =gmdct[i];
  115610. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115611. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115612. }
  115613. }
  115614. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115615. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115616. k++){
  115617. oggpack_buffer *opb=vbi->packetblob[k];
  115618. /* start out our new packet blob with packet type and mode */
  115619. /* Encode the packet type */
  115620. oggpack_write(opb,0,1);
  115621. /* Encode the modenumber */
  115622. /* Encode frame mode, pre,post windowsize, then dispatch */
  115623. oggpack_write(opb,modenumber,b->modebits);
  115624. if(vb->W){
  115625. oggpack_write(opb,vb->lW,1);
  115626. oggpack_write(opb,vb->nW,1);
  115627. }
  115628. /* encode floor, compute masking curve, sep out residue */
  115629. for(i=0;i<vi->channels;i++){
  115630. int submap=info->chmuxlist[i];
  115631. float *mdct =gmdct[i];
  115632. float *res =vb->pcm[i];
  115633. int *ilogmask=ilogmaskch[i]=
  115634. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115635. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115636. floor_posts[i][k],
  115637. ilogmask);
  115638. #if 0
  115639. {
  115640. char buf[80];
  115641. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115642. float work[n/2];
  115643. for(j=0;j<n/2;j++)
  115644. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115645. _analysis_output(buf,seq,work,n/2,1,1,0);
  115646. }
  115647. #endif
  115648. _vp_remove_floor(psy_look,
  115649. mdct,
  115650. ilogmask,
  115651. res,
  115652. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115653. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115654. #if 0
  115655. {
  115656. char buf[80];
  115657. float work[n/2];
  115658. for(j=0;j<n/2;j++)
  115659. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115660. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115661. _analysis_output(buf,seq,work,n/2,1,1,0);
  115662. }
  115663. #endif
  115664. }
  115665. /* our iteration is now based on masking curve, not prequant and
  115666. coupling. Only one prequant/coupling step */
  115667. /* quantize/couple */
  115668. /* incomplete implementation that assumes the tree is all depth
  115669. one, or no tree at all */
  115670. if(info->coupling_steps){
  115671. _vp_couple(k,
  115672. &ci->psy_g_param,
  115673. psy_look,
  115674. info,
  115675. vb->pcm,
  115676. mag_memo,
  115677. mag_sort,
  115678. ilogmaskch,
  115679. nonzero,
  115680. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115681. }
  115682. /* classify and encode by submap */
  115683. for(i=0;i<info->submaps;i++){
  115684. int ch_in_bundle=0;
  115685. long **classifications;
  115686. int resnum=info->residuesubmap[i];
  115687. for(j=0;j<vi->channels;j++){
  115688. if(info->chmuxlist[j]==i){
  115689. zerobundle[ch_in_bundle]=0;
  115690. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115691. res_bundle[ch_in_bundle]=vb->pcm[j];
  115692. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115693. }
  115694. }
  115695. classifications=_residue_P[ci->residue_type[resnum]]->
  115696. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115697. _residue_P[ci->residue_type[resnum]]->
  115698. forward(opb,vb,b->residue[resnum],
  115699. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115700. }
  115701. /* ok, done encoding. Next protopacket. */
  115702. }
  115703. }
  115704. #if 0
  115705. seq++;
  115706. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115707. #endif
  115708. return(0);
  115709. }
  115710. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115711. vorbis_dsp_state *vd=vb->vd;
  115712. vorbis_info *vi=vd->vi;
  115713. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115714. private_state *b=(private_state*)vd->backend_state;
  115715. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115716. int i,j;
  115717. long n=vb->pcmend=ci->blocksizes[vb->W];
  115718. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115719. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115720. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115721. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115722. /* recover the spectral envelope; store it in the PCM vector for now */
  115723. for(i=0;i<vi->channels;i++){
  115724. int submap=info->chmuxlist[i];
  115725. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115726. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115727. if(floormemo[i])
  115728. nonzero[i]=1;
  115729. else
  115730. nonzero[i]=0;
  115731. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115732. }
  115733. /* channel coupling can 'dirty' the nonzero listing */
  115734. for(i=0;i<info->coupling_steps;i++){
  115735. if(nonzero[info->coupling_mag[i]] ||
  115736. nonzero[info->coupling_ang[i]]){
  115737. nonzero[info->coupling_mag[i]]=1;
  115738. nonzero[info->coupling_ang[i]]=1;
  115739. }
  115740. }
  115741. /* recover the residue into our working vectors */
  115742. for(i=0;i<info->submaps;i++){
  115743. int ch_in_bundle=0;
  115744. for(j=0;j<vi->channels;j++){
  115745. if(info->chmuxlist[j]==i){
  115746. if(nonzero[j])
  115747. zerobundle[ch_in_bundle]=1;
  115748. else
  115749. zerobundle[ch_in_bundle]=0;
  115750. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115751. }
  115752. }
  115753. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115754. inverse(vb,b->residue[info->residuesubmap[i]],
  115755. pcmbundle,zerobundle,ch_in_bundle);
  115756. }
  115757. /* channel coupling */
  115758. for(i=info->coupling_steps-1;i>=0;i--){
  115759. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115760. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115761. for(j=0;j<n/2;j++){
  115762. float mag=pcmM[j];
  115763. float ang=pcmA[j];
  115764. if(mag>0)
  115765. if(ang>0){
  115766. pcmM[j]=mag;
  115767. pcmA[j]=mag-ang;
  115768. }else{
  115769. pcmA[j]=mag;
  115770. pcmM[j]=mag+ang;
  115771. }
  115772. else
  115773. if(ang>0){
  115774. pcmM[j]=mag;
  115775. pcmA[j]=mag+ang;
  115776. }else{
  115777. pcmA[j]=mag;
  115778. pcmM[j]=mag-ang;
  115779. }
  115780. }
  115781. }
  115782. /* compute and apply spectral envelope */
  115783. for(i=0;i<vi->channels;i++){
  115784. float *pcm=vb->pcm[i];
  115785. int submap=info->chmuxlist[i];
  115786. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115787. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115788. floormemo[i],pcm);
  115789. }
  115790. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115791. /* only MDCT right now.... */
  115792. for(i=0;i<vi->channels;i++){
  115793. float *pcm=vb->pcm[i];
  115794. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115795. }
  115796. /* all done! */
  115797. return(0);
  115798. }
  115799. /* export hooks */
  115800. vorbis_func_mapping mapping0_exportbundle={
  115801. &mapping0_pack,
  115802. &mapping0_unpack,
  115803. &mapping0_free_info,
  115804. &mapping0_forward,
  115805. &mapping0_inverse
  115806. };
  115807. #endif
  115808. /*** End of inlined file: mapping0.c ***/
  115809. /*** Start of inlined file: mdct.c ***/
  115810. /* this can also be run as an integer transform by uncommenting a
  115811. define in mdct.h; the integerization is a first pass and although
  115812. it's likely stable for Vorbis, the dynamic range is constrained and
  115813. roundoff isn't done (so it's noisy). Consider it functional, but
  115814. only a starting point. There's no point on a machine with an FPU */
  115815. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115816. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115817. // tasks..
  115818. #if JUCE_MSVC
  115819. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115820. #endif
  115821. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115822. #if JUCE_USE_OGGVORBIS
  115823. #include <stdio.h>
  115824. #include <stdlib.h>
  115825. #include <string.h>
  115826. #include <math.h>
  115827. /* build lookups for trig functions; also pre-figure scaling and
  115828. some window function algebra. */
  115829. void mdct_init(mdct_lookup *lookup,int n){
  115830. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115831. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115832. int i;
  115833. int n2=n>>1;
  115834. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115835. lookup->n=n;
  115836. lookup->trig=T;
  115837. lookup->bitrev=bitrev;
  115838. /* trig lookups... */
  115839. for(i=0;i<n/4;i++){
  115840. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115841. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115842. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115843. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115844. }
  115845. for(i=0;i<n/8;i++){
  115846. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115847. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115848. }
  115849. /* bitreverse lookup... */
  115850. {
  115851. int mask=(1<<(log2n-1))-1,i,j;
  115852. int msb=1<<(log2n-2);
  115853. for(i=0;i<n/8;i++){
  115854. int acc=0;
  115855. for(j=0;msb>>j;j++)
  115856. if((msb>>j)&i)acc|=1<<j;
  115857. bitrev[i*2]=((~acc)&mask)-1;
  115858. bitrev[i*2+1]=acc;
  115859. }
  115860. }
  115861. lookup->scale=FLOAT_CONV(4.f/n);
  115862. }
  115863. /* 8 point butterfly (in place, 4 register) */
  115864. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115865. REG_TYPE r0 = x[6] + x[2];
  115866. REG_TYPE r1 = x[6] - x[2];
  115867. REG_TYPE r2 = x[4] + x[0];
  115868. REG_TYPE r3 = x[4] - x[0];
  115869. x[6] = r0 + r2;
  115870. x[4] = r0 - r2;
  115871. r0 = x[5] - x[1];
  115872. r2 = x[7] - x[3];
  115873. x[0] = r1 + r0;
  115874. x[2] = r1 - r0;
  115875. r0 = x[5] + x[1];
  115876. r1 = x[7] + x[3];
  115877. x[3] = r2 + r3;
  115878. x[1] = r2 - r3;
  115879. x[7] = r1 + r0;
  115880. x[5] = r1 - r0;
  115881. }
  115882. /* 16 point butterfly (in place, 4 register) */
  115883. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115884. REG_TYPE r0 = x[1] - x[9];
  115885. REG_TYPE r1 = x[0] - x[8];
  115886. x[8] += x[0];
  115887. x[9] += x[1];
  115888. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115889. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115890. r0 = x[3] - x[11];
  115891. r1 = x[10] - x[2];
  115892. x[10] += x[2];
  115893. x[11] += x[3];
  115894. x[2] = r0;
  115895. x[3] = r1;
  115896. r0 = x[12] - x[4];
  115897. r1 = x[13] - x[5];
  115898. x[12] += x[4];
  115899. x[13] += x[5];
  115900. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115901. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115902. r0 = x[14] - x[6];
  115903. r1 = x[15] - x[7];
  115904. x[14] += x[6];
  115905. x[15] += x[7];
  115906. x[6] = r0;
  115907. x[7] = r1;
  115908. mdct_butterfly_8(x);
  115909. mdct_butterfly_8(x+8);
  115910. }
  115911. /* 32 point butterfly (in place, 4 register) */
  115912. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115913. REG_TYPE r0 = x[30] - x[14];
  115914. REG_TYPE r1 = x[31] - x[15];
  115915. x[30] += x[14];
  115916. x[31] += x[15];
  115917. x[14] = r0;
  115918. x[15] = r1;
  115919. r0 = x[28] - x[12];
  115920. r1 = x[29] - x[13];
  115921. x[28] += x[12];
  115922. x[29] += x[13];
  115923. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115924. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115925. r0 = x[26] - x[10];
  115926. r1 = x[27] - x[11];
  115927. x[26] += x[10];
  115928. x[27] += x[11];
  115929. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115930. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115931. r0 = x[24] - x[8];
  115932. r1 = x[25] - x[9];
  115933. x[24] += x[8];
  115934. x[25] += x[9];
  115935. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115936. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115937. r0 = x[22] - x[6];
  115938. r1 = x[7] - x[23];
  115939. x[22] += x[6];
  115940. x[23] += x[7];
  115941. x[6] = r1;
  115942. x[7] = r0;
  115943. r0 = x[4] - x[20];
  115944. r1 = x[5] - x[21];
  115945. x[20] += x[4];
  115946. x[21] += x[5];
  115947. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115948. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115949. r0 = x[2] - x[18];
  115950. r1 = x[3] - x[19];
  115951. x[18] += x[2];
  115952. x[19] += x[3];
  115953. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115954. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115955. r0 = x[0] - x[16];
  115956. r1 = x[1] - x[17];
  115957. x[16] += x[0];
  115958. x[17] += x[1];
  115959. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115960. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115961. mdct_butterfly_16(x);
  115962. mdct_butterfly_16(x+16);
  115963. }
  115964. /* N point first stage butterfly (in place, 2 register) */
  115965. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115966. DATA_TYPE *x,
  115967. int points){
  115968. DATA_TYPE *x1 = x + points - 8;
  115969. DATA_TYPE *x2 = x + (points>>1) - 8;
  115970. REG_TYPE r0;
  115971. REG_TYPE r1;
  115972. do{
  115973. r0 = x1[6] - x2[6];
  115974. r1 = x1[7] - x2[7];
  115975. x1[6] += x2[6];
  115976. x1[7] += x2[7];
  115977. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115978. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115979. r0 = x1[4] - x2[4];
  115980. r1 = x1[5] - x2[5];
  115981. x1[4] += x2[4];
  115982. x1[5] += x2[5];
  115983. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115984. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115985. r0 = x1[2] - x2[2];
  115986. r1 = x1[3] - x2[3];
  115987. x1[2] += x2[2];
  115988. x1[3] += x2[3];
  115989. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115990. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115991. r0 = x1[0] - x2[0];
  115992. r1 = x1[1] - x2[1];
  115993. x1[0] += x2[0];
  115994. x1[1] += x2[1];
  115995. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115996. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115997. x1-=8;
  115998. x2-=8;
  115999. T+=16;
  116000. }while(x2>=x);
  116001. }
  116002. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116003. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116004. DATA_TYPE *x,
  116005. int points,
  116006. int trigint){
  116007. DATA_TYPE *x1 = x + points - 8;
  116008. DATA_TYPE *x2 = x + (points>>1) - 8;
  116009. REG_TYPE r0;
  116010. REG_TYPE r1;
  116011. do{
  116012. r0 = x1[6] - x2[6];
  116013. r1 = x1[7] - x2[7];
  116014. x1[6] += x2[6];
  116015. x1[7] += x2[7];
  116016. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116017. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116018. T+=trigint;
  116019. r0 = x1[4] - x2[4];
  116020. r1 = x1[5] - x2[5];
  116021. x1[4] += x2[4];
  116022. x1[5] += x2[5];
  116023. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116024. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116025. T+=trigint;
  116026. r0 = x1[2] - x2[2];
  116027. r1 = x1[3] - x2[3];
  116028. x1[2] += x2[2];
  116029. x1[3] += x2[3];
  116030. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116031. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116032. T+=trigint;
  116033. r0 = x1[0] - x2[0];
  116034. r1 = x1[1] - x2[1];
  116035. x1[0] += x2[0];
  116036. x1[1] += x2[1];
  116037. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116038. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116039. T+=trigint;
  116040. x1-=8;
  116041. x2-=8;
  116042. }while(x2>=x);
  116043. }
  116044. STIN void mdct_butterflies(mdct_lookup *init,
  116045. DATA_TYPE *x,
  116046. int points){
  116047. DATA_TYPE *T=init->trig;
  116048. int stages=init->log2n-5;
  116049. int i,j;
  116050. if(--stages>0){
  116051. mdct_butterfly_first(T,x,points);
  116052. }
  116053. for(i=1;--stages>0;i++){
  116054. for(j=0;j<(1<<i);j++)
  116055. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116056. }
  116057. for(j=0;j<points;j+=32)
  116058. mdct_butterfly_32(x+j);
  116059. }
  116060. void mdct_clear(mdct_lookup *l){
  116061. if(l){
  116062. if(l->trig)_ogg_free(l->trig);
  116063. if(l->bitrev)_ogg_free(l->bitrev);
  116064. memset(l,0,sizeof(*l));
  116065. }
  116066. }
  116067. STIN void mdct_bitreverse(mdct_lookup *init,
  116068. DATA_TYPE *x){
  116069. int n = init->n;
  116070. int *bit = init->bitrev;
  116071. DATA_TYPE *w0 = x;
  116072. DATA_TYPE *w1 = x = w0+(n>>1);
  116073. DATA_TYPE *T = init->trig+n;
  116074. do{
  116075. DATA_TYPE *x0 = x+bit[0];
  116076. DATA_TYPE *x1 = x+bit[1];
  116077. REG_TYPE r0 = x0[1] - x1[1];
  116078. REG_TYPE r1 = x0[0] + x1[0];
  116079. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116080. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116081. w1 -= 4;
  116082. r0 = HALVE(x0[1] + x1[1]);
  116083. r1 = HALVE(x0[0] - x1[0]);
  116084. w0[0] = r0 + r2;
  116085. w1[2] = r0 - r2;
  116086. w0[1] = r1 + r3;
  116087. w1[3] = r3 - r1;
  116088. x0 = x+bit[2];
  116089. x1 = x+bit[3];
  116090. r0 = x0[1] - x1[1];
  116091. r1 = x0[0] + x1[0];
  116092. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116093. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116094. r0 = HALVE(x0[1] + x1[1]);
  116095. r1 = HALVE(x0[0] - x1[0]);
  116096. w0[2] = r0 + r2;
  116097. w1[0] = r0 - r2;
  116098. w0[3] = r1 + r3;
  116099. w1[1] = r3 - r1;
  116100. T += 4;
  116101. bit += 4;
  116102. w0 += 4;
  116103. }while(w0<w1);
  116104. }
  116105. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116106. int n=init->n;
  116107. int n2=n>>1;
  116108. int n4=n>>2;
  116109. /* rotate */
  116110. DATA_TYPE *iX = in+n2-7;
  116111. DATA_TYPE *oX = out+n2+n4;
  116112. DATA_TYPE *T = init->trig+n4;
  116113. do{
  116114. oX -= 4;
  116115. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116116. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116117. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116118. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116119. iX -= 8;
  116120. T += 4;
  116121. }while(iX>=in);
  116122. iX = in+n2-8;
  116123. oX = out+n2+n4;
  116124. T = init->trig+n4;
  116125. do{
  116126. T -= 4;
  116127. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116128. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116129. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116130. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116131. iX -= 8;
  116132. oX += 4;
  116133. }while(iX>=in);
  116134. mdct_butterflies(init,out+n2,n2);
  116135. mdct_bitreverse(init,out);
  116136. /* roatate + window */
  116137. {
  116138. DATA_TYPE *oX1=out+n2+n4;
  116139. DATA_TYPE *oX2=out+n2+n4;
  116140. DATA_TYPE *iX =out;
  116141. T =init->trig+n2;
  116142. do{
  116143. oX1-=4;
  116144. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116145. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116146. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116147. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116148. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116149. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116150. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116151. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116152. oX2+=4;
  116153. iX += 8;
  116154. T += 8;
  116155. }while(iX<oX1);
  116156. iX=out+n2+n4;
  116157. oX1=out+n4;
  116158. oX2=oX1;
  116159. do{
  116160. oX1-=4;
  116161. iX-=4;
  116162. oX2[0] = -(oX1[3] = iX[3]);
  116163. oX2[1] = -(oX1[2] = iX[2]);
  116164. oX2[2] = -(oX1[1] = iX[1]);
  116165. oX2[3] = -(oX1[0] = iX[0]);
  116166. oX2+=4;
  116167. }while(oX2<iX);
  116168. iX=out+n2+n4;
  116169. oX1=out+n2+n4;
  116170. oX2=out+n2;
  116171. do{
  116172. oX1-=4;
  116173. oX1[0]= iX[3];
  116174. oX1[1]= iX[2];
  116175. oX1[2]= iX[1];
  116176. oX1[3]= iX[0];
  116177. iX+=4;
  116178. }while(oX1>oX2);
  116179. }
  116180. }
  116181. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116182. int n=init->n;
  116183. int n2=n>>1;
  116184. int n4=n>>2;
  116185. int n8=n>>3;
  116186. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116187. DATA_TYPE *w2=w+n2;
  116188. /* rotate */
  116189. /* window + rotate + step 1 */
  116190. REG_TYPE r0;
  116191. REG_TYPE r1;
  116192. DATA_TYPE *x0=in+n2+n4;
  116193. DATA_TYPE *x1=x0+1;
  116194. DATA_TYPE *T=init->trig+n2;
  116195. int i=0;
  116196. for(i=0;i<n8;i+=2){
  116197. x0 -=4;
  116198. T-=2;
  116199. r0= x0[2] + x1[0];
  116200. r1= x0[0] + x1[2];
  116201. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116202. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116203. x1 +=4;
  116204. }
  116205. x1=in+1;
  116206. for(;i<n2-n8;i+=2){
  116207. T-=2;
  116208. x0 -=4;
  116209. r0= x0[2] - x1[0];
  116210. r1= x0[0] - x1[2];
  116211. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116212. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116213. x1 +=4;
  116214. }
  116215. x0=in+n;
  116216. for(;i<n2;i+=2){
  116217. T-=2;
  116218. x0 -=4;
  116219. r0= -x0[2] - x1[0];
  116220. r1= -x0[0] - x1[2];
  116221. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116222. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116223. x1 +=4;
  116224. }
  116225. mdct_butterflies(init,w+n2,n2);
  116226. mdct_bitreverse(init,w);
  116227. /* roatate + window */
  116228. T=init->trig+n2;
  116229. x0=out+n2;
  116230. for(i=0;i<n4;i++){
  116231. x0--;
  116232. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116233. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116234. w+=2;
  116235. T+=2;
  116236. }
  116237. }
  116238. #endif
  116239. /*** End of inlined file: mdct.c ***/
  116240. /*** Start of inlined file: psy.c ***/
  116241. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116242. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116243. // tasks..
  116244. #if JUCE_MSVC
  116245. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116246. #endif
  116247. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116248. #if JUCE_USE_OGGVORBIS
  116249. #include <stdlib.h>
  116250. #include <math.h>
  116251. #include <string.h>
  116252. /*** Start of inlined file: masking.h ***/
  116253. #ifndef _V_MASKING_H_
  116254. #define _V_MASKING_H_
  116255. /* more detailed ATH; the bass if flat to save stressing the floor
  116256. overly for only a bin or two of savings. */
  116257. #define MAX_ATH 88
  116258. static float ATH[]={
  116259. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116260. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116261. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116262. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116263. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116264. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116265. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116266. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116267. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116268. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116269. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116270. };
  116271. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116272. replaced by an empirically collected data set. The previously
  116273. published values were, far too often, simply on crack. */
  116274. #define EHMER_OFFSET 16
  116275. #define EHMER_MAX 56
  116276. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116277. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116278. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116279. for collection of these curves) */
  116280. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116281. /* 62.5 Hz */
  116282. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116283. -60, -60, -60, -60, -62, -62, -65, -73,
  116284. -69, -68, -68, -67, -70, -70, -72, -74,
  116285. -75, -79, -79, -80, -83, -88, -93, -100,
  116286. -110, -999, -999, -999, -999, -999, -999, -999,
  116287. -999, -999, -999, -999, -999, -999, -999, -999,
  116288. -999, -999, -999, -999, -999, -999, -999, -999},
  116289. { -48, -48, -48, -48, -48, -48, -48, -48,
  116290. -48, -48, -48, -48, -48, -53, -61, -66,
  116291. -66, -68, -67, -70, -76, -76, -72, -73,
  116292. -75, -76, -78, -79, -83, -88, -93, -100,
  116293. -110, -999, -999, -999, -999, -999, -999, -999,
  116294. -999, -999, -999, -999, -999, -999, -999, -999,
  116295. -999, -999, -999, -999, -999, -999, -999, -999},
  116296. { -37, -37, -37, -37, -37, -37, -37, -37,
  116297. -38, -40, -42, -46, -48, -53, -55, -62,
  116298. -65, -58, -56, -56, -61, -60, -65, -67,
  116299. -69, -71, -77, -77, -78, -80, -82, -84,
  116300. -88, -93, -98, -106, -112, -999, -999, -999,
  116301. -999, -999, -999, -999, -999, -999, -999, -999,
  116302. -999, -999, -999, -999, -999, -999, -999, -999},
  116303. { -25, -25, -25, -25, -25, -25, -25, -25,
  116304. -25, -26, -27, -29, -32, -38, -48, -52,
  116305. -52, -50, -48, -48, -51, -52, -54, -60,
  116306. -67, -67, -66, -68, -69, -73, -73, -76,
  116307. -80, -81, -81, -85, -85, -86, -88, -93,
  116308. -100, -110, -999, -999, -999, -999, -999, -999,
  116309. -999, -999, -999, -999, -999, -999, -999, -999},
  116310. { -16, -16, -16, -16, -16, -16, -16, -16,
  116311. -17, -19, -20, -22, -26, -28, -31, -40,
  116312. -47, -39, -39, -40, -42, -43, -47, -51,
  116313. -57, -52, -55, -55, -60, -58, -62, -63,
  116314. -70, -67, -69, -72, -73, -77, -80, -82,
  116315. -83, -87, -90, -94, -98, -104, -115, -999,
  116316. -999, -999, -999, -999, -999, -999, -999, -999},
  116317. { -8, -8, -8, -8, -8, -8, -8, -8,
  116318. -8, -8, -10, -11, -15, -19, -25, -30,
  116319. -34, -31, -30, -31, -29, -32, -35, -42,
  116320. -48, -42, -44, -46, -50, -50, -51, -52,
  116321. -59, -54, -55, -55, -58, -62, -63, -66,
  116322. -72, -73, -76, -75, -78, -80, -80, -81,
  116323. -84, -88, -90, -94, -98, -101, -106, -110}},
  116324. /* 88Hz */
  116325. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116326. -66, -66, -66, -66, -66, -67, -67, -67,
  116327. -76, -72, -71, -74, -76, -76, -75, -78,
  116328. -79, -79, -81, -83, -86, -89, -93, -97,
  116329. -100, -105, -110, -999, -999, -999, -999, -999,
  116330. -999, -999, -999, -999, -999, -999, -999, -999,
  116331. -999, -999, -999, -999, -999, -999, -999, -999},
  116332. { -47, -47, -47, -47, -47, -47, -47, -47,
  116333. -47, -47, -47, -48, -51, -55, -59, -66,
  116334. -66, -66, -67, -66, -68, -69, -70, -74,
  116335. -79, -77, -77, -78, -80, -81, -82, -84,
  116336. -86, -88, -91, -95, -100, -108, -116, -999,
  116337. -999, -999, -999, -999, -999, -999, -999, -999,
  116338. -999, -999, -999, -999, -999, -999, -999, -999},
  116339. { -36, -36, -36, -36, -36, -36, -36, -36,
  116340. -36, -37, -37, -41, -44, -48, -51, -58,
  116341. -62, -60, -57, -59, -59, -60, -63, -65,
  116342. -72, -71, -70, -72, -74, -77, -76, -78,
  116343. -81, -81, -80, -83, -86, -91, -96, -100,
  116344. -105, -110, -999, -999, -999, -999, -999, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999},
  116346. { -28, -28, -28, -28, -28, -28, -28, -28,
  116347. -28, -30, -32, -32, -33, -35, -41, -49,
  116348. -50, -49, -47, -48, -48, -52, -51, -57,
  116349. -65, -61, -59, -61, -64, -69, -70, -74,
  116350. -77, -77, -78, -81, -84, -85, -87, -90,
  116351. -92, -96, -100, -107, -112, -999, -999, -999,
  116352. -999, -999, -999, -999, -999, -999, -999, -999},
  116353. { -19, -19, -19, -19, -19, -19, -19, -19,
  116354. -20, -21, -23, -27, -30, -35, -36, -41,
  116355. -46, -44, -42, -40, -41, -41, -43, -48,
  116356. -55, -53, -52, -53, -56, -59, -58, -60,
  116357. -67, -66, -69, -71, -72, -75, -79, -81,
  116358. -84, -87, -90, -93, -97, -101, -107, -114,
  116359. -999, -999, -999, -999, -999, -999, -999, -999},
  116360. { -9, -9, -9, -9, -9, -9, -9, -9,
  116361. -11, -12, -12, -15, -16, -20, -23, -30,
  116362. -37, -34, -33, -34, -31, -32, -32, -38,
  116363. -47, -44, -41, -40, -47, -49, -46, -46,
  116364. -58, -50, -50, -54, -58, -62, -64, -67,
  116365. -67, -70, -72, -76, -79, -83, -87, -91,
  116366. -96, -100, -104, -110, -999, -999, -999, -999}},
  116367. /* 125 Hz */
  116368. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116369. -62, -62, -63, -64, -66, -67, -66, -68,
  116370. -75, -72, -76, -75, -76, -78, -79, -82,
  116371. -84, -85, -90, -94, -101, -110, -999, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -999, -999, -999, -999, -999,
  116374. -999, -999, -999, -999, -999, -999, -999, -999},
  116375. { -59, -59, -59, -59, -59, -59, -59, -59,
  116376. -59, -59, -59, -60, -60, -61, -63, -66,
  116377. -71, -68, -70, -70, -71, -72, -72, -75,
  116378. -81, -78, -79, -82, -83, -86, -90, -97,
  116379. -103, -113, -999, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -999, -999, -999, -999, -999,
  116381. -999, -999, -999, -999, -999, -999, -999, -999},
  116382. { -53, -53, -53, -53, -53, -53, -53, -53,
  116383. -53, -54, -55, -57, -56, -57, -55, -61,
  116384. -65, -60, -60, -62, -63, -63, -66, -68,
  116385. -74, -73, -75, -75, -78, -80, -80, -82,
  116386. -85, -90, -96, -101, -108, -999, -999, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999},
  116389. { -46, -46, -46, -46, -46, -46, -46, -46,
  116390. -46, -46, -47, -47, -47, -47, -48, -51,
  116391. -57, -51, -49, -50, -51, -53, -54, -59,
  116392. -66, -60, -62, -67, -67, -70, -72, -75,
  116393. -76, -78, -81, -85, -88, -94, -97, -104,
  116394. -112, -999, -999, -999, -999, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -999, -999, -999},
  116396. { -36, -36, -36, -36, -36, -36, -36, -36,
  116397. -39, -41, -42, -42, -39, -38, -41, -43,
  116398. -52, -44, -40, -39, -37, -37, -40, -47,
  116399. -54, -50, -48, -50, -55, -61, -59, -62,
  116400. -66, -66, -66, -69, -69, -73, -74, -74,
  116401. -75, -77, -79, -82, -87, -91, -95, -100,
  116402. -108, -115, -999, -999, -999, -999, -999, -999},
  116403. { -28, -26, -24, -22, -20, -20, -23, -29,
  116404. -30, -31, -28, -27, -28, -28, -28, -35,
  116405. -40, -33, -32, -29, -30, -30, -30, -37,
  116406. -45, -41, -37, -38, -45, -47, -47, -48,
  116407. -53, -49, -48, -50, -49, -49, -51, -52,
  116408. -58, -56, -57, -56, -60, -61, -62, -70,
  116409. -72, -74, -78, -83, -88, -93, -100, -106}},
  116410. /* 177 Hz */
  116411. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -110, -105, -100, -95, -91, -87, -83,
  116413. -80, -78, -76, -78, -78, -81, -83, -85,
  116414. -86, -85, -86, -87, -90, -97, -107, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999,
  116417. -999, -999, -999, -999, -999, -999, -999, -999},
  116418. {-999, -999, -999, -110, -105, -100, -95, -90,
  116419. -85, -81, -77, -73, -70, -67, -67, -68,
  116420. -75, -73, -70, -69, -70, -72, -75, -79,
  116421. -84, -83, -84, -86, -88, -89, -89, -93,
  116422. -98, -105, -112, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -999, -999, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999},
  116425. {-105, -100, -95, -90, -85, -80, -76, -71,
  116426. -68, -68, -65, -63, -63, -62, -62, -64,
  116427. -65, -64, -61, -62, -63, -64, -66, -68,
  116428. -73, -73, -74, -75, -76, -81, -83, -85,
  116429. -88, -89, -92, -95, -100, -108, -999, -999,
  116430. -999, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999},
  116432. { -80, -75, -71, -68, -65, -63, -62, -61,
  116433. -61, -61, -61, -59, -56, -57, -53, -50,
  116434. -58, -52, -50, -50, -52, -53, -54, -58,
  116435. -67, -63, -67, -68, -72, -75, -78, -80,
  116436. -81, -81, -82, -85, -89, -90, -93, -97,
  116437. -101, -107, -114, -999, -999, -999, -999, -999,
  116438. -999, -999, -999, -999, -999, -999, -999, -999},
  116439. { -65, -61, -59, -57, -56, -55, -55, -56,
  116440. -56, -57, -55, -53, -52, -47, -44, -44,
  116441. -50, -44, -41, -39, -39, -42, -40, -46,
  116442. -51, -49, -50, -53, -54, -63, -60, -61,
  116443. -62, -66, -66, -66, -70, -73, -74, -75,
  116444. -76, -75, -79, -85, -89, -91, -96, -102,
  116445. -110, -999, -999, -999, -999, -999, -999, -999},
  116446. { -52, -50, -49, -49, -48, -48, -48, -49,
  116447. -50, -50, -49, -46, -43, -39, -35, -33,
  116448. -38, -36, -32, -29, -32, -32, -32, -35,
  116449. -44, -39, -38, -38, -46, -50, -45, -46,
  116450. -53, -50, -50, -50, -54, -54, -53, -53,
  116451. -56, -57, -59, -66, -70, -72, -74, -79,
  116452. -83, -85, -90, -97, -114, -999, -999, -999}},
  116453. /* 250 Hz */
  116454. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116455. -100, -95, -90, -86, -80, -75, -75, -79,
  116456. -80, -79, -80, -81, -82, -88, -95, -103,
  116457. -110, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -999, -999, -999, -999, -999, -999, -999},
  116461. {-999, -999, -999, -999, -108, -103, -98, -93,
  116462. -88, -83, -79, -78, -75, -71, -67, -68,
  116463. -73, -73, -72, -73, -75, -77, -80, -82,
  116464. -88, -93, -100, -107, -114, -999, -999, -999,
  116465. -999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999},
  116468. {-999, -999, -999, -110, -105, -101, -96, -90,
  116469. -86, -81, -77, -73, -69, -66, -61, -62,
  116470. -66, -64, -62, -65, -66, -70, -72, -76,
  116471. -81, -80, -84, -90, -95, -102, -110, -999,
  116472. -999, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999},
  116475. {-999, -999, -999, -107, -103, -97, -92, -88,
  116476. -83, -79, -74, -70, -66, -59, -53, -58,
  116477. -62, -55, -54, -54, -54, -58, -61, -62,
  116478. -72, -70, -72, -75, -78, -80, -81, -80,
  116479. -83, -83, -88, -93, -100, -107, -115, -999,
  116480. -999, -999, -999, -999, -999, -999, -999, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999},
  116482. {-999, -999, -999, -105, -100, -95, -90, -85,
  116483. -80, -75, -70, -66, -62, -56, -48, -44,
  116484. -48, -46, -46, -43, -46, -48, -48, -51,
  116485. -58, -58, -59, -60, -62, -62, -61, -61,
  116486. -65, -64, -65, -68, -70, -74, -75, -78,
  116487. -81, -86, -95, -110, -999, -999, -999, -999,
  116488. -999, -999, -999, -999, -999, -999, -999, -999},
  116489. {-999, -999, -105, -100, -95, -90, -85, -80,
  116490. -75, -70, -65, -61, -55, -49, -39, -33,
  116491. -40, -35, -32, -38, -40, -33, -35, -37,
  116492. -46, -41, -45, -44, -46, -42, -45, -46,
  116493. -52, -50, -50, -50, -54, -54, -55, -57,
  116494. -62, -64, -66, -68, -70, -76, -81, -90,
  116495. -100, -110, -999, -999, -999, -999, -999, -999}},
  116496. /* 354 hz */
  116497. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116498. -105, -98, -90, -85, -82, -83, -80, -78,
  116499. -84, -79, -80, -83, -87, -89, -91, -93,
  116500. -99, -106, -117, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999,
  116503. -999, -999, -999, -999, -999, -999, -999, -999},
  116504. {-999, -999, -999, -999, -999, -999, -999, -999,
  116505. -105, -98, -90, -85, -80, -75, -70, -68,
  116506. -74, -72, -74, -77, -80, -82, -85, -87,
  116507. -92, -89, -91, -95, -100, -106, -112, -999,
  116508. -999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999},
  116511. {-999, -999, -999, -999, -999, -999, -999, -999,
  116512. -105, -98, -90, -83, -75, -71, -63, -64,
  116513. -67, -62, -64, -67, -70, -73, -77, -81,
  116514. -84, -83, -85, -89, -90, -93, -98, -104,
  116515. -109, -114, -999, -999, -999, -999, -999, -999,
  116516. -999, -999, -999, -999, -999, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999},
  116518. {-999, -999, -999, -999, -999, -999, -999, -999,
  116519. -103, -96, -88, -81, -75, -68, -58, -54,
  116520. -56, -54, -56, -56, -58, -60, -63, -66,
  116521. -74, -69, -72, -72, -75, -74, -77, -81,
  116522. -81, -82, -84, -87, -93, -96, -99, -104,
  116523. -110, -999, -999, -999, -999, -999, -999, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999},
  116525. {-999, -999, -999, -999, -999, -108, -102, -96,
  116526. -91, -85, -80, -74, -68, -60, -51, -46,
  116527. -48, -46, -43, -45, -47, -47, -49, -48,
  116528. -56, -53, -55, -58, -57, -63, -58, -60,
  116529. -66, -64, -67, -70, -70, -74, -77, -84,
  116530. -86, -89, -91, -93, -94, -101, -109, -118,
  116531. -999, -999, -999, -999, -999, -999, -999, -999},
  116532. {-999, -999, -999, -108, -103, -98, -93, -88,
  116533. -83, -78, -73, -68, -60, -53, -44, -35,
  116534. -38, -38, -34, -34, -36, -40, -41, -44,
  116535. -51, -45, -46, -47, -46, -54, -50, -49,
  116536. -50, -50, -50, -51, -54, -57, -58, -60,
  116537. -66, -66, -66, -64, -65, -68, -77, -82,
  116538. -87, -95, -110, -999, -999, -999, -999, -999}},
  116539. /* 500 Hz */
  116540. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116541. -107, -102, -97, -92, -87, -83, -78, -75,
  116542. -82, -79, -83, -85, -89, -92, -95, -98,
  116543. -101, -105, -109, -113, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -999, -999, -999, -999,
  116546. -999, -999, -999, -999, -999, -999, -999, -999},
  116547. {-999, -999, -999, -999, -999, -999, -999, -106,
  116548. -100, -95, -90, -86, -81, -78, -74, -69,
  116549. -74, -74, -76, -79, -83, -84, -86, -89,
  116550. -92, -97, -93, -100, -103, -107, -110, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999},
  116554. {-999, -999, -999, -999, -999, -999, -106, -100,
  116555. -95, -90, -87, -83, -80, -75, -69, -60,
  116556. -66, -66, -68, -70, -74, -78, -79, -81,
  116557. -81, -83, -84, -87, -93, -96, -99, -103,
  116558. -107, -110, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999},
  116561. {-999, -999, -999, -999, -999, -108, -103, -98,
  116562. -93, -89, -85, -82, -78, -71, -62, -55,
  116563. -58, -58, -54, -54, -55, -59, -61, -62,
  116564. -70, -66, -66, -67, -70, -72, -75, -78,
  116565. -84, -84, -84, -88, -91, -90, -95, -98,
  116566. -102, -103, -106, -110, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999},
  116568. {-999, -999, -999, -999, -108, -103, -98, -94,
  116569. -90, -87, -82, -79, -73, -67, -58, -47,
  116570. -50, -45, -41, -45, -48, -44, -44, -49,
  116571. -54, -51, -48, -47, -49, -50, -51, -57,
  116572. -58, -60, -63, -69, -70, -69, -71, -74,
  116573. -78, -82, -90, -95, -101, -105, -110, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999},
  116575. {-999, -999, -999, -105, -101, -97, -93, -90,
  116576. -85, -80, -77, -72, -65, -56, -48, -37,
  116577. -40, -36, -34, -40, -50, -47, -38, -41,
  116578. -47, -38, -35, -39, -38, -43, -40, -45,
  116579. -50, -45, -44, -47, -50, -55, -48, -48,
  116580. -52, -66, -70, -76, -82, -90, -97, -105,
  116581. -110, -999, -999, -999, -999, -999, -999, -999}},
  116582. /* 707 Hz */
  116583. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116584. -999, -108, -103, -98, -93, -86, -79, -76,
  116585. -83, -81, -85, -87, -89, -93, -98, -102,
  116586. -107, -112, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999,
  116589. -999, -999, -999, -999, -999, -999, -999, -999},
  116590. {-999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -108, -103, -98, -93, -86, -79, -71,
  116592. -77, -74, -77, -79, -81, -84, -85, -90,
  116593. -92, -93, -92, -98, -101, -108, -112, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999},
  116597. {-999, -999, -999, -999, -999, -999, -999, -999,
  116598. -108, -103, -98, -93, -87, -78, -68, -65,
  116599. -66, -62, -65, -67, -70, -73, -75, -78,
  116600. -82, -82, -83, -84, -91, -93, -98, -102,
  116601. -106, -110, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -999,
  116603. -999, -999, -999, -999, -999, -999, -999, -999},
  116604. {-999, -999, -999, -999, -999, -999, -999, -999,
  116605. -105, -100, -95, -90, -82, -74, -62, -57,
  116606. -58, -56, -51, -52, -52, -54, -54, -58,
  116607. -66, -59, -60, -63, -66, -69, -73, -79,
  116608. -83, -84, -80, -81, -81, -82, -88, -92,
  116609. -98, -105, -113, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -999, -999, -999, -999, -999},
  116611. {-999, -999, -999, -999, -999, -999, -999, -107,
  116612. -102, -97, -92, -84, -79, -69, -57, -47,
  116613. -52, -47, -44, -45, -50, -52, -42, -42,
  116614. -53, -43, -43, -48, -51, -56, -55, -52,
  116615. -57, -59, -61, -62, -67, -71, -78, -83,
  116616. -86, -94, -98, -103, -110, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999},
  116618. {-999, -999, -999, -999, -999, -999, -105, -100,
  116619. -95, -90, -84, -78, -70, -61, -51, -41,
  116620. -40, -38, -40, -46, -52, -51, -41, -40,
  116621. -46, -40, -38, -38, -41, -46, -41, -46,
  116622. -47, -43, -43, -45, -41, -45, -56, -67,
  116623. -68, -83, -87, -90, -95, -102, -107, -113,
  116624. -999, -999, -999, -999, -999, -999, -999, -999}},
  116625. /* 1000 Hz */
  116626. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116627. -999, -109, -105, -101, -96, -91, -84, -77,
  116628. -82, -82, -85, -89, -94, -100, -106, -110,
  116629. -999, -999, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999},
  116633. {-999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -106, -103, -98, -92, -85, -80, -71,
  116635. -75, -72, -76, -80, -84, -86, -89, -93,
  116636. -100, -107, -113, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999},
  116640. {-999, -999, -999, -999, -999, -999, -999, -107,
  116641. -104, -101, -97, -92, -88, -84, -80, -64,
  116642. -66, -63, -64, -66, -69, -73, -77, -83,
  116643. -83, -86, -91, -98, -104, -111, -999, -999,
  116644. -999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999,
  116646. -999, -999, -999, -999, -999, -999, -999, -999},
  116647. {-999, -999, -999, -999, -999, -999, -999, -107,
  116648. -104, -101, -97, -92, -90, -84, -74, -57,
  116649. -58, -52, -55, -54, -50, -52, -50, -52,
  116650. -63, -62, -69, -76, -77, -78, -78, -79,
  116651. -82, -88, -94, -100, -106, -111, -999, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -999, -999, -999, -999},
  116654. {-999, -999, -999, -999, -999, -999, -106, -102,
  116655. -98, -95, -90, -85, -83, -78, -70, -50,
  116656. -50, -41, -44, -49, -47, -50, -50, -44,
  116657. -55, -46, -47, -48, -48, -54, -49, -49,
  116658. -58, -62, -71, -81, -87, -92, -97, -102,
  116659. -108, -114, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999},
  116661. {-999, -999, -999, -999, -999, -999, -106, -102,
  116662. -98, -95, -90, -85, -83, -78, -70, -45,
  116663. -43, -41, -47, -50, -51, -50, -49, -45,
  116664. -47, -41, -44, -41, -39, -43, -38, -37,
  116665. -40, -41, -44, -50, -58, -65, -73, -79,
  116666. -85, -92, -97, -101, -105, -109, -113, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999}},
  116668. /* 1414 Hz */
  116669. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -107, -100, -95, -87, -81,
  116671. -85, -83, -88, -93, -100, -107, -114, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999},
  116676. {-999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -107, -101, -95, -88, -83, -76,
  116678. -73, -72, -79, -84, -90, -95, -100, -105,
  116679. -110, -115, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999},
  116683. {-999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -104, -98, -92, -87, -81, -70,
  116685. -65, -62, -67, -71, -74, -80, -85, -91,
  116686. -95, -99, -103, -108, -111, -114, -999, -999,
  116687. -999, -999, -999, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999},
  116690. {-999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -103, -97, -90, -85, -76, -60,
  116692. -56, -54, -60, -62, -61, -56, -63, -65,
  116693. -73, -74, -77, -75, -78, -81, -86, -87,
  116694. -88, -91, -94, -98, -103, -110, -999, -999,
  116695. -999, -999, -999, -999, -999, -999, -999, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999},
  116697. {-999, -999, -999, -999, -999, -999, -999, -105,
  116698. -100, -97, -92, -86, -81, -79, -70, -57,
  116699. -51, -47, -51, -58, -60, -56, -53, -50,
  116700. -58, -52, -50, -50, -53, -55, -64, -69,
  116701. -71, -85, -82, -78, -81, -85, -95, -102,
  116702. -112, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999},
  116704. {-999, -999, -999, -999, -999, -999, -999, -105,
  116705. -100, -97, -92, -85, -83, -79, -72, -49,
  116706. -40, -43, -43, -54, -56, -51, -50, -40,
  116707. -43, -38, -36, -35, -37, -38, -37, -44,
  116708. -54, -60, -57, -60, -70, -75, -84, -92,
  116709. -103, -112, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999}},
  116711. /* 2000 Hz */
  116712. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -110, -102, -95, -89, -82,
  116714. -83, -84, -90, -92, -99, -107, -113, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999},
  116719. {-999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -107, -101, -95, -89, -83, -72,
  116721. -74, -78, -85, -88, -88, -90, -92, -98,
  116722. -105, -111, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999},
  116726. {-999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -109, -103, -97, -93, -87, -81, -70,
  116728. -70, -67, -75, -73, -76, -79, -81, -83,
  116729. -88, -89, -97, -103, -110, -999, -999, -999,
  116730. -999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999},
  116733. {-999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -107, -100, -94, -88, -83, -75, -63,
  116735. -59, -59, -63, -66, -60, -62, -67, -67,
  116736. -77, -76, -81, -88, -86, -92, -96, -102,
  116737. -109, -116, -999, -999, -999, -999, -999, -999,
  116738. -999, -999, -999, -999, -999, -999, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999},
  116740. {-999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -105, -98, -92, -86, -81, -73, -56,
  116742. -52, -47, -55, -60, -58, -52, -51, -45,
  116743. -49, -50, -53, -54, -61, -71, -70, -69,
  116744. -78, -79, -87, -90, -96, -104, -112, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999},
  116747. {-999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -103, -96, -90, -86, -78, -70, -51,
  116749. -42, -47, -48, -55, -54, -54, -53, -42,
  116750. -35, -28, -33, -38, -37, -44, -47, -49,
  116751. -54, -63, -68, -78, -82, -89, -94, -99,
  116752. -104, -109, -114, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999}},
  116754. /* 2828 Hz */
  116755. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -110, -100, -90, -79,
  116757. -85, -81, -82, -82, -89, -94, -99, -103,
  116758. -109, -115, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999},
  116762. {-999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -105, -97, -85, -72,
  116764. -74, -70, -70, -70, -76, -85, -91, -93,
  116765. -97, -103, -109, -115, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999},
  116769. {-999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -112, -93, -81, -68,
  116771. -62, -60, -60, -57, -63, -70, -77, -82,
  116772. -90, -93, -98, -104, -109, -113, -999, -999,
  116773. -999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999},
  116776. {-999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -113, -100, -93, -84, -63,
  116778. -58, -48, -53, -54, -52, -52, -57, -64,
  116779. -66, -76, -83, -81, -85, -85, -90, -95,
  116780. -98, -101, -103, -106, -108, -111, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999},
  116783. {-999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -105, -95, -86, -74, -53,
  116785. -50, -38, -43, -49, -43, -42, -39, -39,
  116786. -46, -52, -57, -56, -72, -69, -74, -81,
  116787. -87, -92, -94, -97, -99, -102, -105, -108,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999},
  116790. {-999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -108, -99, -90, -76, -66, -45,
  116792. -43, -41, -44, -47, -43, -47, -40, -30,
  116793. -31, -31, -39, -33, -40, -41, -43, -53,
  116794. -59, -70, -73, -77, -79, -82, -84, -87,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999}},
  116797. /* 4000 Hz */
  116798. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -999, -110, -91, -76,
  116800. -75, -85, -93, -98, -104, -110, -999, -999,
  116801. -999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999},
  116805. {-999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -999, -999, -110, -91, -70,
  116807. -70, -75, -86, -89, -94, -98, -101, -106,
  116808. -110, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999},
  116812. {-999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -999, -110, -95, -80, -60,
  116814. -65, -64, -74, -83, -88, -91, -95, -99,
  116815. -103, -107, -110, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999},
  116819. {-999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -110, -95, -80, -58,
  116821. -55, -49, -66, -68, -71, -78, -78, -80,
  116822. -88, -85, -89, -97, -100, -105, -110, -999,
  116823. -999, -999, -999, -999, -999, -999, -999, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999},
  116826. {-999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -110, -95, -80, -53,
  116828. -52, -41, -59, -59, -49, -58, -56, -63,
  116829. -86, -79, -90, -93, -98, -103, -107, -112,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999},
  116833. {-999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -110, -97, -91, -73, -45,
  116835. -40, -33, -53, -61, -49, -54, -50, -50,
  116836. -60, -52, -67, -74, -81, -92, -96, -100,
  116837. -105, -110, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999}},
  116840. /* 5657 Hz */
  116841. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -113, -106, -99, -92, -77,
  116843. -80, -88, -97, -106, -115, -999, -999, -999,
  116844. -999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999},
  116848. {-999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -116, -109, -102, -95, -89, -74,
  116850. -72, -88, -87, -95, -102, -109, -116, -999,
  116851. -999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999},
  116855. {-999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -116, -109, -102, -95, -89, -75,
  116857. -66, -74, -77, -78, -86, -87, -90, -96,
  116858. -105, -115, -999, -999, -999, -999, -999, -999,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999},
  116862. {-999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -115, -108, -101, -94, -88, -66,
  116864. -56, -61, -70, -65, -78, -72, -83, -84,
  116865. -93, -98, -105, -110, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -999, -999, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999},
  116869. {-999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -110, -105, -95, -89, -82, -57,
  116871. -52, -52, -59, -56, -59, -58, -69, -67,
  116872. -88, -82, -82, -89, -94, -100, -108, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999},
  116876. {-999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -110, -101, -96, -90, -83, -77, -54,
  116878. -43, -38, -50, -48, -52, -48, -42, -42,
  116879. -51, -52, -53, -59, -65, -71, -78, -85,
  116880. -95, -999, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999}},
  116883. /* 8000 Hz */
  116884. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -999, -120, -105, -86, -68,
  116886. -78, -79, -90, -100, -110, -999, -999, -999,
  116887. -999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999},
  116891. {-999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -999, -120, -105, -86, -66,
  116893. -73, -77, -88, -96, -105, -115, -999, -999,
  116894. -999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999},
  116898. {-999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -120, -105, -92, -80, -61,
  116900. -64, -68, -80, -87, -92, -100, -110, -999,
  116901. -999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999},
  116905. {-999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -120, -104, -91, -79, -52,
  116907. -60, -54, -64, -69, -77, -80, -82, -84,
  116908. -85, -87, -88, -90, -999, -999, -999, -999,
  116909. -999, -999, -999, -999, -999, -999, -999, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999},
  116912. {-999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -118, -100, -87, -77, -49,
  116914. -50, -44, -58, -61, -61, -67, -65, -62,
  116915. -62, -62, -65, -68, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999},
  116919. {-999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -115, -98, -84, -62, -49,
  116921. -44, -38, -46, -49, -49, -46, -39, -37,
  116922. -39, -40, -42, -43, -999, -999, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999}},
  116926. /* 11314 Hz */
  116927. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -999, -999, -110, -88, -74,
  116929. -77, -82, -82, -85, -90, -94, -99, -104,
  116930. -999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999},
  116934. {-999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -999, -999, -110, -88, -66,
  116936. -70, -81, -80, -81, -84, -88, -91, -93,
  116937. -999, -999, -999, -999, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999},
  116941. {-999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -999, -999, -110, -88, -61,
  116943. -63, -70, -71, -74, -77, -80, -83, -85,
  116944. -999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999},
  116948. {-999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -110, -86, -62,
  116950. -63, -62, -62, -58, -52, -50, -50, -52,
  116951. -54, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999},
  116955. {-999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -118, -108, -84, -53,
  116957. -50, -50, -50, -55, -47, -45, -40, -40,
  116958. -40, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -999, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999},
  116962. {-999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -118, -100, -73, -43,
  116964. -37, -42, -43, -53, -38, -37, -35, -35,
  116965. -38, -999, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999}},
  116969. /* 16000 Hz */
  116970. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116971. -999, -999, -999, -110, -100, -91, -84, -74,
  116972. -80, -80, -80, -80, -80, -999, -999, -999,
  116973. -999, -999, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999},
  116977. {-999, -999, -999, -999, -999, -999, -999, -999,
  116978. -999, -999, -999, -110, -100, -91, -84, -74,
  116979. -68, -68, -68, -68, -68, -999, -999, -999,
  116980. -999, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999},
  116984. {-999, -999, -999, -999, -999, -999, -999, -999,
  116985. -999, -999, -999, -110, -100, -86, -78, -70,
  116986. -60, -45, -30, -21, -999, -999, -999, -999,
  116987. -999, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999},
  116991. {-999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -110, -100, -87, -78, -67,
  116993. -48, -38, -29, -21, -999, -999, -999, -999,
  116994. -999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999},
  116998. {-999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -110, -100, -86, -69, -56,
  117000. -45, -35, -33, -29, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -999, -999, -999, -999, -999, -999,
  117003. -999, -999, -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, -110, -100, -83, -71, -48,
  117007. -27, -38, -37, -34, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -999, -999, -999, -999,
  117009. -999, -999, -999, -999, -999, -999, -999, -999,
  117010. -999, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999}}
  117012. };
  117013. #endif
  117014. /*** End of inlined file: masking.h ***/
  117015. #define NEGINF -9999.f
  117016. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117017. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117018. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117019. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117020. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117021. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117022. look->channels=vi->channels;
  117023. look->ampmax=-9999.;
  117024. look->gi=gi;
  117025. return(look);
  117026. }
  117027. void _vp_global_free(vorbis_look_psy_global *look){
  117028. if(look){
  117029. memset(look,0,sizeof(*look));
  117030. _ogg_free(look);
  117031. }
  117032. }
  117033. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117034. if(i){
  117035. memset(i,0,sizeof(*i));
  117036. _ogg_free(i);
  117037. }
  117038. }
  117039. void _vi_psy_free(vorbis_info_psy *i){
  117040. if(i){
  117041. memset(i,0,sizeof(*i));
  117042. _ogg_free(i);
  117043. }
  117044. }
  117045. static void min_curve(float *c,
  117046. float *c2){
  117047. int i;
  117048. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117049. }
  117050. static void max_curve(float *c,
  117051. float *c2){
  117052. int i;
  117053. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117054. }
  117055. static void attenuate_curve(float *c,float att){
  117056. int i;
  117057. for(i=0;i<EHMER_MAX;i++)
  117058. c[i]+=att;
  117059. }
  117060. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117061. float center_boost, float center_decay_rate){
  117062. int i,j,k,m;
  117063. float ath[EHMER_MAX];
  117064. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117065. float athc[P_LEVELS][EHMER_MAX];
  117066. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117067. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117068. memset(workc,0,sizeof(workc));
  117069. for(i=0;i<P_BANDS;i++){
  117070. /* we add back in the ATH to avoid low level curves falling off to
  117071. -infinity and unnecessarily cutting off high level curves in the
  117072. curve limiting (last step). */
  117073. /* A half-band's settings must be valid over the whole band, and
  117074. it's better to mask too little than too much */
  117075. int ath_offset=i*4;
  117076. for(j=0;j<EHMER_MAX;j++){
  117077. float min=999.;
  117078. for(k=0;k<4;k++)
  117079. if(j+k+ath_offset<MAX_ATH){
  117080. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117081. }else{
  117082. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117083. }
  117084. ath[j]=min;
  117085. }
  117086. /* copy curves into working space, replicate the 50dB curve to 30
  117087. and 40, replicate the 100dB curve to 110 */
  117088. for(j=0;j<6;j++)
  117089. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117090. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117091. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117092. /* apply centered curve boost/decay */
  117093. for(j=0;j<P_LEVELS;j++){
  117094. for(k=0;k<EHMER_MAX;k++){
  117095. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117096. if(adj<0. && center_boost>0)adj=0.;
  117097. if(adj>0. && center_boost<0)adj=0.;
  117098. workc[i][j][k]+=adj;
  117099. }
  117100. }
  117101. /* normalize curves so the driving amplitude is 0dB */
  117102. /* make temp curves with the ATH overlayed */
  117103. for(j=0;j<P_LEVELS;j++){
  117104. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117105. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117106. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117107. max_curve(athc[j],workc[i][j]);
  117108. }
  117109. /* Now limit the louder curves.
  117110. the idea is this: We don't know what the playback attenuation
  117111. will be; 0dB SL moves every time the user twiddles the volume
  117112. knob. So that means we have to use a single 'most pessimal' curve
  117113. for all masking amplitudes, right? Wrong. The *loudest* sound
  117114. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117115. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117116. etc... */
  117117. for(j=1;j<P_LEVELS;j++){
  117118. min_curve(athc[j],athc[j-1]);
  117119. min_curve(workc[i][j],athc[j]);
  117120. }
  117121. }
  117122. for(i=0;i<P_BANDS;i++){
  117123. int hi_curve,lo_curve,bin;
  117124. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117125. /* low frequency curves are measured with greater resolution than
  117126. the MDCT/FFT will actually give us; we want the curve applied
  117127. to the tone data to be pessimistic and thus apply the minimum
  117128. masking possible for a given bin. That means that a single bin
  117129. could span more than one octave and that the curve will be a
  117130. composite of multiple octaves. It also may mean that a single
  117131. bin may span > an eighth of an octave and that the eighth
  117132. octave values may also be composited. */
  117133. /* which octave curves will we be compositing? */
  117134. bin=floor(fromOC(i*.5)/binHz);
  117135. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117136. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117137. if(lo_curve>i)lo_curve=i;
  117138. if(lo_curve<0)lo_curve=0;
  117139. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117140. for(m=0;m<P_LEVELS;m++){
  117141. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117142. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117143. /* render the curve into bins, then pull values back into curve.
  117144. The point is that any inherent subsampling aliasing results in
  117145. a safe minimum */
  117146. for(k=lo_curve;k<=hi_curve;k++){
  117147. int l=0;
  117148. for(j=0;j<EHMER_MAX;j++){
  117149. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117150. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117151. if(lo_bin<0)lo_bin=0;
  117152. if(lo_bin>n)lo_bin=n;
  117153. if(lo_bin<l)l=lo_bin;
  117154. if(hi_bin<0)hi_bin=0;
  117155. if(hi_bin>n)hi_bin=n;
  117156. for(;l<hi_bin && l<n;l++)
  117157. if(brute_buffer[l]>workc[k][m][j])
  117158. brute_buffer[l]=workc[k][m][j];
  117159. }
  117160. for(;l<n;l++)
  117161. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117162. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117163. }
  117164. /* be equally paranoid about being valid up to next half ocatve */
  117165. if(i+1<P_BANDS){
  117166. int l=0;
  117167. k=i+1;
  117168. for(j=0;j<EHMER_MAX;j++){
  117169. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117170. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117171. if(lo_bin<0)lo_bin=0;
  117172. if(lo_bin>n)lo_bin=n;
  117173. if(lo_bin<l)l=lo_bin;
  117174. if(hi_bin<0)hi_bin=0;
  117175. if(hi_bin>n)hi_bin=n;
  117176. for(;l<hi_bin && l<n;l++)
  117177. if(brute_buffer[l]>workc[k][m][j])
  117178. brute_buffer[l]=workc[k][m][j];
  117179. }
  117180. for(;l<n;l++)
  117181. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117182. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117183. }
  117184. for(j=0;j<EHMER_MAX;j++){
  117185. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117186. if(bin<0){
  117187. ret[i][m][j+2]=-999.;
  117188. }else{
  117189. if(bin>=n){
  117190. ret[i][m][j+2]=-999.;
  117191. }else{
  117192. ret[i][m][j+2]=brute_buffer[bin];
  117193. }
  117194. }
  117195. }
  117196. /* add fenceposts */
  117197. for(j=0;j<EHMER_OFFSET;j++)
  117198. if(ret[i][m][j+2]>-200.f)break;
  117199. ret[i][m][0]=j;
  117200. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117201. if(ret[i][m][j+2]>-200.f)
  117202. break;
  117203. ret[i][m][1]=j;
  117204. }
  117205. }
  117206. return(ret);
  117207. }
  117208. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117209. vorbis_info_psy_global *gi,int n,long rate){
  117210. long i,j,lo=-99,hi=1;
  117211. long maxoc;
  117212. memset(p,0,sizeof(*p));
  117213. p->eighth_octave_lines=gi->eighth_octave_lines;
  117214. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117215. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117216. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117217. p->total_octave_lines=maxoc-p->firstoc+1;
  117218. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117219. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117220. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117221. p->vi=vi;
  117222. p->n=n;
  117223. p->rate=rate;
  117224. /* AoTuV HF weighting */
  117225. p->m_val = 1.;
  117226. if(rate < 26000) p->m_val = 0;
  117227. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117228. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117229. /* set up the lookups for a given blocksize and sample rate */
  117230. for(i=0,j=0;i<MAX_ATH-1;i++){
  117231. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117232. float base=ATH[i];
  117233. if(j<endpos){
  117234. float delta=(ATH[i+1]-base)/(endpos-j);
  117235. for(;j<endpos && j<n;j++){
  117236. p->ath[j]=base+100.;
  117237. base+=delta;
  117238. }
  117239. }
  117240. }
  117241. for(i=0;i<n;i++){
  117242. float bark=toBARK(rate/(2*n)*i);
  117243. for(;lo+vi->noisewindowlomin<i &&
  117244. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117245. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117246. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117247. p->bark[i]=((lo-1)<<16)+(hi-1);
  117248. }
  117249. for(i=0;i<n;i++)
  117250. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117251. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117252. vi->tone_centerboost,vi->tone_decay);
  117253. /* set up rolling noise median */
  117254. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117255. for(i=0;i<P_NOISECURVES;i++)
  117256. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117257. for(i=0;i<n;i++){
  117258. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117259. int inthalfoc;
  117260. float del;
  117261. if(halfoc<0)halfoc=0;
  117262. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117263. inthalfoc=(int)halfoc;
  117264. del=halfoc-inthalfoc;
  117265. for(j=0;j<P_NOISECURVES;j++)
  117266. p->noiseoffset[j][i]=
  117267. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117268. p->vi->noiseoff[j][inthalfoc+1]*del;
  117269. }
  117270. #if 0
  117271. {
  117272. static int ls=0;
  117273. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117274. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117275. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117276. }
  117277. #endif
  117278. }
  117279. void _vp_psy_clear(vorbis_look_psy *p){
  117280. int i,j;
  117281. if(p){
  117282. if(p->ath)_ogg_free(p->ath);
  117283. if(p->octave)_ogg_free(p->octave);
  117284. if(p->bark)_ogg_free(p->bark);
  117285. if(p->tonecurves){
  117286. for(i=0;i<P_BANDS;i++){
  117287. for(j=0;j<P_LEVELS;j++){
  117288. _ogg_free(p->tonecurves[i][j]);
  117289. }
  117290. _ogg_free(p->tonecurves[i]);
  117291. }
  117292. _ogg_free(p->tonecurves);
  117293. }
  117294. if(p->noiseoffset){
  117295. for(i=0;i<P_NOISECURVES;i++){
  117296. _ogg_free(p->noiseoffset[i]);
  117297. }
  117298. _ogg_free(p->noiseoffset);
  117299. }
  117300. memset(p,0,sizeof(*p));
  117301. }
  117302. }
  117303. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117304. static void seed_curve(float *seed,
  117305. const float **curves,
  117306. float amp,
  117307. int oc, int n,
  117308. int linesper,float dBoffset){
  117309. int i,post1;
  117310. int seedptr;
  117311. const float *posts,*curve;
  117312. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117313. choice=max(choice,0);
  117314. choice=min(choice,P_LEVELS-1);
  117315. posts=curves[choice];
  117316. curve=posts+2;
  117317. post1=(int)posts[1];
  117318. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117319. for(i=posts[0];i<post1;i++){
  117320. if(seedptr>0){
  117321. float lin=amp+curve[i];
  117322. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117323. }
  117324. seedptr+=linesper;
  117325. if(seedptr>=n)break;
  117326. }
  117327. }
  117328. static void seed_loop(vorbis_look_psy *p,
  117329. const float ***curves,
  117330. const float *f,
  117331. const float *flr,
  117332. float *seed,
  117333. float specmax){
  117334. vorbis_info_psy *vi=p->vi;
  117335. long n=p->n,i;
  117336. float dBoffset=vi->max_curve_dB-specmax;
  117337. /* prime the working vector with peak values */
  117338. for(i=0;i<n;i++){
  117339. float max=f[i];
  117340. long oc=p->octave[i];
  117341. while(i+1<n && p->octave[i+1]==oc){
  117342. i++;
  117343. if(f[i]>max)max=f[i];
  117344. }
  117345. if(max+6.f>flr[i]){
  117346. oc=oc>>p->shiftoc;
  117347. if(oc>=P_BANDS)oc=P_BANDS-1;
  117348. if(oc<0)oc=0;
  117349. seed_curve(seed,
  117350. curves[oc],
  117351. max,
  117352. p->octave[i]-p->firstoc,
  117353. p->total_octave_lines,
  117354. p->eighth_octave_lines,
  117355. dBoffset);
  117356. }
  117357. }
  117358. }
  117359. static void seed_chase(float *seeds, int linesper, long n){
  117360. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117361. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117362. long stack=0;
  117363. long pos=0;
  117364. long i;
  117365. for(i=0;i<n;i++){
  117366. if(stack<2){
  117367. posstack[stack]=i;
  117368. ampstack[stack++]=seeds[i];
  117369. }else{
  117370. while(1){
  117371. if(seeds[i]<ampstack[stack-1]){
  117372. posstack[stack]=i;
  117373. ampstack[stack++]=seeds[i];
  117374. break;
  117375. }else{
  117376. if(i<posstack[stack-1]+linesper){
  117377. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117378. i<posstack[stack-2]+linesper){
  117379. /* we completely overlap, making stack-1 irrelevant. pop it */
  117380. stack--;
  117381. continue;
  117382. }
  117383. }
  117384. posstack[stack]=i;
  117385. ampstack[stack++]=seeds[i];
  117386. break;
  117387. }
  117388. }
  117389. }
  117390. }
  117391. /* the stack now contains only the positions that are relevant. Scan
  117392. 'em straight through */
  117393. for(i=0;i<stack;i++){
  117394. long endpos;
  117395. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117396. endpos=posstack[i+1];
  117397. }else{
  117398. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117399. discarded in short frames */
  117400. }
  117401. if(endpos>n)endpos=n;
  117402. for(;pos<endpos;pos++)
  117403. seeds[pos]=ampstack[i];
  117404. }
  117405. /* there. Linear time. I now remember this was on a problem set I
  117406. had in Grad Skool... I didn't solve it at the time ;-) */
  117407. }
  117408. /* bleaugh, this is more complicated than it needs to be */
  117409. #include<stdio.h>
  117410. static void max_seeds(vorbis_look_psy *p,
  117411. float *seed,
  117412. float *flr){
  117413. long n=p->total_octave_lines;
  117414. int linesper=p->eighth_octave_lines;
  117415. long linpos=0;
  117416. long pos;
  117417. seed_chase(seed,linesper,n); /* for masking */
  117418. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117419. while(linpos+1<p->n){
  117420. float minV=seed[pos];
  117421. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117422. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117423. while(pos+1<=end){
  117424. pos++;
  117425. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117426. minV=seed[pos];
  117427. }
  117428. end=pos+p->firstoc;
  117429. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117430. if(flr[linpos]<minV)flr[linpos]=minV;
  117431. }
  117432. {
  117433. float minV=seed[p->total_octave_lines-1];
  117434. for(;linpos<p->n;linpos++)
  117435. if(flr[linpos]<minV)flr[linpos]=minV;
  117436. }
  117437. }
  117438. static void bark_noise_hybridmp(int n,const long *b,
  117439. const float *f,
  117440. float *noise,
  117441. const float offset,
  117442. const int fixed){
  117443. float *N=(float*) alloca(n*sizeof(*N));
  117444. float *X=(float*) alloca(n*sizeof(*N));
  117445. float *XX=(float*) alloca(n*sizeof(*N));
  117446. float *Y=(float*) alloca(n*sizeof(*N));
  117447. float *XY=(float*) alloca(n*sizeof(*N));
  117448. float tN, tX, tXX, tY, tXY;
  117449. int i;
  117450. int lo, hi;
  117451. float R, A, B, D;
  117452. float w, x, y;
  117453. tN = tX = tXX = tY = tXY = 0.f;
  117454. y = f[0] + offset;
  117455. if (y < 1.f) y = 1.f;
  117456. w = y * y * .5;
  117457. tN += w;
  117458. tX += w;
  117459. tY += w * y;
  117460. N[0] = tN;
  117461. X[0] = tX;
  117462. XX[0] = tXX;
  117463. Y[0] = tY;
  117464. XY[0] = tXY;
  117465. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117466. y = f[i] + offset;
  117467. if (y < 1.f) y = 1.f;
  117468. w = y * y;
  117469. tN += w;
  117470. tX += w * x;
  117471. tXX += w * x * x;
  117472. tY += w * y;
  117473. tXY += w * x * y;
  117474. N[i] = tN;
  117475. X[i] = tX;
  117476. XX[i] = tXX;
  117477. Y[i] = tY;
  117478. XY[i] = tXY;
  117479. }
  117480. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117481. lo = b[i] >> 16;
  117482. if( lo>=0 ) break;
  117483. hi = b[i] & 0xffff;
  117484. tN = N[hi] + N[-lo];
  117485. tX = X[hi] - X[-lo];
  117486. tXX = XX[hi] + XX[-lo];
  117487. tY = Y[hi] + Y[-lo];
  117488. tXY = XY[hi] - XY[-lo];
  117489. A = tY * tXX - tX * tXY;
  117490. B = tN * tXY - tX * tY;
  117491. D = tN * tXX - tX * tX;
  117492. R = (A + x * B) / D;
  117493. if (R < 0.f)
  117494. R = 0.f;
  117495. noise[i] = R - offset;
  117496. }
  117497. for ( ;; i++, x += 1.f) {
  117498. lo = b[i] >> 16;
  117499. hi = b[i] & 0xffff;
  117500. if(hi>=n)break;
  117501. tN = N[hi] - N[lo];
  117502. tX = X[hi] - X[lo];
  117503. tXX = XX[hi] - XX[lo];
  117504. tY = Y[hi] - Y[lo];
  117505. tXY = XY[hi] - XY[lo];
  117506. A = tY * tXX - tX * tXY;
  117507. B = tN * tXY - tX * tY;
  117508. D = tN * tXX - tX * tX;
  117509. R = (A + x * B) / D;
  117510. if (R < 0.f) R = 0.f;
  117511. noise[i] = R - offset;
  117512. }
  117513. for ( ; i < n; i++, x += 1.f) {
  117514. R = (A + x * B) / D;
  117515. if (R < 0.f) R = 0.f;
  117516. noise[i] = R - offset;
  117517. }
  117518. if (fixed <= 0) return;
  117519. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117520. hi = i + fixed / 2;
  117521. lo = hi - fixed;
  117522. if(lo>=0)break;
  117523. tN = N[hi] + N[-lo];
  117524. tX = X[hi] - X[-lo];
  117525. tXX = XX[hi] + XX[-lo];
  117526. tY = Y[hi] + Y[-lo];
  117527. tXY = XY[hi] - XY[-lo];
  117528. A = tY * tXX - tX * tXY;
  117529. B = tN * tXY - tX * tY;
  117530. D = tN * tXX - tX * tX;
  117531. R = (A + x * B) / D;
  117532. if (R - offset < noise[i]) noise[i] = R - offset;
  117533. }
  117534. for ( ;; i++, x += 1.f) {
  117535. hi = i + fixed / 2;
  117536. lo = hi - fixed;
  117537. if(hi>=n)break;
  117538. tN = N[hi] - N[lo];
  117539. tX = X[hi] - X[lo];
  117540. tXX = XX[hi] - XX[lo];
  117541. tY = Y[hi] - Y[lo];
  117542. tXY = XY[hi] - XY[lo];
  117543. A = tY * tXX - tX * tXY;
  117544. B = tN * tXY - tX * tY;
  117545. D = tN * tXX - tX * tX;
  117546. R = (A + x * B) / D;
  117547. if (R - offset < noise[i]) noise[i] = R - offset;
  117548. }
  117549. for ( ; i < n; i++, x += 1.f) {
  117550. R = (A + x * B) / D;
  117551. if (R - offset < noise[i]) noise[i] = R - offset;
  117552. }
  117553. }
  117554. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117555. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117556. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117557. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117558. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117559. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117560. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117561. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117562. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117563. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117564. 973377.F, 913981.F, 858210.F, 805842.F,
  117565. 756669.F, 710497.F, 667142.F, 626433.F,
  117566. 588208.F, 552316.F, 518613.F, 486967.F,
  117567. 457252.F, 429351.F, 403152.F, 378551.F,
  117568. 355452.F, 333762.F, 313396.F, 294273.F,
  117569. 276316.F, 259455.F, 243623.F, 228757.F,
  117570. 214798.F, 201691.F, 189384.F, 177828.F,
  117571. 166977.F, 156788.F, 147221.F, 138237.F,
  117572. 129802.F, 121881.F, 114444.F, 107461.F,
  117573. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117574. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117575. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117576. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117577. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117578. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117579. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117580. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117581. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117582. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117583. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117584. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117585. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117586. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117587. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117588. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117589. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117590. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117591. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117592. 842.910F, 791.475F, 743.179F, 697.830F,
  117593. 655.249F, 615.265F, 577.722F, 542.469F,
  117594. 509.367F, 478.286F, 449.101F, 421.696F,
  117595. 395.964F, 371.803F, 349.115F, 327.812F,
  117596. 307.809F, 289.026F, 271.390F, 254.830F,
  117597. 239.280F, 224.679F, 210.969F, 198.096F,
  117598. 186.008F, 174.658F, 164.000F, 153.993F,
  117599. 144.596F, 135.773F, 127.488F, 119.708F,
  117600. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117601. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117602. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117603. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117604. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117605. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117606. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117607. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117608. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117609. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117610. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117611. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117612. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117613. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117614. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117615. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117616. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117617. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117618. 1.20790F, 1.13419F, 1.06499F, 1.F
  117619. };
  117620. void _vp_remove_floor(vorbis_look_psy *p,
  117621. float *mdct,
  117622. int *codedflr,
  117623. float *residue,
  117624. int sliding_lowpass){
  117625. int i,n=p->n;
  117626. if(sliding_lowpass>n)sliding_lowpass=n;
  117627. for(i=0;i<sliding_lowpass;i++){
  117628. residue[i]=
  117629. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117630. }
  117631. for(;i<n;i++)
  117632. residue[i]=0.;
  117633. }
  117634. void _vp_noisemask(vorbis_look_psy *p,
  117635. float *logmdct,
  117636. float *logmask){
  117637. int i,n=p->n;
  117638. float *work=(float*) alloca(n*sizeof(*work));
  117639. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117640. 140.,-1);
  117641. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117642. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117643. p->vi->noisewindowfixed);
  117644. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117645. #if 0
  117646. {
  117647. static int seq=0;
  117648. float work2[n];
  117649. for(i=0;i<n;i++){
  117650. work2[i]=logmask[i]+work[i];
  117651. }
  117652. if(seq&1)
  117653. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117654. else
  117655. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117656. if(seq&1)
  117657. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117658. else
  117659. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117660. seq++;
  117661. }
  117662. #endif
  117663. for(i=0;i<n;i++){
  117664. int dB=logmask[i]+.5;
  117665. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117666. if(dB<0)dB=0;
  117667. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117668. }
  117669. }
  117670. void _vp_tonemask(vorbis_look_psy *p,
  117671. float *logfft,
  117672. float *logmask,
  117673. float global_specmax,
  117674. float local_specmax){
  117675. int i,n=p->n;
  117676. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117677. float att=local_specmax+p->vi->ath_adjatt;
  117678. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117679. /* set the ATH (floating below localmax, not global max by a
  117680. specified att) */
  117681. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117682. for(i=0;i<n;i++)
  117683. logmask[i]=p->ath[i]+att;
  117684. /* tone masking */
  117685. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117686. max_seeds(p,seed,logmask);
  117687. }
  117688. void _vp_offset_and_mix(vorbis_look_psy *p,
  117689. float *noise,
  117690. float *tone,
  117691. int offset_select,
  117692. float *logmask,
  117693. float *mdct,
  117694. float *logmdct){
  117695. int i,n=p->n;
  117696. float de, coeffi, cx;/* AoTuV */
  117697. float toneatt=p->vi->tone_masteratt[offset_select];
  117698. cx = p->m_val;
  117699. for(i=0;i<n;i++){
  117700. float val= noise[i]+p->noiseoffset[offset_select][i];
  117701. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117702. logmask[i]=max(val,tone[i]+toneatt);
  117703. /* AoTuV */
  117704. /** @ M1 **
  117705. The following codes improve a noise problem.
  117706. A fundamental idea uses the value of masking and carries out
  117707. the relative compensation of the MDCT.
  117708. However, this code is not perfect and all noise problems cannot be solved.
  117709. by Aoyumi @ 2004/04/18
  117710. */
  117711. if(offset_select == 1) {
  117712. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117713. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117714. if(val > coeffi){
  117715. /* mdct value is > -17.2 dB below floor */
  117716. de = 1.0-((val-coeffi)*0.005*cx);
  117717. /* pro-rated attenuation:
  117718. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117719. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117720. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117721. etc... */
  117722. if(de < 0) de = 0.0001;
  117723. }else
  117724. /* mdct value is <= -17.2 dB below floor */
  117725. de = 1.0-((val-coeffi)*0.0003*cx);
  117726. /* pro-rated attenuation:
  117727. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117728. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117729. etc... */
  117730. mdct[i] *= de;
  117731. }
  117732. }
  117733. }
  117734. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117735. vorbis_info *vi=vd->vi;
  117736. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117737. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117738. int n=ci->blocksizes[vd->W]/2;
  117739. float secs=(float)n/vi->rate;
  117740. amp+=secs*gi->ampmax_att_per_sec;
  117741. if(amp<-9999)amp=-9999;
  117742. return(amp);
  117743. }
  117744. static void couple_lossless(float A, float B,
  117745. float *qA, float *qB){
  117746. int test1=fabs(*qA)>fabs(*qB);
  117747. test1-= fabs(*qA)<fabs(*qB);
  117748. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117749. if(test1==1){
  117750. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117751. }else{
  117752. float temp=*qB;
  117753. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117754. *qA=temp;
  117755. }
  117756. if(*qB>fabs(*qA)*1.9999f){
  117757. *qB= -fabs(*qA)*2.f;
  117758. *qA= -*qA;
  117759. }
  117760. }
  117761. static float hypot_lookup[32]={
  117762. -0.009935, -0.011245, -0.012726, -0.014397,
  117763. -0.016282, -0.018407, -0.020800, -0.023494,
  117764. -0.026522, -0.029923, -0.033737, -0.038010,
  117765. -0.042787, -0.048121, -0.054064, -0.060671,
  117766. -0.068000, -0.076109, -0.085054, -0.094892,
  117767. -0.105675, -0.117451, -0.130260, -0.144134,
  117768. -0.159093, -0.175146, -0.192286, -0.210490,
  117769. -0.229718, -0.249913, -0.271001, -0.292893};
  117770. static void precomputed_couple_point(float premag,
  117771. int floorA,int floorB,
  117772. float *mag, float *ang){
  117773. int test=(floorA>floorB)-1;
  117774. int offset=31-abs(floorA-floorB);
  117775. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117776. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117777. *mag=premag*floormag;
  117778. *ang=0.f;
  117779. }
  117780. /* just like below, this is currently set up to only do
  117781. single-step-depth coupling. Otherwise, we'd have to do more
  117782. copying (which will be inevitable later) */
  117783. /* doing the real circular magnitude calculation is audibly superior
  117784. to (A+B)/sqrt(2) */
  117785. static float dipole_hypot(float a, float b){
  117786. if(a>0.){
  117787. if(b>0.)return sqrt(a*a+b*b);
  117788. if(a>-b)return sqrt(a*a-b*b);
  117789. return -sqrt(b*b-a*a);
  117790. }
  117791. if(b<0.)return -sqrt(a*a+b*b);
  117792. if(-a>b)return -sqrt(a*a-b*b);
  117793. return sqrt(b*b-a*a);
  117794. }
  117795. static float round_hypot(float a, float b){
  117796. if(a>0.){
  117797. if(b>0.)return sqrt(a*a+b*b);
  117798. if(a>-b)return sqrt(a*a+b*b);
  117799. return -sqrt(b*b+a*a);
  117800. }
  117801. if(b<0.)return -sqrt(a*a+b*b);
  117802. if(-a>b)return -sqrt(a*a+b*b);
  117803. return sqrt(b*b+a*a);
  117804. }
  117805. /* revert to round hypot for now */
  117806. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117807. vorbis_info_psy_global *g,
  117808. vorbis_look_psy *p,
  117809. vorbis_info_mapping0 *vi,
  117810. float **mdct){
  117811. int i,j,n=p->n;
  117812. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117813. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117814. for(i=0;i<vi->coupling_steps;i++){
  117815. float *mdctM=mdct[vi->coupling_mag[i]];
  117816. float *mdctA=mdct[vi->coupling_ang[i]];
  117817. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117818. for(j=0;j<limit;j++)
  117819. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117820. for(;j<n;j++)
  117821. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117822. }
  117823. return(ret);
  117824. }
  117825. /* this is for per-channel noise normalization */
  117826. static int JUCE_CDECL apsort(const void *a, const void *b){
  117827. float f1=fabs(**(float**)a);
  117828. float f2=fabs(**(float**)b);
  117829. return (f1<f2)-(f1>f2);
  117830. }
  117831. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117832. vorbis_look_psy *p,
  117833. vorbis_info_mapping0 *vi,
  117834. float **mags){
  117835. if(p->vi->normal_point_p){
  117836. int i,j,k,n=p->n;
  117837. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117838. int partition=p->vi->normal_partition;
  117839. float **work=(float**) alloca(sizeof(*work)*partition);
  117840. for(i=0;i<vi->coupling_steps;i++){
  117841. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117842. for(j=0;j<n;j+=partition){
  117843. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117844. qsort(work,partition,sizeof(*work),apsort);
  117845. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117846. }
  117847. }
  117848. return(ret);
  117849. }
  117850. return(NULL);
  117851. }
  117852. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117853. float *magnitudes,int *sortedindex){
  117854. int i,j,n=p->n;
  117855. vorbis_info_psy *vi=p->vi;
  117856. int partition=vi->normal_partition;
  117857. float **work=(float**) alloca(sizeof(*work)*partition);
  117858. int start=vi->normal_start;
  117859. for(j=start;j<n;j+=partition){
  117860. if(j+partition>n)partition=n-j;
  117861. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117862. qsort(work,partition,sizeof(*work),apsort);
  117863. for(i=0;i<partition;i++){
  117864. sortedindex[i+j-start]=work[i]-magnitudes;
  117865. }
  117866. }
  117867. }
  117868. void _vp_noise_normalize(vorbis_look_psy *p,
  117869. float *in,float *out,int *sortedindex){
  117870. int flag=0,i,j=0,n=p->n;
  117871. vorbis_info_psy *vi=p->vi;
  117872. int partition=vi->normal_partition;
  117873. int start=vi->normal_start;
  117874. if(start>n)start=n;
  117875. if(vi->normal_channel_p){
  117876. for(;j<start;j++)
  117877. out[j]=rint(in[j]);
  117878. for(;j+partition<=n;j+=partition){
  117879. float acc=0.;
  117880. int k;
  117881. for(i=j;i<j+partition;i++)
  117882. acc+=in[i]*in[i];
  117883. for(i=0;i<partition;i++){
  117884. k=sortedindex[i+j-start];
  117885. if(in[k]*in[k]>=.25f){
  117886. out[k]=rint(in[k]);
  117887. acc-=in[k]*in[k];
  117888. flag=1;
  117889. }else{
  117890. if(acc<vi->normal_thresh)break;
  117891. out[k]=unitnorm(in[k]);
  117892. acc-=1.;
  117893. }
  117894. }
  117895. for(;i<partition;i++){
  117896. k=sortedindex[i+j-start];
  117897. out[k]=0.;
  117898. }
  117899. }
  117900. }
  117901. for(;j<n;j++)
  117902. out[j]=rint(in[j]);
  117903. }
  117904. void _vp_couple(int blobno,
  117905. vorbis_info_psy_global *g,
  117906. vorbis_look_psy *p,
  117907. vorbis_info_mapping0 *vi,
  117908. float **res,
  117909. float **mag_memo,
  117910. int **mag_sort,
  117911. int **ifloor,
  117912. int *nonzero,
  117913. int sliding_lowpass){
  117914. int i,j,k,n=p->n;
  117915. /* perform any requested channel coupling */
  117916. /* point stereo can only be used in a first stage (in this encoder)
  117917. because of the dependency on floor lookups */
  117918. for(i=0;i<vi->coupling_steps;i++){
  117919. /* once we're doing multistage coupling in which a channel goes
  117920. through more than one coupling step, the floor vector
  117921. magnitudes will also have to be recalculated an propogated
  117922. along with PCM. Right now, we're not (that will wait until 5.1
  117923. most likely), so the code isn't here yet. The memory management
  117924. here is all assuming single depth couplings anyway. */
  117925. /* make sure coupling a zero and a nonzero channel results in two
  117926. nonzero channels. */
  117927. if(nonzero[vi->coupling_mag[i]] ||
  117928. nonzero[vi->coupling_ang[i]]){
  117929. float *rM=res[vi->coupling_mag[i]];
  117930. float *rA=res[vi->coupling_ang[i]];
  117931. float *qM=rM+n;
  117932. float *qA=rA+n;
  117933. int *floorM=ifloor[vi->coupling_mag[i]];
  117934. int *floorA=ifloor[vi->coupling_ang[i]];
  117935. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117936. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117937. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117938. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117939. int pointlimit=limit;
  117940. nonzero[vi->coupling_mag[i]]=1;
  117941. nonzero[vi->coupling_ang[i]]=1;
  117942. /* The threshold of a stereo is changed with the size of n */
  117943. if(n > 1000)
  117944. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117945. for(j=0;j<p->n;j+=partition){
  117946. float acc=0.f;
  117947. for(k=0;k<partition;k++){
  117948. int l=k+j;
  117949. if(l<sliding_lowpass){
  117950. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117951. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117952. precomputed_couple_point(mag_memo[i][l],
  117953. floorM[l],floorA[l],
  117954. qM+l,qA+l);
  117955. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117956. }else{
  117957. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117958. }
  117959. }else{
  117960. qM[l]=0.;
  117961. qA[l]=0.;
  117962. }
  117963. }
  117964. if(p->vi->normal_point_p){
  117965. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117966. int l=mag_sort[i][j+k];
  117967. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117968. qM[l]=unitnorm(qM[l]);
  117969. acc-=1.f;
  117970. }
  117971. }
  117972. }
  117973. }
  117974. }
  117975. }
  117976. }
  117977. /* AoTuV */
  117978. /** @ M2 **
  117979. The boost problem by the combination of noise normalization and point stereo is eased.
  117980. However, this is a temporary patch.
  117981. by Aoyumi @ 2004/04/18
  117982. */
  117983. void hf_reduction(vorbis_info_psy_global *g,
  117984. vorbis_look_psy *p,
  117985. vorbis_info_mapping0 *vi,
  117986. float **mdct){
  117987. int i,j,n=p->n, de=0.3*p->m_val;
  117988. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117989. for(i=0; i<vi->coupling_steps; i++){
  117990. /* for(j=start; j<limit; j++){} // ???*/
  117991. for(j=limit; j<n; j++)
  117992. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117993. }
  117994. }
  117995. #endif
  117996. /*** End of inlined file: psy.c ***/
  117997. /*** Start of inlined file: registry.c ***/
  117998. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117999. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118000. // tasks..
  118001. #if JUCE_MSVC
  118002. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118003. #endif
  118004. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118005. #if JUCE_USE_OGGVORBIS
  118006. /* seems like major overkill now; the backend numbers will grow into
  118007. the infrastructure soon enough */
  118008. extern vorbis_func_floor floor0_exportbundle;
  118009. extern vorbis_func_floor floor1_exportbundle;
  118010. extern vorbis_func_residue residue0_exportbundle;
  118011. extern vorbis_func_residue residue1_exportbundle;
  118012. extern vorbis_func_residue residue2_exportbundle;
  118013. extern vorbis_func_mapping mapping0_exportbundle;
  118014. vorbis_func_floor *_floor_P[]={
  118015. &floor0_exportbundle,
  118016. &floor1_exportbundle,
  118017. };
  118018. vorbis_func_residue *_residue_P[]={
  118019. &residue0_exportbundle,
  118020. &residue1_exportbundle,
  118021. &residue2_exportbundle,
  118022. };
  118023. vorbis_func_mapping *_mapping_P[]={
  118024. &mapping0_exportbundle,
  118025. };
  118026. #endif
  118027. /*** End of inlined file: registry.c ***/
  118028. /*** Start of inlined file: res0.c ***/
  118029. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118030. encode/decode loops are coded for clarity and performance is not
  118031. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118032. it's slow. */
  118033. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118034. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118035. // tasks..
  118036. #if JUCE_MSVC
  118037. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118038. #endif
  118039. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118040. #if JUCE_USE_OGGVORBIS
  118041. #include <stdlib.h>
  118042. #include <string.h>
  118043. #include <math.h>
  118044. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118045. #include <stdio.h>
  118046. #endif
  118047. typedef struct {
  118048. vorbis_info_residue0 *info;
  118049. int parts;
  118050. int stages;
  118051. codebook *fullbooks;
  118052. codebook *phrasebook;
  118053. codebook ***partbooks;
  118054. int partvals;
  118055. int **decodemap;
  118056. long postbits;
  118057. long phrasebits;
  118058. long frames;
  118059. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118060. int train_seq;
  118061. long *training_data[8][64];
  118062. float training_max[8][64];
  118063. float training_min[8][64];
  118064. float tmin;
  118065. float tmax;
  118066. #endif
  118067. } vorbis_look_residue0;
  118068. void res0_free_info(vorbis_info_residue *i){
  118069. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118070. if(info){
  118071. memset(info,0,sizeof(*info));
  118072. _ogg_free(info);
  118073. }
  118074. }
  118075. void res0_free_look(vorbis_look_residue *i){
  118076. int j;
  118077. if(i){
  118078. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118079. #ifdef TRAIN_RES
  118080. {
  118081. int j,k,l;
  118082. for(j=0;j<look->parts;j++){
  118083. /*fprintf(stderr,"partition %d: ",j);*/
  118084. for(k=0;k<8;k++)
  118085. if(look->training_data[k][j]){
  118086. char buffer[80];
  118087. FILE *of;
  118088. codebook *statebook=look->partbooks[j][k];
  118089. /* long and short into the same bucket by current convention */
  118090. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118091. of=fopen(buffer,"a");
  118092. for(l=0;l<statebook->entries;l++)
  118093. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118094. fclose(of);
  118095. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118096. look->training_min[k][j],look->training_max[k][j]);*/
  118097. _ogg_free(look->training_data[k][j]);
  118098. look->training_data[k][j]=NULL;
  118099. }
  118100. /*fprintf(stderr,"\n");*/
  118101. }
  118102. }
  118103. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118104. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118105. (float)look->phrasebits/look->frames,
  118106. (float)look->postbits/look->frames,
  118107. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118108. #endif
  118109. /*vorbis_info_residue0 *info=look->info;
  118110. fprintf(stderr,
  118111. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118112. "(%g/frame) \n",look->frames,look->phrasebits,
  118113. look->resbitsflat,
  118114. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118115. for(j=0;j<look->parts;j++){
  118116. long acc=0;
  118117. fprintf(stderr,"\t[%d] == ",j);
  118118. for(k=0;k<look->stages;k++)
  118119. if((info->secondstages[j]>>k)&1){
  118120. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118121. acc+=look->resbits[j][k];
  118122. }
  118123. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118124. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118125. }
  118126. fprintf(stderr,"\n");*/
  118127. for(j=0;j<look->parts;j++)
  118128. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118129. _ogg_free(look->partbooks);
  118130. for(j=0;j<look->partvals;j++)
  118131. _ogg_free(look->decodemap[j]);
  118132. _ogg_free(look->decodemap);
  118133. memset(look,0,sizeof(*look));
  118134. _ogg_free(look);
  118135. }
  118136. }
  118137. static int icount(unsigned int v){
  118138. int ret=0;
  118139. while(v){
  118140. ret+=v&1;
  118141. v>>=1;
  118142. }
  118143. return(ret);
  118144. }
  118145. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118146. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118147. int j,acc=0;
  118148. oggpack_write(opb,info->begin,24);
  118149. oggpack_write(opb,info->end,24);
  118150. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118151. code with a partitioned book */
  118152. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118153. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118154. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118155. bitmask of one indicates this partition class has bits to write
  118156. this pass */
  118157. for(j=0;j<info->partitions;j++){
  118158. if(ilog(info->secondstages[j])>3){
  118159. /* yes, this is a minor hack due to not thinking ahead */
  118160. oggpack_write(opb,info->secondstages[j],3);
  118161. oggpack_write(opb,1,1);
  118162. oggpack_write(opb,info->secondstages[j]>>3,5);
  118163. }else
  118164. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118165. acc+=icount(info->secondstages[j]);
  118166. }
  118167. for(j=0;j<acc;j++)
  118168. oggpack_write(opb,info->booklist[j],8);
  118169. }
  118170. /* vorbis_info is for range checking */
  118171. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118172. int j,acc=0;
  118173. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118174. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118175. info->begin=oggpack_read(opb,24);
  118176. info->end=oggpack_read(opb,24);
  118177. info->grouping=oggpack_read(opb,24)+1;
  118178. info->partitions=oggpack_read(opb,6)+1;
  118179. info->groupbook=oggpack_read(opb,8);
  118180. for(j=0;j<info->partitions;j++){
  118181. int cascade=oggpack_read(opb,3);
  118182. if(oggpack_read(opb,1))
  118183. cascade|=(oggpack_read(opb,5)<<3);
  118184. info->secondstages[j]=cascade;
  118185. acc+=icount(cascade);
  118186. }
  118187. for(j=0;j<acc;j++)
  118188. info->booklist[j]=oggpack_read(opb,8);
  118189. if(info->groupbook>=ci->books)goto errout;
  118190. for(j=0;j<acc;j++)
  118191. if(info->booklist[j]>=ci->books)goto errout;
  118192. return(info);
  118193. errout:
  118194. res0_free_info(info);
  118195. return(NULL);
  118196. }
  118197. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118198. vorbis_info_residue *vr){
  118199. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118200. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118201. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118202. int j,k,acc=0;
  118203. int dim;
  118204. int maxstage=0;
  118205. look->info=info;
  118206. look->parts=info->partitions;
  118207. look->fullbooks=ci->fullbooks;
  118208. look->phrasebook=ci->fullbooks+info->groupbook;
  118209. dim=look->phrasebook->dim;
  118210. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118211. for(j=0;j<look->parts;j++){
  118212. int stages=ilog(info->secondstages[j]);
  118213. if(stages){
  118214. if(stages>maxstage)maxstage=stages;
  118215. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118216. for(k=0;k<stages;k++)
  118217. if(info->secondstages[j]&(1<<k)){
  118218. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118219. #ifdef TRAIN_RES
  118220. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118221. sizeof(***look->training_data));
  118222. #endif
  118223. }
  118224. }
  118225. }
  118226. look->partvals=rint(pow((float)look->parts,(float)dim));
  118227. look->stages=maxstage;
  118228. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118229. for(j=0;j<look->partvals;j++){
  118230. long val=j;
  118231. long mult=look->partvals/look->parts;
  118232. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118233. for(k=0;k<dim;k++){
  118234. long deco=val/mult;
  118235. val-=deco*mult;
  118236. mult/=look->parts;
  118237. look->decodemap[j][k]=deco;
  118238. }
  118239. }
  118240. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118241. {
  118242. static int train_seq=0;
  118243. look->train_seq=train_seq++;
  118244. }
  118245. #endif
  118246. return(look);
  118247. }
  118248. /* break an abstraction and copy some code for performance purposes */
  118249. static int local_book_besterror(codebook *book,float *a){
  118250. int dim=book->dim,i,k,o;
  118251. int best=0;
  118252. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118253. /* find the quant val of each scalar */
  118254. for(k=0,o=dim;k<dim;++k){
  118255. float val=a[--o];
  118256. i=tt->threshvals>>1;
  118257. if(val<tt->quantthresh[i]){
  118258. if(val<tt->quantthresh[i-1]){
  118259. for(--i;i>0;--i)
  118260. if(val>=tt->quantthresh[i-1])
  118261. break;
  118262. }
  118263. }else{
  118264. for(++i;i<tt->threshvals-1;++i)
  118265. if(val<tt->quantthresh[i])break;
  118266. }
  118267. best=(best*tt->quantvals)+tt->quantmap[i];
  118268. }
  118269. /* regular lattices are easy :-) */
  118270. if(book->c->lengthlist[best]<=0){
  118271. const static_codebook *c=book->c;
  118272. int i,j;
  118273. float bestf=0.f;
  118274. float *e=book->valuelist;
  118275. best=-1;
  118276. for(i=0;i<book->entries;i++){
  118277. if(c->lengthlist[i]>0){
  118278. float thisx=0.f;
  118279. for(j=0;j<dim;j++){
  118280. float val=(e[j]-a[j]);
  118281. thisx+=val*val;
  118282. }
  118283. if(best==-1 || thisx<bestf){
  118284. bestf=thisx;
  118285. best=i;
  118286. }
  118287. }
  118288. e+=dim;
  118289. }
  118290. }
  118291. {
  118292. float *ptr=book->valuelist+best*dim;
  118293. for(i=0;i<dim;i++)
  118294. *a++ -= *ptr++;
  118295. }
  118296. return(best);
  118297. }
  118298. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118299. codebook *book,long *acc){
  118300. int i,bits=0;
  118301. int dim=book->dim;
  118302. int step=n/dim;
  118303. for(i=0;i<step;i++){
  118304. int entry=local_book_besterror(book,vec+i*dim);
  118305. #ifdef TRAIN_RES
  118306. acc[entry]++;
  118307. #endif
  118308. bits+=vorbis_book_encode(book,entry,opb);
  118309. }
  118310. return(bits);
  118311. }
  118312. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118313. float **in,int ch){
  118314. long i,j,k;
  118315. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118316. vorbis_info_residue0 *info=look->info;
  118317. /* move all this setup out later */
  118318. int samples_per_partition=info->grouping;
  118319. int possible_partitions=info->partitions;
  118320. int n=info->end-info->begin;
  118321. int partvals=n/samples_per_partition;
  118322. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118323. float scale=100./samples_per_partition;
  118324. /* we find the partition type for each partition of each
  118325. channel. We'll go back and do the interleaved encoding in a
  118326. bit. For now, clarity */
  118327. for(i=0;i<ch;i++){
  118328. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118329. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118330. }
  118331. for(i=0;i<partvals;i++){
  118332. int offset=i*samples_per_partition+info->begin;
  118333. for(j=0;j<ch;j++){
  118334. float max=0.;
  118335. float ent=0.;
  118336. for(k=0;k<samples_per_partition;k++){
  118337. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118338. ent+=fabs(rint(in[j][offset+k]));
  118339. }
  118340. ent*=scale;
  118341. for(k=0;k<possible_partitions-1;k++)
  118342. if(max<=info->classmetric1[k] &&
  118343. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118344. break;
  118345. partword[j][i]=k;
  118346. }
  118347. }
  118348. #ifdef TRAIN_RESAUX
  118349. {
  118350. FILE *of;
  118351. char buffer[80];
  118352. for(i=0;i<ch;i++){
  118353. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118354. of=fopen(buffer,"a");
  118355. for(j=0;j<partvals;j++)
  118356. fprintf(of,"%ld, ",partword[i][j]);
  118357. fprintf(of,"\n");
  118358. fclose(of);
  118359. }
  118360. }
  118361. #endif
  118362. look->frames++;
  118363. return(partword);
  118364. }
  118365. /* designed for stereo or other modes where the partition size is an
  118366. integer multiple of the number of channels encoded in the current
  118367. submap */
  118368. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118369. int ch){
  118370. long i,j,k,l;
  118371. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118372. vorbis_info_residue0 *info=look->info;
  118373. /* move all this setup out later */
  118374. int samples_per_partition=info->grouping;
  118375. int possible_partitions=info->partitions;
  118376. int n=info->end-info->begin;
  118377. int partvals=n/samples_per_partition;
  118378. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118379. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118380. FILE *of;
  118381. char buffer[80];
  118382. #endif
  118383. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118384. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118385. for(i=0,l=info->begin/ch;i<partvals;i++){
  118386. float magmax=0.f;
  118387. float angmax=0.f;
  118388. for(j=0;j<samples_per_partition;j+=ch){
  118389. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118390. for(k=1;k<ch;k++)
  118391. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118392. l++;
  118393. }
  118394. for(j=0;j<possible_partitions-1;j++)
  118395. if(magmax<=info->classmetric1[j] &&
  118396. angmax<=info->classmetric2[j])
  118397. break;
  118398. partword[0][i]=j;
  118399. }
  118400. #ifdef TRAIN_RESAUX
  118401. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118402. of=fopen(buffer,"a");
  118403. for(i=0;i<partvals;i++)
  118404. fprintf(of,"%ld, ",partword[0][i]);
  118405. fprintf(of,"\n");
  118406. fclose(of);
  118407. #endif
  118408. look->frames++;
  118409. return(partword);
  118410. }
  118411. static int _01forward(oggpack_buffer *opb,
  118412. vorbis_block *vb,vorbis_look_residue *vl,
  118413. float **in,int ch,
  118414. long **partword,
  118415. int (*encode)(oggpack_buffer *,float *,int,
  118416. codebook *,long *)){
  118417. long i,j,k,s;
  118418. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118419. vorbis_info_residue0 *info=look->info;
  118420. /* move all this setup out later */
  118421. int samples_per_partition=info->grouping;
  118422. int possible_partitions=info->partitions;
  118423. int partitions_per_word=look->phrasebook->dim;
  118424. int n=info->end-info->begin;
  118425. int partvals=n/samples_per_partition;
  118426. long resbits[128];
  118427. long resvals[128];
  118428. #ifdef TRAIN_RES
  118429. for(i=0;i<ch;i++)
  118430. for(j=info->begin;j<info->end;j++){
  118431. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118432. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118433. }
  118434. #endif
  118435. memset(resbits,0,sizeof(resbits));
  118436. memset(resvals,0,sizeof(resvals));
  118437. /* we code the partition words for each channel, then the residual
  118438. words for a partition per channel until we've written all the
  118439. residual words for that partition word. Then write the next
  118440. partition channel words... */
  118441. for(s=0;s<look->stages;s++){
  118442. for(i=0;i<partvals;){
  118443. /* first we encode a partition codeword for each channel */
  118444. if(s==0){
  118445. for(j=0;j<ch;j++){
  118446. long val=partword[j][i];
  118447. for(k=1;k<partitions_per_word;k++){
  118448. val*=possible_partitions;
  118449. if(i+k<partvals)
  118450. val+=partword[j][i+k];
  118451. }
  118452. /* training hack */
  118453. if(val<look->phrasebook->entries)
  118454. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118455. #if 0 /*def TRAIN_RES*/
  118456. else
  118457. fprintf(stderr,"!");
  118458. #endif
  118459. }
  118460. }
  118461. /* now we encode interleaved residual values for the partitions */
  118462. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118463. long offset=i*samples_per_partition+info->begin;
  118464. for(j=0;j<ch;j++){
  118465. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118466. if(info->secondstages[partword[j][i]]&(1<<s)){
  118467. codebook *statebook=look->partbooks[partword[j][i]][s];
  118468. if(statebook){
  118469. int ret;
  118470. long *accumulator=NULL;
  118471. #ifdef TRAIN_RES
  118472. accumulator=look->training_data[s][partword[j][i]];
  118473. {
  118474. int l;
  118475. float *samples=in[j]+offset;
  118476. for(l=0;l<samples_per_partition;l++){
  118477. if(samples[l]<look->training_min[s][partword[j][i]])
  118478. look->training_min[s][partword[j][i]]=samples[l];
  118479. if(samples[l]>look->training_max[s][partword[j][i]])
  118480. look->training_max[s][partword[j][i]]=samples[l];
  118481. }
  118482. }
  118483. #endif
  118484. ret=encode(opb,in[j]+offset,samples_per_partition,
  118485. statebook,accumulator);
  118486. look->postbits+=ret;
  118487. resbits[partword[j][i]]+=ret;
  118488. }
  118489. }
  118490. }
  118491. }
  118492. }
  118493. }
  118494. /*{
  118495. long total=0;
  118496. long totalbits=0;
  118497. fprintf(stderr,"%d :: ",vb->mode);
  118498. for(k=0;k<possible_partitions;k++){
  118499. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118500. total+=resvals[k];
  118501. totalbits+=resbits[k];
  118502. }
  118503. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118504. }*/
  118505. return(0);
  118506. }
  118507. /* a truncated packet here just means 'stop working'; it's not an error */
  118508. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118509. float **in,int ch,
  118510. long (*decodepart)(codebook *, float *,
  118511. oggpack_buffer *,int)){
  118512. long i,j,k,l,s;
  118513. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118514. vorbis_info_residue0 *info=look->info;
  118515. /* move all this setup out later */
  118516. int samples_per_partition=info->grouping;
  118517. int partitions_per_word=look->phrasebook->dim;
  118518. int n=info->end-info->begin;
  118519. int partvals=n/samples_per_partition;
  118520. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118521. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118522. for(j=0;j<ch;j++)
  118523. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118524. for(s=0;s<look->stages;s++){
  118525. /* each loop decodes on partition codeword containing
  118526. partitions_pre_word partitions */
  118527. for(i=0,l=0;i<partvals;l++){
  118528. if(s==0){
  118529. /* fetch the partition word for each channel */
  118530. for(j=0;j<ch;j++){
  118531. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118532. if(temp==-1)goto eopbreak;
  118533. partword[j][l]=look->decodemap[temp];
  118534. if(partword[j][l]==NULL)goto errout;
  118535. }
  118536. }
  118537. /* now we decode residual values for the partitions */
  118538. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118539. for(j=0;j<ch;j++){
  118540. long offset=info->begin+i*samples_per_partition;
  118541. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118542. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118543. if(stagebook){
  118544. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118545. samples_per_partition)==-1)goto eopbreak;
  118546. }
  118547. }
  118548. }
  118549. }
  118550. }
  118551. errout:
  118552. eopbreak:
  118553. return(0);
  118554. }
  118555. #if 0
  118556. /* residue 0 and 1 are just slight variants of one another. 0 is
  118557. interleaved, 1 is not */
  118558. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118559. float **in,int *nonzero,int ch){
  118560. /* we encode only the nonzero parts of a bundle */
  118561. int i,used=0;
  118562. for(i=0;i<ch;i++)
  118563. if(nonzero[i])
  118564. in[used++]=in[i];
  118565. if(used)
  118566. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118567. return(_01class(vb,vl,in,used));
  118568. else
  118569. return(0);
  118570. }
  118571. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118572. float **in,float **out,int *nonzero,int ch,
  118573. long **partword){
  118574. /* we encode only the nonzero parts of a bundle */
  118575. int i,j,used=0,n=vb->pcmend/2;
  118576. for(i=0;i<ch;i++)
  118577. if(nonzero[i]){
  118578. if(out)
  118579. for(j=0;j<n;j++)
  118580. out[i][j]+=in[i][j];
  118581. in[used++]=in[i];
  118582. }
  118583. if(used){
  118584. int ret=_01forward(vb,vl,in,used,partword,
  118585. _interleaved_encodepart);
  118586. if(out){
  118587. used=0;
  118588. for(i=0;i<ch;i++)
  118589. if(nonzero[i]){
  118590. for(j=0;j<n;j++)
  118591. out[i][j]-=in[used][j];
  118592. used++;
  118593. }
  118594. }
  118595. return(ret);
  118596. }else{
  118597. return(0);
  118598. }
  118599. }
  118600. #endif
  118601. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118602. float **in,int *nonzero,int ch){
  118603. int i,used=0;
  118604. for(i=0;i<ch;i++)
  118605. if(nonzero[i])
  118606. in[used++]=in[i];
  118607. if(used)
  118608. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118609. else
  118610. return(0);
  118611. }
  118612. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118613. float **in,float **out,int *nonzero,int ch,
  118614. long **partword){
  118615. int i,j,used=0,n=vb->pcmend/2;
  118616. for(i=0;i<ch;i++)
  118617. if(nonzero[i]){
  118618. if(out)
  118619. for(j=0;j<n;j++)
  118620. out[i][j]+=in[i][j];
  118621. in[used++]=in[i];
  118622. }
  118623. if(used){
  118624. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118625. if(out){
  118626. used=0;
  118627. for(i=0;i<ch;i++)
  118628. if(nonzero[i]){
  118629. for(j=0;j<n;j++)
  118630. out[i][j]-=in[used][j];
  118631. used++;
  118632. }
  118633. }
  118634. return(ret);
  118635. }else{
  118636. return(0);
  118637. }
  118638. }
  118639. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118640. float **in,int *nonzero,int ch){
  118641. int i,used=0;
  118642. for(i=0;i<ch;i++)
  118643. if(nonzero[i])
  118644. in[used++]=in[i];
  118645. if(used)
  118646. return(_01class(vb,vl,in,used));
  118647. else
  118648. return(0);
  118649. }
  118650. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118651. float **in,int *nonzero,int ch){
  118652. int i,used=0;
  118653. for(i=0;i<ch;i++)
  118654. if(nonzero[i])
  118655. in[used++]=in[i];
  118656. if(used)
  118657. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118658. else
  118659. return(0);
  118660. }
  118661. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118662. float **in,int *nonzero,int ch){
  118663. int i,used=0;
  118664. for(i=0;i<ch;i++)
  118665. if(nonzero[i])used++;
  118666. if(used)
  118667. return(_2class(vb,vl,in,ch));
  118668. else
  118669. return(0);
  118670. }
  118671. /* res2 is slightly more different; all the channels are interleaved
  118672. into a single vector and encoded. */
  118673. int res2_forward(oggpack_buffer *opb,
  118674. vorbis_block *vb,vorbis_look_residue *vl,
  118675. float **in,float **out,int *nonzero,int ch,
  118676. long **partword){
  118677. long i,j,k,n=vb->pcmend/2,used=0;
  118678. /* don't duplicate the code; use a working vector hack for now and
  118679. reshape ourselves into a single channel res1 */
  118680. /* ugly; reallocs for each coupling pass :-( */
  118681. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118682. for(i=0;i<ch;i++){
  118683. float *pcm=in[i];
  118684. if(nonzero[i])used++;
  118685. for(j=0,k=i;j<n;j++,k+=ch)
  118686. work[k]=pcm[j];
  118687. }
  118688. if(used){
  118689. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118690. /* update the sofar vector */
  118691. if(out){
  118692. for(i=0;i<ch;i++){
  118693. float *pcm=in[i];
  118694. float *sofar=out[i];
  118695. for(j=0,k=i;j<n;j++,k+=ch)
  118696. sofar[j]+=pcm[j]-work[k];
  118697. }
  118698. }
  118699. return(ret);
  118700. }else{
  118701. return(0);
  118702. }
  118703. }
  118704. /* duplicate code here as speed is somewhat more important */
  118705. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118706. float **in,int *nonzero,int ch){
  118707. long i,k,l,s;
  118708. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118709. vorbis_info_residue0 *info=look->info;
  118710. /* move all this setup out later */
  118711. int samples_per_partition=info->grouping;
  118712. int partitions_per_word=look->phrasebook->dim;
  118713. int n=info->end-info->begin;
  118714. int partvals=n/samples_per_partition;
  118715. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118716. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118717. for(i=0;i<ch;i++)if(nonzero[i])break;
  118718. if(i==ch)return(0); /* no nonzero vectors */
  118719. for(s=0;s<look->stages;s++){
  118720. for(i=0,l=0;i<partvals;l++){
  118721. if(s==0){
  118722. /* fetch the partition word */
  118723. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118724. if(temp==-1)goto eopbreak;
  118725. partword[l]=look->decodemap[temp];
  118726. if(partword[l]==NULL)goto errout;
  118727. }
  118728. /* now we decode residual values for the partitions */
  118729. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118730. if(info->secondstages[partword[l][k]]&(1<<s)){
  118731. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118732. if(stagebook){
  118733. if(vorbis_book_decodevv_add(stagebook,in,
  118734. i*samples_per_partition+info->begin,ch,
  118735. &vb->opb,samples_per_partition)==-1)
  118736. goto eopbreak;
  118737. }
  118738. }
  118739. }
  118740. }
  118741. errout:
  118742. eopbreak:
  118743. return(0);
  118744. }
  118745. vorbis_func_residue residue0_exportbundle={
  118746. NULL,
  118747. &res0_unpack,
  118748. &res0_look,
  118749. &res0_free_info,
  118750. &res0_free_look,
  118751. NULL,
  118752. NULL,
  118753. &res0_inverse
  118754. };
  118755. vorbis_func_residue residue1_exportbundle={
  118756. &res0_pack,
  118757. &res0_unpack,
  118758. &res0_look,
  118759. &res0_free_info,
  118760. &res0_free_look,
  118761. &res1_class,
  118762. &res1_forward,
  118763. &res1_inverse
  118764. };
  118765. vorbis_func_residue residue2_exportbundle={
  118766. &res0_pack,
  118767. &res0_unpack,
  118768. &res0_look,
  118769. &res0_free_info,
  118770. &res0_free_look,
  118771. &res2_class,
  118772. &res2_forward,
  118773. &res2_inverse
  118774. };
  118775. #endif
  118776. /*** End of inlined file: res0.c ***/
  118777. /*** Start of inlined file: sharedbook.c ***/
  118778. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118779. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118780. // tasks..
  118781. #if JUCE_MSVC
  118782. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118783. #endif
  118784. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118785. #if JUCE_USE_OGGVORBIS
  118786. #include <stdlib.h>
  118787. #include <math.h>
  118788. #include <string.h>
  118789. /**** pack/unpack helpers ******************************************/
  118790. int _ilog(unsigned int v){
  118791. int ret=0;
  118792. while(v){
  118793. ret++;
  118794. v>>=1;
  118795. }
  118796. return(ret);
  118797. }
  118798. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118799. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118800. Why not IEEE? It's just not that important here. */
  118801. #define VQ_FEXP 10
  118802. #define VQ_FMAN 21
  118803. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118804. /* doesn't currently guard under/overflow */
  118805. long _float32_pack(float val){
  118806. int sign=0;
  118807. long exp;
  118808. long mant;
  118809. if(val<0){
  118810. sign=0x80000000;
  118811. val= -val;
  118812. }
  118813. exp= floor(log(val)/log(2.f));
  118814. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118815. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118816. return(sign|exp|mant);
  118817. }
  118818. float _float32_unpack(long val){
  118819. double mant=val&0x1fffff;
  118820. int sign=val&0x80000000;
  118821. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118822. if(sign)mant= -mant;
  118823. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118824. }
  118825. /* given a list of word lengths, generate a list of codewords. Works
  118826. for length ordered or unordered, always assigns the lowest valued
  118827. codewords first. Extended to handle unused entries (length 0) */
  118828. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118829. long i,j,count=0;
  118830. ogg_uint32_t marker[33];
  118831. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118832. memset(marker,0,sizeof(marker));
  118833. for(i=0;i<n;i++){
  118834. long length=l[i];
  118835. if(length>0){
  118836. ogg_uint32_t entry=marker[length];
  118837. /* when we claim a node for an entry, we also claim the nodes
  118838. below it (pruning off the imagined tree that may have dangled
  118839. from it) as well as blocking the use of any nodes directly
  118840. above for leaves */
  118841. /* update ourself */
  118842. if(length<32 && (entry>>length)){
  118843. /* error condition; the lengths must specify an overpopulated tree */
  118844. _ogg_free(r);
  118845. return(NULL);
  118846. }
  118847. r[count++]=entry;
  118848. /* Look to see if the next shorter marker points to the node
  118849. above. if so, update it and repeat. */
  118850. {
  118851. for(j=length;j>0;j--){
  118852. if(marker[j]&1){
  118853. /* have to jump branches */
  118854. if(j==1)
  118855. marker[1]++;
  118856. else
  118857. marker[j]=marker[j-1]<<1;
  118858. break; /* invariant says next upper marker would already
  118859. have been moved if it was on the same path */
  118860. }
  118861. marker[j]++;
  118862. }
  118863. }
  118864. /* prune the tree; the implicit invariant says all the longer
  118865. markers were dangling from our just-taken node. Dangle them
  118866. from our *new* node. */
  118867. for(j=length+1;j<33;j++)
  118868. if((marker[j]>>1) == entry){
  118869. entry=marker[j];
  118870. marker[j]=marker[j-1]<<1;
  118871. }else
  118872. break;
  118873. }else
  118874. if(sparsecount==0)count++;
  118875. }
  118876. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118877. endian */
  118878. for(i=0,count=0;i<n;i++){
  118879. ogg_uint32_t temp=0;
  118880. for(j=0;j<l[i];j++){
  118881. temp<<=1;
  118882. temp|=(r[count]>>j)&1;
  118883. }
  118884. if(sparsecount){
  118885. if(l[i])
  118886. r[count++]=temp;
  118887. }else
  118888. r[count++]=temp;
  118889. }
  118890. return(r);
  118891. }
  118892. /* there might be a straightforward one-line way to do the below
  118893. that's portable and totally safe against roundoff, but I haven't
  118894. thought of it. Therefore, we opt on the side of caution */
  118895. long _book_maptype1_quantvals(const static_codebook *b){
  118896. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118897. /* the above *should* be reliable, but we'll not assume that FP is
  118898. ever reliable when bitstream sync is at stake; verify via integer
  118899. means that vals really is the greatest value of dim for which
  118900. vals^b->bim <= b->entries */
  118901. /* treat the above as an initial guess */
  118902. while(1){
  118903. long acc=1;
  118904. long acc1=1;
  118905. int i;
  118906. for(i=0;i<b->dim;i++){
  118907. acc*=vals;
  118908. acc1*=vals+1;
  118909. }
  118910. if(acc<=b->entries && acc1>b->entries){
  118911. return(vals);
  118912. }else{
  118913. if(acc>b->entries){
  118914. vals--;
  118915. }else{
  118916. vals++;
  118917. }
  118918. }
  118919. }
  118920. }
  118921. /* unpack the quantized list of values for encode/decode ***********/
  118922. /* we need to deal with two map types: in map type 1, the values are
  118923. generated algorithmically (each column of the vector counts through
  118924. the values in the quant vector). in map type 2, all the values came
  118925. in in an explicit list. Both value lists must be unpacked */
  118926. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118927. long j,k,count=0;
  118928. if(b->maptype==1 || b->maptype==2){
  118929. int quantvals;
  118930. float mindel=_float32_unpack(b->q_min);
  118931. float delta=_float32_unpack(b->q_delta);
  118932. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118933. /* maptype 1 and 2 both use a quantized value vector, but
  118934. different sizes */
  118935. switch(b->maptype){
  118936. case 1:
  118937. /* most of the time, entries%dimensions == 0, but we need to be
  118938. well defined. We define that the possible vales at each
  118939. scalar is values == entries/dim. If entries%dim != 0, we'll
  118940. have 'too few' values (values*dim<entries), which means that
  118941. we'll have 'left over' entries; left over entries use zeroed
  118942. values (and are wasted). So don't generate codebooks like
  118943. that */
  118944. quantvals=_book_maptype1_quantvals(b);
  118945. for(j=0;j<b->entries;j++){
  118946. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118947. float last=0.f;
  118948. int indexdiv=1;
  118949. for(k=0;k<b->dim;k++){
  118950. int index= (j/indexdiv)%quantvals;
  118951. float val=b->quantlist[index];
  118952. val=fabs(val)*delta+mindel+last;
  118953. if(b->q_sequencep)last=val;
  118954. if(sparsemap)
  118955. r[sparsemap[count]*b->dim+k]=val;
  118956. else
  118957. r[count*b->dim+k]=val;
  118958. indexdiv*=quantvals;
  118959. }
  118960. count++;
  118961. }
  118962. }
  118963. break;
  118964. case 2:
  118965. for(j=0;j<b->entries;j++){
  118966. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118967. float last=0.f;
  118968. for(k=0;k<b->dim;k++){
  118969. float val=b->quantlist[j*b->dim+k];
  118970. val=fabs(val)*delta+mindel+last;
  118971. if(b->q_sequencep)last=val;
  118972. if(sparsemap)
  118973. r[sparsemap[count]*b->dim+k]=val;
  118974. else
  118975. r[count*b->dim+k]=val;
  118976. }
  118977. count++;
  118978. }
  118979. }
  118980. break;
  118981. }
  118982. return(r);
  118983. }
  118984. return(NULL);
  118985. }
  118986. void vorbis_staticbook_clear(static_codebook *b){
  118987. if(b->allocedp){
  118988. if(b->quantlist)_ogg_free(b->quantlist);
  118989. if(b->lengthlist)_ogg_free(b->lengthlist);
  118990. if(b->nearest_tree){
  118991. _ogg_free(b->nearest_tree->ptr0);
  118992. _ogg_free(b->nearest_tree->ptr1);
  118993. _ogg_free(b->nearest_tree->p);
  118994. _ogg_free(b->nearest_tree->q);
  118995. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118996. _ogg_free(b->nearest_tree);
  118997. }
  118998. if(b->thresh_tree){
  118999. _ogg_free(b->thresh_tree->quantthresh);
  119000. _ogg_free(b->thresh_tree->quantmap);
  119001. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119002. _ogg_free(b->thresh_tree);
  119003. }
  119004. memset(b,0,sizeof(*b));
  119005. }
  119006. }
  119007. void vorbis_staticbook_destroy(static_codebook *b){
  119008. if(b->allocedp){
  119009. vorbis_staticbook_clear(b);
  119010. _ogg_free(b);
  119011. }
  119012. }
  119013. void vorbis_book_clear(codebook *b){
  119014. /* static book is not cleared; we're likely called on the lookup and
  119015. the static codebook belongs to the info struct */
  119016. if(b->valuelist)_ogg_free(b->valuelist);
  119017. if(b->codelist)_ogg_free(b->codelist);
  119018. if(b->dec_index)_ogg_free(b->dec_index);
  119019. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119020. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119021. memset(b,0,sizeof(*b));
  119022. }
  119023. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119024. memset(c,0,sizeof(*c));
  119025. c->c=s;
  119026. c->entries=s->entries;
  119027. c->used_entries=s->entries;
  119028. c->dim=s->dim;
  119029. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119030. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119031. return(0);
  119032. }
  119033. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119034. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119035. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119036. }
  119037. /* decode codebook arrangement is more heavily optimized than encode */
  119038. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119039. int i,j,n=0,tabn;
  119040. int *sortindex;
  119041. memset(c,0,sizeof(*c));
  119042. /* count actually used entries */
  119043. for(i=0;i<s->entries;i++)
  119044. if(s->lengthlist[i]>0)
  119045. n++;
  119046. c->entries=s->entries;
  119047. c->used_entries=n;
  119048. c->dim=s->dim;
  119049. /* two different remappings go on here.
  119050. First, we collapse the likely sparse codebook down only to
  119051. actually represented values/words. This collapsing needs to be
  119052. indexed as map-valueless books are used to encode original entry
  119053. positions as integers.
  119054. Second, we reorder all vectors, including the entry index above,
  119055. by sorted bitreversed codeword to allow treeless decode. */
  119056. {
  119057. /* perform sort */
  119058. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119059. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119060. if(codes==NULL)goto err_out;
  119061. for(i=0;i<n;i++){
  119062. codes[i]=ogg_bitreverse(codes[i]);
  119063. codep[i]=codes+i;
  119064. }
  119065. qsort(codep,n,sizeof(*codep),sort32a);
  119066. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119067. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119068. /* the index is a reverse index */
  119069. for(i=0;i<n;i++){
  119070. int position=codep[i]-codes;
  119071. sortindex[position]=i;
  119072. }
  119073. for(i=0;i<n;i++)
  119074. c->codelist[sortindex[i]]=codes[i];
  119075. _ogg_free(codes);
  119076. }
  119077. c->valuelist=_book_unquantize(s,n,sortindex);
  119078. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119079. for(n=0,i=0;i<s->entries;i++)
  119080. if(s->lengthlist[i]>0)
  119081. c->dec_index[sortindex[n++]]=i;
  119082. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119083. for(n=0,i=0;i<s->entries;i++)
  119084. if(s->lengthlist[i]>0)
  119085. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119086. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119087. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119088. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119089. tabn=1<<c->dec_firsttablen;
  119090. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119091. c->dec_maxlength=0;
  119092. for(i=0;i<n;i++){
  119093. if(c->dec_maxlength<c->dec_codelengths[i])
  119094. c->dec_maxlength=c->dec_codelengths[i];
  119095. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119096. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119097. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119098. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119099. }
  119100. }
  119101. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119102. hints for the non-direct-hits */
  119103. {
  119104. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119105. long lo=0,hi=0;
  119106. for(i=0;i<tabn;i++){
  119107. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119108. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119109. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119110. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119111. /* we only actually have 15 bits per hint to play with here.
  119112. In order to overflow gracefully (nothing breaks, efficiency
  119113. just drops), encode as the difference from the extremes. */
  119114. {
  119115. unsigned long loval=lo;
  119116. unsigned long hival=n-hi;
  119117. if(loval>0x7fff)loval=0x7fff;
  119118. if(hival>0x7fff)hival=0x7fff;
  119119. c->dec_firsttable[ogg_bitreverse(word)]=
  119120. 0x80000000UL | (loval<<15) | hival;
  119121. }
  119122. }
  119123. }
  119124. }
  119125. return(0);
  119126. err_out:
  119127. vorbis_book_clear(c);
  119128. return(-1);
  119129. }
  119130. static float _dist(int el,float *ref, float *b,int step){
  119131. int i;
  119132. float acc=0.f;
  119133. for(i=0;i<el;i++){
  119134. float val=(ref[i]-b[i*step]);
  119135. acc+=val*val;
  119136. }
  119137. return(acc);
  119138. }
  119139. int _best(codebook *book, float *a, int step){
  119140. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119141. #if 0
  119142. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119143. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119144. #endif
  119145. int dim=book->dim;
  119146. int k,o;
  119147. /*int savebest=-1;
  119148. float saverr;*/
  119149. /* do we have a threshhold encode hint? */
  119150. if(tt){
  119151. int index=0,i;
  119152. /* find the quant val of each scalar */
  119153. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119154. i=tt->threshvals>>1;
  119155. if(a[o]<tt->quantthresh[i]){
  119156. for(;i>0;i--)
  119157. if(a[o]>=tt->quantthresh[i-1])
  119158. break;
  119159. }else{
  119160. for(i++;i<tt->threshvals-1;i++)
  119161. if(a[o]<tt->quantthresh[i])break;
  119162. }
  119163. index=(index*tt->quantvals)+tt->quantmap[i];
  119164. }
  119165. /* regular lattices are easy :-) */
  119166. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119167. use a decision tree after all
  119168. and fall through*/
  119169. return(index);
  119170. }
  119171. #if 0
  119172. /* do we have a pigeonhole encode hint? */
  119173. if(pt){
  119174. const static_codebook *c=book->c;
  119175. int i,besti=-1;
  119176. float best=0.f;
  119177. int entry=0;
  119178. /* dealing with sequentialness is a pain in the ass */
  119179. if(c->q_sequencep){
  119180. int pv;
  119181. long mul=1;
  119182. float qlast=0;
  119183. for(k=0,o=0;k<dim;k++,o+=step){
  119184. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119185. if(pv<0 || pv>=pt->mapentries)break;
  119186. entry+=pt->pigeonmap[pv]*mul;
  119187. mul*=pt->quantvals;
  119188. qlast+=pv*pt->del+pt->min;
  119189. }
  119190. }else{
  119191. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119192. int pv=(int)((a[o]-pt->min)/pt->del);
  119193. if(pv<0 || pv>=pt->mapentries)break;
  119194. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119195. }
  119196. }
  119197. /* must be within the pigeonholable range; if we quant outside (or
  119198. in an entry that we define no list for), brute force it */
  119199. if(k==dim && pt->fitlength[entry]){
  119200. /* search the abbreviated list */
  119201. long *list=pt->fitlist+pt->fitmap[entry];
  119202. for(i=0;i<pt->fitlength[entry];i++){
  119203. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119204. if(besti==-1 || this<best){
  119205. best=this;
  119206. besti=list[i];
  119207. }
  119208. }
  119209. return(besti);
  119210. }
  119211. }
  119212. if(nt){
  119213. /* optimized using the decision tree */
  119214. while(1){
  119215. float c=0.f;
  119216. float *p=book->valuelist+nt->p[ptr];
  119217. float *q=book->valuelist+nt->q[ptr];
  119218. for(k=0,o=0;k<dim;k++,o+=step)
  119219. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119220. if(c>0.f) /* in A */
  119221. ptr= -nt->ptr0[ptr];
  119222. else /* in B */
  119223. ptr= -nt->ptr1[ptr];
  119224. if(ptr<=0)break;
  119225. }
  119226. return(-ptr);
  119227. }
  119228. #endif
  119229. /* brute force it! */
  119230. {
  119231. const static_codebook *c=book->c;
  119232. int i,besti=-1;
  119233. float best=0.f;
  119234. float *e=book->valuelist;
  119235. for(i=0;i<book->entries;i++){
  119236. if(c->lengthlist[i]>0){
  119237. float thisx=_dist(dim,e,a,step);
  119238. if(besti==-1 || thisx<best){
  119239. best=thisx;
  119240. besti=i;
  119241. }
  119242. }
  119243. e+=dim;
  119244. }
  119245. /*if(savebest!=-1 && savebest!=besti){
  119246. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119247. "original:");
  119248. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119249. fprintf(stderr,"\n"
  119250. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119251. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119252. (book->valuelist+savebest*dim)[i]);
  119253. fprintf(stderr,"\n"
  119254. "bruteforce (entry %d, err %g):",besti,best);
  119255. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119256. (book->valuelist+besti*dim)[i]);
  119257. fprintf(stderr,"\n");
  119258. }*/
  119259. return(besti);
  119260. }
  119261. }
  119262. long vorbis_book_codeword(codebook *book,int entry){
  119263. if(book->c) /* only use with encode; decode optimizations are
  119264. allowed to break this */
  119265. return book->codelist[entry];
  119266. return -1;
  119267. }
  119268. long vorbis_book_codelen(codebook *book,int entry){
  119269. if(book->c) /* only use with encode; decode optimizations are
  119270. allowed to break this */
  119271. return book->c->lengthlist[entry];
  119272. return -1;
  119273. }
  119274. #ifdef _V_SELFTEST
  119275. /* Unit tests of the dequantizer; this stuff will be OK
  119276. cross-platform, I simply want to be sure that special mapping cases
  119277. actually work properly; a bug could go unnoticed for a while */
  119278. #include <stdio.h>
  119279. /* cases:
  119280. no mapping
  119281. full, explicit mapping
  119282. algorithmic mapping
  119283. nonsequential
  119284. sequential
  119285. */
  119286. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119287. static long partial_quantlist1[]={0,7,2};
  119288. /* no mapping */
  119289. static_codebook test1={
  119290. 4,16,
  119291. NULL,
  119292. 0,
  119293. 0,0,0,0,
  119294. NULL,
  119295. NULL,NULL
  119296. };
  119297. static float *test1_result=NULL;
  119298. /* linear, full mapping, nonsequential */
  119299. static_codebook test2={
  119300. 4,3,
  119301. NULL,
  119302. 2,
  119303. -533200896,1611661312,4,0,
  119304. full_quantlist1,
  119305. NULL,NULL
  119306. };
  119307. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119308. /* linear, full mapping, sequential */
  119309. static_codebook test3={
  119310. 4,3,
  119311. NULL,
  119312. 2,
  119313. -533200896,1611661312,4,1,
  119314. full_quantlist1,
  119315. NULL,NULL
  119316. };
  119317. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119318. /* linear, algorithmic mapping, nonsequential */
  119319. static_codebook test4={
  119320. 3,27,
  119321. NULL,
  119322. 1,
  119323. -533200896,1611661312,4,0,
  119324. partial_quantlist1,
  119325. NULL,NULL
  119326. };
  119327. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119328. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119329. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119330. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119331. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119332. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119333. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119334. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119335. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119336. /* linear, algorithmic mapping, sequential */
  119337. static_codebook test5={
  119338. 3,27,
  119339. NULL,
  119340. 1,
  119341. -533200896,1611661312,4,1,
  119342. partial_quantlist1,
  119343. NULL,NULL
  119344. };
  119345. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119346. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119347. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119348. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119349. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119350. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119351. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119352. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119353. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119354. void run_test(static_codebook *b,float *comp){
  119355. float *out=_book_unquantize(b,b->entries,NULL);
  119356. int i;
  119357. if(comp){
  119358. if(!out){
  119359. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119360. exit(1);
  119361. }
  119362. for(i=0;i<b->entries*b->dim;i++)
  119363. if(fabs(out[i]-comp[i])>.0001){
  119364. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119365. "position %d, %g != %g\n",i,out[i],comp[i]);
  119366. exit(1);
  119367. }
  119368. }else{
  119369. if(out){
  119370. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119371. " correct result should have been NULL\n");
  119372. exit(1);
  119373. }
  119374. }
  119375. }
  119376. int main(){
  119377. /* run the nine dequant tests, and compare to the hand-rolled results */
  119378. fprintf(stderr,"Dequant test 1... ");
  119379. run_test(&test1,test1_result);
  119380. fprintf(stderr,"OK\nDequant test 2... ");
  119381. run_test(&test2,test2_result);
  119382. fprintf(stderr,"OK\nDequant test 3... ");
  119383. run_test(&test3,test3_result);
  119384. fprintf(stderr,"OK\nDequant test 4... ");
  119385. run_test(&test4,test4_result);
  119386. fprintf(stderr,"OK\nDequant test 5... ");
  119387. run_test(&test5,test5_result);
  119388. fprintf(stderr,"OK\n\n");
  119389. return(0);
  119390. }
  119391. #endif
  119392. #endif
  119393. /*** End of inlined file: sharedbook.c ***/
  119394. /*** Start of inlined file: smallft.c ***/
  119395. /* FFT implementation from OggSquish, minus cosine transforms,
  119396. * minus all but radix 2/4 case. In Vorbis we only need this
  119397. * cut-down version.
  119398. *
  119399. * To do more than just power-of-two sized vectors, see the full
  119400. * version I wrote for NetLib.
  119401. *
  119402. * Note that the packing is a little strange; rather than the FFT r/i
  119403. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119404. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119405. * FORTRAN version
  119406. */
  119407. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119408. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119409. // tasks..
  119410. #if JUCE_MSVC
  119411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119412. #endif
  119413. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119414. #if JUCE_USE_OGGVORBIS
  119415. #include <stdlib.h>
  119416. #include <string.h>
  119417. #include <math.h>
  119418. static void drfti1(int n, float *wa, int *ifac){
  119419. static int ntryh[4] = { 4,2,3,5 };
  119420. static float tpi = 6.28318530717958648f;
  119421. float arg,argh,argld,fi;
  119422. int ntry=0,i,j=-1;
  119423. int k1, l1, l2, ib;
  119424. int ld, ii, ip, is, nq, nr;
  119425. int ido, ipm, nfm1;
  119426. int nl=n;
  119427. int nf=0;
  119428. L101:
  119429. j++;
  119430. if (j < 4)
  119431. ntry=ntryh[j];
  119432. else
  119433. ntry+=2;
  119434. L104:
  119435. nq=nl/ntry;
  119436. nr=nl-ntry*nq;
  119437. if (nr!=0) goto L101;
  119438. nf++;
  119439. ifac[nf+1]=ntry;
  119440. nl=nq;
  119441. if(ntry!=2)goto L107;
  119442. if(nf==1)goto L107;
  119443. for (i=1;i<nf;i++){
  119444. ib=nf-i+1;
  119445. ifac[ib+1]=ifac[ib];
  119446. }
  119447. ifac[2] = 2;
  119448. L107:
  119449. if(nl!=1)goto L104;
  119450. ifac[0]=n;
  119451. ifac[1]=nf;
  119452. argh=tpi/n;
  119453. is=0;
  119454. nfm1=nf-1;
  119455. l1=1;
  119456. if(nfm1==0)return;
  119457. for (k1=0;k1<nfm1;k1++){
  119458. ip=ifac[k1+2];
  119459. ld=0;
  119460. l2=l1*ip;
  119461. ido=n/l2;
  119462. ipm=ip-1;
  119463. for (j=0;j<ipm;j++){
  119464. ld+=l1;
  119465. i=is;
  119466. argld=(float)ld*argh;
  119467. fi=0.f;
  119468. for (ii=2;ii<ido;ii+=2){
  119469. fi+=1.f;
  119470. arg=fi*argld;
  119471. wa[i++]=cos(arg);
  119472. wa[i++]=sin(arg);
  119473. }
  119474. is+=ido;
  119475. }
  119476. l1=l2;
  119477. }
  119478. }
  119479. static void fdrffti(int n, float *wsave, int *ifac){
  119480. if (n == 1) return;
  119481. drfti1(n, wsave+n, ifac);
  119482. }
  119483. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119484. int i,k;
  119485. float ti2,tr2;
  119486. int t0,t1,t2,t3,t4,t5,t6;
  119487. t1=0;
  119488. t0=(t2=l1*ido);
  119489. t3=ido<<1;
  119490. for(k=0;k<l1;k++){
  119491. ch[t1<<1]=cc[t1]+cc[t2];
  119492. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119493. t1+=ido;
  119494. t2+=ido;
  119495. }
  119496. if(ido<2)return;
  119497. if(ido==2)goto L105;
  119498. t1=0;
  119499. t2=t0;
  119500. for(k=0;k<l1;k++){
  119501. t3=t2;
  119502. t4=(t1<<1)+(ido<<1);
  119503. t5=t1;
  119504. t6=t1+t1;
  119505. for(i=2;i<ido;i+=2){
  119506. t3+=2;
  119507. t4-=2;
  119508. t5+=2;
  119509. t6+=2;
  119510. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119511. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119512. ch[t6]=cc[t5]+ti2;
  119513. ch[t4]=ti2-cc[t5];
  119514. ch[t6-1]=cc[t5-1]+tr2;
  119515. ch[t4-1]=cc[t5-1]-tr2;
  119516. }
  119517. t1+=ido;
  119518. t2+=ido;
  119519. }
  119520. if(ido%2==1)return;
  119521. L105:
  119522. t3=(t2=(t1=ido)-1);
  119523. t2+=t0;
  119524. for(k=0;k<l1;k++){
  119525. ch[t1]=-cc[t2];
  119526. ch[t1-1]=cc[t3];
  119527. t1+=ido<<1;
  119528. t2+=ido;
  119529. t3+=ido;
  119530. }
  119531. }
  119532. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119533. float *wa2,float *wa3){
  119534. static float hsqt2 = .70710678118654752f;
  119535. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119536. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119537. t0=l1*ido;
  119538. t1=t0;
  119539. t4=t1<<1;
  119540. t2=t1+(t1<<1);
  119541. t3=0;
  119542. for(k=0;k<l1;k++){
  119543. tr1=cc[t1]+cc[t2];
  119544. tr2=cc[t3]+cc[t4];
  119545. ch[t5=t3<<2]=tr1+tr2;
  119546. ch[(ido<<2)+t5-1]=tr2-tr1;
  119547. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119548. ch[t5]=cc[t2]-cc[t1];
  119549. t1+=ido;
  119550. t2+=ido;
  119551. t3+=ido;
  119552. t4+=ido;
  119553. }
  119554. if(ido<2)return;
  119555. if(ido==2)goto L105;
  119556. t1=0;
  119557. for(k=0;k<l1;k++){
  119558. t2=t1;
  119559. t4=t1<<2;
  119560. t5=(t6=ido<<1)+t4;
  119561. for(i=2;i<ido;i+=2){
  119562. t3=(t2+=2);
  119563. t4+=2;
  119564. t5-=2;
  119565. t3+=t0;
  119566. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119567. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119568. t3+=t0;
  119569. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119570. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119571. t3+=t0;
  119572. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119573. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119574. tr1=cr2+cr4;
  119575. tr4=cr4-cr2;
  119576. ti1=ci2+ci4;
  119577. ti4=ci2-ci4;
  119578. ti2=cc[t2]+ci3;
  119579. ti3=cc[t2]-ci3;
  119580. tr2=cc[t2-1]+cr3;
  119581. tr3=cc[t2-1]-cr3;
  119582. ch[t4-1]=tr1+tr2;
  119583. ch[t4]=ti1+ti2;
  119584. ch[t5-1]=tr3-ti4;
  119585. ch[t5]=tr4-ti3;
  119586. ch[t4+t6-1]=ti4+tr3;
  119587. ch[t4+t6]=tr4+ti3;
  119588. ch[t5+t6-1]=tr2-tr1;
  119589. ch[t5+t6]=ti1-ti2;
  119590. }
  119591. t1+=ido;
  119592. }
  119593. if(ido&1)return;
  119594. L105:
  119595. t2=(t1=t0+ido-1)+(t0<<1);
  119596. t3=ido<<2;
  119597. t4=ido;
  119598. t5=ido<<1;
  119599. t6=ido;
  119600. for(k=0;k<l1;k++){
  119601. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119602. tr1=hsqt2*(cc[t1]-cc[t2]);
  119603. ch[t4-1]=tr1+cc[t6-1];
  119604. ch[t4+t5-1]=cc[t6-1]-tr1;
  119605. ch[t4]=ti1-cc[t1+t0];
  119606. ch[t4+t5]=ti1+cc[t1+t0];
  119607. t1+=ido;
  119608. t2+=ido;
  119609. t4+=t3;
  119610. t6+=ido;
  119611. }
  119612. }
  119613. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119614. float *c2,float *ch,float *ch2,float *wa){
  119615. static float tpi=6.283185307179586f;
  119616. int idij,ipph,i,j,k,l,ic,ik,is;
  119617. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119618. float dc2,ai1,ai2,ar1,ar2,ds2;
  119619. int nbd;
  119620. float dcp,arg,dsp,ar1h,ar2h;
  119621. int idp2,ipp2;
  119622. arg=tpi/(float)ip;
  119623. dcp=cos(arg);
  119624. dsp=sin(arg);
  119625. ipph=(ip+1)>>1;
  119626. ipp2=ip;
  119627. idp2=ido;
  119628. nbd=(ido-1)>>1;
  119629. t0=l1*ido;
  119630. t10=ip*ido;
  119631. if(ido==1)goto L119;
  119632. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119633. t1=0;
  119634. for(j=1;j<ip;j++){
  119635. t1+=t0;
  119636. t2=t1;
  119637. for(k=0;k<l1;k++){
  119638. ch[t2]=c1[t2];
  119639. t2+=ido;
  119640. }
  119641. }
  119642. is=-ido;
  119643. t1=0;
  119644. if(nbd>l1){
  119645. for(j=1;j<ip;j++){
  119646. t1+=t0;
  119647. is+=ido;
  119648. t2= -ido+t1;
  119649. for(k=0;k<l1;k++){
  119650. idij=is-1;
  119651. t2+=ido;
  119652. t3=t2;
  119653. for(i=2;i<ido;i+=2){
  119654. idij+=2;
  119655. t3+=2;
  119656. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119657. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119658. }
  119659. }
  119660. }
  119661. }else{
  119662. for(j=1;j<ip;j++){
  119663. is+=ido;
  119664. idij=is-1;
  119665. t1+=t0;
  119666. t2=t1;
  119667. for(i=2;i<ido;i+=2){
  119668. idij+=2;
  119669. t2+=2;
  119670. t3=t2;
  119671. for(k=0;k<l1;k++){
  119672. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119673. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119674. t3+=ido;
  119675. }
  119676. }
  119677. }
  119678. }
  119679. t1=0;
  119680. t2=ipp2*t0;
  119681. if(nbd<l1){
  119682. for(j=1;j<ipph;j++){
  119683. t1+=t0;
  119684. t2-=t0;
  119685. t3=t1;
  119686. t4=t2;
  119687. for(i=2;i<ido;i+=2){
  119688. t3+=2;
  119689. t4+=2;
  119690. t5=t3-ido;
  119691. t6=t4-ido;
  119692. for(k=0;k<l1;k++){
  119693. t5+=ido;
  119694. t6+=ido;
  119695. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119696. c1[t6-1]=ch[t5]-ch[t6];
  119697. c1[t5]=ch[t5]+ch[t6];
  119698. c1[t6]=ch[t6-1]-ch[t5-1];
  119699. }
  119700. }
  119701. }
  119702. }else{
  119703. for(j=1;j<ipph;j++){
  119704. t1+=t0;
  119705. t2-=t0;
  119706. t3=t1;
  119707. t4=t2;
  119708. for(k=0;k<l1;k++){
  119709. t5=t3;
  119710. t6=t4;
  119711. for(i=2;i<ido;i+=2){
  119712. t5+=2;
  119713. t6+=2;
  119714. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119715. c1[t6-1]=ch[t5]-ch[t6];
  119716. c1[t5]=ch[t5]+ch[t6];
  119717. c1[t6]=ch[t6-1]-ch[t5-1];
  119718. }
  119719. t3+=ido;
  119720. t4+=ido;
  119721. }
  119722. }
  119723. }
  119724. L119:
  119725. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119726. t1=0;
  119727. t2=ipp2*idl1;
  119728. for(j=1;j<ipph;j++){
  119729. t1+=t0;
  119730. t2-=t0;
  119731. t3=t1-ido;
  119732. t4=t2-ido;
  119733. for(k=0;k<l1;k++){
  119734. t3+=ido;
  119735. t4+=ido;
  119736. c1[t3]=ch[t3]+ch[t4];
  119737. c1[t4]=ch[t4]-ch[t3];
  119738. }
  119739. }
  119740. ar1=1.f;
  119741. ai1=0.f;
  119742. t1=0;
  119743. t2=ipp2*idl1;
  119744. t3=(ip-1)*idl1;
  119745. for(l=1;l<ipph;l++){
  119746. t1+=idl1;
  119747. t2-=idl1;
  119748. ar1h=dcp*ar1-dsp*ai1;
  119749. ai1=dcp*ai1+dsp*ar1;
  119750. ar1=ar1h;
  119751. t4=t1;
  119752. t5=t2;
  119753. t6=t3;
  119754. t7=idl1;
  119755. for(ik=0;ik<idl1;ik++){
  119756. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119757. ch2[t5++]=ai1*c2[t6++];
  119758. }
  119759. dc2=ar1;
  119760. ds2=ai1;
  119761. ar2=ar1;
  119762. ai2=ai1;
  119763. t4=idl1;
  119764. t5=(ipp2-1)*idl1;
  119765. for(j=2;j<ipph;j++){
  119766. t4+=idl1;
  119767. t5-=idl1;
  119768. ar2h=dc2*ar2-ds2*ai2;
  119769. ai2=dc2*ai2+ds2*ar2;
  119770. ar2=ar2h;
  119771. t6=t1;
  119772. t7=t2;
  119773. t8=t4;
  119774. t9=t5;
  119775. for(ik=0;ik<idl1;ik++){
  119776. ch2[t6++]+=ar2*c2[t8++];
  119777. ch2[t7++]+=ai2*c2[t9++];
  119778. }
  119779. }
  119780. }
  119781. t1=0;
  119782. for(j=1;j<ipph;j++){
  119783. t1+=idl1;
  119784. t2=t1;
  119785. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119786. }
  119787. if(ido<l1)goto L132;
  119788. t1=0;
  119789. t2=0;
  119790. for(k=0;k<l1;k++){
  119791. t3=t1;
  119792. t4=t2;
  119793. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119794. t1+=ido;
  119795. t2+=t10;
  119796. }
  119797. goto L135;
  119798. L132:
  119799. for(i=0;i<ido;i++){
  119800. t1=i;
  119801. t2=i;
  119802. for(k=0;k<l1;k++){
  119803. cc[t2]=ch[t1];
  119804. t1+=ido;
  119805. t2+=t10;
  119806. }
  119807. }
  119808. L135:
  119809. t1=0;
  119810. t2=ido<<1;
  119811. t3=0;
  119812. t4=ipp2*t0;
  119813. for(j=1;j<ipph;j++){
  119814. t1+=t2;
  119815. t3+=t0;
  119816. t4-=t0;
  119817. t5=t1;
  119818. t6=t3;
  119819. t7=t4;
  119820. for(k=0;k<l1;k++){
  119821. cc[t5-1]=ch[t6];
  119822. cc[t5]=ch[t7];
  119823. t5+=t10;
  119824. t6+=ido;
  119825. t7+=ido;
  119826. }
  119827. }
  119828. if(ido==1)return;
  119829. if(nbd<l1)goto L141;
  119830. t1=-ido;
  119831. t3=0;
  119832. t4=0;
  119833. t5=ipp2*t0;
  119834. for(j=1;j<ipph;j++){
  119835. t1+=t2;
  119836. t3+=t2;
  119837. t4+=t0;
  119838. t5-=t0;
  119839. t6=t1;
  119840. t7=t3;
  119841. t8=t4;
  119842. t9=t5;
  119843. for(k=0;k<l1;k++){
  119844. for(i=2;i<ido;i+=2){
  119845. ic=idp2-i;
  119846. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119847. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119848. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119849. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119850. }
  119851. t6+=t10;
  119852. t7+=t10;
  119853. t8+=ido;
  119854. t9+=ido;
  119855. }
  119856. }
  119857. return;
  119858. L141:
  119859. t1=-ido;
  119860. t3=0;
  119861. t4=0;
  119862. t5=ipp2*t0;
  119863. for(j=1;j<ipph;j++){
  119864. t1+=t2;
  119865. t3+=t2;
  119866. t4+=t0;
  119867. t5-=t0;
  119868. for(i=2;i<ido;i+=2){
  119869. t6=idp2+t1-i;
  119870. t7=i+t3;
  119871. t8=i+t4;
  119872. t9=i+t5;
  119873. for(k=0;k<l1;k++){
  119874. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119875. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119876. cc[t7]=ch[t8]+ch[t9];
  119877. cc[t6]=ch[t9]-ch[t8];
  119878. t6+=t10;
  119879. t7+=t10;
  119880. t8+=ido;
  119881. t9+=ido;
  119882. }
  119883. }
  119884. }
  119885. }
  119886. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119887. int i,k1,l1,l2;
  119888. int na,kh,nf;
  119889. int ip,iw,ido,idl1,ix2,ix3;
  119890. nf=ifac[1];
  119891. na=1;
  119892. l2=n;
  119893. iw=n;
  119894. for(k1=0;k1<nf;k1++){
  119895. kh=nf-k1;
  119896. ip=ifac[kh+1];
  119897. l1=l2/ip;
  119898. ido=n/l2;
  119899. idl1=ido*l1;
  119900. iw-=(ip-1)*ido;
  119901. na=1-na;
  119902. if(ip!=4)goto L102;
  119903. ix2=iw+ido;
  119904. ix3=ix2+ido;
  119905. if(na!=0)
  119906. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119907. else
  119908. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119909. goto L110;
  119910. L102:
  119911. if(ip!=2)goto L104;
  119912. if(na!=0)goto L103;
  119913. dradf2(ido,l1,c,ch,wa+iw-1);
  119914. goto L110;
  119915. L103:
  119916. dradf2(ido,l1,ch,c,wa+iw-1);
  119917. goto L110;
  119918. L104:
  119919. if(ido==1)na=1-na;
  119920. if(na!=0)goto L109;
  119921. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119922. na=1;
  119923. goto L110;
  119924. L109:
  119925. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119926. na=0;
  119927. L110:
  119928. l2=l1;
  119929. }
  119930. if(na==1)return;
  119931. for(i=0;i<n;i++)c[i]=ch[i];
  119932. }
  119933. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119934. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119935. float ti2,tr2;
  119936. t0=l1*ido;
  119937. t1=0;
  119938. t2=0;
  119939. t3=(ido<<1)-1;
  119940. for(k=0;k<l1;k++){
  119941. ch[t1]=cc[t2]+cc[t3+t2];
  119942. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119943. t2=(t1+=ido)<<1;
  119944. }
  119945. if(ido<2)return;
  119946. if(ido==2)goto L105;
  119947. t1=0;
  119948. t2=0;
  119949. for(k=0;k<l1;k++){
  119950. t3=t1;
  119951. t5=(t4=t2)+(ido<<1);
  119952. t6=t0+t1;
  119953. for(i=2;i<ido;i+=2){
  119954. t3+=2;
  119955. t4+=2;
  119956. t5-=2;
  119957. t6+=2;
  119958. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119959. tr2=cc[t4-1]-cc[t5-1];
  119960. ch[t3]=cc[t4]-cc[t5];
  119961. ti2=cc[t4]+cc[t5];
  119962. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119963. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119964. }
  119965. t2=(t1+=ido)<<1;
  119966. }
  119967. if(ido%2==1)return;
  119968. L105:
  119969. t1=ido-1;
  119970. t2=ido-1;
  119971. for(k=0;k<l1;k++){
  119972. ch[t1]=cc[t2]+cc[t2];
  119973. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119974. t1+=ido;
  119975. t2+=ido<<1;
  119976. }
  119977. }
  119978. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119979. float *wa2){
  119980. static float taur = -.5f;
  119981. static float taui = .8660254037844386f;
  119982. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119983. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119984. t0=l1*ido;
  119985. t1=0;
  119986. t2=t0<<1;
  119987. t3=ido<<1;
  119988. t4=ido+(ido<<1);
  119989. t5=0;
  119990. for(k=0;k<l1;k++){
  119991. tr2=cc[t3-1]+cc[t3-1];
  119992. cr2=cc[t5]+(taur*tr2);
  119993. ch[t1]=cc[t5]+tr2;
  119994. ci3=taui*(cc[t3]+cc[t3]);
  119995. ch[t1+t0]=cr2-ci3;
  119996. ch[t1+t2]=cr2+ci3;
  119997. t1+=ido;
  119998. t3+=t4;
  119999. t5+=t4;
  120000. }
  120001. if(ido==1)return;
  120002. t1=0;
  120003. t3=ido<<1;
  120004. for(k=0;k<l1;k++){
  120005. t7=t1+(t1<<1);
  120006. t6=(t5=t7+t3);
  120007. t8=t1;
  120008. t10=(t9=t1+t0)+t0;
  120009. for(i=2;i<ido;i+=2){
  120010. t5+=2;
  120011. t6-=2;
  120012. t7+=2;
  120013. t8+=2;
  120014. t9+=2;
  120015. t10+=2;
  120016. tr2=cc[t5-1]+cc[t6-1];
  120017. cr2=cc[t7-1]+(taur*tr2);
  120018. ch[t8-1]=cc[t7-1]+tr2;
  120019. ti2=cc[t5]-cc[t6];
  120020. ci2=cc[t7]+(taur*ti2);
  120021. ch[t8]=cc[t7]+ti2;
  120022. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120023. ci3=taui*(cc[t5]+cc[t6]);
  120024. dr2=cr2-ci3;
  120025. dr3=cr2+ci3;
  120026. di2=ci2+cr3;
  120027. di3=ci2-cr3;
  120028. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120029. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120030. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120031. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120032. }
  120033. t1+=ido;
  120034. }
  120035. }
  120036. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120037. float *wa2,float *wa3){
  120038. static float sqrt2=1.414213562373095f;
  120039. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120040. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120041. t0=l1*ido;
  120042. t1=0;
  120043. t2=ido<<2;
  120044. t3=0;
  120045. t6=ido<<1;
  120046. for(k=0;k<l1;k++){
  120047. t4=t3+t6;
  120048. t5=t1;
  120049. tr3=cc[t4-1]+cc[t4-1];
  120050. tr4=cc[t4]+cc[t4];
  120051. tr1=cc[t3]-cc[(t4+=t6)-1];
  120052. tr2=cc[t3]+cc[t4-1];
  120053. ch[t5]=tr2+tr3;
  120054. ch[t5+=t0]=tr1-tr4;
  120055. ch[t5+=t0]=tr2-tr3;
  120056. ch[t5+=t0]=tr1+tr4;
  120057. t1+=ido;
  120058. t3+=t2;
  120059. }
  120060. if(ido<2)return;
  120061. if(ido==2)goto L105;
  120062. t1=0;
  120063. for(k=0;k<l1;k++){
  120064. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120065. t7=t1;
  120066. for(i=2;i<ido;i+=2){
  120067. t2+=2;
  120068. t3+=2;
  120069. t4-=2;
  120070. t5-=2;
  120071. t7+=2;
  120072. ti1=cc[t2]+cc[t5];
  120073. ti2=cc[t2]-cc[t5];
  120074. ti3=cc[t3]-cc[t4];
  120075. tr4=cc[t3]+cc[t4];
  120076. tr1=cc[t2-1]-cc[t5-1];
  120077. tr2=cc[t2-1]+cc[t5-1];
  120078. ti4=cc[t3-1]-cc[t4-1];
  120079. tr3=cc[t3-1]+cc[t4-1];
  120080. ch[t7-1]=tr2+tr3;
  120081. cr3=tr2-tr3;
  120082. ch[t7]=ti2+ti3;
  120083. ci3=ti2-ti3;
  120084. cr2=tr1-tr4;
  120085. cr4=tr1+tr4;
  120086. ci2=ti1+ti4;
  120087. ci4=ti1-ti4;
  120088. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120089. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120090. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120091. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120092. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120093. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120094. }
  120095. t1+=ido;
  120096. }
  120097. if(ido%2 == 1)return;
  120098. L105:
  120099. t1=ido;
  120100. t2=ido<<2;
  120101. t3=ido-1;
  120102. t4=ido+(ido<<1);
  120103. for(k=0;k<l1;k++){
  120104. t5=t3;
  120105. ti1=cc[t1]+cc[t4];
  120106. ti2=cc[t4]-cc[t1];
  120107. tr1=cc[t1-1]-cc[t4-1];
  120108. tr2=cc[t1-1]+cc[t4-1];
  120109. ch[t5]=tr2+tr2;
  120110. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120111. ch[t5+=t0]=ti2+ti2;
  120112. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120113. t3+=ido;
  120114. t1+=t2;
  120115. t4+=t2;
  120116. }
  120117. }
  120118. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120119. float *c2,float *ch,float *ch2,float *wa){
  120120. static float tpi=6.283185307179586f;
  120121. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120122. t11,t12;
  120123. float dc2,ai1,ai2,ar1,ar2,ds2;
  120124. int nbd;
  120125. float dcp,arg,dsp,ar1h,ar2h;
  120126. int ipp2;
  120127. t10=ip*ido;
  120128. t0=l1*ido;
  120129. arg=tpi/(float)ip;
  120130. dcp=cos(arg);
  120131. dsp=sin(arg);
  120132. nbd=(ido-1)>>1;
  120133. ipp2=ip;
  120134. ipph=(ip+1)>>1;
  120135. if(ido<l1)goto L103;
  120136. t1=0;
  120137. t2=0;
  120138. for(k=0;k<l1;k++){
  120139. t3=t1;
  120140. t4=t2;
  120141. for(i=0;i<ido;i++){
  120142. ch[t3]=cc[t4];
  120143. t3++;
  120144. t4++;
  120145. }
  120146. t1+=ido;
  120147. t2+=t10;
  120148. }
  120149. goto L106;
  120150. L103:
  120151. t1=0;
  120152. for(i=0;i<ido;i++){
  120153. t2=t1;
  120154. t3=t1;
  120155. for(k=0;k<l1;k++){
  120156. ch[t2]=cc[t3];
  120157. t2+=ido;
  120158. t3+=t10;
  120159. }
  120160. t1++;
  120161. }
  120162. L106:
  120163. t1=0;
  120164. t2=ipp2*t0;
  120165. t7=(t5=ido<<1);
  120166. for(j=1;j<ipph;j++){
  120167. t1+=t0;
  120168. t2-=t0;
  120169. t3=t1;
  120170. t4=t2;
  120171. t6=t5;
  120172. for(k=0;k<l1;k++){
  120173. ch[t3]=cc[t6-1]+cc[t6-1];
  120174. ch[t4]=cc[t6]+cc[t6];
  120175. t3+=ido;
  120176. t4+=ido;
  120177. t6+=t10;
  120178. }
  120179. t5+=t7;
  120180. }
  120181. if (ido == 1)goto L116;
  120182. if(nbd<l1)goto L112;
  120183. t1=0;
  120184. t2=ipp2*t0;
  120185. t7=0;
  120186. for(j=1;j<ipph;j++){
  120187. t1+=t0;
  120188. t2-=t0;
  120189. t3=t1;
  120190. t4=t2;
  120191. t7+=(ido<<1);
  120192. t8=t7;
  120193. for(k=0;k<l1;k++){
  120194. t5=t3;
  120195. t6=t4;
  120196. t9=t8;
  120197. t11=t8;
  120198. for(i=2;i<ido;i+=2){
  120199. t5+=2;
  120200. t6+=2;
  120201. t9+=2;
  120202. t11-=2;
  120203. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120204. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120205. ch[t5]=cc[t9]-cc[t11];
  120206. ch[t6]=cc[t9]+cc[t11];
  120207. }
  120208. t3+=ido;
  120209. t4+=ido;
  120210. t8+=t10;
  120211. }
  120212. }
  120213. goto L116;
  120214. L112:
  120215. t1=0;
  120216. t2=ipp2*t0;
  120217. t7=0;
  120218. for(j=1;j<ipph;j++){
  120219. t1+=t0;
  120220. t2-=t0;
  120221. t3=t1;
  120222. t4=t2;
  120223. t7+=(ido<<1);
  120224. t8=t7;
  120225. t9=t7;
  120226. for(i=2;i<ido;i+=2){
  120227. t3+=2;
  120228. t4+=2;
  120229. t8+=2;
  120230. t9-=2;
  120231. t5=t3;
  120232. t6=t4;
  120233. t11=t8;
  120234. t12=t9;
  120235. for(k=0;k<l1;k++){
  120236. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120237. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120238. ch[t5]=cc[t11]-cc[t12];
  120239. ch[t6]=cc[t11]+cc[t12];
  120240. t5+=ido;
  120241. t6+=ido;
  120242. t11+=t10;
  120243. t12+=t10;
  120244. }
  120245. }
  120246. }
  120247. L116:
  120248. ar1=1.f;
  120249. ai1=0.f;
  120250. t1=0;
  120251. t9=(t2=ipp2*idl1);
  120252. t3=(ip-1)*idl1;
  120253. for(l=1;l<ipph;l++){
  120254. t1+=idl1;
  120255. t2-=idl1;
  120256. ar1h=dcp*ar1-dsp*ai1;
  120257. ai1=dcp*ai1+dsp*ar1;
  120258. ar1=ar1h;
  120259. t4=t1;
  120260. t5=t2;
  120261. t6=0;
  120262. t7=idl1;
  120263. t8=t3;
  120264. for(ik=0;ik<idl1;ik++){
  120265. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120266. c2[t5++]=ai1*ch2[t8++];
  120267. }
  120268. dc2=ar1;
  120269. ds2=ai1;
  120270. ar2=ar1;
  120271. ai2=ai1;
  120272. t6=idl1;
  120273. t7=t9-idl1;
  120274. for(j=2;j<ipph;j++){
  120275. t6+=idl1;
  120276. t7-=idl1;
  120277. ar2h=dc2*ar2-ds2*ai2;
  120278. ai2=dc2*ai2+ds2*ar2;
  120279. ar2=ar2h;
  120280. t4=t1;
  120281. t5=t2;
  120282. t11=t6;
  120283. t12=t7;
  120284. for(ik=0;ik<idl1;ik++){
  120285. c2[t4++]+=ar2*ch2[t11++];
  120286. c2[t5++]+=ai2*ch2[t12++];
  120287. }
  120288. }
  120289. }
  120290. t1=0;
  120291. for(j=1;j<ipph;j++){
  120292. t1+=idl1;
  120293. t2=t1;
  120294. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120295. }
  120296. t1=0;
  120297. t2=ipp2*t0;
  120298. for(j=1;j<ipph;j++){
  120299. t1+=t0;
  120300. t2-=t0;
  120301. t3=t1;
  120302. t4=t2;
  120303. for(k=0;k<l1;k++){
  120304. ch[t3]=c1[t3]-c1[t4];
  120305. ch[t4]=c1[t3]+c1[t4];
  120306. t3+=ido;
  120307. t4+=ido;
  120308. }
  120309. }
  120310. if(ido==1)goto L132;
  120311. if(nbd<l1)goto L128;
  120312. t1=0;
  120313. t2=ipp2*t0;
  120314. for(j=1;j<ipph;j++){
  120315. t1+=t0;
  120316. t2-=t0;
  120317. t3=t1;
  120318. t4=t2;
  120319. for(k=0;k<l1;k++){
  120320. t5=t3;
  120321. t6=t4;
  120322. for(i=2;i<ido;i+=2){
  120323. t5+=2;
  120324. t6+=2;
  120325. ch[t5-1]=c1[t5-1]-c1[t6];
  120326. ch[t6-1]=c1[t5-1]+c1[t6];
  120327. ch[t5]=c1[t5]+c1[t6-1];
  120328. ch[t6]=c1[t5]-c1[t6-1];
  120329. }
  120330. t3+=ido;
  120331. t4+=ido;
  120332. }
  120333. }
  120334. goto L132;
  120335. L128:
  120336. t1=0;
  120337. t2=ipp2*t0;
  120338. for(j=1;j<ipph;j++){
  120339. t1+=t0;
  120340. t2-=t0;
  120341. t3=t1;
  120342. t4=t2;
  120343. for(i=2;i<ido;i+=2){
  120344. t3+=2;
  120345. t4+=2;
  120346. t5=t3;
  120347. t6=t4;
  120348. for(k=0;k<l1;k++){
  120349. ch[t5-1]=c1[t5-1]-c1[t6];
  120350. ch[t6-1]=c1[t5-1]+c1[t6];
  120351. ch[t5]=c1[t5]+c1[t6-1];
  120352. ch[t6]=c1[t5]-c1[t6-1];
  120353. t5+=ido;
  120354. t6+=ido;
  120355. }
  120356. }
  120357. }
  120358. L132:
  120359. if(ido==1)return;
  120360. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120361. t1=0;
  120362. for(j=1;j<ip;j++){
  120363. t2=(t1+=t0);
  120364. for(k=0;k<l1;k++){
  120365. c1[t2]=ch[t2];
  120366. t2+=ido;
  120367. }
  120368. }
  120369. if(nbd>l1)goto L139;
  120370. is= -ido-1;
  120371. t1=0;
  120372. for(j=1;j<ip;j++){
  120373. is+=ido;
  120374. t1+=t0;
  120375. idij=is;
  120376. t2=t1;
  120377. for(i=2;i<ido;i+=2){
  120378. t2+=2;
  120379. idij+=2;
  120380. t3=t2;
  120381. for(k=0;k<l1;k++){
  120382. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120383. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120384. t3+=ido;
  120385. }
  120386. }
  120387. }
  120388. return;
  120389. L139:
  120390. is= -ido-1;
  120391. t1=0;
  120392. for(j=1;j<ip;j++){
  120393. is+=ido;
  120394. t1+=t0;
  120395. t2=t1;
  120396. for(k=0;k<l1;k++){
  120397. idij=is;
  120398. t3=t2;
  120399. for(i=2;i<ido;i+=2){
  120400. idij+=2;
  120401. t3+=2;
  120402. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120403. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120404. }
  120405. t2+=ido;
  120406. }
  120407. }
  120408. }
  120409. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120410. int i,k1,l1,l2;
  120411. int na;
  120412. int nf,ip,iw,ix2,ix3,ido,idl1;
  120413. nf=ifac[1];
  120414. na=0;
  120415. l1=1;
  120416. iw=1;
  120417. for(k1=0;k1<nf;k1++){
  120418. ip=ifac[k1 + 2];
  120419. l2=ip*l1;
  120420. ido=n/l2;
  120421. idl1=ido*l1;
  120422. if(ip!=4)goto L103;
  120423. ix2=iw+ido;
  120424. ix3=ix2+ido;
  120425. if(na!=0)
  120426. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120427. else
  120428. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120429. na=1-na;
  120430. goto L115;
  120431. L103:
  120432. if(ip!=2)goto L106;
  120433. if(na!=0)
  120434. dradb2(ido,l1,ch,c,wa+iw-1);
  120435. else
  120436. dradb2(ido,l1,c,ch,wa+iw-1);
  120437. na=1-na;
  120438. goto L115;
  120439. L106:
  120440. if(ip!=3)goto L109;
  120441. ix2=iw+ido;
  120442. if(na!=0)
  120443. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120444. else
  120445. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120446. na=1-na;
  120447. goto L115;
  120448. L109:
  120449. /* The radix five case can be translated later..... */
  120450. /* if(ip!=5)goto L112;
  120451. ix2=iw+ido;
  120452. ix3=ix2+ido;
  120453. ix4=ix3+ido;
  120454. if(na!=0)
  120455. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120456. else
  120457. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120458. na=1-na;
  120459. goto L115;
  120460. L112:*/
  120461. if(na!=0)
  120462. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120463. else
  120464. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120465. if(ido==1)na=1-na;
  120466. L115:
  120467. l1=l2;
  120468. iw+=(ip-1)*ido;
  120469. }
  120470. if(na==0)return;
  120471. for(i=0;i<n;i++)c[i]=ch[i];
  120472. }
  120473. void drft_forward(drft_lookup *l,float *data){
  120474. if(l->n==1)return;
  120475. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120476. }
  120477. void drft_backward(drft_lookup *l,float *data){
  120478. if (l->n==1)return;
  120479. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120480. }
  120481. void drft_init(drft_lookup *l,int n){
  120482. l->n=n;
  120483. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120484. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120485. fdrffti(n, l->trigcache, l->splitcache);
  120486. }
  120487. void drft_clear(drft_lookup *l){
  120488. if(l){
  120489. if(l->trigcache)_ogg_free(l->trigcache);
  120490. if(l->splitcache)_ogg_free(l->splitcache);
  120491. memset(l,0,sizeof(*l));
  120492. }
  120493. }
  120494. #endif
  120495. /*** End of inlined file: smallft.c ***/
  120496. /*** Start of inlined file: synthesis.c ***/
  120497. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120498. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120499. // tasks..
  120500. #if JUCE_MSVC
  120501. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120502. #endif
  120503. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120504. #if JUCE_USE_OGGVORBIS
  120505. #include <stdio.h>
  120506. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120507. vorbis_dsp_state *vd=vb->vd;
  120508. private_state *b=(private_state*)vd->backend_state;
  120509. vorbis_info *vi=vd->vi;
  120510. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120511. oggpack_buffer *opb=&vb->opb;
  120512. int type,mode,i;
  120513. /* first things first. Make sure decode is ready */
  120514. _vorbis_block_ripcord(vb);
  120515. oggpack_readinit(opb,op->packet,op->bytes);
  120516. /* Check the packet type */
  120517. if(oggpack_read(opb,1)!=0){
  120518. /* Oops. This is not an audio data packet */
  120519. return(OV_ENOTAUDIO);
  120520. }
  120521. /* read our mode and pre/post windowsize */
  120522. mode=oggpack_read(opb,b->modebits);
  120523. if(mode==-1)return(OV_EBADPACKET);
  120524. vb->mode=mode;
  120525. vb->W=ci->mode_param[mode]->blockflag;
  120526. if(vb->W){
  120527. /* this doesn;t get mapped through mode selection as it's used
  120528. only for window selection */
  120529. vb->lW=oggpack_read(opb,1);
  120530. vb->nW=oggpack_read(opb,1);
  120531. if(vb->nW==-1) return(OV_EBADPACKET);
  120532. }else{
  120533. vb->lW=0;
  120534. vb->nW=0;
  120535. }
  120536. /* more setup */
  120537. vb->granulepos=op->granulepos;
  120538. vb->sequence=op->packetno;
  120539. vb->eofflag=op->e_o_s;
  120540. /* alloc pcm passback storage */
  120541. vb->pcmend=ci->blocksizes[vb->W];
  120542. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120543. for(i=0;i<vi->channels;i++)
  120544. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120545. /* unpack_header enforces range checking */
  120546. type=ci->map_type[ci->mode_param[mode]->mapping];
  120547. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120548. mapping]));
  120549. }
  120550. /* used to track pcm position without actually performing decode.
  120551. Useful for sequential 'fast forward' */
  120552. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120553. vorbis_dsp_state *vd=vb->vd;
  120554. private_state *b=(private_state*)vd->backend_state;
  120555. vorbis_info *vi=vd->vi;
  120556. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120557. oggpack_buffer *opb=&vb->opb;
  120558. int mode;
  120559. /* first things first. Make sure decode is ready */
  120560. _vorbis_block_ripcord(vb);
  120561. oggpack_readinit(opb,op->packet,op->bytes);
  120562. /* Check the packet type */
  120563. if(oggpack_read(opb,1)!=0){
  120564. /* Oops. This is not an audio data packet */
  120565. return(OV_ENOTAUDIO);
  120566. }
  120567. /* read our mode and pre/post windowsize */
  120568. mode=oggpack_read(opb,b->modebits);
  120569. if(mode==-1)return(OV_EBADPACKET);
  120570. vb->mode=mode;
  120571. vb->W=ci->mode_param[mode]->blockflag;
  120572. if(vb->W){
  120573. vb->lW=oggpack_read(opb,1);
  120574. vb->nW=oggpack_read(opb,1);
  120575. if(vb->nW==-1) return(OV_EBADPACKET);
  120576. }else{
  120577. vb->lW=0;
  120578. vb->nW=0;
  120579. }
  120580. /* more setup */
  120581. vb->granulepos=op->granulepos;
  120582. vb->sequence=op->packetno;
  120583. vb->eofflag=op->e_o_s;
  120584. /* no pcm */
  120585. vb->pcmend=0;
  120586. vb->pcm=NULL;
  120587. return(0);
  120588. }
  120589. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120590. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120591. oggpack_buffer opb;
  120592. int mode;
  120593. oggpack_readinit(&opb,op->packet,op->bytes);
  120594. /* Check the packet type */
  120595. if(oggpack_read(&opb,1)!=0){
  120596. /* Oops. This is not an audio data packet */
  120597. return(OV_ENOTAUDIO);
  120598. }
  120599. {
  120600. int modebits=0;
  120601. int v=ci->modes;
  120602. while(v>1){
  120603. modebits++;
  120604. v>>=1;
  120605. }
  120606. /* read our mode and pre/post windowsize */
  120607. mode=oggpack_read(&opb,modebits);
  120608. }
  120609. if(mode==-1)return(OV_EBADPACKET);
  120610. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120611. }
  120612. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120613. /* set / clear half-sample-rate mode */
  120614. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120615. /* right now, our MDCT can't handle < 64 sample windows. */
  120616. if(ci->blocksizes[0]<=64 && flag)return -1;
  120617. ci->halfrate_flag=(flag?1:0);
  120618. return 0;
  120619. }
  120620. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120621. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120622. return ci->halfrate_flag;
  120623. }
  120624. #endif
  120625. /*** End of inlined file: synthesis.c ***/
  120626. /*** Start of inlined file: vorbisenc.c ***/
  120627. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120628. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120629. // tasks..
  120630. #if JUCE_MSVC
  120631. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120632. #endif
  120633. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120634. #if JUCE_USE_OGGVORBIS
  120635. #include <stdlib.h>
  120636. #include <string.h>
  120637. #include <math.h>
  120638. /* careful with this; it's using static array sizing to make managing
  120639. all the modes a little less annoying. If we use a residue backend
  120640. with > 12 partition types, or a different division of iteration,
  120641. this needs to be updated. */
  120642. typedef struct {
  120643. static_codebook *books[12][3];
  120644. } static_bookblock;
  120645. typedef struct {
  120646. int res_type;
  120647. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120648. vorbis_info_residue0 *res;
  120649. static_codebook *book_aux;
  120650. static_codebook *book_aux_managed;
  120651. static_bookblock *books_base;
  120652. static_bookblock *books_base_managed;
  120653. } vorbis_residue_template;
  120654. typedef struct {
  120655. vorbis_info_mapping0 *map;
  120656. vorbis_residue_template *res;
  120657. } vorbis_mapping_template;
  120658. typedef struct vp_adjblock{
  120659. int block[P_BANDS];
  120660. } vp_adjblock;
  120661. typedef struct {
  120662. int data[NOISE_COMPAND_LEVELS];
  120663. } compandblock;
  120664. /* high level configuration information for setting things up
  120665. step-by-step with the detailed vorbis_encode_ctl interface.
  120666. There's a fair amount of redundancy such that interactive setup
  120667. does not directly deal with any vorbis_info or codec_setup_info
  120668. initialization; it's all stored (until full init) in this highlevel
  120669. setup, then flushed out to the real codec setup structs later. */
  120670. typedef struct {
  120671. int att[P_NOISECURVES];
  120672. float boost;
  120673. float decay;
  120674. } att3;
  120675. typedef struct { int data[P_NOISECURVES]; } adj3;
  120676. typedef struct {
  120677. int pre[PACKETBLOBS];
  120678. int post[PACKETBLOBS];
  120679. float kHz[PACKETBLOBS];
  120680. float lowpasskHz[PACKETBLOBS];
  120681. } adj_stereo;
  120682. typedef struct {
  120683. int lo;
  120684. int hi;
  120685. int fixed;
  120686. } noiseguard;
  120687. typedef struct {
  120688. int data[P_NOISECURVES][17];
  120689. } noise3;
  120690. typedef struct {
  120691. int mappings;
  120692. double *rate_mapping;
  120693. double *quality_mapping;
  120694. int coupling_restriction;
  120695. long samplerate_min_restriction;
  120696. long samplerate_max_restriction;
  120697. int *blocksize_short;
  120698. int *blocksize_long;
  120699. att3 *psy_tone_masteratt;
  120700. int *psy_tone_0dB;
  120701. int *psy_tone_dBsuppress;
  120702. vp_adjblock *psy_tone_adj_impulse;
  120703. vp_adjblock *psy_tone_adj_long;
  120704. vp_adjblock *psy_tone_adj_other;
  120705. noiseguard *psy_noiseguards;
  120706. noise3 *psy_noise_bias_impulse;
  120707. noise3 *psy_noise_bias_padding;
  120708. noise3 *psy_noise_bias_trans;
  120709. noise3 *psy_noise_bias_long;
  120710. int *psy_noise_dBsuppress;
  120711. compandblock *psy_noise_compand;
  120712. double *psy_noise_compand_short_mapping;
  120713. double *psy_noise_compand_long_mapping;
  120714. int *psy_noise_normal_start[2];
  120715. int *psy_noise_normal_partition[2];
  120716. double *psy_noise_normal_thresh;
  120717. int *psy_ath_float;
  120718. int *psy_ath_abs;
  120719. double *psy_lowpass;
  120720. vorbis_info_psy_global *global_params;
  120721. double *global_mapping;
  120722. adj_stereo *stereo_modes;
  120723. static_codebook ***floor_books;
  120724. vorbis_info_floor1 *floor_params;
  120725. int *floor_short_mapping;
  120726. int *floor_long_mapping;
  120727. vorbis_mapping_template *maps;
  120728. } ve_setup_data_template;
  120729. /* a few static coder conventions */
  120730. static vorbis_info_mode _mode_template[2]={
  120731. {0,0,0,0},
  120732. {1,0,0,1}
  120733. };
  120734. static vorbis_info_mapping0 _map_nominal[2]={
  120735. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120736. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120737. };
  120738. /*** Start of inlined file: setup_44.h ***/
  120739. /*** Start of inlined file: floor_all.h ***/
  120740. /*** Start of inlined file: floor_books.h ***/
  120741. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120742. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120743. };
  120744. static static_codebook _huff_book_line_256x7_0sub1 = {
  120745. 1, 9,
  120746. _huff_lengthlist_line_256x7_0sub1,
  120747. 0, 0, 0, 0, 0,
  120748. NULL,
  120749. NULL,
  120750. NULL,
  120751. NULL,
  120752. 0
  120753. };
  120754. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120756. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120757. };
  120758. static static_codebook _huff_book_line_256x7_0sub2 = {
  120759. 1, 25,
  120760. _huff_lengthlist_line_256x7_0sub2,
  120761. 0, 0, 0, 0, 0,
  120762. NULL,
  120763. NULL,
  120764. NULL,
  120765. NULL,
  120766. 0
  120767. };
  120768. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120771. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120772. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120773. };
  120774. static static_codebook _huff_book_line_256x7_0sub3 = {
  120775. 1, 64,
  120776. _huff_lengthlist_line_256x7_0sub3,
  120777. 0, 0, 0, 0, 0,
  120778. NULL,
  120779. NULL,
  120780. NULL,
  120781. NULL,
  120782. 0
  120783. };
  120784. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120785. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120786. };
  120787. static static_codebook _huff_book_line_256x7_1sub1 = {
  120788. 1, 9,
  120789. _huff_lengthlist_line_256x7_1sub1,
  120790. 0, 0, 0, 0, 0,
  120791. NULL,
  120792. NULL,
  120793. NULL,
  120794. NULL,
  120795. 0
  120796. };
  120797. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120799. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120800. };
  120801. static static_codebook _huff_book_line_256x7_1sub2 = {
  120802. 1, 25,
  120803. _huff_lengthlist_line_256x7_1sub2,
  120804. 0, 0, 0, 0, 0,
  120805. NULL,
  120806. NULL,
  120807. NULL,
  120808. NULL,
  120809. 0
  120810. };
  120811. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120814. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120815. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120816. };
  120817. static static_codebook _huff_book_line_256x7_1sub3 = {
  120818. 1, 64,
  120819. _huff_lengthlist_line_256x7_1sub3,
  120820. 0, 0, 0, 0, 0,
  120821. NULL,
  120822. NULL,
  120823. NULL,
  120824. NULL,
  120825. 0
  120826. };
  120827. static long _huff_lengthlist_line_256x7_class0[] = {
  120828. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120829. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120830. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120831. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120832. };
  120833. static static_codebook _huff_book_line_256x7_class0 = {
  120834. 1, 64,
  120835. _huff_lengthlist_line_256x7_class0,
  120836. 0, 0, 0, 0, 0,
  120837. NULL,
  120838. NULL,
  120839. NULL,
  120840. NULL,
  120841. 0
  120842. };
  120843. static long _huff_lengthlist_line_256x7_class1[] = {
  120844. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120845. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120846. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120847. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120848. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120849. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120850. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120851. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120852. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120853. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120854. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120855. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120856. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120857. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120858. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120859. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120860. };
  120861. static static_codebook _huff_book_line_256x7_class1 = {
  120862. 1, 256,
  120863. _huff_lengthlist_line_256x7_class1,
  120864. 0, 0, 0, 0, 0,
  120865. NULL,
  120866. NULL,
  120867. NULL,
  120868. NULL,
  120869. 0
  120870. };
  120871. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120872. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120873. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120874. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120875. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120876. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120877. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120878. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120879. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120880. };
  120881. static static_codebook _huff_book_line_512x17_0sub0 = {
  120882. 1, 128,
  120883. _huff_lengthlist_line_512x17_0sub0,
  120884. 0, 0, 0, 0, 0,
  120885. NULL,
  120886. NULL,
  120887. NULL,
  120888. NULL,
  120889. 0
  120890. };
  120891. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120892. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120893. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120894. };
  120895. static static_codebook _huff_book_line_512x17_1sub0 = {
  120896. 1, 32,
  120897. _huff_lengthlist_line_512x17_1sub0,
  120898. 0, 0, 0, 0, 0,
  120899. NULL,
  120900. NULL,
  120901. NULL,
  120902. NULL,
  120903. 0
  120904. };
  120905. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120909. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120910. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120911. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120912. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120913. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120914. };
  120915. static static_codebook _huff_book_line_512x17_1sub1 = {
  120916. 1, 128,
  120917. _huff_lengthlist_line_512x17_1sub1,
  120918. 0, 0, 0, 0, 0,
  120919. NULL,
  120920. NULL,
  120921. NULL,
  120922. NULL,
  120923. 0
  120924. };
  120925. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120926. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120927. 5, 3,
  120928. };
  120929. static static_codebook _huff_book_line_512x17_2sub1 = {
  120930. 1, 18,
  120931. _huff_lengthlist_line_512x17_2sub1,
  120932. 0, 0, 0, 0, 0,
  120933. NULL,
  120934. NULL,
  120935. NULL,
  120936. NULL,
  120937. 0
  120938. };
  120939. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120941. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120942. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120943. 9, 8,
  120944. };
  120945. static static_codebook _huff_book_line_512x17_2sub2 = {
  120946. 1, 50,
  120947. _huff_lengthlist_line_512x17_2sub2,
  120948. 0, 0, 0, 0, 0,
  120949. NULL,
  120950. NULL,
  120951. NULL,
  120952. NULL,
  120953. 0
  120954. };
  120955. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120960. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120961. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120962. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120963. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120964. };
  120965. static static_codebook _huff_book_line_512x17_2sub3 = {
  120966. 1, 128,
  120967. _huff_lengthlist_line_512x17_2sub3,
  120968. 0, 0, 0, 0, 0,
  120969. NULL,
  120970. NULL,
  120971. NULL,
  120972. NULL,
  120973. 0
  120974. };
  120975. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120976. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120977. 5, 5,
  120978. };
  120979. static static_codebook _huff_book_line_512x17_3sub1 = {
  120980. 1, 18,
  120981. _huff_lengthlist_line_512x17_3sub1,
  120982. 0, 0, 0, 0, 0,
  120983. NULL,
  120984. NULL,
  120985. NULL,
  120986. NULL,
  120987. 0
  120988. };
  120989. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120991. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120992. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120993. 11,14,
  120994. };
  120995. static static_codebook _huff_book_line_512x17_3sub2 = {
  120996. 1, 50,
  120997. _huff_lengthlist_line_512x17_3sub2,
  120998. 0, 0, 0, 0, 0,
  120999. NULL,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. 0
  121004. };
  121005. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121010. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121011. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121012. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121013. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121014. };
  121015. static static_codebook _huff_book_line_512x17_3sub3 = {
  121016. 1, 128,
  121017. _huff_lengthlist_line_512x17_3sub3,
  121018. 0, 0, 0, 0, 0,
  121019. NULL,
  121020. NULL,
  121021. NULL,
  121022. NULL,
  121023. 0
  121024. };
  121025. static long _huff_lengthlist_line_512x17_class1[] = {
  121026. 1, 2, 3, 6, 5, 4, 7, 7,
  121027. };
  121028. static static_codebook _huff_book_line_512x17_class1 = {
  121029. 1, 8,
  121030. _huff_lengthlist_line_512x17_class1,
  121031. 0, 0, 0, 0, 0,
  121032. NULL,
  121033. NULL,
  121034. NULL,
  121035. NULL,
  121036. 0
  121037. };
  121038. static long _huff_lengthlist_line_512x17_class2[] = {
  121039. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121040. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121041. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121042. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121043. };
  121044. static static_codebook _huff_book_line_512x17_class2 = {
  121045. 1, 64,
  121046. _huff_lengthlist_line_512x17_class2,
  121047. 0, 0, 0, 0, 0,
  121048. NULL,
  121049. NULL,
  121050. NULL,
  121051. NULL,
  121052. 0
  121053. };
  121054. static long _huff_lengthlist_line_512x17_class3[] = {
  121055. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121056. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121057. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121058. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121059. };
  121060. static static_codebook _huff_book_line_512x17_class3 = {
  121061. 1, 64,
  121062. _huff_lengthlist_line_512x17_class3,
  121063. 0, 0, 0, 0, 0,
  121064. NULL,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. 0
  121069. };
  121070. static long _huff_lengthlist_line_128x4_class0[] = {
  121071. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121072. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121073. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121074. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121075. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121076. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121077. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121078. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121079. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121080. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121081. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121082. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121083. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121084. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121085. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121086. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121087. };
  121088. static static_codebook _huff_book_line_128x4_class0 = {
  121089. 1, 256,
  121090. _huff_lengthlist_line_128x4_class0,
  121091. 0, 0, 0, 0, 0,
  121092. NULL,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. 0
  121097. };
  121098. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121099. 2, 2, 2, 2,
  121100. };
  121101. static static_codebook _huff_book_line_128x4_0sub0 = {
  121102. 1, 4,
  121103. _huff_lengthlist_line_128x4_0sub0,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121112. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121113. };
  121114. static static_codebook _huff_book_line_128x4_0sub1 = {
  121115. 1, 10,
  121116. _huff_lengthlist_line_128x4_0sub1,
  121117. 0, 0, 0, 0, 0,
  121118. NULL,
  121119. NULL,
  121120. NULL,
  121121. NULL,
  121122. 0
  121123. };
  121124. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121126. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121127. };
  121128. static static_codebook _huff_book_line_128x4_0sub2 = {
  121129. 1, 25,
  121130. _huff_lengthlist_line_128x4_0sub2,
  121131. 0, 0, 0, 0, 0,
  121132. NULL,
  121133. NULL,
  121134. NULL,
  121135. NULL,
  121136. 0
  121137. };
  121138. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121141. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121142. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121143. };
  121144. static static_codebook _huff_book_line_128x4_0sub3 = {
  121145. 1, 64,
  121146. _huff_lengthlist_line_128x4_0sub3,
  121147. 0, 0, 0, 0, 0,
  121148. NULL,
  121149. NULL,
  121150. NULL,
  121151. NULL,
  121152. 0
  121153. };
  121154. static long _huff_lengthlist_line_256x4_class0[] = {
  121155. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121156. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121157. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121158. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121159. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121160. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121161. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121162. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121163. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121164. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121165. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121166. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121167. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121168. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121169. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121170. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121171. };
  121172. static static_codebook _huff_book_line_256x4_class0 = {
  121173. 1, 256,
  121174. _huff_lengthlist_line_256x4_class0,
  121175. 0, 0, 0, 0, 0,
  121176. NULL,
  121177. NULL,
  121178. NULL,
  121179. NULL,
  121180. 0
  121181. };
  121182. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121183. 2, 2, 2, 2,
  121184. };
  121185. static static_codebook _huff_book_line_256x4_0sub0 = {
  121186. 1, 4,
  121187. _huff_lengthlist_line_256x4_0sub0,
  121188. 0, 0, 0, 0, 0,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. NULL,
  121193. 0
  121194. };
  121195. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121196. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121197. };
  121198. static static_codebook _huff_book_line_256x4_0sub1 = {
  121199. 1, 10,
  121200. _huff_lengthlist_line_256x4_0sub1,
  121201. 0, 0, 0, 0, 0,
  121202. NULL,
  121203. NULL,
  121204. NULL,
  121205. NULL,
  121206. 0
  121207. };
  121208. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121210. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121211. };
  121212. static static_codebook _huff_book_line_256x4_0sub2 = {
  121213. 1, 25,
  121214. _huff_lengthlist_line_256x4_0sub2,
  121215. 0, 0, 0, 0, 0,
  121216. NULL,
  121217. NULL,
  121218. NULL,
  121219. NULL,
  121220. 0
  121221. };
  121222. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121225. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121226. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121227. };
  121228. static static_codebook _huff_book_line_256x4_0sub3 = {
  121229. 1, 64,
  121230. _huff_lengthlist_line_256x4_0sub3,
  121231. 0, 0, 0, 0, 0,
  121232. NULL,
  121233. NULL,
  121234. NULL,
  121235. NULL,
  121236. 0
  121237. };
  121238. static long _huff_lengthlist_line_128x7_class0[] = {
  121239. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121240. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121241. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121242. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121243. };
  121244. static static_codebook _huff_book_line_128x7_class0 = {
  121245. 1, 64,
  121246. _huff_lengthlist_line_128x7_class0,
  121247. 0, 0, 0, 0, 0,
  121248. NULL,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. 0
  121253. };
  121254. static long _huff_lengthlist_line_128x7_class1[] = {
  121255. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121256. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121257. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121258. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121259. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121260. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121261. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121262. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121263. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121264. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121265. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121266. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121267. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121268. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121269. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121270. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121271. };
  121272. static static_codebook _huff_book_line_128x7_class1 = {
  121273. 1, 256,
  121274. _huff_lengthlist_line_128x7_class1,
  121275. 0, 0, 0, 0, 0,
  121276. NULL,
  121277. NULL,
  121278. NULL,
  121279. NULL,
  121280. 0
  121281. };
  121282. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121283. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121284. };
  121285. static static_codebook _huff_book_line_128x7_0sub1 = {
  121286. 1, 9,
  121287. _huff_lengthlist_line_128x7_0sub1,
  121288. 0, 0, 0, 0, 0,
  121289. NULL,
  121290. NULL,
  121291. NULL,
  121292. NULL,
  121293. 0
  121294. };
  121295. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121297. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121298. };
  121299. static static_codebook _huff_book_line_128x7_0sub2 = {
  121300. 1, 25,
  121301. _huff_lengthlist_line_128x7_0sub2,
  121302. 0, 0, 0, 0, 0,
  121303. NULL,
  121304. NULL,
  121305. NULL,
  121306. NULL,
  121307. 0
  121308. };
  121309. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121312. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121313. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121314. };
  121315. static static_codebook _huff_book_line_128x7_0sub3 = {
  121316. 1, 64,
  121317. _huff_lengthlist_line_128x7_0sub3,
  121318. 0, 0, 0, 0, 0,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. NULL,
  121323. 0
  121324. };
  121325. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121326. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121327. };
  121328. static static_codebook _huff_book_line_128x7_1sub1 = {
  121329. 1, 9,
  121330. _huff_lengthlist_line_128x7_1sub1,
  121331. 0, 0, 0, 0, 0,
  121332. NULL,
  121333. NULL,
  121334. NULL,
  121335. NULL,
  121336. 0
  121337. };
  121338. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121340. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121341. };
  121342. static static_codebook _huff_book_line_128x7_1sub2 = {
  121343. 1, 25,
  121344. _huff_lengthlist_line_128x7_1sub2,
  121345. 0, 0, 0, 0, 0,
  121346. NULL,
  121347. NULL,
  121348. NULL,
  121349. NULL,
  121350. 0
  121351. };
  121352. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121355. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121356. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121357. };
  121358. static static_codebook _huff_book_line_128x7_1sub3 = {
  121359. 1, 64,
  121360. _huff_lengthlist_line_128x7_1sub3,
  121361. 0, 0, 0, 0, 0,
  121362. NULL,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. 0
  121367. };
  121368. static long _huff_lengthlist_line_128x11_class1[] = {
  121369. 1, 6, 3, 7, 2, 4, 5, 7,
  121370. };
  121371. static static_codebook _huff_book_line_128x11_class1 = {
  121372. 1, 8,
  121373. _huff_lengthlist_line_128x11_class1,
  121374. 0, 0, 0, 0, 0,
  121375. NULL,
  121376. NULL,
  121377. NULL,
  121378. NULL,
  121379. 0
  121380. };
  121381. static long _huff_lengthlist_line_128x11_class2[] = {
  121382. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121383. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121384. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121385. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121386. };
  121387. static static_codebook _huff_book_line_128x11_class2 = {
  121388. 1, 64,
  121389. _huff_lengthlist_line_128x11_class2,
  121390. 0, 0, 0, 0, 0,
  121391. NULL,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _huff_lengthlist_line_128x11_class3[] = {
  121398. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121399. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121400. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121401. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121402. };
  121403. static static_codebook _huff_book_line_128x11_class3 = {
  121404. 1, 64,
  121405. _huff_lengthlist_line_128x11_class3,
  121406. 0, 0, 0, 0, 0,
  121407. NULL,
  121408. NULL,
  121409. NULL,
  121410. NULL,
  121411. 0
  121412. };
  121413. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121414. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121415. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121416. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121417. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121418. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121419. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121420. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121421. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121422. };
  121423. static static_codebook _huff_book_line_128x11_0sub0 = {
  121424. 1, 128,
  121425. _huff_lengthlist_line_128x11_0sub0,
  121426. 0, 0, 0, 0, 0,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. 0
  121432. };
  121433. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121434. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121435. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121436. };
  121437. static static_codebook _huff_book_line_128x11_1sub0 = {
  121438. 1, 32,
  121439. _huff_lengthlist_line_128x11_1sub0,
  121440. 0, 0, 0, 0, 0,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. NULL,
  121445. 0
  121446. };
  121447. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121450. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121451. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121452. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121453. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121454. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121455. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121456. };
  121457. static static_codebook _huff_book_line_128x11_1sub1 = {
  121458. 1, 128,
  121459. _huff_lengthlist_line_128x11_1sub1,
  121460. 0, 0, 0, 0, 0,
  121461. NULL,
  121462. NULL,
  121463. NULL,
  121464. NULL,
  121465. 0
  121466. };
  121467. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121468. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121469. 5, 5,
  121470. };
  121471. static static_codebook _huff_book_line_128x11_2sub1 = {
  121472. 1, 18,
  121473. _huff_lengthlist_line_128x11_2sub1,
  121474. 0, 0, 0, 0, 0,
  121475. NULL,
  121476. NULL,
  121477. NULL,
  121478. NULL,
  121479. 0
  121480. };
  121481. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121484. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121485. 8,11,
  121486. };
  121487. static static_codebook _huff_book_line_128x11_2sub2 = {
  121488. 1, 50,
  121489. _huff_lengthlist_line_128x11_2sub2,
  121490. 0, 0, 0, 0, 0,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. NULL,
  121495. 0
  121496. };
  121497. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121502. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121503. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121504. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121505. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121506. };
  121507. static static_codebook _huff_book_line_128x11_2sub3 = {
  121508. 1, 128,
  121509. _huff_lengthlist_line_128x11_2sub3,
  121510. 0, 0, 0, 0, 0,
  121511. NULL,
  121512. NULL,
  121513. NULL,
  121514. NULL,
  121515. 0
  121516. };
  121517. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121518. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121519. 5, 4,
  121520. };
  121521. static static_codebook _huff_book_line_128x11_3sub1 = {
  121522. 1, 18,
  121523. _huff_lengthlist_line_128x11_3sub1,
  121524. 0, 0, 0, 0, 0,
  121525. NULL,
  121526. NULL,
  121527. NULL,
  121528. NULL,
  121529. 0
  121530. };
  121531. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121533. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121534. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121535. 12, 6,
  121536. };
  121537. static static_codebook _huff_book_line_128x11_3sub2 = {
  121538. 1, 50,
  121539. _huff_lengthlist_line_128x11_3sub2,
  121540. 0, 0, 0, 0, 0,
  121541. NULL,
  121542. NULL,
  121543. NULL,
  121544. NULL,
  121545. 0
  121546. };
  121547. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121552. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121553. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121554. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121555. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121556. };
  121557. static static_codebook _huff_book_line_128x11_3sub3 = {
  121558. 1, 128,
  121559. _huff_lengthlist_line_128x11_3sub3,
  121560. 0, 0, 0, 0, 0,
  121561. NULL,
  121562. NULL,
  121563. NULL,
  121564. NULL,
  121565. 0
  121566. };
  121567. static long _huff_lengthlist_line_128x17_class1[] = {
  121568. 1, 3, 4, 7, 2, 5, 6, 7,
  121569. };
  121570. static static_codebook _huff_book_line_128x17_class1 = {
  121571. 1, 8,
  121572. _huff_lengthlist_line_128x17_class1,
  121573. 0, 0, 0, 0, 0,
  121574. NULL,
  121575. NULL,
  121576. NULL,
  121577. NULL,
  121578. 0
  121579. };
  121580. static long _huff_lengthlist_line_128x17_class2[] = {
  121581. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121582. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121583. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121584. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121585. };
  121586. static static_codebook _huff_book_line_128x17_class2 = {
  121587. 1, 64,
  121588. _huff_lengthlist_line_128x17_class2,
  121589. 0, 0, 0, 0, 0,
  121590. NULL,
  121591. NULL,
  121592. NULL,
  121593. NULL,
  121594. 0
  121595. };
  121596. static long _huff_lengthlist_line_128x17_class3[] = {
  121597. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121598. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121599. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121600. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121601. };
  121602. static static_codebook _huff_book_line_128x17_class3 = {
  121603. 1, 64,
  121604. _huff_lengthlist_line_128x17_class3,
  121605. 0, 0, 0, 0, 0,
  121606. NULL,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. 0
  121611. };
  121612. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121613. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121614. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121615. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121616. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121617. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121618. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121619. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121620. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121621. };
  121622. static static_codebook _huff_book_line_128x17_0sub0 = {
  121623. 1, 128,
  121624. _huff_lengthlist_line_128x17_0sub0,
  121625. 0, 0, 0, 0, 0,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. NULL,
  121630. 0
  121631. };
  121632. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121633. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121634. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121635. };
  121636. static static_codebook _huff_book_line_128x17_1sub0 = {
  121637. 1, 32,
  121638. _huff_lengthlist_line_128x17_1sub0,
  121639. 0, 0, 0, 0, 0,
  121640. NULL,
  121641. NULL,
  121642. NULL,
  121643. NULL,
  121644. 0
  121645. };
  121646. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121649. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121650. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121651. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121652. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121653. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121654. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121655. };
  121656. static static_codebook _huff_book_line_128x17_1sub1 = {
  121657. 1, 128,
  121658. _huff_lengthlist_line_128x17_1sub1,
  121659. 0, 0, 0, 0, 0,
  121660. NULL,
  121661. NULL,
  121662. NULL,
  121663. NULL,
  121664. 0
  121665. };
  121666. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121667. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121668. 9, 4,
  121669. };
  121670. static static_codebook _huff_book_line_128x17_2sub1 = {
  121671. 1, 18,
  121672. _huff_lengthlist_line_128x17_2sub1,
  121673. 0, 0, 0, 0, 0,
  121674. NULL,
  121675. NULL,
  121676. NULL,
  121677. NULL,
  121678. 0
  121679. };
  121680. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121683. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121684. 13,13,
  121685. };
  121686. static static_codebook _huff_book_line_128x17_2sub2 = {
  121687. 1, 50,
  121688. _huff_lengthlist_line_128x17_2sub2,
  121689. 0, 0, 0, 0, 0,
  121690. NULL,
  121691. NULL,
  121692. NULL,
  121693. NULL,
  121694. 0
  121695. };
  121696. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121701. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121702. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121703. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121704. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121705. };
  121706. static static_codebook _huff_book_line_128x17_2sub3 = {
  121707. 1, 128,
  121708. _huff_lengthlist_line_128x17_2sub3,
  121709. 0, 0, 0, 0, 0,
  121710. NULL,
  121711. NULL,
  121712. NULL,
  121713. NULL,
  121714. 0
  121715. };
  121716. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121717. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121718. 6, 4,
  121719. };
  121720. static static_codebook _huff_book_line_128x17_3sub1 = {
  121721. 1, 18,
  121722. _huff_lengthlist_line_128x17_3sub1,
  121723. 0, 0, 0, 0, 0,
  121724. NULL,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. 0
  121729. };
  121730. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121733. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121734. 10, 8,
  121735. };
  121736. static static_codebook _huff_book_line_128x17_3sub2 = {
  121737. 1, 50,
  121738. _huff_lengthlist_line_128x17_3sub2,
  121739. 0, 0, 0, 0, 0,
  121740. NULL,
  121741. NULL,
  121742. NULL,
  121743. NULL,
  121744. 0
  121745. };
  121746. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121751. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121752. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121755. };
  121756. static static_codebook _huff_book_line_128x17_3sub3 = {
  121757. 1, 128,
  121758. _huff_lengthlist_line_128x17_3sub3,
  121759. 0, 0, 0, 0, 0,
  121760. NULL,
  121761. NULL,
  121762. NULL,
  121763. NULL,
  121764. 0
  121765. };
  121766. static long _huff_lengthlist_line_1024x27_class1[] = {
  121767. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121768. };
  121769. static static_codebook _huff_book_line_1024x27_class1 = {
  121770. 1, 16,
  121771. _huff_lengthlist_line_1024x27_class1,
  121772. 0, 0, 0, 0, 0,
  121773. NULL,
  121774. NULL,
  121775. NULL,
  121776. NULL,
  121777. 0
  121778. };
  121779. static long _huff_lengthlist_line_1024x27_class2[] = {
  121780. 1, 4, 2, 6, 3, 7, 5, 7,
  121781. };
  121782. static static_codebook _huff_book_line_1024x27_class2 = {
  121783. 1, 8,
  121784. _huff_lengthlist_line_1024x27_class2,
  121785. 0, 0, 0, 0, 0,
  121786. NULL,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. 0
  121791. };
  121792. static long _huff_lengthlist_line_1024x27_class3[] = {
  121793. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121794. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121795. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121796. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121797. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121798. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121799. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121800. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121801. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121802. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121803. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121804. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121805. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121806. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121807. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121808. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121809. };
  121810. static static_codebook _huff_book_line_1024x27_class3 = {
  121811. 1, 256,
  121812. _huff_lengthlist_line_1024x27_class3,
  121813. 0, 0, 0, 0, 0,
  121814. NULL,
  121815. NULL,
  121816. NULL,
  121817. NULL,
  121818. 0
  121819. };
  121820. static long _huff_lengthlist_line_1024x27_class4[] = {
  121821. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121822. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121823. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121824. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121825. };
  121826. static static_codebook _huff_book_line_1024x27_class4 = {
  121827. 1, 64,
  121828. _huff_lengthlist_line_1024x27_class4,
  121829. 0, 0, 0, 0, 0,
  121830. NULL,
  121831. NULL,
  121832. NULL,
  121833. NULL,
  121834. 0
  121835. };
  121836. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121837. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121838. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121839. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121840. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121841. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121842. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121843. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121844. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121845. };
  121846. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121847. 1, 128,
  121848. _huff_lengthlist_line_1024x27_0sub0,
  121849. 0, 0, 0, 0, 0,
  121850. NULL,
  121851. NULL,
  121852. NULL,
  121853. NULL,
  121854. 0
  121855. };
  121856. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121857. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121858. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121859. };
  121860. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121861. 1, 32,
  121862. _huff_lengthlist_line_1024x27_1sub0,
  121863. 0, 0, 0, 0, 0,
  121864. NULL,
  121865. NULL,
  121866. NULL,
  121867. NULL,
  121868. 0
  121869. };
  121870. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121874. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121875. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121876. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121877. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121878. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121879. };
  121880. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121881. 1, 128,
  121882. _huff_lengthlist_line_1024x27_1sub1,
  121883. 0, 0, 0, 0, 0,
  121884. NULL,
  121885. NULL,
  121886. NULL,
  121887. NULL,
  121888. 0
  121889. };
  121890. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121891. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121892. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121893. };
  121894. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121895. 1, 32,
  121896. _huff_lengthlist_line_1024x27_2sub0,
  121897. 0, 0, 0, 0, 0,
  121898. NULL,
  121899. NULL,
  121900. NULL,
  121901. NULL,
  121902. 0
  121903. };
  121904. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121908. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121909. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121910. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121911. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121912. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121913. };
  121914. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121915. 1, 128,
  121916. _huff_lengthlist_line_1024x27_2sub1,
  121917. 0, 0, 0, 0, 0,
  121918. NULL,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. 0
  121923. };
  121924. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121925. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121926. 5, 5,
  121927. };
  121928. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121929. 1, 18,
  121930. _huff_lengthlist_line_1024x27_3sub1,
  121931. 0, 0, 0, 0, 0,
  121932. NULL,
  121933. NULL,
  121934. NULL,
  121935. NULL,
  121936. 0
  121937. };
  121938. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121941. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121942. 9,11,
  121943. };
  121944. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121945. 1, 50,
  121946. _huff_lengthlist_line_1024x27_3sub2,
  121947. 0, 0, 0, 0, 0,
  121948. NULL,
  121949. NULL,
  121950. NULL,
  121951. NULL,
  121952. 0
  121953. };
  121954. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121959. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121960. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121961. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121962. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121963. };
  121964. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121965. 1, 128,
  121966. _huff_lengthlist_line_1024x27_3sub3,
  121967. 0, 0, 0, 0, 0,
  121968. NULL,
  121969. NULL,
  121970. NULL,
  121971. NULL,
  121972. 0
  121973. };
  121974. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121975. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121976. 5, 4,
  121977. };
  121978. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121979. 1, 18,
  121980. _huff_lengthlist_line_1024x27_4sub1,
  121981. 0, 0, 0, 0, 0,
  121982. NULL,
  121983. NULL,
  121984. NULL,
  121985. NULL,
  121986. 0
  121987. };
  121988. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121991. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121992. 9,12,
  121993. };
  121994. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121995. 1, 50,
  121996. _huff_lengthlist_line_1024x27_4sub2,
  121997. 0, 0, 0, 0, 0,
  121998. NULL,
  121999. NULL,
  122000. NULL,
  122001. NULL,
  122002. 0
  122003. };
  122004. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122009. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122012. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122013. };
  122014. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122015. 1, 128,
  122016. _huff_lengthlist_line_1024x27_4sub3,
  122017. 0, 0, 0, 0, 0,
  122018. NULL,
  122019. NULL,
  122020. NULL,
  122021. NULL,
  122022. 0
  122023. };
  122024. static long _huff_lengthlist_line_2048x27_class1[] = {
  122025. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122026. };
  122027. static static_codebook _huff_book_line_2048x27_class1 = {
  122028. 1, 16,
  122029. _huff_lengthlist_line_2048x27_class1,
  122030. 0, 0, 0, 0, 0,
  122031. NULL,
  122032. NULL,
  122033. NULL,
  122034. NULL,
  122035. 0
  122036. };
  122037. static long _huff_lengthlist_line_2048x27_class2[] = {
  122038. 1, 2, 3, 6, 4, 7, 5, 7,
  122039. };
  122040. static static_codebook _huff_book_line_2048x27_class2 = {
  122041. 1, 8,
  122042. _huff_lengthlist_line_2048x27_class2,
  122043. 0, 0, 0, 0, 0,
  122044. NULL,
  122045. NULL,
  122046. NULL,
  122047. NULL,
  122048. 0
  122049. };
  122050. static long _huff_lengthlist_line_2048x27_class3[] = {
  122051. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122052. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122053. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122054. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122055. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122056. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122057. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122058. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122059. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122060. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122061. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122062. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122063. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122064. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122065. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122066. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122067. };
  122068. static static_codebook _huff_book_line_2048x27_class3 = {
  122069. 1, 256,
  122070. _huff_lengthlist_line_2048x27_class3,
  122071. 0, 0, 0, 0, 0,
  122072. NULL,
  122073. NULL,
  122074. NULL,
  122075. NULL,
  122076. 0
  122077. };
  122078. static long _huff_lengthlist_line_2048x27_class4[] = {
  122079. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122080. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122081. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122082. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122083. };
  122084. static static_codebook _huff_book_line_2048x27_class4 = {
  122085. 1, 64,
  122086. _huff_lengthlist_line_2048x27_class4,
  122087. 0, 0, 0, 0, 0,
  122088. NULL,
  122089. NULL,
  122090. NULL,
  122091. NULL,
  122092. 0
  122093. };
  122094. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122095. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122096. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122097. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122098. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122099. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122100. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122101. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122102. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122103. };
  122104. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122105. 1, 128,
  122106. _huff_lengthlist_line_2048x27_0sub0,
  122107. 0, 0, 0, 0, 0,
  122108. NULL,
  122109. NULL,
  122110. NULL,
  122111. NULL,
  122112. 0
  122113. };
  122114. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122115. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122116. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122117. };
  122118. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122119. 1, 32,
  122120. _huff_lengthlist_line_2048x27_1sub0,
  122121. 0, 0, 0, 0, 0,
  122122. NULL,
  122123. NULL,
  122124. NULL,
  122125. NULL,
  122126. 0
  122127. };
  122128. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122132. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122133. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122134. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122135. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122136. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122137. };
  122138. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122139. 1, 128,
  122140. _huff_lengthlist_line_2048x27_1sub1,
  122141. 0, 0, 0, 0, 0,
  122142. NULL,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. 0
  122147. };
  122148. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122149. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122150. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122151. };
  122152. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122153. 1, 32,
  122154. _huff_lengthlist_line_2048x27_2sub0,
  122155. 0, 0, 0, 0, 0,
  122156. NULL,
  122157. NULL,
  122158. NULL,
  122159. NULL,
  122160. 0
  122161. };
  122162. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122166. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122167. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122168. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122169. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122170. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122171. };
  122172. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122173. 1, 128,
  122174. _huff_lengthlist_line_2048x27_2sub1,
  122175. 0, 0, 0, 0, 0,
  122176. NULL,
  122177. NULL,
  122178. NULL,
  122179. NULL,
  122180. 0
  122181. };
  122182. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122183. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122184. 5, 5,
  122185. };
  122186. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122187. 1, 18,
  122188. _huff_lengthlist_line_2048x27_3sub1,
  122189. 0, 0, 0, 0, 0,
  122190. NULL,
  122191. NULL,
  122192. NULL,
  122193. NULL,
  122194. 0
  122195. };
  122196. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122199. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122200. 10,12,
  122201. };
  122202. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122203. 1, 50,
  122204. _huff_lengthlist_line_2048x27_3sub2,
  122205. 0, 0, 0, 0, 0,
  122206. NULL,
  122207. NULL,
  122208. NULL,
  122209. NULL,
  122210. 0
  122211. };
  122212. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122217. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122218. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122219. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122220. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122221. };
  122222. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122223. 1, 128,
  122224. _huff_lengthlist_line_2048x27_3sub3,
  122225. 0, 0, 0, 0, 0,
  122226. NULL,
  122227. NULL,
  122228. NULL,
  122229. NULL,
  122230. 0
  122231. };
  122232. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122233. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122234. 4, 5,
  122235. };
  122236. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122237. 1, 18,
  122238. _huff_lengthlist_line_2048x27_4sub1,
  122239. 0, 0, 0, 0, 0,
  122240. NULL,
  122241. NULL,
  122242. NULL,
  122243. NULL,
  122244. 0
  122245. };
  122246. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122249. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122250. 10,10,
  122251. };
  122252. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122253. 1, 50,
  122254. _huff_lengthlist_line_2048x27_4sub2,
  122255. 0, 0, 0, 0, 0,
  122256. NULL,
  122257. NULL,
  122258. NULL,
  122259. NULL,
  122260. 0
  122261. };
  122262. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122267. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122268. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122269. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122270. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122271. };
  122272. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122273. 1, 128,
  122274. _huff_lengthlist_line_2048x27_4sub3,
  122275. 0, 0, 0, 0, 0,
  122276. NULL,
  122277. NULL,
  122278. NULL,
  122279. NULL,
  122280. 0
  122281. };
  122282. static long _huff_lengthlist_line_256x4low_class0[] = {
  122283. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122284. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122285. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122286. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122287. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122288. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122289. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122290. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122291. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122292. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122293. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122294. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122295. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122296. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122297. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122298. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122299. };
  122300. static static_codebook _huff_book_line_256x4low_class0 = {
  122301. 1, 256,
  122302. _huff_lengthlist_line_256x4low_class0,
  122303. 0, 0, 0, 0, 0,
  122304. NULL,
  122305. NULL,
  122306. NULL,
  122307. NULL,
  122308. 0
  122309. };
  122310. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122311. 1, 3, 2, 3,
  122312. };
  122313. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122314. 1, 4,
  122315. _huff_lengthlist_line_256x4low_0sub0,
  122316. 0, 0, 0, 0, 0,
  122317. NULL,
  122318. NULL,
  122319. NULL,
  122320. NULL,
  122321. 0
  122322. };
  122323. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122324. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122325. };
  122326. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122327. 1, 10,
  122328. _huff_lengthlist_line_256x4low_0sub1,
  122329. 0, 0, 0, 0, 0,
  122330. NULL,
  122331. NULL,
  122332. NULL,
  122333. NULL,
  122334. 0
  122335. };
  122336. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122338. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122339. };
  122340. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122341. 1, 25,
  122342. _huff_lengthlist_line_256x4low_0sub2,
  122343. 0, 0, 0, 0, 0,
  122344. NULL,
  122345. NULL,
  122346. NULL,
  122347. NULL,
  122348. 0
  122349. };
  122350. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122353. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122354. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122355. };
  122356. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122357. 1, 64,
  122358. _huff_lengthlist_line_256x4low_0sub3,
  122359. 0, 0, 0, 0, 0,
  122360. NULL,
  122361. NULL,
  122362. NULL,
  122363. NULL,
  122364. 0
  122365. };
  122366. /*** End of inlined file: floor_books.h ***/
  122367. static static_codebook *_floor_128x4_books[]={
  122368. &_huff_book_line_128x4_class0,
  122369. &_huff_book_line_128x4_0sub0,
  122370. &_huff_book_line_128x4_0sub1,
  122371. &_huff_book_line_128x4_0sub2,
  122372. &_huff_book_line_128x4_0sub3,
  122373. };
  122374. static static_codebook *_floor_256x4_books[]={
  122375. &_huff_book_line_256x4_class0,
  122376. &_huff_book_line_256x4_0sub0,
  122377. &_huff_book_line_256x4_0sub1,
  122378. &_huff_book_line_256x4_0sub2,
  122379. &_huff_book_line_256x4_0sub3,
  122380. };
  122381. static static_codebook *_floor_128x7_books[]={
  122382. &_huff_book_line_128x7_class0,
  122383. &_huff_book_line_128x7_class1,
  122384. &_huff_book_line_128x7_0sub1,
  122385. &_huff_book_line_128x7_0sub2,
  122386. &_huff_book_line_128x7_0sub3,
  122387. &_huff_book_line_128x7_1sub1,
  122388. &_huff_book_line_128x7_1sub2,
  122389. &_huff_book_line_128x7_1sub3,
  122390. };
  122391. static static_codebook *_floor_256x7_books[]={
  122392. &_huff_book_line_256x7_class0,
  122393. &_huff_book_line_256x7_class1,
  122394. &_huff_book_line_256x7_0sub1,
  122395. &_huff_book_line_256x7_0sub2,
  122396. &_huff_book_line_256x7_0sub3,
  122397. &_huff_book_line_256x7_1sub1,
  122398. &_huff_book_line_256x7_1sub2,
  122399. &_huff_book_line_256x7_1sub3,
  122400. };
  122401. static static_codebook *_floor_128x11_books[]={
  122402. &_huff_book_line_128x11_class1,
  122403. &_huff_book_line_128x11_class2,
  122404. &_huff_book_line_128x11_class3,
  122405. &_huff_book_line_128x11_0sub0,
  122406. &_huff_book_line_128x11_1sub0,
  122407. &_huff_book_line_128x11_1sub1,
  122408. &_huff_book_line_128x11_2sub1,
  122409. &_huff_book_line_128x11_2sub2,
  122410. &_huff_book_line_128x11_2sub3,
  122411. &_huff_book_line_128x11_3sub1,
  122412. &_huff_book_line_128x11_3sub2,
  122413. &_huff_book_line_128x11_3sub3,
  122414. };
  122415. static static_codebook *_floor_128x17_books[]={
  122416. &_huff_book_line_128x17_class1,
  122417. &_huff_book_line_128x17_class2,
  122418. &_huff_book_line_128x17_class3,
  122419. &_huff_book_line_128x17_0sub0,
  122420. &_huff_book_line_128x17_1sub0,
  122421. &_huff_book_line_128x17_1sub1,
  122422. &_huff_book_line_128x17_2sub1,
  122423. &_huff_book_line_128x17_2sub2,
  122424. &_huff_book_line_128x17_2sub3,
  122425. &_huff_book_line_128x17_3sub1,
  122426. &_huff_book_line_128x17_3sub2,
  122427. &_huff_book_line_128x17_3sub3,
  122428. };
  122429. static static_codebook *_floor_256x4low_books[]={
  122430. &_huff_book_line_256x4low_class0,
  122431. &_huff_book_line_256x4low_0sub0,
  122432. &_huff_book_line_256x4low_0sub1,
  122433. &_huff_book_line_256x4low_0sub2,
  122434. &_huff_book_line_256x4low_0sub3,
  122435. };
  122436. static static_codebook *_floor_1024x27_books[]={
  122437. &_huff_book_line_1024x27_class1,
  122438. &_huff_book_line_1024x27_class2,
  122439. &_huff_book_line_1024x27_class3,
  122440. &_huff_book_line_1024x27_class4,
  122441. &_huff_book_line_1024x27_0sub0,
  122442. &_huff_book_line_1024x27_1sub0,
  122443. &_huff_book_line_1024x27_1sub1,
  122444. &_huff_book_line_1024x27_2sub0,
  122445. &_huff_book_line_1024x27_2sub1,
  122446. &_huff_book_line_1024x27_3sub1,
  122447. &_huff_book_line_1024x27_3sub2,
  122448. &_huff_book_line_1024x27_3sub3,
  122449. &_huff_book_line_1024x27_4sub1,
  122450. &_huff_book_line_1024x27_4sub2,
  122451. &_huff_book_line_1024x27_4sub3,
  122452. };
  122453. static static_codebook *_floor_2048x27_books[]={
  122454. &_huff_book_line_2048x27_class1,
  122455. &_huff_book_line_2048x27_class2,
  122456. &_huff_book_line_2048x27_class3,
  122457. &_huff_book_line_2048x27_class4,
  122458. &_huff_book_line_2048x27_0sub0,
  122459. &_huff_book_line_2048x27_1sub0,
  122460. &_huff_book_line_2048x27_1sub1,
  122461. &_huff_book_line_2048x27_2sub0,
  122462. &_huff_book_line_2048x27_2sub1,
  122463. &_huff_book_line_2048x27_3sub1,
  122464. &_huff_book_line_2048x27_3sub2,
  122465. &_huff_book_line_2048x27_3sub3,
  122466. &_huff_book_line_2048x27_4sub1,
  122467. &_huff_book_line_2048x27_4sub2,
  122468. &_huff_book_line_2048x27_4sub3,
  122469. };
  122470. static static_codebook *_floor_512x17_books[]={
  122471. &_huff_book_line_512x17_class1,
  122472. &_huff_book_line_512x17_class2,
  122473. &_huff_book_line_512x17_class3,
  122474. &_huff_book_line_512x17_0sub0,
  122475. &_huff_book_line_512x17_1sub0,
  122476. &_huff_book_line_512x17_1sub1,
  122477. &_huff_book_line_512x17_2sub1,
  122478. &_huff_book_line_512x17_2sub2,
  122479. &_huff_book_line_512x17_2sub3,
  122480. &_huff_book_line_512x17_3sub1,
  122481. &_huff_book_line_512x17_3sub2,
  122482. &_huff_book_line_512x17_3sub3,
  122483. };
  122484. static static_codebook **_floor_books[10]={
  122485. _floor_128x4_books,
  122486. _floor_256x4_books,
  122487. _floor_128x7_books,
  122488. _floor_256x7_books,
  122489. _floor_128x11_books,
  122490. _floor_128x17_books,
  122491. _floor_256x4low_books,
  122492. _floor_1024x27_books,
  122493. _floor_2048x27_books,
  122494. _floor_512x17_books,
  122495. };
  122496. static vorbis_info_floor1 _floor[10]={
  122497. /* 128 x 4 */
  122498. {
  122499. 1,{0},{4},{2},{0},
  122500. {{1,2,3,4}},
  122501. 4,{0,128, 33,8,16,70},
  122502. 60,30,500, 1.,18., -1
  122503. },
  122504. /* 256 x 4 */
  122505. {
  122506. 1,{0},{4},{2},{0},
  122507. {{1,2,3,4}},
  122508. 4,{0,256, 66,16,32,140},
  122509. 60,30,500, 1.,18., -1
  122510. },
  122511. /* 128 x 7 */
  122512. {
  122513. 2,{0,1},{3,4},{2,2},{0,1},
  122514. {{-1,2,3,4},{-1,5,6,7}},
  122515. 4,{0,128, 14,4,58, 2,8,28,90},
  122516. 60,30,500, 1.,18., -1
  122517. },
  122518. /* 256 x 7 */
  122519. {
  122520. 2,{0,1},{3,4},{2,2},{0,1},
  122521. {{-1,2,3,4},{-1,5,6,7}},
  122522. 4,{0,256, 28,8,116, 4,16,56,180},
  122523. 60,30,500, 1.,18., -1
  122524. },
  122525. /* 128 x 11 */
  122526. {
  122527. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122528. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122529. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122530. 60,30,500, 1,18., -1
  122531. },
  122532. /* 128 x 17 */
  122533. {
  122534. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122535. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122536. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122537. 60,30,500, 1,18., -1
  122538. },
  122539. /* 256 x 4 (low bitrate version) */
  122540. {
  122541. 1,{0},{4},{2},{0},
  122542. {{1,2,3,4}},
  122543. 4,{0,256, 66,16,32,140},
  122544. 60,30,500, 1.,18., -1
  122545. },
  122546. /* 1024 x 27 */
  122547. {
  122548. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122549. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122550. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122551. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122552. 60,30,500, 3,18., -1 /* lowpass */
  122553. },
  122554. /* 2048 x 27 */
  122555. {
  122556. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122557. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122558. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122559. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122560. 60,30,500, 3,18., -1 /* lowpass */
  122561. },
  122562. /* 512 x 17 */
  122563. {
  122564. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122565. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122566. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122567. 7,23,39, 55,79,110, 156,232,360},
  122568. 60,30,500, 1,18., -1 /* lowpass! */
  122569. },
  122570. };
  122571. /*** End of inlined file: floor_all.h ***/
  122572. /*** Start of inlined file: residue_44.h ***/
  122573. /*** Start of inlined file: res_books_stereo.h ***/
  122574. static long _vq_quantlist__16c0_s_p1_0[] = {
  122575. 1,
  122576. 0,
  122577. 2,
  122578. };
  122579. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122580. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122581. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122586. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122591. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122626. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122631. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122636. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122672. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122677. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122682. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 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,
  122991. };
  122992. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122993. -0.5, 0.5,
  122994. };
  122995. static long _vq_quantmap__16c0_s_p1_0[] = {
  122996. 1, 0, 2,
  122997. };
  122998. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122999. _vq_quantthresh__16c0_s_p1_0,
  123000. _vq_quantmap__16c0_s_p1_0,
  123001. 3,
  123002. 3
  123003. };
  123004. static static_codebook _16c0_s_p1_0 = {
  123005. 8, 6561,
  123006. _vq_lengthlist__16c0_s_p1_0,
  123007. 1, -535822336, 1611661312, 2, 0,
  123008. _vq_quantlist__16c0_s_p1_0,
  123009. NULL,
  123010. &_vq_auxt__16c0_s_p1_0,
  123011. NULL,
  123012. 0
  123013. };
  123014. static long _vq_quantlist__16c0_s_p2_0[] = {
  123015. 2,
  123016. 1,
  123017. 3,
  123018. 0,
  123019. 4,
  123020. };
  123021. static long _vq_lengthlist__16c0_s_p2_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,
  123062. };
  123063. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123064. -1.5, -0.5, 0.5, 1.5,
  123065. };
  123066. static long _vq_quantmap__16c0_s_p2_0[] = {
  123067. 3, 1, 0, 2, 4,
  123068. };
  123069. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123070. _vq_quantthresh__16c0_s_p2_0,
  123071. _vq_quantmap__16c0_s_p2_0,
  123072. 5,
  123073. 5
  123074. };
  123075. static static_codebook _16c0_s_p2_0 = {
  123076. 4, 625,
  123077. _vq_lengthlist__16c0_s_p2_0,
  123078. 1, -533725184, 1611661312, 3, 0,
  123079. _vq_quantlist__16c0_s_p2_0,
  123080. NULL,
  123081. &_vq_auxt__16c0_s_p2_0,
  123082. NULL,
  123083. 0
  123084. };
  123085. static long _vq_quantlist__16c0_s_p3_0[] = {
  123086. 2,
  123087. 1,
  123088. 3,
  123089. 0,
  123090. 4,
  123091. };
  123092. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123093. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  123133. };
  123134. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123135. -1.5, -0.5, 0.5, 1.5,
  123136. };
  123137. static long _vq_quantmap__16c0_s_p3_0[] = {
  123138. 3, 1, 0, 2, 4,
  123139. };
  123140. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123141. _vq_quantthresh__16c0_s_p3_0,
  123142. _vq_quantmap__16c0_s_p3_0,
  123143. 5,
  123144. 5
  123145. };
  123146. static static_codebook _16c0_s_p3_0 = {
  123147. 4, 625,
  123148. _vq_lengthlist__16c0_s_p3_0,
  123149. 1, -533725184, 1611661312, 3, 0,
  123150. _vq_quantlist__16c0_s_p3_0,
  123151. NULL,
  123152. &_vq_auxt__16c0_s_p3_0,
  123153. NULL,
  123154. 0
  123155. };
  123156. static long _vq_quantlist__16c0_s_p4_0[] = {
  123157. 4,
  123158. 3,
  123159. 5,
  123160. 2,
  123161. 6,
  123162. 1,
  123163. 7,
  123164. 0,
  123165. 8,
  123166. };
  123167. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123168. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123169. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123170. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123171. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123172. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0,
  123174. };
  123175. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123176. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123177. };
  123178. static long _vq_quantmap__16c0_s_p4_0[] = {
  123179. 7, 5, 3, 1, 0, 2, 4, 6,
  123180. 8,
  123181. };
  123182. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123183. _vq_quantthresh__16c0_s_p4_0,
  123184. _vq_quantmap__16c0_s_p4_0,
  123185. 9,
  123186. 9
  123187. };
  123188. static static_codebook _16c0_s_p4_0 = {
  123189. 2, 81,
  123190. _vq_lengthlist__16c0_s_p4_0,
  123191. 1, -531628032, 1611661312, 4, 0,
  123192. _vq_quantlist__16c0_s_p4_0,
  123193. NULL,
  123194. &_vq_auxt__16c0_s_p4_0,
  123195. NULL,
  123196. 0
  123197. };
  123198. static long _vq_quantlist__16c0_s_p5_0[] = {
  123199. 4,
  123200. 3,
  123201. 5,
  123202. 2,
  123203. 6,
  123204. 1,
  123205. 7,
  123206. 0,
  123207. 8,
  123208. };
  123209. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123210. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123211. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123212. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123213. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123214. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123215. 10,
  123216. };
  123217. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123218. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123219. };
  123220. static long _vq_quantmap__16c0_s_p5_0[] = {
  123221. 7, 5, 3, 1, 0, 2, 4, 6,
  123222. 8,
  123223. };
  123224. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123225. _vq_quantthresh__16c0_s_p5_0,
  123226. _vq_quantmap__16c0_s_p5_0,
  123227. 9,
  123228. 9
  123229. };
  123230. static static_codebook _16c0_s_p5_0 = {
  123231. 2, 81,
  123232. _vq_lengthlist__16c0_s_p5_0,
  123233. 1, -531628032, 1611661312, 4, 0,
  123234. _vq_quantlist__16c0_s_p5_0,
  123235. NULL,
  123236. &_vq_auxt__16c0_s_p5_0,
  123237. NULL,
  123238. 0
  123239. };
  123240. static long _vq_quantlist__16c0_s_p6_0[] = {
  123241. 8,
  123242. 7,
  123243. 9,
  123244. 6,
  123245. 10,
  123246. 5,
  123247. 11,
  123248. 4,
  123249. 12,
  123250. 3,
  123251. 13,
  123252. 2,
  123253. 14,
  123254. 1,
  123255. 15,
  123256. 0,
  123257. 16,
  123258. };
  123259. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123260. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123261. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123262. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123263. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123264. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123265. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123266. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123267. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123268. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123269. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123270. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123271. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123272. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123273. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123274. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123275. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123276. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123278. 14,
  123279. };
  123280. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123281. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123282. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123283. };
  123284. static long _vq_quantmap__16c0_s_p6_0[] = {
  123285. 15, 13, 11, 9, 7, 5, 3, 1,
  123286. 0, 2, 4, 6, 8, 10, 12, 14,
  123287. 16,
  123288. };
  123289. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123290. _vq_quantthresh__16c0_s_p6_0,
  123291. _vq_quantmap__16c0_s_p6_0,
  123292. 17,
  123293. 17
  123294. };
  123295. static static_codebook _16c0_s_p6_0 = {
  123296. 2, 289,
  123297. _vq_lengthlist__16c0_s_p6_0,
  123298. 1, -529530880, 1611661312, 5, 0,
  123299. _vq_quantlist__16c0_s_p6_0,
  123300. NULL,
  123301. &_vq_auxt__16c0_s_p6_0,
  123302. NULL,
  123303. 0
  123304. };
  123305. static long _vq_quantlist__16c0_s_p7_0[] = {
  123306. 1,
  123307. 0,
  123308. 2,
  123309. };
  123310. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123311. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123312. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123313. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123314. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123315. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123316. 13,
  123317. };
  123318. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123319. -5.5, 5.5,
  123320. };
  123321. static long _vq_quantmap__16c0_s_p7_0[] = {
  123322. 1, 0, 2,
  123323. };
  123324. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123325. _vq_quantthresh__16c0_s_p7_0,
  123326. _vq_quantmap__16c0_s_p7_0,
  123327. 3,
  123328. 3
  123329. };
  123330. static static_codebook _16c0_s_p7_0 = {
  123331. 4, 81,
  123332. _vq_lengthlist__16c0_s_p7_0,
  123333. 1, -529137664, 1618345984, 2, 0,
  123334. _vq_quantlist__16c0_s_p7_0,
  123335. NULL,
  123336. &_vq_auxt__16c0_s_p7_0,
  123337. NULL,
  123338. 0
  123339. };
  123340. static long _vq_quantlist__16c0_s_p7_1[] = {
  123341. 5,
  123342. 4,
  123343. 6,
  123344. 3,
  123345. 7,
  123346. 2,
  123347. 8,
  123348. 1,
  123349. 9,
  123350. 0,
  123351. 10,
  123352. };
  123353. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123354. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123355. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123356. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123357. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123358. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123359. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123360. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123361. 11,11,11, 9, 9, 9, 9,10,10,
  123362. };
  123363. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123364. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123365. 3.5, 4.5,
  123366. };
  123367. static long _vq_quantmap__16c0_s_p7_1[] = {
  123368. 9, 7, 5, 3, 1, 0, 2, 4,
  123369. 6, 8, 10,
  123370. };
  123371. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123372. _vq_quantthresh__16c0_s_p7_1,
  123373. _vq_quantmap__16c0_s_p7_1,
  123374. 11,
  123375. 11
  123376. };
  123377. static static_codebook _16c0_s_p7_1 = {
  123378. 2, 121,
  123379. _vq_lengthlist__16c0_s_p7_1,
  123380. 1, -531365888, 1611661312, 4, 0,
  123381. _vq_quantlist__16c0_s_p7_1,
  123382. NULL,
  123383. &_vq_auxt__16c0_s_p7_1,
  123384. NULL,
  123385. 0
  123386. };
  123387. static long _vq_quantlist__16c0_s_p8_0[] = {
  123388. 6,
  123389. 5,
  123390. 7,
  123391. 4,
  123392. 8,
  123393. 3,
  123394. 9,
  123395. 2,
  123396. 10,
  123397. 1,
  123398. 11,
  123399. 0,
  123400. 12,
  123401. };
  123402. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123403. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123404. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123405. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123406. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123407. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123408. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123409. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123410. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123411. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123412. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123413. 0,12,13,13,12,13,14,14,14,
  123414. };
  123415. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123416. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123417. 12.5, 17.5, 22.5, 27.5,
  123418. };
  123419. static long _vq_quantmap__16c0_s_p8_0[] = {
  123420. 11, 9, 7, 5, 3, 1, 0, 2,
  123421. 4, 6, 8, 10, 12,
  123422. };
  123423. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123424. _vq_quantthresh__16c0_s_p8_0,
  123425. _vq_quantmap__16c0_s_p8_0,
  123426. 13,
  123427. 13
  123428. };
  123429. static static_codebook _16c0_s_p8_0 = {
  123430. 2, 169,
  123431. _vq_lengthlist__16c0_s_p8_0,
  123432. 1, -526516224, 1616117760, 4, 0,
  123433. _vq_quantlist__16c0_s_p8_0,
  123434. NULL,
  123435. &_vq_auxt__16c0_s_p8_0,
  123436. NULL,
  123437. 0
  123438. };
  123439. static long _vq_quantlist__16c0_s_p8_1[] = {
  123440. 2,
  123441. 1,
  123442. 3,
  123443. 0,
  123444. 4,
  123445. };
  123446. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123447. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123448. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123449. };
  123450. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123451. -1.5, -0.5, 0.5, 1.5,
  123452. };
  123453. static long _vq_quantmap__16c0_s_p8_1[] = {
  123454. 3, 1, 0, 2, 4,
  123455. };
  123456. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123457. _vq_quantthresh__16c0_s_p8_1,
  123458. _vq_quantmap__16c0_s_p8_1,
  123459. 5,
  123460. 5
  123461. };
  123462. static static_codebook _16c0_s_p8_1 = {
  123463. 2, 25,
  123464. _vq_lengthlist__16c0_s_p8_1,
  123465. 1, -533725184, 1611661312, 3, 0,
  123466. _vq_quantlist__16c0_s_p8_1,
  123467. NULL,
  123468. &_vq_auxt__16c0_s_p8_1,
  123469. NULL,
  123470. 0
  123471. };
  123472. static long _vq_quantlist__16c0_s_p9_0[] = {
  123473. 1,
  123474. 0,
  123475. 2,
  123476. };
  123477. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123478. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123479. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123480. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123481. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123482. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123483. 7,
  123484. };
  123485. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123486. -157.5, 157.5,
  123487. };
  123488. static long _vq_quantmap__16c0_s_p9_0[] = {
  123489. 1, 0, 2,
  123490. };
  123491. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123492. _vq_quantthresh__16c0_s_p9_0,
  123493. _vq_quantmap__16c0_s_p9_0,
  123494. 3,
  123495. 3
  123496. };
  123497. static static_codebook _16c0_s_p9_0 = {
  123498. 4, 81,
  123499. _vq_lengthlist__16c0_s_p9_0,
  123500. 1, -518803456, 1628680192, 2, 0,
  123501. _vq_quantlist__16c0_s_p9_0,
  123502. NULL,
  123503. &_vq_auxt__16c0_s_p9_0,
  123504. NULL,
  123505. 0
  123506. };
  123507. static long _vq_quantlist__16c0_s_p9_1[] = {
  123508. 7,
  123509. 6,
  123510. 8,
  123511. 5,
  123512. 9,
  123513. 4,
  123514. 10,
  123515. 3,
  123516. 11,
  123517. 2,
  123518. 12,
  123519. 1,
  123520. 13,
  123521. 0,
  123522. 14,
  123523. };
  123524. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123525. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123526. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123527. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123528. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123529. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123531. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123532. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123537. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123539. 10,
  123540. };
  123541. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123542. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123543. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123544. };
  123545. static long _vq_quantmap__16c0_s_p9_1[] = {
  123546. 13, 11, 9, 7, 5, 3, 1, 0,
  123547. 2, 4, 6, 8, 10, 12, 14,
  123548. };
  123549. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123550. _vq_quantthresh__16c0_s_p9_1,
  123551. _vq_quantmap__16c0_s_p9_1,
  123552. 15,
  123553. 15
  123554. };
  123555. static static_codebook _16c0_s_p9_1 = {
  123556. 2, 225,
  123557. _vq_lengthlist__16c0_s_p9_1,
  123558. 1, -520986624, 1620377600, 4, 0,
  123559. _vq_quantlist__16c0_s_p9_1,
  123560. NULL,
  123561. &_vq_auxt__16c0_s_p9_1,
  123562. NULL,
  123563. 0
  123564. };
  123565. static long _vq_quantlist__16c0_s_p9_2[] = {
  123566. 10,
  123567. 9,
  123568. 11,
  123569. 8,
  123570. 12,
  123571. 7,
  123572. 13,
  123573. 6,
  123574. 14,
  123575. 5,
  123576. 15,
  123577. 4,
  123578. 16,
  123579. 3,
  123580. 17,
  123581. 2,
  123582. 18,
  123583. 1,
  123584. 19,
  123585. 0,
  123586. 20,
  123587. };
  123588. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123589. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123590. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123591. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123592. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123593. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123594. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123595. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123596. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123597. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123598. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123599. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123600. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123601. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123602. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123603. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123604. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123605. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123606. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123607. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123608. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123609. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123610. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123611. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123612. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123613. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123614. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123615. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123616. 10,11,10,10,11, 9,10,10,10,
  123617. };
  123618. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123619. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123620. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123621. 6.5, 7.5, 8.5, 9.5,
  123622. };
  123623. static long _vq_quantmap__16c0_s_p9_2[] = {
  123624. 19, 17, 15, 13, 11, 9, 7, 5,
  123625. 3, 1, 0, 2, 4, 6, 8, 10,
  123626. 12, 14, 16, 18, 20,
  123627. };
  123628. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123629. _vq_quantthresh__16c0_s_p9_2,
  123630. _vq_quantmap__16c0_s_p9_2,
  123631. 21,
  123632. 21
  123633. };
  123634. static static_codebook _16c0_s_p9_2 = {
  123635. 2, 441,
  123636. _vq_lengthlist__16c0_s_p9_2,
  123637. 1, -529268736, 1611661312, 5, 0,
  123638. _vq_quantlist__16c0_s_p9_2,
  123639. NULL,
  123640. &_vq_auxt__16c0_s_p9_2,
  123641. NULL,
  123642. 0
  123643. };
  123644. static long _huff_lengthlist__16c0_s_single[] = {
  123645. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123646. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123647. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123648. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123649. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123650. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123651. 16,16,18,18,
  123652. };
  123653. static static_codebook _huff_book__16c0_s_single = {
  123654. 2, 100,
  123655. _huff_lengthlist__16c0_s_single,
  123656. 0, 0, 0, 0, 0,
  123657. NULL,
  123658. NULL,
  123659. NULL,
  123660. NULL,
  123661. 0
  123662. };
  123663. static long _huff_lengthlist__16c1_s_long[] = {
  123664. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123665. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123666. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123667. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123668. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123669. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123670. 12,11,11,13,
  123671. };
  123672. static static_codebook _huff_book__16c1_s_long = {
  123673. 2, 100,
  123674. _huff_lengthlist__16c1_s_long,
  123675. 0, 0, 0, 0, 0,
  123676. NULL,
  123677. NULL,
  123678. NULL,
  123679. NULL,
  123680. 0
  123681. };
  123682. static long _vq_quantlist__16c1_s_p1_0[] = {
  123683. 1,
  123684. 0,
  123685. 2,
  123686. };
  123687. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123688. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123689. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123694. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123699. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123734. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123739. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123744. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123780. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123785. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123790. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 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,
  124099. };
  124100. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124101. -0.5, 0.5,
  124102. };
  124103. static long _vq_quantmap__16c1_s_p1_0[] = {
  124104. 1, 0, 2,
  124105. };
  124106. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124107. _vq_quantthresh__16c1_s_p1_0,
  124108. _vq_quantmap__16c1_s_p1_0,
  124109. 3,
  124110. 3
  124111. };
  124112. static static_codebook _16c1_s_p1_0 = {
  124113. 8, 6561,
  124114. _vq_lengthlist__16c1_s_p1_0,
  124115. 1, -535822336, 1611661312, 2, 0,
  124116. _vq_quantlist__16c1_s_p1_0,
  124117. NULL,
  124118. &_vq_auxt__16c1_s_p1_0,
  124119. NULL,
  124120. 0
  124121. };
  124122. static long _vq_quantlist__16c1_s_p2_0[] = {
  124123. 2,
  124124. 1,
  124125. 3,
  124126. 0,
  124127. 4,
  124128. };
  124129. static long _vq_lengthlist__16c1_s_p2_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,
  124170. };
  124171. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124172. -1.5, -0.5, 0.5, 1.5,
  124173. };
  124174. static long _vq_quantmap__16c1_s_p2_0[] = {
  124175. 3, 1, 0, 2, 4,
  124176. };
  124177. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124178. _vq_quantthresh__16c1_s_p2_0,
  124179. _vq_quantmap__16c1_s_p2_0,
  124180. 5,
  124181. 5
  124182. };
  124183. static static_codebook _16c1_s_p2_0 = {
  124184. 4, 625,
  124185. _vq_lengthlist__16c1_s_p2_0,
  124186. 1, -533725184, 1611661312, 3, 0,
  124187. _vq_quantlist__16c1_s_p2_0,
  124188. NULL,
  124189. &_vq_auxt__16c1_s_p2_0,
  124190. NULL,
  124191. 0
  124192. };
  124193. static long _vq_quantlist__16c1_s_p3_0[] = {
  124194. 2,
  124195. 1,
  124196. 3,
  124197. 0,
  124198. 4,
  124199. };
  124200. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124201. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  124241. };
  124242. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124243. -1.5, -0.5, 0.5, 1.5,
  124244. };
  124245. static long _vq_quantmap__16c1_s_p3_0[] = {
  124246. 3, 1, 0, 2, 4,
  124247. };
  124248. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124249. _vq_quantthresh__16c1_s_p3_0,
  124250. _vq_quantmap__16c1_s_p3_0,
  124251. 5,
  124252. 5
  124253. };
  124254. static static_codebook _16c1_s_p3_0 = {
  124255. 4, 625,
  124256. _vq_lengthlist__16c1_s_p3_0,
  124257. 1, -533725184, 1611661312, 3, 0,
  124258. _vq_quantlist__16c1_s_p3_0,
  124259. NULL,
  124260. &_vq_auxt__16c1_s_p3_0,
  124261. NULL,
  124262. 0
  124263. };
  124264. static long _vq_quantlist__16c1_s_p4_0[] = {
  124265. 4,
  124266. 3,
  124267. 5,
  124268. 2,
  124269. 6,
  124270. 1,
  124271. 7,
  124272. 0,
  124273. 8,
  124274. };
  124275. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124276. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124277. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124278. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124279. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124280. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0,
  124282. };
  124283. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124284. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124285. };
  124286. static long _vq_quantmap__16c1_s_p4_0[] = {
  124287. 7, 5, 3, 1, 0, 2, 4, 6,
  124288. 8,
  124289. };
  124290. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124291. _vq_quantthresh__16c1_s_p4_0,
  124292. _vq_quantmap__16c1_s_p4_0,
  124293. 9,
  124294. 9
  124295. };
  124296. static static_codebook _16c1_s_p4_0 = {
  124297. 2, 81,
  124298. _vq_lengthlist__16c1_s_p4_0,
  124299. 1, -531628032, 1611661312, 4, 0,
  124300. _vq_quantlist__16c1_s_p4_0,
  124301. NULL,
  124302. &_vq_auxt__16c1_s_p4_0,
  124303. NULL,
  124304. 0
  124305. };
  124306. static long _vq_quantlist__16c1_s_p5_0[] = {
  124307. 4,
  124308. 3,
  124309. 5,
  124310. 2,
  124311. 6,
  124312. 1,
  124313. 7,
  124314. 0,
  124315. 8,
  124316. };
  124317. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124318. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124319. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124320. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124321. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124322. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124323. 10,
  124324. };
  124325. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124326. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124327. };
  124328. static long _vq_quantmap__16c1_s_p5_0[] = {
  124329. 7, 5, 3, 1, 0, 2, 4, 6,
  124330. 8,
  124331. };
  124332. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124333. _vq_quantthresh__16c1_s_p5_0,
  124334. _vq_quantmap__16c1_s_p5_0,
  124335. 9,
  124336. 9
  124337. };
  124338. static static_codebook _16c1_s_p5_0 = {
  124339. 2, 81,
  124340. _vq_lengthlist__16c1_s_p5_0,
  124341. 1, -531628032, 1611661312, 4, 0,
  124342. _vq_quantlist__16c1_s_p5_0,
  124343. NULL,
  124344. &_vq_auxt__16c1_s_p5_0,
  124345. NULL,
  124346. 0
  124347. };
  124348. static long _vq_quantlist__16c1_s_p6_0[] = {
  124349. 8,
  124350. 7,
  124351. 9,
  124352. 6,
  124353. 10,
  124354. 5,
  124355. 11,
  124356. 4,
  124357. 12,
  124358. 3,
  124359. 13,
  124360. 2,
  124361. 14,
  124362. 1,
  124363. 15,
  124364. 0,
  124365. 16,
  124366. };
  124367. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124368. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124369. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124370. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124371. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124372. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124373. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124374. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124375. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124376. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124377. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124378. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124379. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124380. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124381. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124382. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124383. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124384. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124386. 14,
  124387. };
  124388. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124389. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124390. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124391. };
  124392. static long _vq_quantmap__16c1_s_p6_0[] = {
  124393. 15, 13, 11, 9, 7, 5, 3, 1,
  124394. 0, 2, 4, 6, 8, 10, 12, 14,
  124395. 16,
  124396. };
  124397. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124398. _vq_quantthresh__16c1_s_p6_0,
  124399. _vq_quantmap__16c1_s_p6_0,
  124400. 17,
  124401. 17
  124402. };
  124403. static static_codebook _16c1_s_p6_0 = {
  124404. 2, 289,
  124405. _vq_lengthlist__16c1_s_p6_0,
  124406. 1, -529530880, 1611661312, 5, 0,
  124407. _vq_quantlist__16c1_s_p6_0,
  124408. NULL,
  124409. &_vq_auxt__16c1_s_p6_0,
  124410. NULL,
  124411. 0
  124412. };
  124413. static long _vq_quantlist__16c1_s_p7_0[] = {
  124414. 1,
  124415. 0,
  124416. 2,
  124417. };
  124418. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124419. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124420. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124421. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124422. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124423. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124424. 11,
  124425. };
  124426. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124427. -5.5, 5.5,
  124428. };
  124429. static long _vq_quantmap__16c1_s_p7_0[] = {
  124430. 1, 0, 2,
  124431. };
  124432. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124433. _vq_quantthresh__16c1_s_p7_0,
  124434. _vq_quantmap__16c1_s_p7_0,
  124435. 3,
  124436. 3
  124437. };
  124438. static static_codebook _16c1_s_p7_0 = {
  124439. 4, 81,
  124440. _vq_lengthlist__16c1_s_p7_0,
  124441. 1, -529137664, 1618345984, 2, 0,
  124442. _vq_quantlist__16c1_s_p7_0,
  124443. NULL,
  124444. &_vq_auxt__16c1_s_p7_0,
  124445. NULL,
  124446. 0
  124447. };
  124448. static long _vq_quantlist__16c1_s_p7_1[] = {
  124449. 5,
  124450. 4,
  124451. 6,
  124452. 3,
  124453. 7,
  124454. 2,
  124455. 8,
  124456. 1,
  124457. 9,
  124458. 0,
  124459. 10,
  124460. };
  124461. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124462. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124463. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124464. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124465. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124466. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124467. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124468. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124469. 10,10,10, 8, 8, 8, 8, 9, 9,
  124470. };
  124471. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124472. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124473. 3.5, 4.5,
  124474. };
  124475. static long _vq_quantmap__16c1_s_p7_1[] = {
  124476. 9, 7, 5, 3, 1, 0, 2, 4,
  124477. 6, 8, 10,
  124478. };
  124479. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124480. _vq_quantthresh__16c1_s_p7_1,
  124481. _vq_quantmap__16c1_s_p7_1,
  124482. 11,
  124483. 11
  124484. };
  124485. static static_codebook _16c1_s_p7_1 = {
  124486. 2, 121,
  124487. _vq_lengthlist__16c1_s_p7_1,
  124488. 1, -531365888, 1611661312, 4, 0,
  124489. _vq_quantlist__16c1_s_p7_1,
  124490. NULL,
  124491. &_vq_auxt__16c1_s_p7_1,
  124492. NULL,
  124493. 0
  124494. };
  124495. static long _vq_quantlist__16c1_s_p8_0[] = {
  124496. 6,
  124497. 5,
  124498. 7,
  124499. 4,
  124500. 8,
  124501. 3,
  124502. 9,
  124503. 2,
  124504. 10,
  124505. 1,
  124506. 11,
  124507. 0,
  124508. 12,
  124509. };
  124510. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124511. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124512. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124513. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124514. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124515. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124516. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124517. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124518. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124519. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124520. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124521. 0,12,12,12,12,13,13,14,15,
  124522. };
  124523. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124524. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124525. 12.5, 17.5, 22.5, 27.5,
  124526. };
  124527. static long _vq_quantmap__16c1_s_p8_0[] = {
  124528. 11, 9, 7, 5, 3, 1, 0, 2,
  124529. 4, 6, 8, 10, 12,
  124530. };
  124531. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124532. _vq_quantthresh__16c1_s_p8_0,
  124533. _vq_quantmap__16c1_s_p8_0,
  124534. 13,
  124535. 13
  124536. };
  124537. static static_codebook _16c1_s_p8_0 = {
  124538. 2, 169,
  124539. _vq_lengthlist__16c1_s_p8_0,
  124540. 1, -526516224, 1616117760, 4, 0,
  124541. _vq_quantlist__16c1_s_p8_0,
  124542. NULL,
  124543. &_vq_auxt__16c1_s_p8_0,
  124544. NULL,
  124545. 0
  124546. };
  124547. static long _vq_quantlist__16c1_s_p8_1[] = {
  124548. 2,
  124549. 1,
  124550. 3,
  124551. 0,
  124552. 4,
  124553. };
  124554. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124555. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124556. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124557. };
  124558. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124559. -1.5, -0.5, 0.5, 1.5,
  124560. };
  124561. static long _vq_quantmap__16c1_s_p8_1[] = {
  124562. 3, 1, 0, 2, 4,
  124563. };
  124564. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124565. _vq_quantthresh__16c1_s_p8_1,
  124566. _vq_quantmap__16c1_s_p8_1,
  124567. 5,
  124568. 5
  124569. };
  124570. static static_codebook _16c1_s_p8_1 = {
  124571. 2, 25,
  124572. _vq_lengthlist__16c1_s_p8_1,
  124573. 1, -533725184, 1611661312, 3, 0,
  124574. _vq_quantlist__16c1_s_p8_1,
  124575. NULL,
  124576. &_vq_auxt__16c1_s_p8_1,
  124577. NULL,
  124578. 0
  124579. };
  124580. static long _vq_quantlist__16c1_s_p9_0[] = {
  124581. 6,
  124582. 5,
  124583. 7,
  124584. 4,
  124585. 8,
  124586. 3,
  124587. 9,
  124588. 2,
  124589. 10,
  124590. 1,
  124591. 11,
  124592. 0,
  124593. 12,
  124594. };
  124595. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124596. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124601. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124602. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124604. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124605. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124606. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124607. };
  124608. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124609. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124610. 787.5, 1102.5, 1417.5, 1732.5,
  124611. };
  124612. static long _vq_quantmap__16c1_s_p9_0[] = {
  124613. 11, 9, 7, 5, 3, 1, 0, 2,
  124614. 4, 6, 8, 10, 12,
  124615. };
  124616. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124617. _vq_quantthresh__16c1_s_p9_0,
  124618. _vq_quantmap__16c1_s_p9_0,
  124619. 13,
  124620. 13
  124621. };
  124622. static static_codebook _16c1_s_p9_0 = {
  124623. 2, 169,
  124624. _vq_lengthlist__16c1_s_p9_0,
  124625. 1, -513964032, 1628680192, 4, 0,
  124626. _vq_quantlist__16c1_s_p9_0,
  124627. NULL,
  124628. &_vq_auxt__16c1_s_p9_0,
  124629. NULL,
  124630. 0
  124631. };
  124632. static long _vq_quantlist__16c1_s_p9_1[] = {
  124633. 7,
  124634. 6,
  124635. 8,
  124636. 5,
  124637. 9,
  124638. 4,
  124639. 10,
  124640. 3,
  124641. 11,
  124642. 2,
  124643. 12,
  124644. 1,
  124645. 13,
  124646. 0,
  124647. 14,
  124648. };
  124649. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124650. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124651. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124652. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124653. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124654. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124655. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124656. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124657. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124658. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124659. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124660. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124661. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124662. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124663. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124664. 13,
  124665. };
  124666. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124667. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124668. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124669. };
  124670. static long _vq_quantmap__16c1_s_p9_1[] = {
  124671. 13, 11, 9, 7, 5, 3, 1, 0,
  124672. 2, 4, 6, 8, 10, 12, 14,
  124673. };
  124674. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124675. _vq_quantthresh__16c1_s_p9_1,
  124676. _vq_quantmap__16c1_s_p9_1,
  124677. 15,
  124678. 15
  124679. };
  124680. static static_codebook _16c1_s_p9_1 = {
  124681. 2, 225,
  124682. _vq_lengthlist__16c1_s_p9_1,
  124683. 1, -520986624, 1620377600, 4, 0,
  124684. _vq_quantlist__16c1_s_p9_1,
  124685. NULL,
  124686. &_vq_auxt__16c1_s_p9_1,
  124687. NULL,
  124688. 0
  124689. };
  124690. static long _vq_quantlist__16c1_s_p9_2[] = {
  124691. 10,
  124692. 9,
  124693. 11,
  124694. 8,
  124695. 12,
  124696. 7,
  124697. 13,
  124698. 6,
  124699. 14,
  124700. 5,
  124701. 15,
  124702. 4,
  124703. 16,
  124704. 3,
  124705. 17,
  124706. 2,
  124707. 18,
  124708. 1,
  124709. 19,
  124710. 0,
  124711. 20,
  124712. };
  124713. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124714. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124715. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124716. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124717. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124718. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124719. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124720. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124721. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124722. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124723. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124724. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124725. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124726. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124727. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124728. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124729. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124730. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124731. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124732. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124733. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124734. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124735. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124736. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124737. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124738. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124739. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124740. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124741. 11,11,11,11,12,11,11,12,11,
  124742. };
  124743. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124744. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124745. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124746. 6.5, 7.5, 8.5, 9.5,
  124747. };
  124748. static long _vq_quantmap__16c1_s_p9_2[] = {
  124749. 19, 17, 15, 13, 11, 9, 7, 5,
  124750. 3, 1, 0, 2, 4, 6, 8, 10,
  124751. 12, 14, 16, 18, 20,
  124752. };
  124753. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124754. _vq_quantthresh__16c1_s_p9_2,
  124755. _vq_quantmap__16c1_s_p9_2,
  124756. 21,
  124757. 21
  124758. };
  124759. static static_codebook _16c1_s_p9_2 = {
  124760. 2, 441,
  124761. _vq_lengthlist__16c1_s_p9_2,
  124762. 1, -529268736, 1611661312, 5, 0,
  124763. _vq_quantlist__16c1_s_p9_2,
  124764. NULL,
  124765. &_vq_auxt__16c1_s_p9_2,
  124766. NULL,
  124767. 0
  124768. };
  124769. static long _huff_lengthlist__16c1_s_short[] = {
  124770. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124771. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124772. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124773. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124774. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124775. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124776. 9, 9,10,13,
  124777. };
  124778. static static_codebook _huff_book__16c1_s_short = {
  124779. 2, 100,
  124780. _huff_lengthlist__16c1_s_short,
  124781. 0, 0, 0, 0, 0,
  124782. NULL,
  124783. NULL,
  124784. NULL,
  124785. NULL,
  124786. 0
  124787. };
  124788. static long _huff_lengthlist__16c2_s_long[] = {
  124789. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124790. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124791. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124792. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124793. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124794. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124795. 14,14,16,18,
  124796. };
  124797. static static_codebook _huff_book__16c2_s_long = {
  124798. 2, 100,
  124799. _huff_lengthlist__16c2_s_long,
  124800. 0, 0, 0, 0, 0,
  124801. NULL,
  124802. NULL,
  124803. NULL,
  124804. NULL,
  124805. 0
  124806. };
  124807. static long _vq_quantlist__16c2_s_p1_0[] = {
  124808. 1,
  124809. 0,
  124810. 2,
  124811. };
  124812. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124813. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124814. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0,
  124819. };
  124820. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124821. -0.5, 0.5,
  124822. };
  124823. static long _vq_quantmap__16c2_s_p1_0[] = {
  124824. 1, 0, 2,
  124825. };
  124826. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124827. _vq_quantthresh__16c2_s_p1_0,
  124828. _vq_quantmap__16c2_s_p1_0,
  124829. 3,
  124830. 3
  124831. };
  124832. static static_codebook _16c2_s_p1_0 = {
  124833. 4, 81,
  124834. _vq_lengthlist__16c2_s_p1_0,
  124835. 1, -535822336, 1611661312, 2, 0,
  124836. _vq_quantlist__16c2_s_p1_0,
  124837. NULL,
  124838. &_vq_auxt__16c2_s_p1_0,
  124839. NULL,
  124840. 0
  124841. };
  124842. static long _vq_quantlist__16c2_s_p2_0[] = {
  124843. 2,
  124844. 1,
  124845. 3,
  124846. 0,
  124847. 4,
  124848. };
  124849. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124850. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124851. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124852. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124853. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124854. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124855. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124856. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124857. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124863. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124864. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124865. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124871. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124872. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124873. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124879. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124880. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124881. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124886. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124887. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124888. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124889. 13,
  124890. };
  124891. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124892. -1.5, -0.5, 0.5, 1.5,
  124893. };
  124894. static long _vq_quantmap__16c2_s_p2_0[] = {
  124895. 3, 1, 0, 2, 4,
  124896. };
  124897. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124898. _vq_quantthresh__16c2_s_p2_0,
  124899. _vq_quantmap__16c2_s_p2_0,
  124900. 5,
  124901. 5
  124902. };
  124903. static static_codebook _16c2_s_p2_0 = {
  124904. 4, 625,
  124905. _vq_lengthlist__16c2_s_p2_0,
  124906. 1, -533725184, 1611661312, 3, 0,
  124907. _vq_quantlist__16c2_s_p2_0,
  124908. NULL,
  124909. &_vq_auxt__16c2_s_p2_0,
  124910. NULL,
  124911. 0
  124912. };
  124913. static long _vq_quantlist__16c2_s_p3_0[] = {
  124914. 4,
  124915. 3,
  124916. 5,
  124917. 2,
  124918. 6,
  124919. 1,
  124920. 7,
  124921. 0,
  124922. 8,
  124923. };
  124924. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124925. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124926. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124927. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124928. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0,
  124931. };
  124932. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124933. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124934. };
  124935. static long _vq_quantmap__16c2_s_p3_0[] = {
  124936. 7, 5, 3, 1, 0, 2, 4, 6,
  124937. 8,
  124938. };
  124939. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124940. _vq_quantthresh__16c2_s_p3_0,
  124941. _vq_quantmap__16c2_s_p3_0,
  124942. 9,
  124943. 9
  124944. };
  124945. static static_codebook _16c2_s_p3_0 = {
  124946. 2, 81,
  124947. _vq_lengthlist__16c2_s_p3_0,
  124948. 1, -531628032, 1611661312, 4, 0,
  124949. _vq_quantlist__16c2_s_p3_0,
  124950. NULL,
  124951. &_vq_auxt__16c2_s_p3_0,
  124952. NULL,
  124953. 0
  124954. };
  124955. static long _vq_quantlist__16c2_s_p4_0[] = {
  124956. 8,
  124957. 7,
  124958. 9,
  124959. 6,
  124960. 10,
  124961. 5,
  124962. 11,
  124963. 4,
  124964. 12,
  124965. 3,
  124966. 13,
  124967. 2,
  124968. 14,
  124969. 1,
  124970. 15,
  124971. 0,
  124972. 16,
  124973. };
  124974. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124975. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124976. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124977. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124978. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124979. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124980. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124981. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124982. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124983. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124984. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0,
  124994. };
  124995. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124996. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124997. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124998. };
  124999. static long _vq_quantmap__16c2_s_p4_0[] = {
  125000. 15, 13, 11, 9, 7, 5, 3, 1,
  125001. 0, 2, 4, 6, 8, 10, 12, 14,
  125002. 16,
  125003. };
  125004. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125005. _vq_quantthresh__16c2_s_p4_0,
  125006. _vq_quantmap__16c2_s_p4_0,
  125007. 17,
  125008. 17
  125009. };
  125010. static static_codebook _16c2_s_p4_0 = {
  125011. 2, 289,
  125012. _vq_lengthlist__16c2_s_p4_0,
  125013. 1, -529530880, 1611661312, 5, 0,
  125014. _vq_quantlist__16c2_s_p4_0,
  125015. NULL,
  125016. &_vq_auxt__16c2_s_p4_0,
  125017. NULL,
  125018. 0
  125019. };
  125020. static long _vq_quantlist__16c2_s_p5_0[] = {
  125021. 1,
  125022. 0,
  125023. 2,
  125024. };
  125025. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125026. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125027. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125028. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125029. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125030. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125031. 12,
  125032. };
  125033. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125034. -5.5, 5.5,
  125035. };
  125036. static long _vq_quantmap__16c2_s_p5_0[] = {
  125037. 1, 0, 2,
  125038. };
  125039. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125040. _vq_quantthresh__16c2_s_p5_0,
  125041. _vq_quantmap__16c2_s_p5_0,
  125042. 3,
  125043. 3
  125044. };
  125045. static static_codebook _16c2_s_p5_0 = {
  125046. 4, 81,
  125047. _vq_lengthlist__16c2_s_p5_0,
  125048. 1, -529137664, 1618345984, 2, 0,
  125049. _vq_quantlist__16c2_s_p5_0,
  125050. NULL,
  125051. &_vq_auxt__16c2_s_p5_0,
  125052. NULL,
  125053. 0
  125054. };
  125055. static long _vq_quantlist__16c2_s_p5_1[] = {
  125056. 5,
  125057. 4,
  125058. 6,
  125059. 3,
  125060. 7,
  125061. 2,
  125062. 8,
  125063. 1,
  125064. 9,
  125065. 0,
  125066. 10,
  125067. };
  125068. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125069. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125070. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125071. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125072. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125073. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125074. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125075. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125076. 11,11,11, 7, 7, 8, 8, 8, 8,
  125077. };
  125078. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125079. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125080. 3.5, 4.5,
  125081. };
  125082. static long _vq_quantmap__16c2_s_p5_1[] = {
  125083. 9, 7, 5, 3, 1, 0, 2, 4,
  125084. 6, 8, 10,
  125085. };
  125086. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125087. _vq_quantthresh__16c2_s_p5_1,
  125088. _vq_quantmap__16c2_s_p5_1,
  125089. 11,
  125090. 11
  125091. };
  125092. static static_codebook _16c2_s_p5_1 = {
  125093. 2, 121,
  125094. _vq_lengthlist__16c2_s_p5_1,
  125095. 1, -531365888, 1611661312, 4, 0,
  125096. _vq_quantlist__16c2_s_p5_1,
  125097. NULL,
  125098. &_vq_auxt__16c2_s_p5_1,
  125099. NULL,
  125100. 0
  125101. };
  125102. static long _vq_quantlist__16c2_s_p6_0[] = {
  125103. 6,
  125104. 5,
  125105. 7,
  125106. 4,
  125107. 8,
  125108. 3,
  125109. 9,
  125110. 2,
  125111. 10,
  125112. 1,
  125113. 11,
  125114. 0,
  125115. 12,
  125116. };
  125117. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125118. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125119. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125120. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125121. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125122. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125123. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 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,
  125129. };
  125130. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125131. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125132. 12.5, 17.5, 22.5, 27.5,
  125133. };
  125134. static long _vq_quantmap__16c2_s_p6_0[] = {
  125135. 11, 9, 7, 5, 3, 1, 0, 2,
  125136. 4, 6, 8, 10, 12,
  125137. };
  125138. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125139. _vq_quantthresh__16c2_s_p6_0,
  125140. _vq_quantmap__16c2_s_p6_0,
  125141. 13,
  125142. 13
  125143. };
  125144. static static_codebook _16c2_s_p6_0 = {
  125145. 2, 169,
  125146. _vq_lengthlist__16c2_s_p6_0,
  125147. 1, -526516224, 1616117760, 4, 0,
  125148. _vq_quantlist__16c2_s_p6_0,
  125149. NULL,
  125150. &_vq_auxt__16c2_s_p6_0,
  125151. NULL,
  125152. 0
  125153. };
  125154. static long _vq_quantlist__16c2_s_p6_1[] = {
  125155. 2,
  125156. 1,
  125157. 3,
  125158. 0,
  125159. 4,
  125160. };
  125161. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125162. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125163. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125164. };
  125165. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125166. -1.5, -0.5, 0.5, 1.5,
  125167. };
  125168. static long _vq_quantmap__16c2_s_p6_1[] = {
  125169. 3, 1, 0, 2, 4,
  125170. };
  125171. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125172. _vq_quantthresh__16c2_s_p6_1,
  125173. _vq_quantmap__16c2_s_p6_1,
  125174. 5,
  125175. 5
  125176. };
  125177. static static_codebook _16c2_s_p6_1 = {
  125178. 2, 25,
  125179. _vq_lengthlist__16c2_s_p6_1,
  125180. 1, -533725184, 1611661312, 3, 0,
  125181. _vq_quantlist__16c2_s_p6_1,
  125182. NULL,
  125183. &_vq_auxt__16c2_s_p6_1,
  125184. NULL,
  125185. 0
  125186. };
  125187. static long _vq_quantlist__16c2_s_p7_0[] = {
  125188. 6,
  125189. 5,
  125190. 7,
  125191. 4,
  125192. 8,
  125193. 3,
  125194. 9,
  125195. 2,
  125196. 10,
  125197. 1,
  125198. 11,
  125199. 0,
  125200. 12,
  125201. };
  125202. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125203. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125204. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125205. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125206. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125207. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125208. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125209. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125210. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125211. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125212. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125213. 18,13,14,13,13,14,13,15,14,
  125214. };
  125215. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125216. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125217. 27.5, 38.5, 49.5, 60.5,
  125218. };
  125219. static long _vq_quantmap__16c2_s_p7_0[] = {
  125220. 11, 9, 7, 5, 3, 1, 0, 2,
  125221. 4, 6, 8, 10, 12,
  125222. };
  125223. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125224. _vq_quantthresh__16c2_s_p7_0,
  125225. _vq_quantmap__16c2_s_p7_0,
  125226. 13,
  125227. 13
  125228. };
  125229. static static_codebook _16c2_s_p7_0 = {
  125230. 2, 169,
  125231. _vq_lengthlist__16c2_s_p7_0,
  125232. 1, -523206656, 1618345984, 4, 0,
  125233. _vq_quantlist__16c2_s_p7_0,
  125234. NULL,
  125235. &_vq_auxt__16c2_s_p7_0,
  125236. NULL,
  125237. 0
  125238. };
  125239. static long _vq_quantlist__16c2_s_p7_1[] = {
  125240. 5,
  125241. 4,
  125242. 6,
  125243. 3,
  125244. 7,
  125245. 2,
  125246. 8,
  125247. 1,
  125248. 9,
  125249. 0,
  125250. 10,
  125251. };
  125252. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125253. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125254. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125255. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125256. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125257. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125258. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125259. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125260. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125261. };
  125262. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125263. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125264. 3.5, 4.5,
  125265. };
  125266. static long _vq_quantmap__16c2_s_p7_1[] = {
  125267. 9, 7, 5, 3, 1, 0, 2, 4,
  125268. 6, 8, 10,
  125269. };
  125270. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125271. _vq_quantthresh__16c2_s_p7_1,
  125272. _vq_quantmap__16c2_s_p7_1,
  125273. 11,
  125274. 11
  125275. };
  125276. static static_codebook _16c2_s_p7_1 = {
  125277. 2, 121,
  125278. _vq_lengthlist__16c2_s_p7_1,
  125279. 1, -531365888, 1611661312, 4, 0,
  125280. _vq_quantlist__16c2_s_p7_1,
  125281. NULL,
  125282. &_vq_auxt__16c2_s_p7_1,
  125283. NULL,
  125284. 0
  125285. };
  125286. static long _vq_quantlist__16c2_s_p8_0[] = {
  125287. 7,
  125288. 6,
  125289. 8,
  125290. 5,
  125291. 9,
  125292. 4,
  125293. 10,
  125294. 3,
  125295. 11,
  125296. 2,
  125297. 12,
  125298. 1,
  125299. 13,
  125300. 0,
  125301. 14,
  125302. };
  125303. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125304. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125305. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125306. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125307. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125308. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125309. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125310. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125311. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125312. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125313. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125314. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125315. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125316. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125317. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125318. 13,
  125319. };
  125320. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125321. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125322. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125323. };
  125324. static long _vq_quantmap__16c2_s_p8_0[] = {
  125325. 13, 11, 9, 7, 5, 3, 1, 0,
  125326. 2, 4, 6, 8, 10, 12, 14,
  125327. };
  125328. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125329. _vq_quantthresh__16c2_s_p8_0,
  125330. _vq_quantmap__16c2_s_p8_0,
  125331. 15,
  125332. 15
  125333. };
  125334. static static_codebook _16c2_s_p8_0 = {
  125335. 2, 225,
  125336. _vq_lengthlist__16c2_s_p8_0,
  125337. 1, -520986624, 1620377600, 4, 0,
  125338. _vq_quantlist__16c2_s_p8_0,
  125339. NULL,
  125340. &_vq_auxt__16c2_s_p8_0,
  125341. NULL,
  125342. 0
  125343. };
  125344. static long _vq_quantlist__16c2_s_p8_1[] = {
  125345. 10,
  125346. 9,
  125347. 11,
  125348. 8,
  125349. 12,
  125350. 7,
  125351. 13,
  125352. 6,
  125353. 14,
  125354. 5,
  125355. 15,
  125356. 4,
  125357. 16,
  125358. 3,
  125359. 17,
  125360. 2,
  125361. 18,
  125362. 1,
  125363. 19,
  125364. 0,
  125365. 20,
  125366. };
  125367. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125368. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125369. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125370. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125371. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125372. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125373. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125374. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125375. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125376. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125377. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125378. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125379. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125380. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125381. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125382. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125383. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125384. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125385. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125386. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125387. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125388. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125389. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125390. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125391. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125392. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125393. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125394. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125395. 10,11,10,10,10,10,10,10,10,
  125396. };
  125397. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125398. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125399. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125400. 6.5, 7.5, 8.5, 9.5,
  125401. };
  125402. static long _vq_quantmap__16c2_s_p8_1[] = {
  125403. 19, 17, 15, 13, 11, 9, 7, 5,
  125404. 3, 1, 0, 2, 4, 6, 8, 10,
  125405. 12, 14, 16, 18, 20,
  125406. };
  125407. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125408. _vq_quantthresh__16c2_s_p8_1,
  125409. _vq_quantmap__16c2_s_p8_1,
  125410. 21,
  125411. 21
  125412. };
  125413. static static_codebook _16c2_s_p8_1 = {
  125414. 2, 441,
  125415. _vq_lengthlist__16c2_s_p8_1,
  125416. 1, -529268736, 1611661312, 5, 0,
  125417. _vq_quantlist__16c2_s_p8_1,
  125418. NULL,
  125419. &_vq_auxt__16c2_s_p8_1,
  125420. NULL,
  125421. 0
  125422. };
  125423. static long _vq_quantlist__16c2_s_p9_0[] = {
  125424. 6,
  125425. 5,
  125426. 7,
  125427. 4,
  125428. 8,
  125429. 3,
  125430. 9,
  125431. 2,
  125432. 10,
  125433. 1,
  125434. 11,
  125435. 0,
  125436. 12,
  125437. };
  125438. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125439. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125440. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125442. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125443. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125444. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125445. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125446. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125447. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125448. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125449. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125450. };
  125451. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125452. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125453. 2327.5, 3258.5, 4189.5, 5120.5,
  125454. };
  125455. static long _vq_quantmap__16c2_s_p9_0[] = {
  125456. 11, 9, 7, 5, 3, 1, 0, 2,
  125457. 4, 6, 8, 10, 12,
  125458. };
  125459. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125460. _vq_quantthresh__16c2_s_p9_0,
  125461. _vq_quantmap__16c2_s_p9_0,
  125462. 13,
  125463. 13
  125464. };
  125465. static static_codebook _16c2_s_p9_0 = {
  125466. 2, 169,
  125467. _vq_lengthlist__16c2_s_p9_0,
  125468. 1, -510275072, 1631393792, 4, 0,
  125469. _vq_quantlist__16c2_s_p9_0,
  125470. NULL,
  125471. &_vq_auxt__16c2_s_p9_0,
  125472. NULL,
  125473. 0
  125474. };
  125475. static long _vq_quantlist__16c2_s_p9_1[] = {
  125476. 8,
  125477. 7,
  125478. 9,
  125479. 6,
  125480. 10,
  125481. 5,
  125482. 11,
  125483. 4,
  125484. 12,
  125485. 3,
  125486. 13,
  125487. 2,
  125488. 14,
  125489. 1,
  125490. 15,
  125491. 0,
  125492. 16,
  125493. };
  125494. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125495. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125496. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125497. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125498. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125499. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125500. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125501. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125502. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125503. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125504. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125505. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125506. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125507. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125508. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125509. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125510. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125511. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125512. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125513. 10,
  125514. };
  125515. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125516. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125517. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125518. };
  125519. static long _vq_quantmap__16c2_s_p9_1[] = {
  125520. 15, 13, 11, 9, 7, 5, 3, 1,
  125521. 0, 2, 4, 6, 8, 10, 12, 14,
  125522. 16,
  125523. };
  125524. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125525. _vq_quantthresh__16c2_s_p9_1,
  125526. _vq_quantmap__16c2_s_p9_1,
  125527. 17,
  125528. 17
  125529. };
  125530. static static_codebook _16c2_s_p9_1 = {
  125531. 2, 289,
  125532. _vq_lengthlist__16c2_s_p9_1,
  125533. 1, -518488064, 1622704128, 5, 0,
  125534. _vq_quantlist__16c2_s_p9_1,
  125535. NULL,
  125536. &_vq_auxt__16c2_s_p9_1,
  125537. NULL,
  125538. 0
  125539. };
  125540. static long _vq_quantlist__16c2_s_p9_2[] = {
  125541. 13,
  125542. 12,
  125543. 14,
  125544. 11,
  125545. 15,
  125546. 10,
  125547. 16,
  125548. 9,
  125549. 17,
  125550. 8,
  125551. 18,
  125552. 7,
  125553. 19,
  125554. 6,
  125555. 20,
  125556. 5,
  125557. 21,
  125558. 4,
  125559. 22,
  125560. 3,
  125561. 23,
  125562. 2,
  125563. 24,
  125564. 1,
  125565. 25,
  125566. 0,
  125567. 26,
  125568. };
  125569. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125570. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125571. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125572. };
  125573. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125574. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125575. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125576. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125577. 11.5, 12.5,
  125578. };
  125579. static long _vq_quantmap__16c2_s_p9_2[] = {
  125580. 25, 23, 21, 19, 17, 15, 13, 11,
  125581. 9, 7, 5, 3, 1, 0, 2, 4,
  125582. 6, 8, 10, 12, 14, 16, 18, 20,
  125583. 22, 24, 26,
  125584. };
  125585. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125586. _vq_quantthresh__16c2_s_p9_2,
  125587. _vq_quantmap__16c2_s_p9_2,
  125588. 27,
  125589. 27
  125590. };
  125591. static static_codebook _16c2_s_p9_2 = {
  125592. 1, 27,
  125593. _vq_lengthlist__16c2_s_p9_2,
  125594. 1, -528875520, 1611661312, 5, 0,
  125595. _vq_quantlist__16c2_s_p9_2,
  125596. NULL,
  125597. &_vq_auxt__16c2_s_p9_2,
  125598. NULL,
  125599. 0
  125600. };
  125601. static long _huff_lengthlist__16c2_s_short[] = {
  125602. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125603. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125604. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125605. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125606. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125607. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125608. 15,12,14,14,
  125609. };
  125610. static static_codebook _huff_book__16c2_s_short = {
  125611. 2, 100,
  125612. _huff_lengthlist__16c2_s_short,
  125613. 0, 0, 0, 0, 0,
  125614. NULL,
  125615. NULL,
  125616. NULL,
  125617. NULL,
  125618. 0
  125619. };
  125620. static long _vq_quantlist__8c0_s_p1_0[] = {
  125621. 1,
  125622. 0,
  125623. 2,
  125624. };
  125625. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125626. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125627. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125632. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125637. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125672. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125677. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125682. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125718. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125723. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125728. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 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,
  126037. };
  126038. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126039. -0.5, 0.5,
  126040. };
  126041. static long _vq_quantmap__8c0_s_p1_0[] = {
  126042. 1, 0, 2,
  126043. };
  126044. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126045. _vq_quantthresh__8c0_s_p1_0,
  126046. _vq_quantmap__8c0_s_p1_0,
  126047. 3,
  126048. 3
  126049. };
  126050. static static_codebook _8c0_s_p1_0 = {
  126051. 8, 6561,
  126052. _vq_lengthlist__8c0_s_p1_0,
  126053. 1, -535822336, 1611661312, 2, 0,
  126054. _vq_quantlist__8c0_s_p1_0,
  126055. NULL,
  126056. &_vq_auxt__8c0_s_p1_0,
  126057. NULL,
  126058. 0
  126059. };
  126060. static long _vq_quantlist__8c0_s_p2_0[] = {
  126061. 2,
  126062. 1,
  126063. 3,
  126064. 0,
  126065. 4,
  126066. };
  126067. static long _vq_lengthlist__8c0_s_p2_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,
  126108. };
  126109. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126110. -1.5, -0.5, 0.5, 1.5,
  126111. };
  126112. static long _vq_quantmap__8c0_s_p2_0[] = {
  126113. 3, 1, 0, 2, 4,
  126114. };
  126115. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126116. _vq_quantthresh__8c0_s_p2_0,
  126117. _vq_quantmap__8c0_s_p2_0,
  126118. 5,
  126119. 5
  126120. };
  126121. static static_codebook _8c0_s_p2_0 = {
  126122. 4, 625,
  126123. _vq_lengthlist__8c0_s_p2_0,
  126124. 1, -533725184, 1611661312, 3, 0,
  126125. _vq_quantlist__8c0_s_p2_0,
  126126. NULL,
  126127. &_vq_auxt__8c0_s_p2_0,
  126128. NULL,
  126129. 0
  126130. };
  126131. static long _vq_quantlist__8c0_s_p3_0[] = {
  126132. 2,
  126133. 1,
  126134. 3,
  126135. 0,
  126136. 4,
  126137. };
  126138. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126139. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  126179. };
  126180. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126181. -1.5, -0.5, 0.5, 1.5,
  126182. };
  126183. static long _vq_quantmap__8c0_s_p3_0[] = {
  126184. 3, 1, 0, 2, 4,
  126185. };
  126186. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126187. _vq_quantthresh__8c0_s_p3_0,
  126188. _vq_quantmap__8c0_s_p3_0,
  126189. 5,
  126190. 5
  126191. };
  126192. static static_codebook _8c0_s_p3_0 = {
  126193. 4, 625,
  126194. _vq_lengthlist__8c0_s_p3_0,
  126195. 1, -533725184, 1611661312, 3, 0,
  126196. _vq_quantlist__8c0_s_p3_0,
  126197. NULL,
  126198. &_vq_auxt__8c0_s_p3_0,
  126199. NULL,
  126200. 0
  126201. };
  126202. static long _vq_quantlist__8c0_s_p4_0[] = {
  126203. 4,
  126204. 3,
  126205. 5,
  126206. 2,
  126207. 6,
  126208. 1,
  126209. 7,
  126210. 0,
  126211. 8,
  126212. };
  126213. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126214. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126215. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126216. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126217. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126218. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0,
  126220. };
  126221. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126222. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126223. };
  126224. static long _vq_quantmap__8c0_s_p4_0[] = {
  126225. 7, 5, 3, 1, 0, 2, 4, 6,
  126226. 8,
  126227. };
  126228. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126229. _vq_quantthresh__8c0_s_p4_0,
  126230. _vq_quantmap__8c0_s_p4_0,
  126231. 9,
  126232. 9
  126233. };
  126234. static static_codebook _8c0_s_p4_0 = {
  126235. 2, 81,
  126236. _vq_lengthlist__8c0_s_p4_0,
  126237. 1, -531628032, 1611661312, 4, 0,
  126238. _vq_quantlist__8c0_s_p4_0,
  126239. NULL,
  126240. &_vq_auxt__8c0_s_p4_0,
  126241. NULL,
  126242. 0
  126243. };
  126244. static long _vq_quantlist__8c0_s_p5_0[] = {
  126245. 4,
  126246. 3,
  126247. 5,
  126248. 2,
  126249. 6,
  126250. 1,
  126251. 7,
  126252. 0,
  126253. 8,
  126254. };
  126255. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126256. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126257. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126258. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126259. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126260. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126261. 10,
  126262. };
  126263. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126264. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126265. };
  126266. static long _vq_quantmap__8c0_s_p5_0[] = {
  126267. 7, 5, 3, 1, 0, 2, 4, 6,
  126268. 8,
  126269. };
  126270. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126271. _vq_quantthresh__8c0_s_p5_0,
  126272. _vq_quantmap__8c0_s_p5_0,
  126273. 9,
  126274. 9
  126275. };
  126276. static static_codebook _8c0_s_p5_0 = {
  126277. 2, 81,
  126278. _vq_lengthlist__8c0_s_p5_0,
  126279. 1, -531628032, 1611661312, 4, 0,
  126280. _vq_quantlist__8c0_s_p5_0,
  126281. NULL,
  126282. &_vq_auxt__8c0_s_p5_0,
  126283. NULL,
  126284. 0
  126285. };
  126286. static long _vq_quantlist__8c0_s_p6_0[] = {
  126287. 8,
  126288. 7,
  126289. 9,
  126290. 6,
  126291. 10,
  126292. 5,
  126293. 11,
  126294. 4,
  126295. 12,
  126296. 3,
  126297. 13,
  126298. 2,
  126299. 14,
  126300. 1,
  126301. 15,
  126302. 0,
  126303. 16,
  126304. };
  126305. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126306. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126307. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126308. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126309. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126310. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126311. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126312. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126313. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126314. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126315. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126316. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126317. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126318. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126319. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126320. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126321. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126322. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126324. 14,
  126325. };
  126326. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126327. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126328. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126329. };
  126330. static long _vq_quantmap__8c0_s_p6_0[] = {
  126331. 15, 13, 11, 9, 7, 5, 3, 1,
  126332. 0, 2, 4, 6, 8, 10, 12, 14,
  126333. 16,
  126334. };
  126335. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126336. _vq_quantthresh__8c0_s_p6_0,
  126337. _vq_quantmap__8c0_s_p6_0,
  126338. 17,
  126339. 17
  126340. };
  126341. static static_codebook _8c0_s_p6_0 = {
  126342. 2, 289,
  126343. _vq_lengthlist__8c0_s_p6_0,
  126344. 1, -529530880, 1611661312, 5, 0,
  126345. _vq_quantlist__8c0_s_p6_0,
  126346. NULL,
  126347. &_vq_auxt__8c0_s_p6_0,
  126348. NULL,
  126349. 0
  126350. };
  126351. static long _vq_quantlist__8c0_s_p7_0[] = {
  126352. 1,
  126353. 0,
  126354. 2,
  126355. };
  126356. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126357. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126358. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126359. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126360. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126361. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126362. 10,
  126363. };
  126364. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126365. -5.5, 5.5,
  126366. };
  126367. static long _vq_quantmap__8c0_s_p7_0[] = {
  126368. 1, 0, 2,
  126369. };
  126370. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126371. _vq_quantthresh__8c0_s_p7_0,
  126372. _vq_quantmap__8c0_s_p7_0,
  126373. 3,
  126374. 3
  126375. };
  126376. static static_codebook _8c0_s_p7_0 = {
  126377. 4, 81,
  126378. _vq_lengthlist__8c0_s_p7_0,
  126379. 1, -529137664, 1618345984, 2, 0,
  126380. _vq_quantlist__8c0_s_p7_0,
  126381. NULL,
  126382. &_vq_auxt__8c0_s_p7_0,
  126383. NULL,
  126384. 0
  126385. };
  126386. static long _vq_quantlist__8c0_s_p7_1[] = {
  126387. 5,
  126388. 4,
  126389. 6,
  126390. 3,
  126391. 7,
  126392. 2,
  126393. 8,
  126394. 1,
  126395. 9,
  126396. 0,
  126397. 10,
  126398. };
  126399. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126400. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126401. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126402. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126403. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126404. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126405. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126406. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126407. 10,10,10, 9, 9, 9,10,10,10,
  126408. };
  126409. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126410. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126411. 3.5, 4.5,
  126412. };
  126413. static long _vq_quantmap__8c0_s_p7_1[] = {
  126414. 9, 7, 5, 3, 1, 0, 2, 4,
  126415. 6, 8, 10,
  126416. };
  126417. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126418. _vq_quantthresh__8c0_s_p7_1,
  126419. _vq_quantmap__8c0_s_p7_1,
  126420. 11,
  126421. 11
  126422. };
  126423. static static_codebook _8c0_s_p7_1 = {
  126424. 2, 121,
  126425. _vq_lengthlist__8c0_s_p7_1,
  126426. 1, -531365888, 1611661312, 4, 0,
  126427. _vq_quantlist__8c0_s_p7_1,
  126428. NULL,
  126429. &_vq_auxt__8c0_s_p7_1,
  126430. NULL,
  126431. 0
  126432. };
  126433. static long _vq_quantlist__8c0_s_p8_0[] = {
  126434. 6,
  126435. 5,
  126436. 7,
  126437. 4,
  126438. 8,
  126439. 3,
  126440. 9,
  126441. 2,
  126442. 10,
  126443. 1,
  126444. 11,
  126445. 0,
  126446. 12,
  126447. };
  126448. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126449. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126450. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126451. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126452. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126453. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126454. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126455. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126456. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126457. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126458. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126459. 0, 0,13,13,11,13,13,11,12,
  126460. };
  126461. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126462. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126463. 12.5, 17.5, 22.5, 27.5,
  126464. };
  126465. static long _vq_quantmap__8c0_s_p8_0[] = {
  126466. 11, 9, 7, 5, 3, 1, 0, 2,
  126467. 4, 6, 8, 10, 12,
  126468. };
  126469. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126470. _vq_quantthresh__8c0_s_p8_0,
  126471. _vq_quantmap__8c0_s_p8_0,
  126472. 13,
  126473. 13
  126474. };
  126475. static static_codebook _8c0_s_p8_0 = {
  126476. 2, 169,
  126477. _vq_lengthlist__8c0_s_p8_0,
  126478. 1, -526516224, 1616117760, 4, 0,
  126479. _vq_quantlist__8c0_s_p8_0,
  126480. NULL,
  126481. &_vq_auxt__8c0_s_p8_0,
  126482. NULL,
  126483. 0
  126484. };
  126485. static long _vq_quantlist__8c0_s_p8_1[] = {
  126486. 2,
  126487. 1,
  126488. 3,
  126489. 0,
  126490. 4,
  126491. };
  126492. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126493. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126494. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126495. };
  126496. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126497. -1.5, -0.5, 0.5, 1.5,
  126498. };
  126499. static long _vq_quantmap__8c0_s_p8_1[] = {
  126500. 3, 1, 0, 2, 4,
  126501. };
  126502. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126503. _vq_quantthresh__8c0_s_p8_1,
  126504. _vq_quantmap__8c0_s_p8_1,
  126505. 5,
  126506. 5
  126507. };
  126508. static static_codebook _8c0_s_p8_1 = {
  126509. 2, 25,
  126510. _vq_lengthlist__8c0_s_p8_1,
  126511. 1, -533725184, 1611661312, 3, 0,
  126512. _vq_quantlist__8c0_s_p8_1,
  126513. NULL,
  126514. &_vq_auxt__8c0_s_p8_1,
  126515. NULL,
  126516. 0
  126517. };
  126518. static long _vq_quantlist__8c0_s_p9_0[] = {
  126519. 1,
  126520. 0,
  126521. 2,
  126522. };
  126523. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126524. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126525. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126526. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126527. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126528. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126529. 7,
  126530. };
  126531. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126532. -157.5, 157.5,
  126533. };
  126534. static long _vq_quantmap__8c0_s_p9_0[] = {
  126535. 1, 0, 2,
  126536. };
  126537. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126538. _vq_quantthresh__8c0_s_p9_0,
  126539. _vq_quantmap__8c0_s_p9_0,
  126540. 3,
  126541. 3
  126542. };
  126543. static static_codebook _8c0_s_p9_0 = {
  126544. 4, 81,
  126545. _vq_lengthlist__8c0_s_p9_0,
  126546. 1, -518803456, 1628680192, 2, 0,
  126547. _vq_quantlist__8c0_s_p9_0,
  126548. NULL,
  126549. &_vq_auxt__8c0_s_p9_0,
  126550. NULL,
  126551. 0
  126552. };
  126553. static long _vq_quantlist__8c0_s_p9_1[] = {
  126554. 7,
  126555. 6,
  126556. 8,
  126557. 5,
  126558. 9,
  126559. 4,
  126560. 10,
  126561. 3,
  126562. 11,
  126563. 2,
  126564. 12,
  126565. 1,
  126566. 13,
  126567. 0,
  126568. 14,
  126569. };
  126570. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126571. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126572. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126573. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126574. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126575. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126576. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126579. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126580. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126581. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126584. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126585. 11,
  126586. };
  126587. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126588. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126589. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126590. };
  126591. static long _vq_quantmap__8c0_s_p9_1[] = {
  126592. 13, 11, 9, 7, 5, 3, 1, 0,
  126593. 2, 4, 6, 8, 10, 12, 14,
  126594. };
  126595. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126596. _vq_quantthresh__8c0_s_p9_1,
  126597. _vq_quantmap__8c0_s_p9_1,
  126598. 15,
  126599. 15
  126600. };
  126601. static static_codebook _8c0_s_p9_1 = {
  126602. 2, 225,
  126603. _vq_lengthlist__8c0_s_p9_1,
  126604. 1, -520986624, 1620377600, 4, 0,
  126605. _vq_quantlist__8c0_s_p9_1,
  126606. NULL,
  126607. &_vq_auxt__8c0_s_p9_1,
  126608. NULL,
  126609. 0
  126610. };
  126611. static long _vq_quantlist__8c0_s_p9_2[] = {
  126612. 10,
  126613. 9,
  126614. 11,
  126615. 8,
  126616. 12,
  126617. 7,
  126618. 13,
  126619. 6,
  126620. 14,
  126621. 5,
  126622. 15,
  126623. 4,
  126624. 16,
  126625. 3,
  126626. 17,
  126627. 2,
  126628. 18,
  126629. 1,
  126630. 19,
  126631. 0,
  126632. 20,
  126633. };
  126634. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126635. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126636. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126637. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126638. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126639. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126640. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126641. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126642. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126643. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126644. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126645. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126646. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126647. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126648. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126649. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126650. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126651. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126652. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126653. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126654. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126655. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126656. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126657. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126658. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126659. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126660. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126661. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126662. 10,11, 9,11,10, 9,10, 9,10,
  126663. };
  126664. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126665. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126666. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126667. 6.5, 7.5, 8.5, 9.5,
  126668. };
  126669. static long _vq_quantmap__8c0_s_p9_2[] = {
  126670. 19, 17, 15, 13, 11, 9, 7, 5,
  126671. 3, 1, 0, 2, 4, 6, 8, 10,
  126672. 12, 14, 16, 18, 20,
  126673. };
  126674. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126675. _vq_quantthresh__8c0_s_p9_2,
  126676. _vq_quantmap__8c0_s_p9_2,
  126677. 21,
  126678. 21
  126679. };
  126680. static static_codebook _8c0_s_p9_2 = {
  126681. 2, 441,
  126682. _vq_lengthlist__8c0_s_p9_2,
  126683. 1, -529268736, 1611661312, 5, 0,
  126684. _vq_quantlist__8c0_s_p9_2,
  126685. NULL,
  126686. &_vq_auxt__8c0_s_p9_2,
  126687. NULL,
  126688. 0
  126689. };
  126690. static long _huff_lengthlist__8c0_s_single[] = {
  126691. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126692. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126693. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126694. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126695. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126696. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126697. 17,16,17,17,
  126698. };
  126699. static static_codebook _huff_book__8c0_s_single = {
  126700. 2, 100,
  126701. _huff_lengthlist__8c0_s_single,
  126702. 0, 0, 0, 0, 0,
  126703. NULL,
  126704. NULL,
  126705. NULL,
  126706. NULL,
  126707. 0
  126708. };
  126709. static long _vq_quantlist__8c1_s_p1_0[] = {
  126710. 1,
  126711. 0,
  126712. 2,
  126713. };
  126714. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126715. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126716. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126721. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126726. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126761. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126766. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126771. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126807. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126812. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126817. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 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,
  127126. };
  127127. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127128. -0.5, 0.5,
  127129. };
  127130. static long _vq_quantmap__8c1_s_p1_0[] = {
  127131. 1, 0, 2,
  127132. };
  127133. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127134. _vq_quantthresh__8c1_s_p1_0,
  127135. _vq_quantmap__8c1_s_p1_0,
  127136. 3,
  127137. 3
  127138. };
  127139. static static_codebook _8c1_s_p1_0 = {
  127140. 8, 6561,
  127141. _vq_lengthlist__8c1_s_p1_0,
  127142. 1, -535822336, 1611661312, 2, 0,
  127143. _vq_quantlist__8c1_s_p1_0,
  127144. NULL,
  127145. &_vq_auxt__8c1_s_p1_0,
  127146. NULL,
  127147. 0
  127148. };
  127149. static long _vq_quantlist__8c1_s_p2_0[] = {
  127150. 2,
  127151. 1,
  127152. 3,
  127153. 0,
  127154. 4,
  127155. };
  127156. static long _vq_lengthlist__8c1_s_p2_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,
  127197. };
  127198. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127199. -1.5, -0.5, 0.5, 1.5,
  127200. };
  127201. static long _vq_quantmap__8c1_s_p2_0[] = {
  127202. 3, 1, 0, 2, 4,
  127203. };
  127204. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127205. _vq_quantthresh__8c1_s_p2_0,
  127206. _vq_quantmap__8c1_s_p2_0,
  127207. 5,
  127208. 5
  127209. };
  127210. static static_codebook _8c1_s_p2_0 = {
  127211. 4, 625,
  127212. _vq_lengthlist__8c1_s_p2_0,
  127213. 1, -533725184, 1611661312, 3, 0,
  127214. _vq_quantlist__8c1_s_p2_0,
  127215. NULL,
  127216. &_vq_auxt__8c1_s_p2_0,
  127217. NULL,
  127218. 0
  127219. };
  127220. static long _vq_quantlist__8c1_s_p3_0[] = {
  127221. 2,
  127222. 1,
  127223. 3,
  127224. 0,
  127225. 4,
  127226. };
  127227. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127228. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  127268. };
  127269. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127270. -1.5, -0.5, 0.5, 1.5,
  127271. };
  127272. static long _vq_quantmap__8c1_s_p3_0[] = {
  127273. 3, 1, 0, 2, 4,
  127274. };
  127275. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127276. _vq_quantthresh__8c1_s_p3_0,
  127277. _vq_quantmap__8c1_s_p3_0,
  127278. 5,
  127279. 5
  127280. };
  127281. static static_codebook _8c1_s_p3_0 = {
  127282. 4, 625,
  127283. _vq_lengthlist__8c1_s_p3_0,
  127284. 1, -533725184, 1611661312, 3, 0,
  127285. _vq_quantlist__8c1_s_p3_0,
  127286. NULL,
  127287. &_vq_auxt__8c1_s_p3_0,
  127288. NULL,
  127289. 0
  127290. };
  127291. static long _vq_quantlist__8c1_s_p4_0[] = {
  127292. 4,
  127293. 3,
  127294. 5,
  127295. 2,
  127296. 6,
  127297. 1,
  127298. 7,
  127299. 0,
  127300. 8,
  127301. };
  127302. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127303. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127304. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127305. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127306. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127307. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0,
  127309. };
  127310. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127311. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127312. };
  127313. static long _vq_quantmap__8c1_s_p4_0[] = {
  127314. 7, 5, 3, 1, 0, 2, 4, 6,
  127315. 8,
  127316. };
  127317. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127318. _vq_quantthresh__8c1_s_p4_0,
  127319. _vq_quantmap__8c1_s_p4_0,
  127320. 9,
  127321. 9
  127322. };
  127323. static static_codebook _8c1_s_p4_0 = {
  127324. 2, 81,
  127325. _vq_lengthlist__8c1_s_p4_0,
  127326. 1, -531628032, 1611661312, 4, 0,
  127327. _vq_quantlist__8c1_s_p4_0,
  127328. NULL,
  127329. &_vq_auxt__8c1_s_p4_0,
  127330. NULL,
  127331. 0
  127332. };
  127333. static long _vq_quantlist__8c1_s_p5_0[] = {
  127334. 4,
  127335. 3,
  127336. 5,
  127337. 2,
  127338. 6,
  127339. 1,
  127340. 7,
  127341. 0,
  127342. 8,
  127343. };
  127344. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127345. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127346. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127347. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127348. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127349. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127350. 10,
  127351. };
  127352. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127353. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127354. };
  127355. static long _vq_quantmap__8c1_s_p5_0[] = {
  127356. 7, 5, 3, 1, 0, 2, 4, 6,
  127357. 8,
  127358. };
  127359. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127360. _vq_quantthresh__8c1_s_p5_0,
  127361. _vq_quantmap__8c1_s_p5_0,
  127362. 9,
  127363. 9
  127364. };
  127365. static static_codebook _8c1_s_p5_0 = {
  127366. 2, 81,
  127367. _vq_lengthlist__8c1_s_p5_0,
  127368. 1, -531628032, 1611661312, 4, 0,
  127369. _vq_quantlist__8c1_s_p5_0,
  127370. NULL,
  127371. &_vq_auxt__8c1_s_p5_0,
  127372. NULL,
  127373. 0
  127374. };
  127375. static long _vq_quantlist__8c1_s_p6_0[] = {
  127376. 8,
  127377. 7,
  127378. 9,
  127379. 6,
  127380. 10,
  127381. 5,
  127382. 11,
  127383. 4,
  127384. 12,
  127385. 3,
  127386. 13,
  127387. 2,
  127388. 14,
  127389. 1,
  127390. 15,
  127391. 0,
  127392. 16,
  127393. };
  127394. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127395. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127396. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127397. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127398. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127399. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127400. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127401. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127402. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127403. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127404. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127405. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127406. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127407. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127408. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127409. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127410. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127411. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127413. 14,
  127414. };
  127415. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127416. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127417. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127418. };
  127419. static long _vq_quantmap__8c1_s_p6_0[] = {
  127420. 15, 13, 11, 9, 7, 5, 3, 1,
  127421. 0, 2, 4, 6, 8, 10, 12, 14,
  127422. 16,
  127423. };
  127424. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127425. _vq_quantthresh__8c1_s_p6_0,
  127426. _vq_quantmap__8c1_s_p6_0,
  127427. 17,
  127428. 17
  127429. };
  127430. static static_codebook _8c1_s_p6_0 = {
  127431. 2, 289,
  127432. _vq_lengthlist__8c1_s_p6_0,
  127433. 1, -529530880, 1611661312, 5, 0,
  127434. _vq_quantlist__8c1_s_p6_0,
  127435. NULL,
  127436. &_vq_auxt__8c1_s_p6_0,
  127437. NULL,
  127438. 0
  127439. };
  127440. static long _vq_quantlist__8c1_s_p7_0[] = {
  127441. 1,
  127442. 0,
  127443. 2,
  127444. };
  127445. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127446. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127447. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127448. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127449. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127450. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127451. 9,
  127452. };
  127453. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127454. -5.5, 5.5,
  127455. };
  127456. static long _vq_quantmap__8c1_s_p7_0[] = {
  127457. 1, 0, 2,
  127458. };
  127459. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127460. _vq_quantthresh__8c1_s_p7_0,
  127461. _vq_quantmap__8c1_s_p7_0,
  127462. 3,
  127463. 3
  127464. };
  127465. static static_codebook _8c1_s_p7_0 = {
  127466. 4, 81,
  127467. _vq_lengthlist__8c1_s_p7_0,
  127468. 1, -529137664, 1618345984, 2, 0,
  127469. _vq_quantlist__8c1_s_p7_0,
  127470. NULL,
  127471. &_vq_auxt__8c1_s_p7_0,
  127472. NULL,
  127473. 0
  127474. };
  127475. static long _vq_quantlist__8c1_s_p7_1[] = {
  127476. 5,
  127477. 4,
  127478. 6,
  127479. 3,
  127480. 7,
  127481. 2,
  127482. 8,
  127483. 1,
  127484. 9,
  127485. 0,
  127486. 10,
  127487. };
  127488. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127489. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127490. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127491. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127492. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127493. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127494. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127495. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127496. 10,10,10, 8, 8, 8, 8, 8, 8,
  127497. };
  127498. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127499. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127500. 3.5, 4.5,
  127501. };
  127502. static long _vq_quantmap__8c1_s_p7_1[] = {
  127503. 9, 7, 5, 3, 1, 0, 2, 4,
  127504. 6, 8, 10,
  127505. };
  127506. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127507. _vq_quantthresh__8c1_s_p7_1,
  127508. _vq_quantmap__8c1_s_p7_1,
  127509. 11,
  127510. 11
  127511. };
  127512. static static_codebook _8c1_s_p7_1 = {
  127513. 2, 121,
  127514. _vq_lengthlist__8c1_s_p7_1,
  127515. 1, -531365888, 1611661312, 4, 0,
  127516. _vq_quantlist__8c1_s_p7_1,
  127517. NULL,
  127518. &_vq_auxt__8c1_s_p7_1,
  127519. NULL,
  127520. 0
  127521. };
  127522. static long _vq_quantlist__8c1_s_p8_0[] = {
  127523. 6,
  127524. 5,
  127525. 7,
  127526. 4,
  127527. 8,
  127528. 3,
  127529. 9,
  127530. 2,
  127531. 10,
  127532. 1,
  127533. 11,
  127534. 0,
  127535. 12,
  127536. };
  127537. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127538. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127539. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127540. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127541. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127542. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127543. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127544. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127545. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127546. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127547. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127548. 0,12,12,11,10,12,11,13,12,
  127549. };
  127550. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127551. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127552. 12.5, 17.5, 22.5, 27.5,
  127553. };
  127554. static long _vq_quantmap__8c1_s_p8_0[] = {
  127555. 11, 9, 7, 5, 3, 1, 0, 2,
  127556. 4, 6, 8, 10, 12,
  127557. };
  127558. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127559. _vq_quantthresh__8c1_s_p8_0,
  127560. _vq_quantmap__8c1_s_p8_0,
  127561. 13,
  127562. 13
  127563. };
  127564. static static_codebook _8c1_s_p8_0 = {
  127565. 2, 169,
  127566. _vq_lengthlist__8c1_s_p8_0,
  127567. 1, -526516224, 1616117760, 4, 0,
  127568. _vq_quantlist__8c1_s_p8_0,
  127569. NULL,
  127570. &_vq_auxt__8c1_s_p8_0,
  127571. NULL,
  127572. 0
  127573. };
  127574. static long _vq_quantlist__8c1_s_p8_1[] = {
  127575. 2,
  127576. 1,
  127577. 3,
  127578. 0,
  127579. 4,
  127580. };
  127581. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127582. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127583. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127584. };
  127585. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127586. -1.5, -0.5, 0.5, 1.5,
  127587. };
  127588. static long _vq_quantmap__8c1_s_p8_1[] = {
  127589. 3, 1, 0, 2, 4,
  127590. };
  127591. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127592. _vq_quantthresh__8c1_s_p8_1,
  127593. _vq_quantmap__8c1_s_p8_1,
  127594. 5,
  127595. 5
  127596. };
  127597. static static_codebook _8c1_s_p8_1 = {
  127598. 2, 25,
  127599. _vq_lengthlist__8c1_s_p8_1,
  127600. 1, -533725184, 1611661312, 3, 0,
  127601. _vq_quantlist__8c1_s_p8_1,
  127602. NULL,
  127603. &_vq_auxt__8c1_s_p8_1,
  127604. NULL,
  127605. 0
  127606. };
  127607. static long _vq_quantlist__8c1_s_p9_0[] = {
  127608. 6,
  127609. 5,
  127610. 7,
  127611. 4,
  127612. 8,
  127613. 3,
  127614. 9,
  127615. 2,
  127616. 10,
  127617. 1,
  127618. 11,
  127619. 0,
  127620. 12,
  127621. };
  127622. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127623. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127624. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127629. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127632. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127633. 10,10,10,10,10, 9, 9, 9, 9,
  127634. };
  127635. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127636. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127637. 787.5, 1102.5, 1417.5, 1732.5,
  127638. };
  127639. static long _vq_quantmap__8c1_s_p9_0[] = {
  127640. 11, 9, 7, 5, 3, 1, 0, 2,
  127641. 4, 6, 8, 10, 12,
  127642. };
  127643. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127644. _vq_quantthresh__8c1_s_p9_0,
  127645. _vq_quantmap__8c1_s_p9_0,
  127646. 13,
  127647. 13
  127648. };
  127649. static static_codebook _8c1_s_p9_0 = {
  127650. 2, 169,
  127651. _vq_lengthlist__8c1_s_p9_0,
  127652. 1, -513964032, 1628680192, 4, 0,
  127653. _vq_quantlist__8c1_s_p9_0,
  127654. NULL,
  127655. &_vq_auxt__8c1_s_p9_0,
  127656. NULL,
  127657. 0
  127658. };
  127659. static long _vq_quantlist__8c1_s_p9_1[] = {
  127660. 7,
  127661. 6,
  127662. 8,
  127663. 5,
  127664. 9,
  127665. 4,
  127666. 10,
  127667. 3,
  127668. 11,
  127669. 2,
  127670. 12,
  127671. 1,
  127672. 13,
  127673. 0,
  127674. 14,
  127675. };
  127676. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127677. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127678. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127679. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127680. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127681. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127682. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127683. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127684. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127685. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127686. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127687. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127688. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127689. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127690. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127691. 15,
  127692. };
  127693. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127694. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127695. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127696. };
  127697. static long _vq_quantmap__8c1_s_p9_1[] = {
  127698. 13, 11, 9, 7, 5, 3, 1, 0,
  127699. 2, 4, 6, 8, 10, 12, 14,
  127700. };
  127701. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127702. _vq_quantthresh__8c1_s_p9_1,
  127703. _vq_quantmap__8c1_s_p9_1,
  127704. 15,
  127705. 15
  127706. };
  127707. static static_codebook _8c1_s_p9_1 = {
  127708. 2, 225,
  127709. _vq_lengthlist__8c1_s_p9_1,
  127710. 1, -520986624, 1620377600, 4, 0,
  127711. _vq_quantlist__8c1_s_p9_1,
  127712. NULL,
  127713. &_vq_auxt__8c1_s_p9_1,
  127714. NULL,
  127715. 0
  127716. };
  127717. static long _vq_quantlist__8c1_s_p9_2[] = {
  127718. 10,
  127719. 9,
  127720. 11,
  127721. 8,
  127722. 12,
  127723. 7,
  127724. 13,
  127725. 6,
  127726. 14,
  127727. 5,
  127728. 15,
  127729. 4,
  127730. 16,
  127731. 3,
  127732. 17,
  127733. 2,
  127734. 18,
  127735. 1,
  127736. 19,
  127737. 0,
  127738. 20,
  127739. };
  127740. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127741. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127742. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127743. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127744. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127745. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127746. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127747. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127748. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127749. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127750. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127751. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127752. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127753. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127754. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127755. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127756. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127757. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127758. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127759. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127760. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127761. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127762. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127763. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127764. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127765. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127766. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127767. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127768. 10,10,10,10,10,10,10,10,10,
  127769. };
  127770. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127771. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127772. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127773. 6.5, 7.5, 8.5, 9.5,
  127774. };
  127775. static long _vq_quantmap__8c1_s_p9_2[] = {
  127776. 19, 17, 15, 13, 11, 9, 7, 5,
  127777. 3, 1, 0, 2, 4, 6, 8, 10,
  127778. 12, 14, 16, 18, 20,
  127779. };
  127780. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127781. _vq_quantthresh__8c1_s_p9_2,
  127782. _vq_quantmap__8c1_s_p9_2,
  127783. 21,
  127784. 21
  127785. };
  127786. static static_codebook _8c1_s_p9_2 = {
  127787. 2, 441,
  127788. _vq_lengthlist__8c1_s_p9_2,
  127789. 1, -529268736, 1611661312, 5, 0,
  127790. _vq_quantlist__8c1_s_p9_2,
  127791. NULL,
  127792. &_vq_auxt__8c1_s_p9_2,
  127793. NULL,
  127794. 0
  127795. };
  127796. static long _huff_lengthlist__8c1_s_single[] = {
  127797. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127798. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127799. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127800. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127801. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127802. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127803. 9, 7, 7, 8,
  127804. };
  127805. static static_codebook _huff_book__8c1_s_single = {
  127806. 2, 100,
  127807. _huff_lengthlist__8c1_s_single,
  127808. 0, 0, 0, 0, 0,
  127809. NULL,
  127810. NULL,
  127811. NULL,
  127812. NULL,
  127813. 0
  127814. };
  127815. static long _huff_lengthlist__44c2_s_long[] = {
  127816. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127817. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127818. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127819. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127820. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127821. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127822. 10, 8, 8, 9,
  127823. };
  127824. static static_codebook _huff_book__44c2_s_long = {
  127825. 2, 100,
  127826. _huff_lengthlist__44c2_s_long,
  127827. 0, 0, 0, 0, 0,
  127828. NULL,
  127829. NULL,
  127830. NULL,
  127831. NULL,
  127832. 0
  127833. };
  127834. static long _vq_quantlist__44c2_s_p1_0[] = {
  127835. 1,
  127836. 0,
  127837. 2,
  127838. };
  127839. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127840. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127841. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127846. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127851. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127886. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127891. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127896. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127932. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127937. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127942. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 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,
  128251. };
  128252. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128253. -0.5, 0.5,
  128254. };
  128255. static long _vq_quantmap__44c2_s_p1_0[] = {
  128256. 1, 0, 2,
  128257. };
  128258. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128259. _vq_quantthresh__44c2_s_p1_0,
  128260. _vq_quantmap__44c2_s_p1_0,
  128261. 3,
  128262. 3
  128263. };
  128264. static static_codebook _44c2_s_p1_0 = {
  128265. 8, 6561,
  128266. _vq_lengthlist__44c2_s_p1_0,
  128267. 1, -535822336, 1611661312, 2, 0,
  128268. _vq_quantlist__44c2_s_p1_0,
  128269. NULL,
  128270. &_vq_auxt__44c2_s_p1_0,
  128271. NULL,
  128272. 0
  128273. };
  128274. static long _vq_quantlist__44c2_s_p2_0[] = {
  128275. 2,
  128276. 1,
  128277. 3,
  128278. 0,
  128279. 4,
  128280. };
  128281. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128282. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128283. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128284. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128285. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128286. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128292. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128293. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128294. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128300. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128301. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128308. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128309. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128322. };
  128323. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128324. -1.5, -0.5, 0.5, 1.5,
  128325. };
  128326. static long _vq_quantmap__44c2_s_p2_0[] = {
  128327. 3, 1, 0, 2, 4,
  128328. };
  128329. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128330. _vq_quantthresh__44c2_s_p2_0,
  128331. _vq_quantmap__44c2_s_p2_0,
  128332. 5,
  128333. 5
  128334. };
  128335. static static_codebook _44c2_s_p2_0 = {
  128336. 4, 625,
  128337. _vq_lengthlist__44c2_s_p2_0,
  128338. 1, -533725184, 1611661312, 3, 0,
  128339. _vq_quantlist__44c2_s_p2_0,
  128340. NULL,
  128341. &_vq_auxt__44c2_s_p2_0,
  128342. NULL,
  128343. 0
  128344. };
  128345. static long _vq_quantlist__44c2_s_p3_0[] = {
  128346. 2,
  128347. 1,
  128348. 3,
  128349. 0,
  128350. 4,
  128351. };
  128352. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128353. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128393. };
  128394. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128395. -1.5, -0.5, 0.5, 1.5,
  128396. };
  128397. static long _vq_quantmap__44c2_s_p3_0[] = {
  128398. 3, 1, 0, 2, 4,
  128399. };
  128400. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128401. _vq_quantthresh__44c2_s_p3_0,
  128402. _vq_quantmap__44c2_s_p3_0,
  128403. 5,
  128404. 5
  128405. };
  128406. static static_codebook _44c2_s_p3_0 = {
  128407. 4, 625,
  128408. _vq_lengthlist__44c2_s_p3_0,
  128409. 1, -533725184, 1611661312, 3, 0,
  128410. _vq_quantlist__44c2_s_p3_0,
  128411. NULL,
  128412. &_vq_auxt__44c2_s_p3_0,
  128413. NULL,
  128414. 0
  128415. };
  128416. static long _vq_quantlist__44c2_s_p4_0[] = {
  128417. 4,
  128418. 3,
  128419. 5,
  128420. 2,
  128421. 6,
  128422. 1,
  128423. 7,
  128424. 0,
  128425. 8,
  128426. };
  128427. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128428. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128429. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128430. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128431. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128432. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0,
  128434. };
  128435. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128436. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128437. };
  128438. static long _vq_quantmap__44c2_s_p4_0[] = {
  128439. 7, 5, 3, 1, 0, 2, 4, 6,
  128440. 8,
  128441. };
  128442. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128443. _vq_quantthresh__44c2_s_p4_0,
  128444. _vq_quantmap__44c2_s_p4_0,
  128445. 9,
  128446. 9
  128447. };
  128448. static static_codebook _44c2_s_p4_0 = {
  128449. 2, 81,
  128450. _vq_lengthlist__44c2_s_p4_0,
  128451. 1, -531628032, 1611661312, 4, 0,
  128452. _vq_quantlist__44c2_s_p4_0,
  128453. NULL,
  128454. &_vq_auxt__44c2_s_p4_0,
  128455. NULL,
  128456. 0
  128457. };
  128458. static long _vq_quantlist__44c2_s_p5_0[] = {
  128459. 4,
  128460. 3,
  128461. 5,
  128462. 2,
  128463. 6,
  128464. 1,
  128465. 7,
  128466. 0,
  128467. 8,
  128468. };
  128469. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128470. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128471. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128472. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128473. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128474. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128475. 11,
  128476. };
  128477. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128478. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128479. };
  128480. static long _vq_quantmap__44c2_s_p5_0[] = {
  128481. 7, 5, 3, 1, 0, 2, 4, 6,
  128482. 8,
  128483. };
  128484. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128485. _vq_quantthresh__44c2_s_p5_0,
  128486. _vq_quantmap__44c2_s_p5_0,
  128487. 9,
  128488. 9
  128489. };
  128490. static static_codebook _44c2_s_p5_0 = {
  128491. 2, 81,
  128492. _vq_lengthlist__44c2_s_p5_0,
  128493. 1, -531628032, 1611661312, 4, 0,
  128494. _vq_quantlist__44c2_s_p5_0,
  128495. NULL,
  128496. &_vq_auxt__44c2_s_p5_0,
  128497. NULL,
  128498. 0
  128499. };
  128500. static long _vq_quantlist__44c2_s_p6_0[] = {
  128501. 8,
  128502. 7,
  128503. 9,
  128504. 6,
  128505. 10,
  128506. 5,
  128507. 11,
  128508. 4,
  128509. 12,
  128510. 3,
  128511. 13,
  128512. 2,
  128513. 14,
  128514. 1,
  128515. 15,
  128516. 0,
  128517. 16,
  128518. };
  128519. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128520. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128521. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128522. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128523. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128524. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128525. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128526. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128527. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128528. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128529. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128530. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128531. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128532. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128533. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128534. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128535. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128536. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128538. 14,
  128539. };
  128540. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128541. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128542. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128543. };
  128544. static long _vq_quantmap__44c2_s_p6_0[] = {
  128545. 15, 13, 11, 9, 7, 5, 3, 1,
  128546. 0, 2, 4, 6, 8, 10, 12, 14,
  128547. 16,
  128548. };
  128549. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128550. _vq_quantthresh__44c2_s_p6_0,
  128551. _vq_quantmap__44c2_s_p6_0,
  128552. 17,
  128553. 17
  128554. };
  128555. static static_codebook _44c2_s_p6_0 = {
  128556. 2, 289,
  128557. _vq_lengthlist__44c2_s_p6_0,
  128558. 1, -529530880, 1611661312, 5, 0,
  128559. _vq_quantlist__44c2_s_p6_0,
  128560. NULL,
  128561. &_vq_auxt__44c2_s_p6_0,
  128562. NULL,
  128563. 0
  128564. };
  128565. static long _vq_quantlist__44c2_s_p7_0[] = {
  128566. 1,
  128567. 0,
  128568. 2,
  128569. };
  128570. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128571. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128572. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128573. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128574. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128575. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128576. 11,
  128577. };
  128578. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128579. -5.5, 5.5,
  128580. };
  128581. static long _vq_quantmap__44c2_s_p7_0[] = {
  128582. 1, 0, 2,
  128583. };
  128584. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128585. _vq_quantthresh__44c2_s_p7_0,
  128586. _vq_quantmap__44c2_s_p7_0,
  128587. 3,
  128588. 3
  128589. };
  128590. static static_codebook _44c2_s_p7_0 = {
  128591. 4, 81,
  128592. _vq_lengthlist__44c2_s_p7_0,
  128593. 1, -529137664, 1618345984, 2, 0,
  128594. _vq_quantlist__44c2_s_p7_0,
  128595. NULL,
  128596. &_vq_auxt__44c2_s_p7_0,
  128597. NULL,
  128598. 0
  128599. };
  128600. static long _vq_quantlist__44c2_s_p7_1[] = {
  128601. 5,
  128602. 4,
  128603. 6,
  128604. 3,
  128605. 7,
  128606. 2,
  128607. 8,
  128608. 1,
  128609. 9,
  128610. 0,
  128611. 10,
  128612. };
  128613. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128614. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128615. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128616. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128617. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128618. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128619. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128620. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128621. 10,10,10, 8, 8, 8, 8, 8, 8,
  128622. };
  128623. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128624. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128625. 3.5, 4.5,
  128626. };
  128627. static long _vq_quantmap__44c2_s_p7_1[] = {
  128628. 9, 7, 5, 3, 1, 0, 2, 4,
  128629. 6, 8, 10,
  128630. };
  128631. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128632. _vq_quantthresh__44c2_s_p7_1,
  128633. _vq_quantmap__44c2_s_p7_1,
  128634. 11,
  128635. 11
  128636. };
  128637. static static_codebook _44c2_s_p7_1 = {
  128638. 2, 121,
  128639. _vq_lengthlist__44c2_s_p7_1,
  128640. 1, -531365888, 1611661312, 4, 0,
  128641. _vq_quantlist__44c2_s_p7_1,
  128642. NULL,
  128643. &_vq_auxt__44c2_s_p7_1,
  128644. NULL,
  128645. 0
  128646. };
  128647. static long _vq_quantlist__44c2_s_p8_0[] = {
  128648. 6,
  128649. 5,
  128650. 7,
  128651. 4,
  128652. 8,
  128653. 3,
  128654. 9,
  128655. 2,
  128656. 10,
  128657. 1,
  128658. 11,
  128659. 0,
  128660. 12,
  128661. };
  128662. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128663. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128664. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128665. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128666. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128667. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128668. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128669. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128670. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128671. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128672. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128673. 0,12,12,12,12,13,12,14,14,
  128674. };
  128675. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128676. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128677. 12.5, 17.5, 22.5, 27.5,
  128678. };
  128679. static long _vq_quantmap__44c2_s_p8_0[] = {
  128680. 11, 9, 7, 5, 3, 1, 0, 2,
  128681. 4, 6, 8, 10, 12,
  128682. };
  128683. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128684. _vq_quantthresh__44c2_s_p8_0,
  128685. _vq_quantmap__44c2_s_p8_0,
  128686. 13,
  128687. 13
  128688. };
  128689. static static_codebook _44c2_s_p8_0 = {
  128690. 2, 169,
  128691. _vq_lengthlist__44c2_s_p8_0,
  128692. 1, -526516224, 1616117760, 4, 0,
  128693. _vq_quantlist__44c2_s_p8_0,
  128694. NULL,
  128695. &_vq_auxt__44c2_s_p8_0,
  128696. NULL,
  128697. 0
  128698. };
  128699. static long _vq_quantlist__44c2_s_p8_1[] = {
  128700. 2,
  128701. 1,
  128702. 3,
  128703. 0,
  128704. 4,
  128705. };
  128706. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128707. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128708. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128709. };
  128710. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128711. -1.5, -0.5, 0.5, 1.5,
  128712. };
  128713. static long _vq_quantmap__44c2_s_p8_1[] = {
  128714. 3, 1, 0, 2, 4,
  128715. };
  128716. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128717. _vq_quantthresh__44c2_s_p8_1,
  128718. _vq_quantmap__44c2_s_p8_1,
  128719. 5,
  128720. 5
  128721. };
  128722. static static_codebook _44c2_s_p8_1 = {
  128723. 2, 25,
  128724. _vq_lengthlist__44c2_s_p8_1,
  128725. 1, -533725184, 1611661312, 3, 0,
  128726. _vq_quantlist__44c2_s_p8_1,
  128727. NULL,
  128728. &_vq_auxt__44c2_s_p8_1,
  128729. NULL,
  128730. 0
  128731. };
  128732. static long _vq_quantlist__44c2_s_p9_0[] = {
  128733. 6,
  128734. 5,
  128735. 7,
  128736. 4,
  128737. 8,
  128738. 3,
  128739. 9,
  128740. 2,
  128741. 10,
  128742. 1,
  128743. 11,
  128744. 0,
  128745. 12,
  128746. };
  128747. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128748. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128749. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128751. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128758. 11,11,11,11,11,11,11,11,11,
  128759. };
  128760. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128761. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128762. 552.5, 773.5, 994.5, 1215.5,
  128763. };
  128764. static long _vq_quantmap__44c2_s_p9_0[] = {
  128765. 11, 9, 7, 5, 3, 1, 0, 2,
  128766. 4, 6, 8, 10, 12,
  128767. };
  128768. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128769. _vq_quantthresh__44c2_s_p9_0,
  128770. _vq_quantmap__44c2_s_p9_0,
  128771. 13,
  128772. 13
  128773. };
  128774. static static_codebook _44c2_s_p9_0 = {
  128775. 2, 169,
  128776. _vq_lengthlist__44c2_s_p9_0,
  128777. 1, -514541568, 1627103232, 4, 0,
  128778. _vq_quantlist__44c2_s_p9_0,
  128779. NULL,
  128780. &_vq_auxt__44c2_s_p9_0,
  128781. NULL,
  128782. 0
  128783. };
  128784. static long _vq_quantlist__44c2_s_p9_1[] = {
  128785. 6,
  128786. 5,
  128787. 7,
  128788. 4,
  128789. 8,
  128790. 3,
  128791. 9,
  128792. 2,
  128793. 10,
  128794. 1,
  128795. 11,
  128796. 0,
  128797. 12,
  128798. };
  128799. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128800. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128801. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128802. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128803. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128804. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128805. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128806. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128807. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128808. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128809. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128810. 17,13,12,12,10,13,11,14,14,
  128811. };
  128812. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128813. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128814. 42.5, 59.5, 76.5, 93.5,
  128815. };
  128816. static long _vq_quantmap__44c2_s_p9_1[] = {
  128817. 11, 9, 7, 5, 3, 1, 0, 2,
  128818. 4, 6, 8, 10, 12,
  128819. };
  128820. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128821. _vq_quantthresh__44c2_s_p9_1,
  128822. _vq_quantmap__44c2_s_p9_1,
  128823. 13,
  128824. 13
  128825. };
  128826. static static_codebook _44c2_s_p9_1 = {
  128827. 2, 169,
  128828. _vq_lengthlist__44c2_s_p9_1,
  128829. 1, -522616832, 1620115456, 4, 0,
  128830. _vq_quantlist__44c2_s_p9_1,
  128831. NULL,
  128832. &_vq_auxt__44c2_s_p9_1,
  128833. NULL,
  128834. 0
  128835. };
  128836. static long _vq_quantlist__44c2_s_p9_2[] = {
  128837. 8,
  128838. 7,
  128839. 9,
  128840. 6,
  128841. 10,
  128842. 5,
  128843. 11,
  128844. 4,
  128845. 12,
  128846. 3,
  128847. 13,
  128848. 2,
  128849. 14,
  128850. 1,
  128851. 15,
  128852. 0,
  128853. 16,
  128854. };
  128855. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128856. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128857. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128858. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128859. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128860. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128861. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128862. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128863. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128864. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128865. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128866. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128867. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128868. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128869. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128870. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128871. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128872. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128873. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128874. 10,
  128875. };
  128876. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128877. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128878. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128879. };
  128880. static long _vq_quantmap__44c2_s_p9_2[] = {
  128881. 15, 13, 11, 9, 7, 5, 3, 1,
  128882. 0, 2, 4, 6, 8, 10, 12, 14,
  128883. 16,
  128884. };
  128885. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128886. _vq_quantthresh__44c2_s_p9_2,
  128887. _vq_quantmap__44c2_s_p9_2,
  128888. 17,
  128889. 17
  128890. };
  128891. static static_codebook _44c2_s_p9_2 = {
  128892. 2, 289,
  128893. _vq_lengthlist__44c2_s_p9_2,
  128894. 1, -529530880, 1611661312, 5, 0,
  128895. _vq_quantlist__44c2_s_p9_2,
  128896. NULL,
  128897. &_vq_auxt__44c2_s_p9_2,
  128898. NULL,
  128899. 0
  128900. };
  128901. static long _huff_lengthlist__44c2_s_short[] = {
  128902. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128903. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128904. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128905. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128906. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128907. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128908. 6, 8, 9,12,
  128909. };
  128910. static static_codebook _huff_book__44c2_s_short = {
  128911. 2, 100,
  128912. _huff_lengthlist__44c2_s_short,
  128913. 0, 0, 0, 0, 0,
  128914. NULL,
  128915. NULL,
  128916. NULL,
  128917. NULL,
  128918. 0
  128919. };
  128920. static long _huff_lengthlist__44c3_s_long[] = {
  128921. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128922. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128923. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128924. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128925. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128926. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128927. 9, 8, 8, 8,
  128928. };
  128929. static static_codebook _huff_book__44c3_s_long = {
  128930. 2, 100,
  128931. _huff_lengthlist__44c3_s_long,
  128932. 0, 0, 0, 0, 0,
  128933. NULL,
  128934. NULL,
  128935. NULL,
  128936. NULL,
  128937. 0
  128938. };
  128939. static long _vq_quantlist__44c3_s_p1_0[] = {
  128940. 1,
  128941. 0,
  128942. 2,
  128943. };
  128944. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128945. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128946. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128951. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128956. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128991. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128996. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129001. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129037. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129042. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129047. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 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,
  129356. };
  129357. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129358. -0.5, 0.5,
  129359. };
  129360. static long _vq_quantmap__44c3_s_p1_0[] = {
  129361. 1, 0, 2,
  129362. };
  129363. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129364. _vq_quantthresh__44c3_s_p1_0,
  129365. _vq_quantmap__44c3_s_p1_0,
  129366. 3,
  129367. 3
  129368. };
  129369. static static_codebook _44c3_s_p1_0 = {
  129370. 8, 6561,
  129371. _vq_lengthlist__44c3_s_p1_0,
  129372. 1, -535822336, 1611661312, 2, 0,
  129373. _vq_quantlist__44c3_s_p1_0,
  129374. NULL,
  129375. &_vq_auxt__44c3_s_p1_0,
  129376. NULL,
  129377. 0
  129378. };
  129379. static long _vq_quantlist__44c3_s_p2_0[] = {
  129380. 2,
  129381. 1,
  129382. 3,
  129383. 0,
  129384. 4,
  129385. };
  129386. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129387. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129388. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129389. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129390. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129391. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129397. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129398. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129399. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129405. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129406. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129413. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129414. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129427. };
  129428. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129429. -1.5, -0.5, 0.5, 1.5,
  129430. };
  129431. static long _vq_quantmap__44c3_s_p2_0[] = {
  129432. 3, 1, 0, 2, 4,
  129433. };
  129434. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129435. _vq_quantthresh__44c3_s_p2_0,
  129436. _vq_quantmap__44c3_s_p2_0,
  129437. 5,
  129438. 5
  129439. };
  129440. static static_codebook _44c3_s_p2_0 = {
  129441. 4, 625,
  129442. _vq_lengthlist__44c3_s_p2_0,
  129443. 1, -533725184, 1611661312, 3, 0,
  129444. _vq_quantlist__44c3_s_p2_0,
  129445. NULL,
  129446. &_vq_auxt__44c3_s_p2_0,
  129447. NULL,
  129448. 0
  129449. };
  129450. static long _vq_quantlist__44c3_s_p3_0[] = {
  129451. 2,
  129452. 1,
  129453. 3,
  129454. 0,
  129455. 4,
  129456. };
  129457. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129458. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129498. };
  129499. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129500. -1.5, -0.5, 0.5, 1.5,
  129501. };
  129502. static long _vq_quantmap__44c3_s_p3_0[] = {
  129503. 3, 1, 0, 2, 4,
  129504. };
  129505. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129506. _vq_quantthresh__44c3_s_p3_0,
  129507. _vq_quantmap__44c3_s_p3_0,
  129508. 5,
  129509. 5
  129510. };
  129511. static static_codebook _44c3_s_p3_0 = {
  129512. 4, 625,
  129513. _vq_lengthlist__44c3_s_p3_0,
  129514. 1, -533725184, 1611661312, 3, 0,
  129515. _vq_quantlist__44c3_s_p3_0,
  129516. NULL,
  129517. &_vq_auxt__44c3_s_p3_0,
  129518. NULL,
  129519. 0
  129520. };
  129521. static long _vq_quantlist__44c3_s_p4_0[] = {
  129522. 4,
  129523. 3,
  129524. 5,
  129525. 2,
  129526. 6,
  129527. 1,
  129528. 7,
  129529. 0,
  129530. 8,
  129531. };
  129532. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129533. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129534. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129535. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129536. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129537. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0,
  129539. };
  129540. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129541. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129542. };
  129543. static long _vq_quantmap__44c3_s_p4_0[] = {
  129544. 7, 5, 3, 1, 0, 2, 4, 6,
  129545. 8,
  129546. };
  129547. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129548. _vq_quantthresh__44c3_s_p4_0,
  129549. _vq_quantmap__44c3_s_p4_0,
  129550. 9,
  129551. 9
  129552. };
  129553. static static_codebook _44c3_s_p4_0 = {
  129554. 2, 81,
  129555. _vq_lengthlist__44c3_s_p4_0,
  129556. 1, -531628032, 1611661312, 4, 0,
  129557. _vq_quantlist__44c3_s_p4_0,
  129558. NULL,
  129559. &_vq_auxt__44c3_s_p4_0,
  129560. NULL,
  129561. 0
  129562. };
  129563. static long _vq_quantlist__44c3_s_p5_0[] = {
  129564. 4,
  129565. 3,
  129566. 5,
  129567. 2,
  129568. 6,
  129569. 1,
  129570. 7,
  129571. 0,
  129572. 8,
  129573. };
  129574. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129575. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129576. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129577. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129578. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129579. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129580. 11,
  129581. };
  129582. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129583. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129584. };
  129585. static long _vq_quantmap__44c3_s_p5_0[] = {
  129586. 7, 5, 3, 1, 0, 2, 4, 6,
  129587. 8,
  129588. };
  129589. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129590. _vq_quantthresh__44c3_s_p5_0,
  129591. _vq_quantmap__44c3_s_p5_0,
  129592. 9,
  129593. 9
  129594. };
  129595. static static_codebook _44c3_s_p5_0 = {
  129596. 2, 81,
  129597. _vq_lengthlist__44c3_s_p5_0,
  129598. 1, -531628032, 1611661312, 4, 0,
  129599. _vq_quantlist__44c3_s_p5_0,
  129600. NULL,
  129601. &_vq_auxt__44c3_s_p5_0,
  129602. NULL,
  129603. 0
  129604. };
  129605. static long _vq_quantlist__44c3_s_p6_0[] = {
  129606. 8,
  129607. 7,
  129608. 9,
  129609. 6,
  129610. 10,
  129611. 5,
  129612. 11,
  129613. 4,
  129614. 12,
  129615. 3,
  129616. 13,
  129617. 2,
  129618. 14,
  129619. 1,
  129620. 15,
  129621. 0,
  129622. 16,
  129623. };
  129624. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129625. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129626. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129627. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129628. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129629. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129630. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129631. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129632. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129633. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129634. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129635. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129636. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129637. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129638. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129639. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129640. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129641. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129643. 13,
  129644. };
  129645. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129646. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129647. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129648. };
  129649. static long _vq_quantmap__44c3_s_p6_0[] = {
  129650. 15, 13, 11, 9, 7, 5, 3, 1,
  129651. 0, 2, 4, 6, 8, 10, 12, 14,
  129652. 16,
  129653. };
  129654. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129655. _vq_quantthresh__44c3_s_p6_0,
  129656. _vq_quantmap__44c3_s_p6_0,
  129657. 17,
  129658. 17
  129659. };
  129660. static static_codebook _44c3_s_p6_0 = {
  129661. 2, 289,
  129662. _vq_lengthlist__44c3_s_p6_0,
  129663. 1, -529530880, 1611661312, 5, 0,
  129664. _vq_quantlist__44c3_s_p6_0,
  129665. NULL,
  129666. &_vq_auxt__44c3_s_p6_0,
  129667. NULL,
  129668. 0
  129669. };
  129670. static long _vq_quantlist__44c3_s_p7_0[] = {
  129671. 1,
  129672. 0,
  129673. 2,
  129674. };
  129675. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129676. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129677. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129678. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129679. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129680. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129681. 10,
  129682. };
  129683. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129684. -5.5, 5.5,
  129685. };
  129686. static long _vq_quantmap__44c3_s_p7_0[] = {
  129687. 1, 0, 2,
  129688. };
  129689. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129690. _vq_quantthresh__44c3_s_p7_0,
  129691. _vq_quantmap__44c3_s_p7_0,
  129692. 3,
  129693. 3
  129694. };
  129695. static static_codebook _44c3_s_p7_0 = {
  129696. 4, 81,
  129697. _vq_lengthlist__44c3_s_p7_0,
  129698. 1, -529137664, 1618345984, 2, 0,
  129699. _vq_quantlist__44c3_s_p7_0,
  129700. NULL,
  129701. &_vq_auxt__44c3_s_p7_0,
  129702. NULL,
  129703. 0
  129704. };
  129705. static long _vq_quantlist__44c3_s_p7_1[] = {
  129706. 5,
  129707. 4,
  129708. 6,
  129709. 3,
  129710. 7,
  129711. 2,
  129712. 8,
  129713. 1,
  129714. 9,
  129715. 0,
  129716. 10,
  129717. };
  129718. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129719. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129720. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129721. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129722. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129723. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129724. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129725. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129726. 10,10,10, 8, 8, 8, 8, 8, 8,
  129727. };
  129728. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129729. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129730. 3.5, 4.5,
  129731. };
  129732. static long _vq_quantmap__44c3_s_p7_1[] = {
  129733. 9, 7, 5, 3, 1, 0, 2, 4,
  129734. 6, 8, 10,
  129735. };
  129736. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129737. _vq_quantthresh__44c3_s_p7_1,
  129738. _vq_quantmap__44c3_s_p7_1,
  129739. 11,
  129740. 11
  129741. };
  129742. static static_codebook _44c3_s_p7_1 = {
  129743. 2, 121,
  129744. _vq_lengthlist__44c3_s_p7_1,
  129745. 1, -531365888, 1611661312, 4, 0,
  129746. _vq_quantlist__44c3_s_p7_1,
  129747. NULL,
  129748. &_vq_auxt__44c3_s_p7_1,
  129749. NULL,
  129750. 0
  129751. };
  129752. static long _vq_quantlist__44c3_s_p8_0[] = {
  129753. 6,
  129754. 5,
  129755. 7,
  129756. 4,
  129757. 8,
  129758. 3,
  129759. 9,
  129760. 2,
  129761. 10,
  129762. 1,
  129763. 11,
  129764. 0,
  129765. 12,
  129766. };
  129767. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129768. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129769. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129770. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129771. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129772. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129773. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129774. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129775. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129776. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129777. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129778. 0,13,13,12,12,13,12,14,13,
  129779. };
  129780. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129781. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129782. 12.5, 17.5, 22.5, 27.5,
  129783. };
  129784. static long _vq_quantmap__44c3_s_p8_0[] = {
  129785. 11, 9, 7, 5, 3, 1, 0, 2,
  129786. 4, 6, 8, 10, 12,
  129787. };
  129788. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129789. _vq_quantthresh__44c3_s_p8_0,
  129790. _vq_quantmap__44c3_s_p8_0,
  129791. 13,
  129792. 13
  129793. };
  129794. static static_codebook _44c3_s_p8_0 = {
  129795. 2, 169,
  129796. _vq_lengthlist__44c3_s_p8_0,
  129797. 1, -526516224, 1616117760, 4, 0,
  129798. _vq_quantlist__44c3_s_p8_0,
  129799. NULL,
  129800. &_vq_auxt__44c3_s_p8_0,
  129801. NULL,
  129802. 0
  129803. };
  129804. static long _vq_quantlist__44c3_s_p8_1[] = {
  129805. 2,
  129806. 1,
  129807. 3,
  129808. 0,
  129809. 4,
  129810. };
  129811. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129812. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129813. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129814. };
  129815. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129816. -1.5, -0.5, 0.5, 1.5,
  129817. };
  129818. static long _vq_quantmap__44c3_s_p8_1[] = {
  129819. 3, 1, 0, 2, 4,
  129820. };
  129821. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129822. _vq_quantthresh__44c3_s_p8_1,
  129823. _vq_quantmap__44c3_s_p8_1,
  129824. 5,
  129825. 5
  129826. };
  129827. static static_codebook _44c3_s_p8_1 = {
  129828. 2, 25,
  129829. _vq_lengthlist__44c3_s_p8_1,
  129830. 1, -533725184, 1611661312, 3, 0,
  129831. _vq_quantlist__44c3_s_p8_1,
  129832. NULL,
  129833. &_vq_auxt__44c3_s_p8_1,
  129834. NULL,
  129835. 0
  129836. };
  129837. static long _vq_quantlist__44c3_s_p9_0[] = {
  129838. 6,
  129839. 5,
  129840. 7,
  129841. 4,
  129842. 8,
  129843. 3,
  129844. 9,
  129845. 2,
  129846. 10,
  129847. 1,
  129848. 11,
  129849. 0,
  129850. 12,
  129851. };
  129852. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129853. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129854. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129855. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129856. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129857. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129858. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129859. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129860. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129861. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129863. 11,11,11,11,11,11,11,11,11,
  129864. };
  129865. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129866. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129867. 637.5, 892.5, 1147.5, 1402.5,
  129868. };
  129869. static long _vq_quantmap__44c3_s_p9_0[] = {
  129870. 11, 9, 7, 5, 3, 1, 0, 2,
  129871. 4, 6, 8, 10, 12,
  129872. };
  129873. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129874. _vq_quantthresh__44c3_s_p9_0,
  129875. _vq_quantmap__44c3_s_p9_0,
  129876. 13,
  129877. 13
  129878. };
  129879. static static_codebook _44c3_s_p9_0 = {
  129880. 2, 169,
  129881. _vq_lengthlist__44c3_s_p9_0,
  129882. 1, -514332672, 1627381760, 4, 0,
  129883. _vq_quantlist__44c3_s_p9_0,
  129884. NULL,
  129885. &_vq_auxt__44c3_s_p9_0,
  129886. NULL,
  129887. 0
  129888. };
  129889. static long _vq_quantlist__44c3_s_p9_1[] = {
  129890. 7,
  129891. 6,
  129892. 8,
  129893. 5,
  129894. 9,
  129895. 4,
  129896. 10,
  129897. 3,
  129898. 11,
  129899. 2,
  129900. 12,
  129901. 1,
  129902. 13,
  129903. 0,
  129904. 14,
  129905. };
  129906. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129907. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129908. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129909. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129910. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129911. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129912. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129913. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129914. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129915. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129916. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129917. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129918. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129919. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129920. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129921. 15,
  129922. };
  129923. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129924. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129925. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129926. };
  129927. static long _vq_quantmap__44c3_s_p9_1[] = {
  129928. 13, 11, 9, 7, 5, 3, 1, 0,
  129929. 2, 4, 6, 8, 10, 12, 14,
  129930. };
  129931. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129932. _vq_quantthresh__44c3_s_p9_1,
  129933. _vq_quantmap__44c3_s_p9_1,
  129934. 15,
  129935. 15
  129936. };
  129937. static static_codebook _44c3_s_p9_1 = {
  129938. 2, 225,
  129939. _vq_lengthlist__44c3_s_p9_1,
  129940. 1, -522338304, 1620115456, 4, 0,
  129941. _vq_quantlist__44c3_s_p9_1,
  129942. NULL,
  129943. &_vq_auxt__44c3_s_p9_1,
  129944. NULL,
  129945. 0
  129946. };
  129947. static long _vq_quantlist__44c3_s_p9_2[] = {
  129948. 8,
  129949. 7,
  129950. 9,
  129951. 6,
  129952. 10,
  129953. 5,
  129954. 11,
  129955. 4,
  129956. 12,
  129957. 3,
  129958. 13,
  129959. 2,
  129960. 14,
  129961. 1,
  129962. 15,
  129963. 0,
  129964. 16,
  129965. };
  129966. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129967. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129968. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129969. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129970. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129971. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129972. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129973. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129974. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129975. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129976. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129977. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129978. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129979. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129980. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129981. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129982. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129983. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129984. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129985. 10,
  129986. };
  129987. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129988. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129989. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129990. };
  129991. static long _vq_quantmap__44c3_s_p9_2[] = {
  129992. 15, 13, 11, 9, 7, 5, 3, 1,
  129993. 0, 2, 4, 6, 8, 10, 12, 14,
  129994. 16,
  129995. };
  129996. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129997. _vq_quantthresh__44c3_s_p9_2,
  129998. _vq_quantmap__44c3_s_p9_2,
  129999. 17,
  130000. 17
  130001. };
  130002. static static_codebook _44c3_s_p9_2 = {
  130003. 2, 289,
  130004. _vq_lengthlist__44c3_s_p9_2,
  130005. 1, -529530880, 1611661312, 5, 0,
  130006. _vq_quantlist__44c3_s_p9_2,
  130007. NULL,
  130008. &_vq_auxt__44c3_s_p9_2,
  130009. NULL,
  130010. 0
  130011. };
  130012. static long _huff_lengthlist__44c3_s_short[] = {
  130013. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130014. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130015. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130016. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130017. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130018. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130019. 6, 8, 9,11,
  130020. };
  130021. static static_codebook _huff_book__44c3_s_short = {
  130022. 2, 100,
  130023. _huff_lengthlist__44c3_s_short,
  130024. 0, 0, 0, 0, 0,
  130025. NULL,
  130026. NULL,
  130027. NULL,
  130028. NULL,
  130029. 0
  130030. };
  130031. static long _huff_lengthlist__44c4_s_long[] = {
  130032. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130033. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130034. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130035. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130036. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130037. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130038. 9, 8, 7, 7,
  130039. };
  130040. static static_codebook _huff_book__44c4_s_long = {
  130041. 2, 100,
  130042. _huff_lengthlist__44c4_s_long,
  130043. 0, 0, 0, 0, 0,
  130044. NULL,
  130045. NULL,
  130046. NULL,
  130047. NULL,
  130048. 0
  130049. };
  130050. static long _vq_quantlist__44c4_s_p1_0[] = {
  130051. 1,
  130052. 0,
  130053. 2,
  130054. };
  130055. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130056. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130057. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130062. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130067. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130102. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130107. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130112. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130148. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130153. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130158. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 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,
  130467. };
  130468. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130469. -0.5, 0.5,
  130470. };
  130471. static long _vq_quantmap__44c4_s_p1_0[] = {
  130472. 1, 0, 2,
  130473. };
  130474. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130475. _vq_quantthresh__44c4_s_p1_0,
  130476. _vq_quantmap__44c4_s_p1_0,
  130477. 3,
  130478. 3
  130479. };
  130480. static static_codebook _44c4_s_p1_0 = {
  130481. 8, 6561,
  130482. _vq_lengthlist__44c4_s_p1_0,
  130483. 1, -535822336, 1611661312, 2, 0,
  130484. _vq_quantlist__44c4_s_p1_0,
  130485. NULL,
  130486. &_vq_auxt__44c4_s_p1_0,
  130487. NULL,
  130488. 0
  130489. };
  130490. static long _vq_quantlist__44c4_s_p2_0[] = {
  130491. 2,
  130492. 1,
  130493. 3,
  130494. 0,
  130495. 4,
  130496. };
  130497. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130498. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130499. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130500. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130501. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130502. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130508. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130509. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130510. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130516. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130517. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130524. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130525. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130538. };
  130539. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130540. -1.5, -0.5, 0.5, 1.5,
  130541. };
  130542. static long _vq_quantmap__44c4_s_p2_0[] = {
  130543. 3, 1, 0, 2, 4,
  130544. };
  130545. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130546. _vq_quantthresh__44c4_s_p2_0,
  130547. _vq_quantmap__44c4_s_p2_0,
  130548. 5,
  130549. 5
  130550. };
  130551. static static_codebook _44c4_s_p2_0 = {
  130552. 4, 625,
  130553. _vq_lengthlist__44c4_s_p2_0,
  130554. 1, -533725184, 1611661312, 3, 0,
  130555. _vq_quantlist__44c4_s_p2_0,
  130556. NULL,
  130557. &_vq_auxt__44c4_s_p2_0,
  130558. NULL,
  130559. 0
  130560. };
  130561. static long _vq_quantlist__44c4_s_p3_0[] = {
  130562. 2,
  130563. 1,
  130564. 3,
  130565. 0,
  130566. 4,
  130567. };
  130568. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130569. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130609. };
  130610. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130611. -1.5, -0.5, 0.5, 1.5,
  130612. };
  130613. static long _vq_quantmap__44c4_s_p3_0[] = {
  130614. 3, 1, 0, 2, 4,
  130615. };
  130616. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130617. _vq_quantthresh__44c4_s_p3_0,
  130618. _vq_quantmap__44c4_s_p3_0,
  130619. 5,
  130620. 5
  130621. };
  130622. static static_codebook _44c4_s_p3_0 = {
  130623. 4, 625,
  130624. _vq_lengthlist__44c4_s_p3_0,
  130625. 1, -533725184, 1611661312, 3, 0,
  130626. _vq_quantlist__44c4_s_p3_0,
  130627. NULL,
  130628. &_vq_auxt__44c4_s_p3_0,
  130629. NULL,
  130630. 0
  130631. };
  130632. static long _vq_quantlist__44c4_s_p4_0[] = {
  130633. 4,
  130634. 3,
  130635. 5,
  130636. 2,
  130637. 6,
  130638. 1,
  130639. 7,
  130640. 0,
  130641. 8,
  130642. };
  130643. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130644. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130645. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130646. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130647. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130648. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0,
  130650. };
  130651. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130652. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130653. };
  130654. static long _vq_quantmap__44c4_s_p4_0[] = {
  130655. 7, 5, 3, 1, 0, 2, 4, 6,
  130656. 8,
  130657. };
  130658. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130659. _vq_quantthresh__44c4_s_p4_0,
  130660. _vq_quantmap__44c4_s_p4_0,
  130661. 9,
  130662. 9
  130663. };
  130664. static static_codebook _44c4_s_p4_0 = {
  130665. 2, 81,
  130666. _vq_lengthlist__44c4_s_p4_0,
  130667. 1, -531628032, 1611661312, 4, 0,
  130668. _vq_quantlist__44c4_s_p4_0,
  130669. NULL,
  130670. &_vq_auxt__44c4_s_p4_0,
  130671. NULL,
  130672. 0
  130673. };
  130674. static long _vq_quantlist__44c4_s_p5_0[] = {
  130675. 4,
  130676. 3,
  130677. 5,
  130678. 2,
  130679. 6,
  130680. 1,
  130681. 7,
  130682. 0,
  130683. 8,
  130684. };
  130685. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130686. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130687. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130688. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130689. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130690. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130691. 10,
  130692. };
  130693. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130694. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130695. };
  130696. static long _vq_quantmap__44c4_s_p5_0[] = {
  130697. 7, 5, 3, 1, 0, 2, 4, 6,
  130698. 8,
  130699. };
  130700. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130701. _vq_quantthresh__44c4_s_p5_0,
  130702. _vq_quantmap__44c4_s_p5_0,
  130703. 9,
  130704. 9
  130705. };
  130706. static static_codebook _44c4_s_p5_0 = {
  130707. 2, 81,
  130708. _vq_lengthlist__44c4_s_p5_0,
  130709. 1, -531628032, 1611661312, 4, 0,
  130710. _vq_quantlist__44c4_s_p5_0,
  130711. NULL,
  130712. &_vq_auxt__44c4_s_p5_0,
  130713. NULL,
  130714. 0
  130715. };
  130716. static long _vq_quantlist__44c4_s_p6_0[] = {
  130717. 8,
  130718. 7,
  130719. 9,
  130720. 6,
  130721. 10,
  130722. 5,
  130723. 11,
  130724. 4,
  130725. 12,
  130726. 3,
  130727. 13,
  130728. 2,
  130729. 14,
  130730. 1,
  130731. 15,
  130732. 0,
  130733. 16,
  130734. };
  130735. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130736. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130737. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130738. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130739. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130740. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130741. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130742. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130743. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130744. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130745. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130746. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130747. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130748. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130749. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130750. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130751. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130752. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130754. 13,
  130755. };
  130756. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130757. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130758. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130759. };
  130760. static long _vq_quantmap__44c4_s_p6_0[] = {
  130761. 15, 13, 11, 9, 7, 5, 3, 1,
  130762. 0, 2, 4, 6, 8, 10, 12, 14,
  130763. 16,
  130764. };
  130765. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130766. _vq_quantthresh__44c4_s_p6_0,
  130767. _vq_quantmap__44c4_s_p6_0,
  130768. 17,
  130769. 17
  130770. };
  130771. static static_codebook _44c4_s_p6_0 = {
  130772. 2, 289,
  130773. _vq_lengthlist__44c4_s_p6_0,
  130774. 1, -529530880, 1611661312, 5, 0,
  130775. _vq_quantlist__44c4_s_p6_0,
  130776. NULL,
  130777. &_vq_auxt__44c4_s_p6_0,
  130778. NULL,
  130779. 0
  130780. };
  130781. static long _vq_quantlist__44c4_s_p7_0[] = {
  130782. 1,
  130783. 0,
  130784. 2,
  130785. };
  130786. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130787. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130788. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130789. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130790. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130791. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130792. 10,
  130793. };
  130794. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130795. -5.5, 5.5,
  130796. };
  130797. static long _vq_quantmap__44c4_s_p7_0[] = {
  130798. 1, 0, 2,
  130799. };
  130800. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130801. _vq_quantthresh__44c4_s_p7_0,
  130802. _vq_quantmap__44c4_s_p7_0,
  130803. 3,
  130804. 3
  130805. };
  130806. static static_codebook _44c4_s_p7_0 = {
  130807. 4, 81,
  130808. _vq_lengthlist__44c4_s_p7_0,
  130809. 1, -529137664, 1618345984, 2, 0,
  130810. _vq_quantlist__44c4_s_p7_0,
  130811. NULL,
  130812. &_vq_auxt__44c4_s_p7_0,
  130813. NULL,
  130814. 0
  130815. };
  130816. static long _vq_quantlist__44c4_s_p7_1[] = {
  130817. 5,
  130818. 4,
  130819. 6,
  130820. 3,
  130821. 7,
  130822. 2,
  130823. 8,
  130824. 1,
  130825. 9,
  130826. 0,
  130827. 10,
  130828. };
  130829. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130830. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130831. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130832. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130833. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130834. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130835. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130836. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130837. 10,10,10, 8, 8, 8, 8, 9, 9,
  130838. };
  130839. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130840. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130841. 3.5, 4.5,
  130842. };
  130843. static long _vq_quantmap__44c4_s_p7_1[] = {
  130844. 9, 7, 5, 3, 1, 0, 2, 4,
  130845. 6, 8, 10,
  130846. };
  130847. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130848. _vq_quantthresh__44c4_s_p7_1,
  130849. _vq_quantmap__44c4_s_p7_1,
  130850. 11,
  130851. 11
  130852. };
  130853. static static_codebook _44c4_s_p7_1 = {
  130854. 2, 121,
  130855. _vq_lengthlist__44c4_s_p7_1,
  130856. 1, -531365888, 1611661312, 4, 0,
  130857. _vq_quantlist__44c4_s_p7_1,
  130858. NULL,
  130859. &_vq_auxt__44c4_s_p7_1,
  130860. NULL,
  130861. 0
  130862. };
  130863. static long _vq_quantlist__44c4_s_p8_0[] = {
  130864. 6,
  130865. 5,
  130866. 7,
  130867. 4,
  130868. 8,
  130869. 3,
  130870. 9,
  130871. 2,
  130872. 10,
  130873. 1,
  130874. 11,
  130875. 0,
  130876. 12,
  130877. };
  130878. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130879. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130880. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130881. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130882. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130883. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130884. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130885. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130886. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130887. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130888. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130889. 0,13,12,12,12,12,12,13,13,
  130890. };
  130891. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130892. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130893. 12.5, 17.5, 22.5, 27.5,
  130894. };
  130895. static long _vq_quantmap__44c4_s_p8_0[] = {
  130896. 11, 9, 7, 5, 3, 1, 0, 2,
  130897. 4, 6, 8, 10, 12,
  130898. };
  130899. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130900. _vq_quantthresh__44c4_s_p8_0,
  130901. _vq_quantmap__44c4_s_p8_0,
  130902. 13,
  130903. 13
  130904. };
  130905. static static_codebook _44c4_s_p8_0 = {
  130906. 2, 169,
  130907. _vq_lengthlist__44c4_s_p8_0,
  130908. 1, -526516224, 1616117760, 4, 0,
  130909. _vq_quantlist__44c4_s_p8_0,
  130910. NULL,
  130911. &_vq_auxt__44c4_s_p8_0,
  130912. NULL,
  130913. 0
  130914. };
  130915. static long _vq_quantlist__44c4_s_p8_1[] = {
  130916. 2,
  130917. 1,
  130918. 3,
  130919. 0,
  130920. 4,
  130921. };
  130922. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130923. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130924. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130925. };
  130926. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130927. -1.5, -0.5, 0.5, 1.5,
  130928. };
  130929. static long _vq_quantmap__44c4_s_p8_1[] = {
  130930. 3, 1, 0, 2, 4,
  130931. };
  130932. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130933. _vq_quantthresh__44c4_s_p8_1,
  130934. _vq_quantmap__44c4_s_p8_1,
  130935. 5,
  130936. 5
  130937. };
  130938. static static_codebook _44c4_s_p8_1 = {
  130939. 2, 25,
  130940. _vq_lengthlist__44c4_s_p8_1,
  130941. 1, -533725184, 1611661312, 3, 0,
  130942. _vq_quantlist__44c4_s_p8_1,
  130943. NULL,
  130944. &_vq_auxt__44c4_s_p8_1,
  130945. NULL,
  130946. 0
  130947. };
  130948. static long _vq_quantlist__44c4_s_p9_0[] = {
  130949. 6,
  130950. 5,
  130951. 7,
  130952. 4,
  130953. 8,
  130954. 3,
  130955. 9,
  130956. 2,
  130957. 10,
  130958. 1,
  130959. 11,
  130960. 0,
  130961. 12,
  130962. };
  130963. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130964. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130965. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130966. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130967. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130968. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130969. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130970. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130971. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130972. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130973. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130974. 12,12,12,12,12,12,12,12,12,
  130975. };
  130976. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130977. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130978. 787.5, 1102.5, 1417.5, 1732.5,
  130979. };
  130980. static long _vq_quantmap__44c4_s_p9_0[] = {
  130981. 11, 9, 7, 5, 3, 1, 0, 2,
  130982. 4, 6, 8, 10, 12,
  130983. };
  130984. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130985. _vq_quantthresh__44c4_s_p9_0,
  130986. _vq_quantmap__44c4_s_p9_0,
  130987. 13,
  130988. 13
  130989. };
  130990. static static_codebook _44c4_s_p9_0 = {
  130991. 2, 169,
  130992. _vq_lengthlist__44c4_s_p9_0,
  130993. 1, -513964032, 1628680192, 4, 0,
  130994. _vq_quantlist__44c4_s_p9_0,
  130995. NULL,
  130996. &_vq_auxt__44c4_s_p9_0,
  130997. NULL,
  130998. 0
  130999. };
  131000. static long _vq_quantlist__44c4_s_p9_1[] = {
  131001. 7,
  131002. 6,
  131003. 8,
  131004. 5,
  131005. 9,
  131006. 4,
  131007. 10,
  131008. 3,
  131009. 11,
  131010. 2,
  131011. 12,
  131012. 1,
  131013. 13,
  131014. 0,
  131015. 14,
  131016. };
  131017. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131018. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131019. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131020. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131021. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131022. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131023. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131024. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131025. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131026. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131027. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131028. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131029. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131030. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131031. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131032. 15,
  131033. };
  131034. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131035. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131036. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131037. };
  131038. static long _vq_quantmap__44c4_s_p9_1[] = {
  131039. 13, 11, 9, 7, 5, 3, 1, 0,
  131040. 2, 4, 6, 8, 10, 12, 14,
  131041. };
  131042. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131043. _vq_quantthresh__44c4_s_p9_1,
  131044. _vq_quantmap__44c4_s_p9_1,
  131045. 15,
  131046. 15
  131047. };
  131048. static static_codebook _44c4_s_p9_1 = {
  131049. 2, 225,
  131050. _vq_lengthlist__44c4_s_p9_1,
  131051. 1, -520986624, 1620377600, 4, 0,
  131052. _vq_quantlist__44c4_s_p9_1,
  131053. NULL,
  131054. &_vq_auxt__44c4_s_p9_1,
  131055. NULL,
  131056. 0
  131057. };
  131058. static long _vq_quantlist__44c4_s_p9_2[] = {
  131059. 10,
  131060. 9,
  131061. 11,
  131062. 8,
  131063. 12,
  131064. 7,
  131065. 13,
  131066. 6,
  131067. 14,
  131068. 5,
  131069. 15,
  131070. 4,
  131071. 16,
  131072. 3,
  131073. 17,
  131074. 2,
  131075. 18,
  131076. 1,
  131077. 19,
  131078. 0,
  131079. 20,
  131080. };
  131081. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131082. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131083. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131084. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131085. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131086. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131087. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131088. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131089. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131090. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131091. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131092. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131093. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131094. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131095. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131096. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131097. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131098. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131099. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131100. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131101. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131102. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131103. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131104. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131105. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131106. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131107. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131108. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131109. 10,10,10,10,10,10,10,10,10,
  131110. };
  131111. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131112. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131113. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131114. 6.5, 7.5, 8.5, 9.5,
  131115. };
  131116. static long _vq_quantmap__44c4_s_p9_2[] = {
  131117. 19, 17, 15, 13, 11, 9, 7, 5,
  131118. 3, 1, 0, 2, 4, 6, 8, 10,
  131119. 12, 14, 16, 18, 20,
  131120. };
  131121. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131122. _vq_quantthresh__44c4_s_p9_2,
  131123. _vq_quantmap__44c4_s_p9_2,
  131124. 21,
  131125. 21
  131126. };
  131127. static static_codebook _44c4_s_p9_2 = {
  131128. 2, 441,
  131129. _vq_lengthlist__44c4_s_p9_2,
  131130. 1, -529268736, 1611661312, 5, 0,
  131131. _vq_quantlist__44c4_s_p9_2,
  131132. NULL,
  131133. &_vq_auxt__44c4_s_p9_2,
  131134. NULL,
  131135. 0
  131136. };
  131137. static long _huff_lengthlist__44c4_s_short[] = {
  131138. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131139. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131140. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131141. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131142. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131143. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131144. 7, 9,12,17,
  131145. };
  131146. static static_codebook _huff_book__44c4_s_short = {
  131147. 2, 100,
  131148. _huff_lengthlist__44c4_s_short,
  131149. 0, 0, 0, 0, 0,
  131150. NULL,
  131151. NULL,
  131152. NULL,
  131153. NULL,
  131154. 0
  131155. };
  131156. static long _huff_lengthlist__44c5_s_long[] = {
  131157. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131158. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131159. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131160. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131161. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131162. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131163. 9, 8, 7, 7,
  131164. };
  131165. static static_codebook _huff_book__44c5_s_long = {
  131166. 2, 100,
  131167. _huff_lengthlist__44c5_s_long,
  131168. 0, 0, 0, 0, 0,
  131169. NULL,
  131170. NULL,
  131171. NULL,
  131172. NULL,
  131173. 0
  131174. };
  131175. static long _vq_quantlist__44c5_s_p1_0[] = {
  131176. 1,
  131177. 0,
  131178. 2,
  131179. };
  131180. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131181. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131182. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131187. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131192. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131227. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131232. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131237. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131273. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131278. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131283. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 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,
  131592. };
  131593. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131594. -0.5, 0.5,
  131595. };
  131596. static long _vq_quantmap__44c5_s_p1_0[] = {
  131597. 1, 0, 2,
  131598. };
  131599. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131600. _vq_quantthresh__44c5_s_p1_0,
  131601. _vq_quantmap__44c5_s_p1_0,
  131602. 3,
  131603. 3
  131604. };
  131605. static static_codebook _44c5_s_p1_0 = {
  131606. 8, 6561,
  131607. _vq_lengthlist__44c5_s_p1_0,
  131608. 1, -535822336, 1611661312, 2, 0,
  131609. _vq_quantlist__44c5_s_p1_0,
  131610. NULL,
  131611. &_vq_auxt__44c5_s_p1_0,
  131612. NULL,
  131613. 0
  131614. };
  131615. static long _vq_quantlist__44c5_s_p2_0[] = {
  131616. 2,
  131617. 1,
  131618. 3,
  131619. 0,
  131620. 4,
  131621. };
  131622. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131623. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131624. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131625. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131626. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131627. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131633. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131634. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131635. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131641. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131642. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131649. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131650. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131663. };
  131664. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131665. -1.5, -0.5, 0.5, 1.5,
  131666. };
  131667. static long _vq_quantmap__44c5_s_p2_0[] = {
  131668. 3, 1, 0, 2, 4,
  131669. };
  131670. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131671. _vq_quantthresh__44c5_s_p2_0,
  131672. _vq_quantmap__44c5_s_p2_0,
  131673. 5,
  131674. 5
  131675. };
  131676. static static_codebook _44c5_s_p2_0 = {
  131677. 4, 625,
  131678. _vq_lengthlist__44c5_s_p2_0,
  131679. 1, -533725184, 1611661312, 3, 0,
  131680. _vq_quantlist__44c5_s_p2_0,
  131681. NULL,
  131682. &_vq_auxt__44c5_s_p2_0,
  131683. NULL,
  131684. 0
  131685. };
  131686. static long _vq_quantlist__44c5_s_p3_0[] = {
  131687. 2,
  131688. 1,
  131689. 3,
  131690. 0,
  131691. 4,
  131692. };
  131693. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131694. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131734. };
  131735. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131736. -1.5, -0.5, 0.5, 1.5,
  131737. };
  131738. static long _vq_quantmap__44c5_s_p3_0[] = {
  131739. 3, 1, 0, 2, 4,
  131740. };
  131741. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131742. _vq_quantthresh__44c5_s_p3_0,
  131743. _vq_quantmap__44c5_s_p3_0,
  131744. 5,
  131745. 5
  131746. };
  131747. static static_codebook _44c5_s_p3_0 = {
  131748. 4, 625,
  131749. _vq_lengthlist__44c5_s_p3_0,
  131750. 1, -533725184, 1611661312, 3, 0,
  131751. _vq_quantlist__44c5_s_p3_0,
  131752. NULL,
  131753. &_vq_auxt__44c5_s_p3_0,
  131754. NULL,
  131755. 0
  131756. };
  131757. static long _vq_quantlist__44c5_s_p4_0[] = {
  131758. 4,
  131759. 3,
  131760. 5,
  131761. 2,
  131762. 6,
  131763. 1,
  131764. 7,
  131765. 0,
  131766. 8,
  131767. };
  131768. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131769. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131770. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131771. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131772. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131773. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0,
  131775. };
  131776. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131777. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131778. };
  131779. static long _vq_quantmap__44c5_s_p4_0[] = {
  131780. 7, 5, 3, 1, 0, 2, 4, 6,
  131781. 8,
  131782. };
  131783. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131784. _vq_quantthresh__44c5_s_p4_0,
  131785. _vq_quantmap__44c5_s_p4_0,
  131786. 9,
  131787. 9
  131788. };
  131789. static static_codebook _44c5_s_p4_0 = {
  131790. 2, 81,
  131791. _vq_lengthlist__44c5_s_p4_0,
  131792. 1, -531628032, 1611661312, 4, 0,
  131793. _vq_quantlist__44c5_s_p4_0,
  131794. NULL,
  131795. &_vq_auxt__44c5_s_p4_0,
  131796. NULL,
  131797. 0
  131798. };
  131799. static long _vq_quantlist__44c5_s_p5_0[] = {
  131800. 4,
  131801. 3,
  131802. 5,
  131803. 2,
  131804. 6,
  131805. 1,
  131806. 7,
  131807. 0,
  131808. 8,
  131809. };
  131810. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131811. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131812. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131813. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131814. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131815. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131816. 10,
  131817. };
  131818. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131819. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131820. };
  131821. static long _vq_quantmap__44c5_s_p5_0[] = {
  131822. 7, 5, 3, 1, 0, 2, 4, 6,
  131823. 8,
  131824. };
  131825. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131826. _vq_quantthresh__44c5_s_p5_0,
  131827. _vq_quantmap__44c5_s_p5_0,
  131828. 9,
  131829. 9
  131830. };
  131831. static static_codebook _44c5_s_p5_0 = {
  131832. 2, 81,
  131833. _vq_lengthlist__44c5_s_p5_0,
  131834. 1, -531628032, 1611661312, 4, 0,
  131835. _vq_quantlist__44c5_s_p5_0,
  131836. NULL,
  131837. &_vq_auxt__44c5_s_p5_0,
  131838. NULL,
  131839. 0
  131840. };
  131841. static long _vq_quantlist__44c5_s_p6_0[] = {
  131842. 8,
  131843. 7,
  131844. 9,
  131845. 6,
  131846. 10,
  131847. 5,
  131848. 11,
  131849. 4,
  131850. 12,
  131851. 3,
  131852. 13,
  131853. 2,
  131854. 14,
  131855. 1,
  131856. 15,
  131857. 0,
  131858. 16,
  131859. };
  131860. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131861. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131862. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131863. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131864. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131865. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131866. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131867. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131868. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131869. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131870. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131871. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131872. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131873. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131874. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131875. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131876. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131877. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131879. 13,
  131880. };
  131881. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131882. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131883. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131884. };
  131885. static long _vq_quantmap__44c5_s_p6_0[] = {
  131886. 15, 13, 11, 9, 7, 5, 3, 1,
  131887. 0, 2, 4, 6, 8, 10, 12, 14,
  131888. 16,
  131889. };
  131890. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131891. _vq_quantthresh__44c5_s_p6_0,
  131892. _vq_quantmap__44c5_s_p6_0,
  131893. 17,
  131894. 17
  131895. };
  131896. static static_codebook _44c5_s_p6_0 = {
  131897. 2, 289,
  131898. _vq_lengthlist__44c5_s_p6_0,
  131899. 1, -529530880, 1611661312, 5, 0,
  131900. _vq_quantlist__44c5_s_p6_0,
  131901. NULL,
  131902. &_vq_auxt__44c5_s_p6_0,
  131903. NULL,
  131904. 0
  131905. };
  131906. static long _vq_quantlist__44c5_s_p7_0[] = {
  131907. 1,
  131908. 0,
  131909. 2,
  131910. };
  131911. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131912. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131913. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131914. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131915. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131916. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131917. 10,
  131918. };
  131919. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131920. -5.5, 5.5,
  131921. };
  131922. static long _vq_quantmap__44c5_s_p7_0[] = {
  131923. 1, 0, 2,
  131924. };
  131925. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131926. _vq_quantthresh__44c5_s_p7_0,
  131927. _vq_quantmap__44c5_s_p7_0,
  131928. 3,
  131929. 3
  131930. };
  131931. static static_codebook _44c5_s_p7_0 = {
  131932. 4, 81,
  131933. _vq_lengthlist__44c5_s_p7_0,
  131934. 1, -529137664, 1618345984, 2, 0,
  131935. _vq_quantlist__44c5_s_p7_0,
  131936. NULL,
  131937. &_vq_auxt__44c5_s_p7_0,
  131938. NULL,
  131939. 0
  131940. };
  131941. static long _vq_quantlist__44c5_s_p7_1[] = {
  131942. 5,
  131943. 4,
  131944. 6,
  131945. 3,
  131946. 7,
  131947. 2,
  131948. 8,
  131949. 1,
  131950. 9,
  131951. 0,
  131952. 10,
  131953. };
  131954. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131955. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131956. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131957. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131958. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131959. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131960. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131961. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131962. 10,10,10, 8, 8, 8, 8, 8, 8,
  131963. };
  131964. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131965. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131966. 3.5, 4.5,
  131967. };
  131968. static long _vq_quantmap__44c5_s_p7_1[] = {
  131969. 9, 7, 5, 3, 1, 0, 2, 4,
  131970. 6, 8, 10,
  131971. };
  131972. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131973. _vq_quantthresh__44c5_s_p7_1,
  131974. _vq_quantmap__44c5_s_p7_1,
  131975. 11,
  131976. 11
  131977. };
  131978. static static_codebook _44c5_s_p7_1 = {
  131979. 2, 121,
  131980. _vq_lengthlist__44c5_s_p7_1,
  131981. 1, -531365888, 1611661312, 4, 0,
  131982. _vq_quantlist__44c5_s_p7_1,
  131983. NULL,
  131984. &_vq_auxt__44c5_s_p7_1,
  131985. NULL,
  131986. 0
  131987. };
  131988. static long _vq_quantlist__44c5_s_p8_0[] = {
  131989. 6,
  131990. 5,
  131991. 7,
  131992. 4,
  131993. 8,
  131994. 3,
  131995. 9,
  131996. 2,
  131997. 10,
  131998. 1,
  131999. 11,
  132000. 0,
  132001. 12,
  132002. };
  132003. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132004. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132005. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132006. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132007. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132008. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132009. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132010. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132011. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132012. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132013. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132014. 0,12,12,12,12,12,12,13,13,
  132015. };
  132016. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132017. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132018. 12.5, 17.5, 22.5, 27.5,
  132019. };
  132020. static long _vq_quantmap__44c5_s_p8_0[] = {
  132021. 11, 9, 7, 5, 3, 1, 0, 2,
  132022. 4, 6, 8, 10, 12,
  132023. };
  132024. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132025. _vq_quantthresh__44c5_s_p8_0,
  132026. _vq_quantmap__44c5_s_p8_0,
  132027. 13,
  132028. 13
  132029. };
  132030. static static_codebook _44c5_s_p8_0 = {
  132031. 2, 169,
  132032. _vq_lengthlist__44c5_s_p8_0,
  132033. 1, -526516224, 1616117760, 4, 0,
  132034. _vq_quantlist__44c5_s_p8_0,
  132035. NULL,
  132036. &_vq_auxt__44c5_s_p8_0,
  132037. NULL,
  132038. 0
  132039. };
  132040. static long _vq_quantlist__44c5_s_p8_1[] = {
  132041. 2,
  132042. 1,
  132043. 3,
  132044. 0,
  132045. 4,
  132046. };
  132047. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132048. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132049. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132050. };
  132051. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132052. -1.5, -0.5, 0.5, 1.5,
  132053. };
  132054. static long _vq_quantmap__44c5_s_p8_1[] = {
  132055. 3, 1, 0, 2, 4,
  132056. };
  132057. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132058. _vq_quantthresh__44c5_s_p8_1,
  132059. _vq_quantmap__44c5_s_p8_1,
  132060. 5,
  132061. 5
  132062. };
  132063. static static_codebook _44c5_s_p8_1 = {
  132064. 2, 25,
  132065. _vq_lengthlist__44c5_s_p8_1,
  132066. 1, -533725184, 1611661312, 3, 0,
  132067. _vq_quantlist__44c5_s_p8_1,
  132068. NULL,
  132069. &_vq_auxt__44c5_s_p8_1,
  132070. NULL,
  132071. 0
  132072. };
  132073. static long _vq_quantlist__44c5_s_p9_0[] = {
  132074. 7,
  132075. 6,
  132076. 8,
  132077. 5,
  132078. 9,
  132079. 4,
  132080. 10,
  132081. 3,
  132082. 11,
  132083. 2,
  132084. 12,
  132085. 1,
  132086. 13,
  132087. 0,
  132088. 14,
  132089. };
  132090. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132091. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132092. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132093. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132094. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132095. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132096. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132097. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132098. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132099. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132100. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132101. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132102. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132103. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132104. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132105. 12,
  132106. };
  132107. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132108. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132109. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132110. };
  132111. static long _vq_quantmap__44c5_s_p9_0[] = {
  132112. 13, 11, 9, 7, 5, 3, 1, 0,
  132113. 2, 4, 6, 8, 10, 12, 14,
  132114. };
  132115. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132116. _vq_quantthresh__44c5_s_p9_0,
  132117. _vq_quantmap__44c5_s_p9_0,
  132118. 15,
  132119. 15
  132120. };
  132121. static static_codebook _44c5_s_p9_0 = {
  132122. 2, 225,
  132123. _vq_lengthlist__44c5_s_p9_0,
  132124. 1, -512522752, 1628852224, 4, 0,
  132125. _vq_quantlist__44c5_s_p9_0,
  132126. NULL,
  132127. &_vq_auxt__44c5_s_p9_0,
  132128. NULL,
  132129. 0
  132130. };
  132131. static long _vq_quantlist__44c5_s_p9_1[] = {
  132132. 8,
  132133. 7,
  132134. 9,
  132135. 6,
  132136. 10,
  132137. 5,
  132138. 11,
  132139. 4,
  132140. 12,
  132141. 3,
  132142. 13,
  132143. 2,
  132144. 14,
  132145. 1,
  132146. 15,
  132147. 0,
  132148. 16,
  132149. };
  132150. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132151. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132152. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132153. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132154. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132155. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132156. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132157. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132158. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132159. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132160. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132161. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132162. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132163. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132164. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132165. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132166. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132167. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132168. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132169. 15,
  132170. };
  132171. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132172. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132173. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132174. };
  132175. static long _vq_quantmap__44c5_s_p9_1[] = {
  132176. 15, 13, 11, 9, 7, 5, 3, 1,
  132177. 0, 2, 4, 6, 8, 10, 12, 14,
  132178. 16,
  132179. };
  132180. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132181. _vq_quantthresh__44c5_s_p9_1,
  132182. _vq_quantmap__44c5_s_p9_1,
  132183. 17,
  132184. 17
  132185. };
  132186. static static_codebook _44c5_s_p9_1 = {
  132187. 2, 289,
  132188. _vq_lengthlist__44c5_s_p9_1,
  132189. 1, -520814592, 1620377600, 5, 0,
  132190. _vq_quantlist__44c5_s_p9_1,
  132191. NULL,
  132192. &_vq_auxt__44c5_s_p9_1,
  132193. NULL,
  132194. 0
  132195. };
  132196. static long _vq_quantlist__44c5_s_p9_2[] = {
  132197. 10,
  132198. 9,
  132199. 11,
  132200. 8,
  132201. 12,
  132202. 7,
  132203. 13,
  132204. 6,
  132205. 14,
  132206. 5,
  132207. 15,
  132208. 4,
  132209. 16,
  132210. 3,
  132211. 17,
  132212. 2,
  132213. 18,
  132214. 1,
  132215. 19,
  132216. 0,
  132217. 20,
  132218. };
  132219. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132220. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132221. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132222. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132223. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132224. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132225. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132226. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132227. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132228. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132229. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132230. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132231. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132232. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132233. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132234. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132235. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132236. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132237. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132238. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132239. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132240. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132241. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132242. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132243. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132244. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132245. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132246. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132247. 10,10,10,10,10,10,10,10,10,
  132248. };
  132249. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132250. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132251. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132252. 6.5, 7.5, 8.5, 9.5,
  132253. };
  132254. static long _vq_quantmap__44c5_s_p9_2[] = {
  132255. 19, 17, 15, 13, 11, 9, 7, 5,
  132256. 3, 1, 0, 2, 4, 6, 8, 10,
  132257. 12, 14, 16, 18, 20,
  132258. };
  132259. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132260. _vq_quantthresh__44c5_s_p9_2,
  132261. _vq_quantmap__44c5_s_p9_2,
  132262. 21,
  132263. 21
  132264. };
  132265. static static_codebook _44c5_s_p9_2 = {
  132266. 2, 441,
  132267. _vq_lengthlist__44c5_s_p9_2,
  132268. 1, -529268736, 1611661312, 5, 0,
  132269. _vq_quantlist__44c5_s_p9_2,
  132270. NULL,
  132271. &_vq_auxt__44c5_s_p9_2,
  132272. NULL,
  132273. 0
  132274. };
  132275. static long _huff_lengthlist__44c5_s_short[] = {
  132276. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132277. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132278. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132279. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132280. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132281. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132282. 6, 8,11,16,
  132283. };
  132284. static static_codebook _huff_book__44c5_s_short = {
  132285. 2, 100,
  132286. _huff_lengthlist__44c5_s_short,
  132287. 0, 0, 0, 0, 0,
  132288. NULL,
  132289. NULL,
  132290. NULL,
  132291. NULL,
  132292. 0
  132293. };
  132294. static long _huff_lengthlist__44c6_s_long[] = {
  132295. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132296. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132297. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132298. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132299. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132300. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132301. 11,10,10,12,
  132302. };
  132303. static static_codebook _huff_book__44c6_s_long = {
  132304. 2, 100,
  132305. _huff_lengthlist__44c6_s_long,
  132306. 0, 0, 0, 0, 0,
  132307. NULL,
  132308. NULL,
  132309. NULL,
  132310. NULL,
  132311. 0
  132312. };
  132313. static long _vq_quantlist__44c6_s_p1_0[] = {
  132314. 1,
  132315. 0,
  132316. 2,
  132317. };
  132318. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132319. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132320. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132321. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132322. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132323. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132324. 8,
  132325. };
  132326. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132327. -0.5, 0.5,
  132328. };
  132329. static long _vq_quantmap__44c6_s_p1_0[] = {
  132330. 1, 0, 2,
  132331. };
  132332. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132333. _vq_quantthresh__44c6_s_p1_0,
  132334. _vq_quantmap__44c6_s_p1_0,
  132335. 3,
  132336. 3
  132337. };
  132338. static static_codebook _44c6_s_p1_0 = {
  132339. 4, 81,
  132340. _vq_lengthlist__44c6_s_p1_0,
  132341. 1, -535822336, 1611661312, 2, 0,
  132342. _vq_quantlist__44c6_s_p1_0,
  132343. NULL,
  132344. &_vq_auxt__44c6_s_p1_0,
  132345. NULL,
  132346. 0
  132347. };
  132348. static long _vq_quantlist__44c6_s_p2_0[] = {
  132349. 2,
  132350. 1,
  132351. 3,
  132352. 0,
  132353. 4,
  132354. };
  132355. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132356. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132357. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132358. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132359. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132360. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132361. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132362. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132363. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132366. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132367. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132368. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132369. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132370. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132371. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132374. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132375. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132376. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132377. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132378. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132379. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132382. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132383. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132384. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132385. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132386. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132387. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132392. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132393. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132394. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132395. 13,
  132396. };
  132397. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132398. -1.5, -0.5, 0.5, 1.5,
  132399. };
  132400. static long _vq_quantmap__44c6_s_p2_0[] = {
  132401. 3, 1, 0, 2, 4,
  132402. };
  132403. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132404. _vq_quantthresh__44c6_s_p2_0,
  132405. _vq_quantmap__44c6_s_p2_0,
  132406. 5,
  132407. 5
  132408. };
  132409. static static_codebook _44c6_s_p2_0 = {
  132410. 4, 625,
  132411. _vq_lengthlist__44c6_s_p2_0,
  132412. 1, -533725184, 1611661312, 3, 0,
  132413. _vq_quantlist__44c6_s_p2_0,
  132414. NULL,
  132415. &_vq_auxt__44c6_s_p2_0,
  132416. NULL,
  132417. 0
  132418. };
  132419. static long _vq_quantlist__44c6_s_p3_0[] = {
  132420. 4,
  132421. 3,
  132422. 5,
  132423. 2,
  132424. 6,
  132425. 1,
  132426. 7,
  132427. 0,
  132428. 8,
  132429. };
  132430. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132431. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132432. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132433. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132434. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0,
  132437. };
  132438. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132440. };
  132441. static long _vq_quantmap__44c6_s_p3_0[] = {
  132442. 7, 5, 3, 1, 0, 2, 4, 6,
  132443. 8,
  132444. };
  132445. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132446. _vq_quantthresh__44c6_s_p3_0,
  132447. _vq_quantmap__44c6_s_p3_0,
  132448. 9,
  132449. 9
  132450. };
  132451. static static_codebook _44c6_s_p3_0 = {
  132452. 2, 81,
  132453. _vq_lengthlist__44c6_s_p3_0,
  132454. 1, -531628032, 1611661312, 4, 0,
  132455. _vq_quantlist__44c6_s_p3_0,
  132456. NULL,
  132457. &_vq_auxt__44c6_s_p3_0,
  132458. NULL,
  132459. 0
  132460. };
  132461. static long _vq_quantlist__44c6_s_p4_0[] = {
  132462. 8,
  132463. 7,
  132464. 9,
  132465. 6,
  132466. 10,
  132467. 5,
  132468. 11,
  132469. 4,
  132470. 12,
  132471. 3,
  132472. 13,
  132473. 2,
  132474. 14,
  132475. 1,
  132476. 15,
  132477. 0,
  132478. 16,
  132479. };
  132480. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132481. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132482. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132483. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132484. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132485. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132486. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132487. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132488. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132489. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132490. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132499. 0,
  132500. };
  132501. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132502. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132503. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132504. };
  132505. static long _vq_quantmap__44c6_s_p4_0[] = {
  132506. 15, 13, 11, 9, 7, 5, 3, 1,
  132507. 0, 2, 4, 6, 8, 10, 12, 14,
  132508. 16,
  132509. };
  132510. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132511. _vq_quantthresh__44c6_s_p4_0,
  132512. _vq_quantmap__44c6_s_p4_0,
  132513. 17,
  132514. 17
  132515. };
  132516. static static_codebook _44c6_s_p4_0 = {
  132517. 2, 289,
  132518. _vq_lengthlist__44c6_s_p4_0,
  132519. 1, -529530880, 1611661312, 5, 0,
  132520. _vq_quantlist__44c6_s_p4_0,
  132521. NULL,
  132522. &_vq_auxt__44c6_s_p4_0,
  132523. NULL,
  132524. 0
  132525. };
  132526. static long _vq_quantlist__44c6_s_p5_0[] = {
  132527. 1,
  132528. 0,
  132529. 2,
  132530. };
  132531. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132532. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132533. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132534. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132535. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132536. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132537. 12,
  132538. };
  132539. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132540. -5.5, 5.5,
  132541. };
  132542. static long _vq_quantmap__44c6_s_p5_0[] = {
  132543. 1, 0, 2,
  132544. };
  132545. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132546. _vq_quantthresh__44c6_s_p5_0,
  132547. _vq_quantmap__44c6_s_p5_0,
  132548. 3,
  132549. 3
  132550. };
  132551. static static_codebook _44c6_s_p5_0 = {
  132552. 4, 81,
  132553. _vq_lengthlist__44c6_s_p5_0,
  132554. 1, -529137664, 1618345984, 2, 0,
  132555. _vq_quantlist__44c6_s_p5_0,
  132556. NULL,
  132557. &_vq_auxt__44c6_s_p5_0,
  132558. NULL,
  132559. 0
  132560. };
  132561. static long _vq_quantlist__44c6_s_p5_1[] = {
  132562. 5,
  132563. 4,
  132564. 6,
  132565. 3,
  132566. 7,
  132567. 2,
  132568. 8,
  132569. 1,
  132570. 9,
  132571. 0,
  132572. 10,
  132573. };
  132574. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132575. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132576. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132577. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132578. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132579. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132580. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132581. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132582. 11,10,10, 7, 7, 8, 8, 8, 8,
  132583. };
  132584. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132585. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132586. 3.5, 4.5,
  132587. };
  132588. static long _vq_quantmap__44c6_s_p5_1[] = {
  132589. 9, 7, 5, 3, 1, 0, 2, 4,
  132590. 6, 8, 10,
  132591. };
  132592. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132593. _vq_quantthresh__44c6_s_p5_1,
  132594. _vq_quantmap__44c6_s_p5_1,
  132595. 11,
  132596. 11
  132597. };
  132598. static static_codebook _44c6_s_p5_1 = {
  132599. 2, 121,
  132600. _vq_lengthlist__44c6_s_p5_1,
  132601. 1, -531365888, 1611661312, 4, 0,
  132602. _vq_quantlist__44c6_s_p5_1,
  132603. NULL,
  132604. &_vq_auxt__44c6_s_p5_1,
  132605. NULL,
  132606. 0
  132607. };
  132608. static long _vq_quantlist__44c6_s_p6_0[] = {
  132609. 6,
  132610. 5,
  132611. 7,
  132612. 4,
  132613. 8,
  132614. 3,
  132615. 9,
  132616. 2,
  132617. 10,
  132618. 1,
  132619. 11,
  132620. 0,
  132621. 12,
  132622. };
  132623. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132624. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132625. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132626. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132627. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132628. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132629. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 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,
  132635. };
  132636. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132637. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132638. 12.5, 17.5, 22.5, 27.5,
  132639. };
  132640. static long _vq_quantmap__44c6_s_p6_0[] = {
  132641. 11, 9, 7, 5, 3, 1, 0, 2,
  132642. 4, 6, 8, 10, 12,
  132643. };
  132644. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132645. _vq_quantthresh__44c6_s_p6_0,
  132646. _vq_quantmap__44c6_s_p6_0,
  132647. 13,
  132648. 13
  132649. };
  132650. static static_codebook _44c6_s_p6_0 = {
  132651. 2, 169,
  132652. _vq_lengthlist__44c6_s_p6_0,
  132653. 1, -526516224, 1616117760, 4, 0,
  132654. _vq_quantlist__44c6_s_p6_0,
  132655. NULL,
  132656. &_vq_auxt__44c6_s_p6_0,
  132657. NULL,
  132658. 0
  132659. };
  132660. static long _vq_quantlist__44c6_s_p6_1[] = {
  132661. 2,
  132662. 1,
  132663. 3,
  132664. 0,
  132665. 4,
  132666. };
  132667. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132668. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132669. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132670. };
  132671. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132672. -1.5, -0.5, 0.5, 1.5,
  132673. };
  132674. static long _vq_quantmap__44c6_s_p6_1[] = {
  132675. 3, 1, 0, 2, 4,
  132676. };
  132677. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132678. _vq_quantthresh__44c6_s_p6_1,
  132679. _vq_quantmap__44c6_s_p6_1,
  132680. 5,
  132681. 5
  132682. };
  132683. static static_codebook _44c6_s_p6_1 = {
  132684. 2, 25,
  132685. _vq_lengthlist__44c6_s_p6_1,
  132686. 1, -533725184, 1611661312, 3, 0,
  132687. _vq_quantlist__44c6_s_p6_1,
  132688. NULL,
  132689. &_vq_auxt__44c6_s_p6_1,
  132690. NULL,
  132691. 0
  132692. };
  132693. static long _vq_quantlist__44c6_s_p7_0[] = {
  132694. 6,
  132695. 5,
  132696. 7,
  132697. 4,
  132698. 8,
  132699. 3,
  132700. 9,
  132701. 2,
  132702. 10,
  132703. 1,
  132704. 11,
  132705. 0,
  132706. 12,
  132707. };
  132708. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132709. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132710. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132711. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132712. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132713. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132714. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132715. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132716. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132717. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132718. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132719. 20,13,13,13,13,13,13,14,14,
  132720. };
  132721. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132722. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132723. 27.5, 38.5, 49.5, 60.5,
  132724. };
  132725. static long _vq_quantmap__44c6_s_p7_0[] = {
  132726. 11, 9, 7, 5, 3, 1, 0, 2,
  132727. 4, 6, 8, 10, 12,
  132728. };
  132729. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132730. _vq_quantthresh__44c6_s_p7_0,
  132731. _vq_quantmap__44c6_s_p7_0,
  132732. 13,
  132733. 13
  132734. };
  132735. static static_codebook _44c6_s_p7_0 = {
  132736. 2, 169,
  132737. _vq_lengthlist__44c6_s_p7_0,
  132738. 1, -523206656, 1618345984, 4, 0,
  132739. _vq_quantlist__44c6_s_p7_0,
  132740. NULL,
  132741. &_vq_auxt__44c6_s_p7_0,
  132742. NULL,
  132743. 0
  132744. };
  132745. static long _vq_quantlist__44c6_s_p7_1[] = {
  132746. 5,
  132747. 4,
  132748. 6,
  132749. 3,
  132750. 7,
  132751. 2,
  132752. 8,
  132753. 1,
  132754. 9,
  132755. 0,
  132756. 10,
  132757. };
  132758. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132759. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132760. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132761. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132762. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132763. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132764. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132765. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132766. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132767. };
  132768. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132769. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132770. 3.5, 4.5,
  132771. };
  132772. static long _vq_quantmap__44c6_s_p7_1[] = {
  132773. 9, 7, 5, 3, 1, 0, 2, 4,
  132774. 6, 8, 10,
  132775. };
  132776. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132777. _vq_quantthresh__44c6_s_p7_1,
  132778. _vq_quantmap__44c6_s_p7_1,
  132779. 11,
  132780. 11
  132781. };
  132782. static static_codebook _44c6_s_p7_1 = {
  132783. 2, 121,
  132784. _vq_lengthlist__44c6_s_p7_1,
  132785. 1, -531365888, 1611661312, 4, 0,
  132786. _vq_quantlist__44c6_s_p7_1,
  132787. NULL,
  132788. &_vq_auxt__44c6_s_p7_1,
  132789. NULL,
  132790. 0
  132791. };
  132792. static long _vq_quantlist__44c6_s_p8_0[] = {
  132793. 7,
  132794. 6,
  132795. 8,
  132796. 5,
  132797. 9,
  132798. 4,
  132799. 10,
  132800. 3,
  132801. 11,
  132802. 2,
  132803. 12,
  132804. 1,
  132805. 13,
  132806. 0,
  132807. 14,
  132808. };
  132809. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132810. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132811. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132812. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132813. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132814. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132815. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132816. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132817. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132818. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132819. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132820. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132821. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132822. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132823. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132824. 14,
  132825. };
  132826. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132827. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132828. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132829. };
  132830. static long _vq_quantmap__44c6_s_p8_0[] = {
  132831. 13, 11, 9, 7, 5, 3, 1, 0,
  132832. 2, 4, 6, 8, 10, 12, 14,
  132833. };
  132834. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132835. _vq_quantthresh__44c6_s_p8_0,
  132836. _vq_quantmap__44c6_s_p8_0,
  132837. 15,
  132838. 15
  132839. };
  132840. static static_codebook _44c6_s_p8_0 = {
  132841. 2, 225,
  132842. _vq_lengthlist__44c6_s_p8_0,
  132843. 1, -520986624, 1620377600, 4, 0,
  132844. _vq_quantlist__44c6_s_p8_0,
  132845. NULL,
  132846. &_vq_auxt__44c6_s_p8_0,
  132847. NULL,
  132848. 0
  132849. };
  132850. static long _vq_quantlist__44c6_s_p8_1[] = {
  132851. 10,
  132852. 9,
  132853. 11,
  132854. 8,
  132855. 12,
  132856. 7,
  132857. 13,
  132858. 6,
  132859. 14,
  132860. 5,
  132861. 15,
  132862. 4,
  132863. 16,
  132864. 3,
  132865. 17,
  132866. 2,
  132867. 18,
  132868. 1,
  132869. 19,
  132870. 0,
  132871. 20,
  132872. };
  132873. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132874. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132875. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132877. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132878. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132879. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132880. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132881. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132882. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132883. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132884. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132885. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132886. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132887. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132888. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132889. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132890. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132891. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132892. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132893. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132894. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132895. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132896. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132897. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132898. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132899. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132900. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132901. 10,10,10,10,10,10,10,10,10,
  132902. };
  132903. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132904. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132905. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132906. 6.5, 7.5, 8.5, 9.5,
  132907. };
  132908. static long _vq_quantmap__44c6_s_p8_1[] = {
  132909. 19, 17, 15, 13, 11, 9, 7, 5,
  132910. 3, 1, 0, 2, 4, 6, 8, 10,
  132911. 12, 14, 16, 18, 20,
  132912. };
  132913. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132914. _vq_quantthresh__44c6_s_p8_1,
  132915. _vq_quantmap__44c6_s_p8_1,
  132916. 21,
  132917. 21
  132918. };
  132919. static static_codebook _44c6_s_p8_1 = {
  132920. 2, 441,
  132921. _vq_lengthlist__44c6_s_p8_1,
  132922. 1, -529268736, 1611661312, 5, 0,
  132923. _vq_quantlist__44c6_s_p8_1,
  132924. NULL,
  132925. &_vq_auxt__44c6_s_p8_1,
  132926. NULL,
  132927. 0
  132928. };
  132929. static long _vq_quantlist__44c6_s_p9_0[] = {
  132930. 6,
  132931. 5,
  132932. 7,
  132933. 4,
  132934. 8,
  132935. 3,
  132936. 9,
  132937. 2,
  132938. 10,
  132939. 1,
  132940. 11,
  132941. 0,
  132942. 12,
  132943. };
  132944. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132945. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132946. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132947. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132948. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132950. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132951. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132952. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132953. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132954. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132955. 10,10,10,10,10,10,10,10,10,
  132956. };
  132957. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132958. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132959. 1592.5, 2229.5, 2866.5, 3503.5,
  132960. };
  132961. static long _vq_quantmap__44c6_s_p9_0[] = {
  132962. 11, 9, 7, 5, 3, 1, 0, 2,
  132963. 4, 6, 8, 10, 12,
  132964. };
  132965. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132966. _vq_quantthresh__44c6_s_p9_0,
  132967. _vq_quantmap__44c6_s_p9_0,
  132968. 13,
  132969. 13
  132970. };
  132971. static static_codebook _44c6_s_p9_0 = {
  132972. 2, 169,
  132973. _vq_lengthlist__44c6_s_p9_0,
  132974. 1, -511845376, 1630791680, 4, 0,
  132975. _vq_quantlist__44c6_s_p9_0,
  132976. NULL,
  132977. &_vq_auxt__44c6_s_p9_0,
  132978. NULL,
  132979. 0
  132980. };
  132981. static long _vq_quantlist__44c6_s_p9_1[] = {
  132982. 6,
  132983. 5,
  132984. 7,
  132985. 4,
  132986. 8,
  132987. 3,
  132988. 9,
  132989. 2,
  132990. 10,
  132991. 1,
  132992. 11,
  132993. 0,
  132994. 12,
  132995. };
  132996. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132997. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132998. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132999. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133000. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133001. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133002. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133003. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133004. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133005. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133006. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133007. 15,12,10,11,11,13,11,12,13,
  133008. };
  133009. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133010. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133011. 122.5, 171.5, 220.5, 269.5,
  133012. };
  133013. static long _vq_quantmap__44c6_s_p9_1[] = {
  133014. 11, 9, 7, 5, 3, 1, 0, 2,
  133015. 4, 6, 8, 10, 12,
  133016. };
  133017. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133018. _vq_quantthresh__44c6_s_p9_1,
  133019. _vq_quantmap__44c6_s_p9_1,
  133020. 13,
  133021. 13
  133022. };
  133023. static static_codebook _44c6_s_p9_1 = {
  133024. 2, 169,
  133025. _vq_lengthlist__44c6_s_p9_1,
  133026. 1, -518889472, 1622704128, 4, 0,
  133027. _vq_quantlist__44c6_s_p9_1,
  133028. NULL,
  133029. &_vq_auxt__44c6_s_p9_1,
  133030. NULL,
  133031. 0
  133032. };
  133033. static long _vq_quantlist__44c6_s_p9_2[] = {
  133034. 24,
  133035. 23,
  133036. 25,
  133037. 22,
  133038. 26,
  133039. 21,
  133040. 27,
  133041. 20,
  133042. 28,
  133043. 19,
  133044. 29,
  133045. 18,
  133046. 30,
  133047. 17,
  133048. 31,
  133049. 16,
  133050. 32,
  133051. 15,
  133052. 33,
  133053. 14,
  133054. 34,
  133055. 13,
  133056. 35,
  133057. 12,
  133058. 36,
  133059. 11,
  133060. 37,
  133061. 10,
  133062. 38,
  133063. 9,
  133064. 39,
  133065. 8,
  133066. 40,
  133067. 7,
  133068. 41,
  133069. 6,
  133070. 42,
  133071. 5,
  133072. 43,
  133073. 4,
  133074. 44,
  133075. 3,
  133076. 45,
  133077. 2,
  133078. 46,
  133079. 1,
  133080. 47,
  133081. 0,
  133082. 48,
  133083. };
  133084. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133085. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133086. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133087. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133088. 7,
  133089. };
  133090. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133091. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133092. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133093. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133094. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133095. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133096. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133097. };
  133098. static long _vq_quantmap__44c6_s_p9_2[] = {
  133099. 47, 45, 43, 41, 39, 37, 35, 33,
  133100. 31, 29, 27, 25, 23, 21, 19, 17,
  133101. 15, 13, 11, 9, 7, 5, 3, 1,
  133102. 0, 2, 4, 6, 8, 10, 12, 14,
  133103. 16, 18, 20, 22, 24, 26, 28, 30,
  133104. 32, 34, 36, 38, 40, 42, 44, 46,
  133105. 48,
  133106. };
  133107. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133108. _vq_quantthresh__44c6_s_p9_2,
  133109. _vq_quantmap__44c6_s_p9_2,
  133110. 49,
  133111. 49
  133112. };
  133113. static static_codebook _44c6_s_p9_2 = {
  133114. 1, 49,
  133115. _vq_lengthlist__44c6_s_p9_2,
  133116. 1, -526909440, 1611661312, 6, 0,
  133117. _vq_quantlist__44c6_s_p9_2,
  133118. NULL,
  133119. &_vq_auxt__44c6_s_p9_2,
  133120. NULL,
  133121. 0
  133122. };
  133123. static long _huff_lengthlist__44c6_s_short[] = {
  133124. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133125. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133126. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133127. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133128. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133129. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133130. 9,10,17,18,
  133131. };
  133132. static static_codebook _huff_book__44c6_s_short = {
  133133. 2, 100,
  133134. _huff_lengthlist__44c6_s_short,
  133135. 0, 0, 0, 0, 0,
  133136. NULL,
  133137. NULL,
  133138. NULL,
  133139. NULL,
  133140. 0
  133141. };
  133142. static long _huff_lengthlist__44c7_s_long[] = {
  133143. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133144. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133145. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133146. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133147. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133148. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133149. 11,10,10,12,
  133150. };
  133151. static static_codebook _huff_book__44c7_s_long = {
  133152. 2, 100,
  133153. _huff_lengthlist__44c7_s_long,
  133154. 0, 0, 0, 0, 0,
  133155. NULL,
  133156. NULL,
  133157. NULL,
  133158. NULL,
  133159. 0
  133160. };
  133161. static long _vq_quantlist__44c7_s_p1_0[] = {
  133162. 1,
  133163. 0,
  133164. 2,
  133165. };
  133166. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133167. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133168. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133169. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133170. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133171. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133172. 8,
  133173. };
  133174. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133175. -0.5, 0.5,
  133176. };
  133177. static long _vq_quantmap__44c7_s_p1_0[] = {
  133178. 1, 0, 2,
  133179. };
  133180. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133181. _vq_quantthresh__44c7_s_p1_0,
  133182. _vq_quantmap__44c7_s_p1_0,
  133183. 3,
  133184. 3
  133185. };
  133186. static static_codebook _44c7_s_p1_0 = {
  133187. 4, 81,
  133188. _vq_lengthlist__44c7_s_p1_0,
  133189. 1, -535822336, 1611661312, 2, 0,
  133190. _vq_quantlist__44c7_s_p1_0,
  133191. NULL,
  133192. &_vq_auxt__44c7_s_p1_0,
  133193. NULL,
  133194. 0
  133195. };
  133196. static long _vq_quantlist__44c7_s_p2_0[] = {
  133197. 2,
  133198. 1,
  133199. 3,
  133200. 0,
  133201. 4,
  133202. };
  133203. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133204. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133205. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133206. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133207. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133208. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133209. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133210. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133211. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133213. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133214. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133215. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133216. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133217. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133218. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133219. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133222. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133223. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133224. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133225. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133226. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133227. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133230. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133231. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133232. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133233. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133234. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133235. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133240. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133241. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133242. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133243. 13,
  133244. };
  133245. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133246. -1.5, -0.5, 0.5, 1.5,
  133247. };
  133248. static long _vq_quantmap__44c7_s_p2_0[] = {
  133249. 3, 1, 0, 2, 4,
  133250. };
  133251. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133252. _vq_quantthresh__44c7_s_p2_0,
  133253. _vq_quantmap__44c7_s_p2_0,
  133254. 5,
  133255. 5
  133256. };
  133257. static static_codebook _44c7_s_p2_0 = {
  133258. 4, 625,
  133259. _vq_lengthlist__44c7_s_p2_0,
  133260. 1, -533725184, 1611661312, 3, 0,
  133261. _vq_quantlist__44c7_s_p2_0,
  133262. NULL,
  133263. &_vq_auxt__44c7_s_p2_0,
  133264. NULL,
  133265. 0
  133266. };
  133267. static long _vq_quantlist__44c7_s_p3_0[] = {
  133268. 4,
  133269. 3,
  133270. 5,
  133271. 2,
  133272. 6,
  133273. 1,
  133274. 7,
  133275. 0,
  133276. 8,
  133277. };
  133278. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133279. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133280. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133281. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133282. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0,
  133285. };
  133286. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133287. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133288. };
  133289. static long _vq_quantmap__44c7_s_p3_0[] = {
  133290. 7, 5, 3, 1, 0, 2, 4, 6,
  133291. 8,
  133292. };
  133293. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133294. _vq_quantthresh__44c7_s_p3_0,
  133295. _vq_quantmap__44c7_s_p3_0,
  133296. 9,
  133297. 9
  133298. };
  133299. static static_codebook _44c7_s_p3_0 = {
  133300. 2, 81,
  133301. _vq_lengthlist__44c7_s_p3_0,
  133302. 1, -531628032, 1611661312, 4, 0,
  133303. _vq_quantlist__44c7_s_p3_0,
  133304. NULL,
  133305. &_vq_auxt__44c7_s_p3_0,
  133306. NULL,
  133307. 0
  133308. };
  133309. static long _vq_quantlist__44c7_s_p4_0[] = {
  133310. 8,
  133311. 7,
  133312. 9,
  133313. 6,
  133314. 10,
  133315. 5,
  133316. 11,
  133317. 4,
  133318. 12,
  133319. 3,
  133320. 13,
  133321. 2,
  133322. 14,
  133323. 1,
  133324. 15,
  133325. 0,
  133326. 16,
  133327. };
  133328. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133329. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133330. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133331. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133332. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133333. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133334. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133335. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133336. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133337. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133338. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0,
  133348. };
  133349. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133350. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133351. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133352. };
  133353. static long _vq_quantmap__44c7_s_p4_0[] = {
  133354. 15, 13, 11, 9, 7, 5, 3, 1,
  133355. 0, 2, 4, 6, 8, 10, 12, 14,
  133356. 16,
  133357. };
  133358. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133359. _vq_quantthresh__44c7_s_p4_0,
  133360. _vq_quantmap__44c7_s_p4_0,
  133361. 17,
  133362. 17
  133363. };
  133364. static static_codebook _44c7_s_p4_0 = {
  133365. 2, 289,
  133366. _vq_lengthlist__44c7_s_p4_0,
  133367. 1, -529530880, 1611661312, 5, 0,
  133368. _vq_quantlist__44c7_s_p4_0,
  133369. NULL,
  133370. &_vq_auxt__44c7_s_p4_0,
  133371. NULL,
  133372. 0
  133373. };
  133374. static long _vq_quantlist__44c7_s_p5_0[] = {
  133375. 1,
  133376. 0,
  133377. 2,
  133378. };
  133379. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133380. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133381. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133382. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133383. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133384. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133385. 12,
  133386. };
  133387. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133388. -5.5, 5.5,
  133389. };
  133390. static long _vq_quantmap__44c7_s_p5_0[] = {
  133391. 1, 0, 2,
  133392. };
  133393. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133394. _vq_quantthresh__44c7_s_p5_0,
  133395. _vq_quantmap__44c7_s_p5_0,
  133396. 3,
  133397. 3
  133398. };
  133399. static static_codebook _44c7_s_p5_0 = {
  133400. 4, 81,
  133401. _vq_lengthlist__44c7_s_p5_0,
  133402. 1, -529137664, 1618345984, 2, 0,
  133403. _vq_quantlist__44c7_s_p5_0,
  133404. NULL,
  133405. &_vq_auxt__44c7_s_p5_0,
  133406. NULL,
  133407. 0
  133408. };
  133409. static long _vq_quantlist__44c7_s_p5_1[] = {
  133410. 5,
  133411. 4,
  133412. 6,
  133413. 3,
  133414. 7,
  133415. 2,
  133416. 8,
  133417. 1,
  133418. 9,
  133419. 0,
  133420. 10,
  133421. };
  133422. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133423. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133424. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133425. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133426. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133427. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133428. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133429. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133430. 11,11,11, 7, 7, 8, 8, 8, 8,
  133431. };
  133432. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133433. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133434. 3.5, 4.5,
  133435. };
  133436. static long _vq_quantmap__44c7_s_p5_1[] = {
  133437. 9, 7, 5, 3, 1, 0, 2, 4,
  133438. 6, 8, 10,
  133439. };
  133440. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133441. _vq_quantthresh__44c7_s_p5_1,
  133442. _vq_quantmap__44c7_s_p5_1,
  133443. 11,
  133444. 11
  133445. };
  133446. static static_codebook _44c7_s_p5_1 = {
  133447. 2, 121,
  133448. _vq_lengthlist__44c7_s_p5_1,
  133449. 1, -531365888, 1611661312, 4, 0,
  133450. _vq_quantlist__44c7_s_p5_1,
  133451. NULL,
  133452. &_vq_auxt__44c7_s_p5_1,
  133453. NULL,
  133454. 0
  133455. };
  133456. static long _vq_quantlist__44c7_s_p6_0[] = {
  133457. 6,
  133458. 5,
  133459. 7,
  133460. 4,
  133461. 8,
  133462. 3,
  133463. 9,
  133464. 2,
  133465. 10,
  133466. 1,
  133467. 11,
  133468. 0,
  133469. 12,
  133470. };
  133471. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133472. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133473. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133474. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133475. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133476. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133477. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133480. 0, 0, 0, 0, 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,
  133483. };
  133484. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133485. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133486. 12.5, 17.5, 22.5, 27.5,
  133487. };
  133488. static long _vq_quantmap__44c7_s_p6_0[] = {
  133489. 11, 9, 7, 5, 3, 1, 0, 2,
  133490. 4, 6, 8, 10, 12,
  133491. };
  133492. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133493. _vq_quantthresh__44c7_s_p6_0,
  133494. _vq_quantmap__44c7_s_p6_0,
  133495. 13,
  133496. 13
  133497. };
  133498. static static_codebook _44c7_s_p6_0 = {
  133499. 2, 169,
  133500. _vq_lengthlist__44c7_s_p6_0,
  133501. 1, -526516224, 1616117760, 4, 0,
  133502. _vq_quantlist__44c7_s_p6_0,
  133503. NULL,
  133504. &_vq_auxt__44c7_s_p6_0,
  133505. NULL,
  133506. 0
  133507. };
  133508. static long _vq_quantlist__44c7_s_p6_1[] = {
  133509. 2,
  133510. 1,
  133511. 3,
  133512. 0,
  133513. 4,
  133514. };
  133515. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133516. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133517. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133518. };
  133519. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133520. -1.5, -0.5, 0.5, 1.5,
  133521. };
  133522. static long _vq_quantmap__44c7_s_p6_1[] = {
  133523. 3, 1, 0, 2, 4,
  133524. };
  133525. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133526. _vq_quantthresh__44c7_s_p6_1,
  133527. _vq_quantmap__44c7_s_p6_1,
  133528. 5,
  133529. 5
  133530. };
  133531. static static_codebook _44c7_s_p6_1 = {
  133532. 2, 25,
  133533. _vq_lengthlist__44c7_s_p6_1,
  133534. 1, -533725184, 1611661312, 3, 0,
  133535. _vq_quantlist__44c7_s_p6_1,
  133536. NULL,
  133537. &_vq_auxt__44c7_s_p6_1,
  133538. NULL,
  133539. 0
  133540. };
  133541. static long _vq_quantlist__44c7_s_p7_0[] = {
  133542. 6,
  133543. 5,
  133544. 7,
  133545. 4,
  133546. 8,
  133547. 3,
  133548. 9,
  133549. 2,
  133550. 10,
  133551. 1,
  133552. 11,
  133553. 0,
  133554. 12,
  133555. };
  133556. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133557. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133558. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133559. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133560. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133561. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133562. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133563. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133564. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133565. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133566. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133567. 19,13,13,13,13,14,14,15,15,
  133568. };
  133569. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133570. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133571. 27.5, 38.5, 49.5, 60.5,
  133572. };
  133573. static long _vq_quantmap__44c7_s_p7_0[] = {
  133574. 11, 9, 7, 5, 3, 1, 0, 2,
  133575. 4, 6, 8, 10, 12,
  133576. };
  133577. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133578. _vq_quantthresh__44c7_s_p7_0,
  133579. _vq_quantmap__44c7_s_p7_0,
  133580. 13,
  133581. 13
  133582. };
  133583. static static_codebook _44c7_s_p7_0 = {
  133584. 2, 169,
  133585. _vq_lengthlist__44c7_s_p7_0,
  133586. 1, -523206656, 1618345984, 4, 0,
  133587. _vq_quantlist__44c7_s_p7_0,
  133588. NULL,
  133589. &_vq_auxt__44c7_s_p7_0,
  133590. NULL,
  133591. 0
  133592. };
  133593. static long _vq_quantlist__44c7_s_p7_1[] = {
  133594. 5,
  133595. 4,
  133596. 6,
  133597. 3,
  133598. 7,
  133599. 2,
  133600. 8,
  133601. 1,
  133602. 9,
  133603. 0,
  133604. 10,
  133605. };
  133606. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133607. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133608. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133609. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133610. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133611. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133612. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133613. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133614. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133615. };
  133616. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133617. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133618. 3.5, 4.5,
  133619. };
  133620. static long _vq_quantmap__44c7_s_p7_1[] = {
  133621. 9, 7, 5, 3, 1, 0, 2, 4,
  133622. 6, 8, 10,
  133623. };
  133624. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133625. _vq_quantthresh__44c7_s_p7_1,
  133626. _vq_quantmap__44c7_s_p7_1,
  133627. 11,
  133628. 11
  133629. };
  133630. static static_codebook _44c7_s_p7_1 = {
  133631. 2, 121,
  133632. _vq_lengthlist__44c7_s_p7_1,
  133633. 1, -531365888, 1611661312, 4, 0,
  133634. _vq_quantlist__44c7_s_p7_1,
  133635. NULL,
  133636. &_vq_auxt__44c7_s_p7_1,
  133637. NULL,
  133638. 0
  133639. };
  133640. static long _vq_quantlist__44c7_s_p8_0[] = {
  133641. 7,
  133642. 6,
  133643. 8,
  133644. 5,
  133645. 9,
  133646. 4,
  133647. 10,
  133648. 3,
  133649. 11,
  133650. 2,
  133651. 12,
  133652. 1,
  133653. 13,
  133654. 0,
  133655. 14,
  133656. };
  133657. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133658. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133659. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133660. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133661. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133662. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133663. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133664. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133665. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133666. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133667. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133668. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133669. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133670. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133671. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133672. 14,
  133673. };
  133674. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133675. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133676. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133677. };
  133678. static long _vq_quantmap__44c7_s_p8_0[] = {
  133679. 13, 11, 9, 7, 5, 3, 1, 0,
  133680. 2, 4, 6, 8, 10, 12, 14,
  133681. };
  133682. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133683. _vq_quantthresh__44c7_s_p8_0,
  133684. _vq_quantmap__44c7_s_p8_0,
  133685. 15,
  133686. 15
  133687. };
  133688. static static_codebook _44c7_s_p8_0 = {
  133689. 2, 225,
  133690. _vq_lengthlist__44c7_s_p8_0,
  133691. 1, -520986624, 1620377600, 4, 0,
  133692. _vq_quantlist__44c7_s_p8_0,
  133693. NULL,
  133694. &_vq_auxt__44c7_s_p8_0,
  133695. NULL,
  133696. 0
  133697. };
  133698. static long _vq_quantlist__44c7_s_p8_1[] = {
  133699. 10,
  133700. 9,
  133701. 11,
  133702. 8,
  133703. 12,
  133704. 7,
  133705. 13,
  133706. 6,
  133707. 14,
  133708. 5,
  133709. 15,
  133710. 4,
  133711. 16,
  133712. 3,
  133713. 17,
  133714. 2,
  133715. 18,
  133716. 1,
  133717. 19,
  133718. 0,
  133719. 20,
  133720. };
  133721. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133722. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133723. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133724. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133725. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133726. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133727. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133728. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133730. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133731. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133732. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133733. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133734. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133735. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133736. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133737. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133738. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133739. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133740. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133741. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133742. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133743. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133744. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133745. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133746. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133747. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133748. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133749. 10,10,10,10,10,10,10,10,10,
  133750. };
  133751. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133752. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133753. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133754. 6.5, 7.5, 8.5, 9.5,
  133755. };
  133756. static long _vq_quantmap__44c7_s_p8_1[] = {
  133757. 19, 17, 15, 13, 11, 9, 7, 5,
  133758. 3, 1, 0, 2, 4, 6, 8, 10,
  133759. 12, 14, 16, 18, 20,
  133760. };
  133761. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133762. _vq_quantthresh__44c7_s_p8_1,
  133763. _vq_quantmap__44c7_s_p8_1,
  133764. 21,
  133765. 21
  133766. };
  133767. static static_codebook _44c7_s_p8_1 = {
  133768. 2, 441,
  133769. _vq_lengthlist__44c7_s_p8_1,
  133770. 1, -529268736, 1611661312, 5, 0,
  133771. _vq_quantlist__44c7_s_p8_1,
  133772. NULL,
  133773. &_vq_auxt__44c7_s_p8_1,
  133774. NULL,
  133775. 0
  133776. };
  133777. static long _vq_quantlist__44c7_s_p9_0[] = {
  133778. 6,
  133779. 5,
  133780. 7,
  133781. 4,
  133782. 8,
  133783. 3,
  133784. 9,
  133785. 2,
  133786. 10,
  133787. 1,
  133788. 11,
  133789. 0,
  133790. 12,
  133791. };
  133792. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133793. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133794. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133803. 11,11,11,11,11,11,11,11,11,
  133804. };
  133805. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133806. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133807. 1592.5, 2229.5, 2866.5, 3503.5,
  133808. };
  133809. static long _vq_quantmap__44c7_s_p9_0[] = {
  133810. 11, 9, 7, 5, 3, 1, 0, 2,
  133811. 4, 6, 8, 10, 12,
  133812. };
  133813. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133814. _vq_quantthresh__44c7_s_p9_0,
  133815. _vq_quantmap__44c7_s_p9_0,
  133816. 13,
  133817. 13
  133818. };
  133819. static static_codebook _44c7_s_p9_0 = {
  133820. 2, 169,
  133821. _vq_lengthlist__44c7_s_p9_0,
  133822. 1, -511845376, 1630791680, 4, 0,
  133823. _vq_quantlist__44c7_s_p9_0,
  133824. NULL,
  133825. &_vq_auxt__44c7_s_p9_0,
  133826. NULL,
  133827. 0
  133828. };
  133829. static long _vq_quantlist__44c7_s_p9_1[] = {
  133830. 6,
  133831. 5,
  133832. 7,
  133833. 4,
  133834. 8,
  133835. 3,
  133836. 9,
  133837. 2,
  133838. 10,
  133839. 1,
  133840. 11,
  133841. 0,
  133842. 12,
  133843. };
  133844. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133845. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133846. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133847. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133848. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133849. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133850. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133851. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133852. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133853. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133854. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133855. 15,11,11,10,10,12,12,12,12,
  133856. };
  133857. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133858. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133859. 122.5, 171.5, 220.5, 269.5,
  133860. };
  133861. static long _vq_quantmap__44c7_s_p9_1[] = {
  133862. 11, 9, 7, 5, 3, 1, 0, 2,
  133863. 4, 6, 8, 10, 12,
  133864. };
  133865. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133866. _vq_quantthresh__44c7_s_p9_1,
  133867. _vq_quantmap__44c7_s_p9_1,
  133868. 13,
  133869. 13
  133870. };
  133871. static static_codebook _44c7_s_p9_1 = {
  133872. 2, 169,
  133873. _vq_lengthlist__44c7_s_p9_1,
  133874. 1, -518889472, 1622704128, 4, 0,
  133875. _vq_quantlist__44c7_s_p9_1,
  133876. NULL,
  133877. &_vq_auxt__44c7_s_p9_1,
  133878. NULL,
  133879. 0
  133880. };
  133881. static long _vq_quantlist__44c7_s_p9_2[] = {
  133882. 24,
  133883. 23,
  133884. 25,
  133885. 22,
  133886. 26,
  133887. 21,
  133888. 27,
  133889. 20,
  133890. 28,
  133891. 19,
  133892. 29,
  133893. 18,
  133894. 30,
  133895. 17,
  133896. 31,
  133897. 16,
  133898. 32,
  133899. 15,
  133900. 33,
  133901. 14,
  133902. 34,
  133903. 13,
  133904. 35,
  133905. 12,
  133906. 36,
  133907. 11,
  133908. 37,
  133909. 10,
  133910. 38,
  133911. 9,
  133912. 39,
  133913. 8,
  133914. 40,
  133915. 7,
  133916. 41,
  133917. 6,
  133918. 42,
  133919. 5,
  133920. 43,
  133921. 4,
  133922. 44,
  133923. 3,
  133924. 45,
  133925. 2,
  133926. 46,
  133927. 1,
  133928. 47,
  133929. 0,
  133930. 48,
  133931. };
  133932. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133933. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133934. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133935. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133936. 7,
  133937. };
  133938. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133939. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133940. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133941. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133942. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133943. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133944. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133945. };
  133946. static long _vq_quantmap__44c7_s_p9_2[] = {
  133947. 47, 45, 43, 41, 39, 37, 35, 33,
  133948. 31, 29, 27, 25, 23, 21, 19, 17,
  133949. 15, 13, 11, 9, 7, 5, 3, 1,
  133950. 0, 2, 4, 6, 8, 10, 12, 14,
  133951. 16, 18, 20, 22, 24, 26, 28, 30,
  133952. 32, 34, 36, 38, 40, 42, 44, 46,
  133953. 48,
  133954. };
  133955. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133956. _vq_quantthresh__44c7_s_p9_2,
  133957. _vq_quantmap__44c7_s_p9_2,
  133958. 49,
  133959. 49
  133960. };
  133961. static static_codebook _44c7_s_p9_2 = {
  133962. 1, 49,
  133963. _vq_lengthlist__44c7_s_p9_2,
  133964. 1, -526909440, 1611661312, 6, 0,
  133965. _vq_quantlist__44c7_s_p9_2,
  133966. NULL,
  133967. &_vq_auxt__44c7_s_p9_2,
  133968. NULL,
  133969. 0
  133970. };
  133971. static long _huff_lengthlist__44c7_s_short[] = {
  133972. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133973. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133974. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133975. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133976. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133977. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133978. 10, 9,11,14,
  133979. };
  133980. static static_codebook _huff_book__44c7_s_short = {
  133981. 2, 100,
  133982. _huff_lengthlist__44c7_s_short,
  133983. 0, 0, 0, 0, 0,
  133984. NULL,
  133985. NULL,
  133986. NULL,
  133987. NULL,
  133988. 0
  133989. };
  133990. static long _huff_lengthlist__44c8_s_long[] = {
  133991. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133992. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133993. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133994. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133995. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133996. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133997. 11, 9, 9,10,
  133998. };
  133999. static static_codebook _huff_book__44c8_s_long = {
  134000. 2, 100,
  134001. _huff_lengthlist__44c8_s_long,
  134002. 0, 0, 0, 0, 0,
  134003. NULL,
  134004. NULL,
  134005. NULL,
  134006. NULL,
  134007. 0
  134008. };
  134009. static long _vq_quantlist__44c8_s_p1_0[] = {
  134010. 1,
  134011. 0,
  134012. 2,
  134013. };
  134014. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134015. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134016. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134017. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134018. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134019. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134020. 8,
  134021. };
  134022. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134023. -0.5, 0.5,
  134024. };
  134025. static long _vq_quantmap__44c8_s_p1_0[] = {
  134026. 1, 0, 2,
  134027. };
  134028. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134029. _vq_quantthresh__44c8_s_p1_0,
  134030. _vq_quantmap__44c8_s_p1_0,
  134031. 3,
  134032. 3
  134033. };
  134034. static static_codebook _44c8_s_p1_0 = {
  134035. 4, 81,
  134036. _vq_lengthlist__44c8_s_p1_0,
  134037. 1, -535822336, 1611661312, 2, 0,
  134038. _vq_quantlist__44c8_s_p1_0,
  134039. NULL,
  134040. &_vq_auxt__44c8_s_p1_0,
  134041. NULL,
  134042. 0
  134043. };
  134044. static long _vq_quantlist__44c8_s_p2_0[] = {
  134045. 2,
  134046. 1,
  134047. 3,
  134048. 0,
  134049. 4,
  134050. };
  134051. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134052. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134053. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134054. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134055. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134056. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134057. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134058. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134059. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134062. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134063. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134064. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134065. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134066. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134067. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134070. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134071. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134072. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134073. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134074. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134075. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134077. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134078. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134079. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134080. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134081. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134082. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134083. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134088. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134089. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134090. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134091. 13,
  134092. };
  134093. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134094. -1.5, -0.5, 0.5, 1.5,
  134095. };
  134096. static long _vq_quantmap__44c8_s_p2_0[] = {
  134097. 3, 1, 0, 2, 4,
  134098. };
  134099. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134100. _vq_quantthresh__44c8_s_p2_0,
  134101. _vq_quantmap__44c8_s_p2_0,
  134102. 5,
  134103. 5
  134104. };
  134105. static static_codebook _44c8_s_p2_0 = {
  134106. 4, 625,
  134107. _vq_lengthlist__44c8_s_p2_0,
  134108. 1, -533725184, 1611661312, 3, 0,
  134109. _vq_quantlist__44c8_s_p2_0,
  134110. NULL,
  134111. &_vq_auxt__44c8_s_p2_0,
  134112. NULL,
  134113. 0
  134114. };
  134115. static long _vq_quantlist__44c8_s_p3_0[] = {
  134116. 4,
  134117. 3,
  134118. 5,
  134119. 2,
  134120. 6,
  134121. 1,
  134122. 7,
  134123. 0,
  134124. 8,
  134125. };
  134126. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134127. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134128. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134129. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134130. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0,
  134133. };
  134134. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134135. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134136. };
  134137. static long _vq_quantmap__44c8_s_p3_0[] = {
  134138. 7, 5, 3, 1, 0, 2, 4, 6,
  134139. 8,
  134140. };
  134141. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134142. _vq_quantthresh__44c8_s_p3_0,
  134143. _vq_quantmap__44c8_s_p3_0,
  134144. 9,
  134145. 9
  134146. };
  134147. static static_codebook _44c8_s_p3_0 = {
  134148. 2, 81,
  134149. _vq_lengthlist__44c8_s_p3_0,
  134150. 1, -531628032, 1611661312, 4, 0,
  134151. _vq_quantlist__44c8_s_p3_0,
  134152. NULL,
  134153. &_vq_auxt__44c8_s_p3_0,
  134154. NULL,
  134155. 0
  134156. };
  134157. static long _vq_quantlist__44c8_s_p4_0[] = {
  134158. 8,
  134159. 7,
  134160. 9,
  134161. 6,
  134162. 10,
  134163. 5,
  134164. 11,
  134165. 4,
  134166. 12,
  134167. 3,
  134168. 13,
  134169. 2,
  134170. 14,
  134171. 1,
  134172. 15,
  134173. 0,
  134174. 16,
  134175. };
  134176. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134177. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134178. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134179. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134180. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134181. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134182. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134183. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134184. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134185. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134186. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134195. 0,
  134196. };
  134197. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134198. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134199. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134200. };
  134201. static long _vq_quantmap__44c8_s_p4_0[] = {
  134202. 15, 13, 11, 9, 7, 5, 3, 1,
  134203. 0, 2, 4, 6, 8, 10, 12, 14,
  134204. 16,
  134205. };
  134206. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134207. _vq_quantthresh__44c8_s_p4_0,
  134208. _vq_quantmap__44c8_s_p4_0,
  134209. 17,
  134210. 17
  134211. };
  134212. static static_codebook _44c8_s_p4_0 = {
  134213. 2, 289,
  134214. _vq_lengthlist__44c8_s_p4_0,
  134215. 1, -529530880, 1611661312, 5, 0,
  134216. _vq_quantlist__44c8_s_p4_0,
  134217. NULL,
  134218. &_vq_auxt__44c8_s_p4_0,
  134219. NULL,
  134220. 0
  134221. };
  134222. static long _vq_quantlist__44c8_s_p5_0[] = {
  134223. 1,
  134224. 0,
  134225. 2,
  134226. };
  134227. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134228. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134229. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134230. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134231. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134232. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134233. 12,
  134234. };
  134235. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134236. -5.5, 5.5,
  134237. };
  134238. static long _vq_quantmap__44c8_s_p5_0[] = {
  134239. 1, 0, 2,
  134240. };
  134241. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134242. _vq_quantthresh__44c8_s_p5_0,
  134243. _vq_quantmap__44c8_s_p5_0,
  134244. 3,
  134245. 3
  134246. };
  134247. static static_codebook _44c8_s_p5_0 = {
  134248. 4, 81,
  134249. _vq_lengthlist__44c8_s_p5_0,
  134250. 1, -529137664, 1618345984, 2, 0,
  134251. _vq_quantlist__44c8_s_p5_0,
  134252. NULL,
  134253. &_vq_auxt__44c8_s_p5_0,
  134254. NULL,
  134255. 0
  134256. };
  134257. static long _vq_quantlist__44c8_s_p5_1[] = {
  134258. 5,
  134259. 4,
  134260. 6,
  134261. 3,
  134262. 7,
  134263. 2,
  134264. 8,
  134265. 1,
  134266. 9,
  134267. 0,
  134268. 10,
  134269. };
  134270. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134271. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134272. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134273. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134274. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134275. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134276. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134277. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134278. 11,11,11, 7, 7, 7, 7, 8, 8,
  134279. };
  134280. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134282. 3.5, 4.5,
  134283. };
  134284. static long _vq_quantmap__44c8_s_p5_1[] = {
  134285. 9, 7, 5, 3, 1, 0, 2, 4,
  134286. 6, 8, 10,
  134287. };
  134288. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134289. _vq_quantthresh__44c8_s_p5_1,
  134290. _vq_quantmap__44c8_s_p5_1,
  134291. 11,
  134292. 11
  134293. };
  134294. static static_codebook _44c8_s_p5_1 = {
  134295. 2, 121,
  134296. _vq_lengthlist__44c8_s_p5_1,
  134297. 1, -531365888, 1611661312, 4, 0,
  134298. _vq_quantlist__44c8_s_p5_1,
  134299. NULL,
  134300. &_vq_auxt__44c8_s_p5_1,
  134301. NULL,
  134302. 0
  134303. };
  134304. static long _vq_quantlist__44c8_s_p6_0[] = {
  134305. 6,
  134306. 5,
  134307. 7,
  134308. 4,
  134309. 8,
  134310. 3,
  134311. 9,
  134312. 2,
  134313. 10,
  134314. 1,
  134315. 11,
  134316. 0,
  134317. 12,
  134318. };
  134319. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134320. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134321. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134322. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134323. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134324. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134325. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 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,
  134331. };
  134332. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134333. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134334. 12.5, 17.5, 22.5, 27.5,
  134335. };
  134336. static long _vq_quantmap__44c8_s_p6_0[] = {
  134337. 11, 9, 7, 5, 3, 1, 0, 2,
  134338. 4, 6, 8, 10, 12,
  134339. };
  134340. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134341. _vq_quantthresh__44c8_s_p6_0,
  134342. _vq_quantmap__44c8_s_p6_0,
  134343. 13,
  134344. 13
  134345. };
  134346. static static_codebook _44c8_s_p6_0 = {
  134347. 2, 169,
  134348. _vq_lengthlist__44c8_s_p6_0,
  134349. 1, -526516224, 1616117760, 4, 0,
  134350. _vq_quantlist__44c8_s_p6_0,
  134351. NULL,
  134352. &_vq_auxt__44c8_s_p6_0,
  134353. NULL,
  134354. 0
  134355. };
  134356. static long _vq_quantlist__44c8_s_p6_1[] = {
  134357. 2,
  134358. 1,
  134359. 3,
  134360. 0,
  134361. 4,
  134362. };
  134363. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134364. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134365. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134366. };
  134367. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134368. -1.5, -0.5, 0.5, 1.5,
  134369. };
  134370. static long _vq_quantmap__44c8_s_p6_1[] = {
  134371. 3, 1, 0, 2, 4,
  134372. };
  134373. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134374. _vq_quantthresh__44c8_s_p6_1,
  134375. _vq_quantmap__44c8_s_p6_1,
  134376. 5,
  134377. 5
  134378. };
  134379. static static_codebook _44c8_s_p6_1 = {
  134380. 2, 25,
  134381. _vq_lengthlist__44c8_s_p6_1,
  134382. 1, -533725184, 1611661312, 3, 0,
  134383. _vq_quantlist__44c8_s_p6_1,
  134384. NULL,
  134385. &_vq_auxt__44c8_s_p6_1,
  134386. NULL,
  134387. 0
  134388. };
  134389. static long _vq_quantlist__44c8_s_p7_0[] = {
  134390. 6,
  134391. 5,
  134392. 7,
  134393. 4,
  134394. 8,
  134395. 3,
  134396. 9,
  134397. 2,
  134398. 10,
  134399. 1,
  134400. 11,
  134401. 0,
  134402. 12,
  134403. };
  134404. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134405. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134406. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134407. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134408. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134409. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134410. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134411. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134412. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134413. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134414. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134415. 20,13,13,13,13,14,13,15,15,
  134416. };
  134417. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134418. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134419. 27.5, 38.5, 49.5, 60.5,
  134420. };
  134421. static long _vq_quantmap__44c8_s_p7_0[] = {
  134422. 11, 9, 7, 5, 3, 1, 0, 2,
  134423. 4, 6, 8, 10, 12,
  134424. };
  134425. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134426. _vq_quantthresh__44c8_s_p7_0,
  134427. _vq_quantmap__44c8_s_p7_0,
  134428. 13,
  134429. 13
  134430. };
  134431. static static_codebook _44c8_s_p7_0 = {
  134432. 2, 169,
  134433. _vq_lengthlist__44c8_s_p7_0,
  134434. 1, -523206656, 1618345984, 4, 0,
  134435. _vq_quantlist__44c8_s_p7_0,
  134436. NULL,
  134437. &_vq_auxt__44c8_s_p7_0,
  134438. NULL,
  134439. 0
  134440. };
  134441. static long _vq_quantlist__44c8_s_p7_1[] = {
  134442. 5,
  134443. 4,
  134444. 6,
  134445. 3,
  134446. 7,
  134447. 2,
  134448. 8,
  134449. 1,
  134450. 9,
  134451. 0,
  134452. 10,
  134453. };
  134454. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134455. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134456. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134457. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134458. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134459. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134460. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134461. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134462. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134463. };
  134464. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134465. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134466. 3.5, 4.5,
  134467. };
  134468. static long _vq_quantmap__44c8_s_p7_1[] = {
  134469. 9, 7, 5, 3, 1, 0, 2, 4,
  134470. 6, 8, 10,
  134471. };
  134472. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134473. _vq_quantthresh__44c8_s_p7_1,
  134474. _vq_quantmap__44c8_s_p7_1,
  134475. 11,
  134476. 11
  134477. };
  134478. static static_codebook _44c8_s_p7_1 = {
  134479. 2, 121,
  134480. _vq_lengthlist__44c8_s_p7_1,
  134481. 1, -531365888, 1611661312, 4, 0,
  134482. _vq_quantlist__44c8_s_p7_1,
  134483. NULL,
  134484. &_vq_auxt__44c8_s_p7_1,
  134485. NULL,
  134486. 0
  134487. };
  134488. static long _vq_quantlist__44c8_s_p8_0[] = {
  134489. 7,
  134490. 6,
  134491. 8,
  134492. 5,
  134493. 9,
  134494. 4,
  134495. 10,
  134496. 3,
  134497. 11,
  134498. 2,
  134499. 12,
  134500. 1,
  134501. 13,
  134502. 0,
  134503. 14,
  134504. };
  134505. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134506. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134507. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134508. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134509. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134510. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134511. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134512. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134513. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134514. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134515. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134516. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134517. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134518. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134519. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134520. 15,
  134521. };
  134522. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134523. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134524. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134525. };
  134526. static long _vq_quantmap__44c8_s_p8_0[] = {
  134527. 13, 11, 9, 7, 5, 3, 1, 0,
  134528. 2, 4, 6, 8, 10, 12, 14,
  134529. };
  134530. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134531. _vq_quantthresh__44c8_s_p8_0,
  134532. _vq_quantmap__44c8_s_p8_0,
  134533. 15,
  134534. 15
  134535. };
  134536. static static_codebook _44c8_s_p8_0 = {
  134537. 2, 225,
  134538. _vq_lengthlist__44c8_s_p8_0,
  134539. 1, -520986624, 1620377600, 4, 0,
  134540. _vq_quantlist__44c8_s_p8_0,
  134541. NULL,
  134542. &_vq_auxt__44c8_s_p8_0,
  134543. NULL,
  134544. 0
  134545. };
  134546. static long _vq_quantlist__44c8_s_p8_1[] = {
  134547. 10,
  134548. 9,
  134549. 11,
  134550. 8,
  134551. 12,
  134552. 7,
  134553. 13,
  134554. 6,
  134555. 14,
  134556. 5,
  134557. 15,
  134558. 4,
  134559. 16,
  134560. 3,
  134561. 17,
  134562. 2,
  134563. 18,
  134564. 1,
  134565. 19,
  134566. 0,
  134567. 20,
  134568. };
  134569. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134570. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134571. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134572. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134573. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134574. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134575. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134576. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134577. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134578. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134579. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134580. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134581. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134582. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134583. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134584. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134585. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134586. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134587. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134588. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134589. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134590. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134591. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134592. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134593. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134594. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134595. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134596. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134597. 10, 9, 9,10,10, 9,10, 9, 9,
  134598. };
  134599. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134600. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134601. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134602. 6.5, 7.5, 8.5, 9.5,
  134603. };
  134604. static long _vq_quantmap__44c8_s_p8_1[] = {
  134605. 19, 17, 15, 13, 11, 9, 7, 5,
  134606. 3, 1, 0, 2, 4, 6, 8, 10,
  134607. 12, 14, 16, 18, 20,
  134608. };
  134609. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134610. _vq_quantthresh__44c8_s_p8_1,
  134611. _vq_quantmap__44c8_s_p8_1,
  134612. 21,
  134613. 21
  134614. };
  134615. static static_codebook _44c8_s_p8_1 = {
  134616. 2, 441,
  134617. _vq_lengthlist__44c8_s_p8_1,
  134618. 1, -529268736, 1611661312, 5, 0,
  134619. _vq_quantlist__44c8_s_p8_1,
  134620. NULL,
  134621. &_vq_auxt__44c8_s_p8_1,
  134622. NULL,
  134623. 0
  134624. };
  134625. static long _vq_quantlist__44c8_s_p9_0[] = {
  134626. 8,
  134627. 7,
  134628. 9,
  134629. 6,
  134630. 10,
  134631. 5,
  134632. 11,
  134633. 4,
  134634. 12,
  134635. 3,
  134636. 13,
  134637. 2,
  134638. 14,
  134639. 1,
  134640. 15,
  134641. 0,
  134642. 16,
  134643. };
  134644. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134645. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134646. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134647. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134659. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134663. 10,
  134664. };
  134665. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134666. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134667. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134668. };
  134669. static long _vq_quantmap__44c8_s_p9_0[] = {
  134670. 15, 13, 11, 9, 7, 5, 3, 1,
  134671. 0, 2, 4, 6, 8, 10, 12, 14,
  134672. 16,
  134673. };
  134674. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134675. _vq_quantthresh__44c8_s_p9_0,
  134676. _vq_quantmap__44c8_s_p9_0,
  134677. 17,
  134678. 17
  134679. };
  134680. static static_codebook _44c8_s_p9_0 = {
  134681. 2, 289,
  134682. _vq_lengthlist__44c8_s_p9_0,
  134683. 1, -509798400, 1631393792, 5, 0,
  134684. _vq_quantlist__44c8_s_p9_0,
  134685. NULL,
  134686. &_vq_auxt__44c8_s_p9_0,
  134687. NULL,
  134688. 0
  134689. };
  134690. static long _vq_quantlist__44c8_s_p9_1[] = {
  134691. 9,
  134692. 8,
  134693. 10,
  134694. 7,
  134695. 11,
  134696. 6,
  134697. 12,
  134698. 5,
  134699. 13,
  134700. 4,
  134701. 14,
  134702. 3,
  134703. 15,
  134704. 2,
  134705. 16,
  134706. 1,
  134707. 17,
  134708. 0,
  134709. 18,
  134710. };
  134711. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134712. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134713. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134714. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134715. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134716. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134717. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134718. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134719. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134720. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134721. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134722. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134723. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134724. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134725. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134726. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134727. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134728. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134729. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134730. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134731. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134732. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134733. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134734. 14,13,13,14,14,15,14,15,14,
  134735. };
  134736. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134737. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134738. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134739. 367.5, 416.5,
  134740. };
  134741. static long _vq_quantmap__44c8_s_p9_1[] = {
  134742. 17, 15, 13, 11, 9, 7, 5, 3,
  134743. 1, 0, 2, 4, 6, 8, 10, 12,
  134744. 14, 16, 18,
  134745. };
  134746. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134747. _vq_quantthresh__44c8_s_p9_1,
  134748. _vq_quantmap__44c8_s_p9_1,
  134749. 19,
  134750. 19
  134751. };
  134752. static static_codebook _44c8_s_p9_1 = {
  134753. 2, 361,
  134754. _vq_lengthlist__44c8_s_p9_1,
  134755. 1, -518287360, 1622704128, 5, 0,
  134756. _vq_quantlist__44c8_s_p9_1,
  134757. NULL,
  134758. &_vq_auxt__44c8_s_p9_1,
  134759. NULL,
  134760. 0
  134761. };
  134762. static long _vq_quantlist__44c8_s_p9_2[] = {
  134763. 24,
  134764. 23,
  134765. 25,
  134766. 22,
  134767. 26,
  134768. 21,
  134769. 27,
  134770. 20,
  134771. 28,
  134772. 19,
  134773. 29,
  134774. 18,
  134775. 30,
  134776. 17,
  134777. 31,
  134778. 16,
  134779. 32,
  134780. 15,
  134781. 33,
  134782. 14,
  134783. 34,
  134784. 13,
  134785. 35,
  134786. 12,
  134787. 36,
  134788. 11,
  134789. 37,
  134790. 10,
  134791. 38,
  134792. 9,
  134793. 39,
  134794. 8,
  134795. 40,
  134796. 7,
  134797. 41,
  134798. 6,
  134799. 42,
  134800. 5,
  134801. 43,
  134802. 4,
  134803. 44,
  134804. 3,
  134805. 45,
  134806. 2,
  134807. 46,
  134808. 1,
  134809. 47,
  134810. 0,
  134811. 48,
  134812. };
  134813. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134814. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134815. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134816. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134817. 7,
  134818. };
  134819. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134820. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134821. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134822. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134823. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134824. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134825. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134826. };
  134827. static long _vq_quantmap__44c8_s_p9_2[] = {
  134828. 47, 45, 43, 41, 39, 37, 35, 33,
  134829. 31, 29, 27, 25, 23, 21, 19, 17,
  134830. 15, 13, 11, 9, 7, 5, 3, 1,
  134831. 0, 2, 4, 6, 8, 10, 12, 14,
  134832. 16, 18, 20, 22, 24, 26, 28, 30,
  134833. 32, 34, 36, 38, 40, 42, 44, 46,
  134834. 48,
  134835. };
  134836. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134837. _vq_quantthresh__44c8_s_p9_2,
  134838. _vq_quantmap__44c8_s_p9_2,
  134839. 49,
  134840. 49
  134841. };
  134842. static static_codebook _44c8_s_p9_2 = {
  134843. 1, 49,
  134844. _vq_lengthlist__44c8_s_p9_2,
  134845. 1, -526909440, 1611661312, 6, 0,
  134846. _vq_quantlist__44c8_s_p9_2,
  134847. NULL,
  134848. &_vq_auxt__44c8_s_p9_2,
  134849. NULL,
  134850. 0
  134851. };
  134852. static long _huff_lengthlist__44c8_s_short[] = {
  134853. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134854. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134855. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134856. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134857. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134858. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134859. 10, 9,11,14,
  134860. };
  134861. static static_codebook _huff_book__44c8_s_short = {
  134862. 2, 100,
  134863. _huff_lengthlist__44c8_s_short,
  134864. 0, 0, 0, 0, 0,
  134865. NULL,
  134866. NULL,
  134867. NULL,
  134868. NULL,
  134869. 0
  134870. };
  134871. static long _huff_lengthlist__44c9_s_long[] = {
  134872. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134873. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134874. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134875. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134876. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134877. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134878. 10, 9, 8, 9,
  134879. };
  134880. static static_codebook _huff_book__44c9_s_long = {
  134881. 2, 100,
  134882. _huff_lengthlist__44c9_s_long,
  134883. 0, 0, 0, 0, 0,
  134884. NULL,
  134885. NULL,
  134886. NULL,
  134887. NULL,
  134888. 0
  134889. };
  134890. static long _vq_quantlist__44c9_s_p1_0[] = {
  134891. 1,
  134892. 0,
  134893. 2,
  134894. };
  134895. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134896. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134897. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134899. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134900. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134901. 7,
  134902. };
  134903. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134904. -0.5, 0.5,
  134905. };
  134906. static long _vq_quantmap__44c9_s_p1_0[] = {
  134907. 1, 0, 2,
  134908. };
  134909. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134910. _vq_quantthresh__44c9_s_p1_0,
  134911. _vq_quantmap__44c9_s_p1_0,
  134912. 3,
  134913. 3
  134914. };
  134915. static static_codebook _44c9_s_p1_0 = {
  134916. 4, 81,
  134917. _vq_lengthlist__44c9_s_p1_0,
  134918. 1, -535822336, 1611661312, 2, 0,
  134919. _vq_quantlist__44c9_s_p1_0,
  134920. NULL,
  134921. &_vq_auxt__44c9_s_p1_0,
  134922. NULL,
  134923. 0
  134924. };
  134925. static long _vq_quantlist__44c9_s_p2_0[] = {
  134926. 2,
  134927. 1,
  134928. 3,
  134929. 0,
  134930. 4,
  134931. };
  134932. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134933. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134934. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134935. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134936. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134937. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134938. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134939. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134940. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134943. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134944. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134945. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134946. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134947. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134948. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134951. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134952. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134953. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134954. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134955. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134956. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134959. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134960. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134961. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134962. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134963. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134964. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134969. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134970. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134971. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134972. 12,
  134973. };
  134974. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134975. -1.5, -0.5, 0.5, 1.5,
  134976. };
  134977. static long _vq_quantmap__44c9_s_p2_0[] = {
  134978. 3, 1, 0, 2, 4,
  134979. };
  134980. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134981. _vq_quantthresh__44c9_s_p2_0,
  134982. _vq_quantmap__44c9_s_p2_0,
  134983. 5,
  134984. 5
  134985. };
  134986. static static_codebook _44c9_s_p2_0 = {
  134987. 4, 625,
  134988. _vq_lengthlist__44c9_s_p2_0,
  134989. 1, -533725184, 1611661312, 3, 0,
  134990. _vq_quantlist__44c9_s_p2_0,
  134991. NULL,
  134992. &_vq_auxt__44c9_s_p2_0,
  134993. NULL,
  134994. 0
  134995. };
  134996. static long _vq_quantlist__44c9_s_p3_0[] = {
  134997. 4,
  134998. 3,
  134999. 5,
  135000. 2,
  135001. 6,
  135002. 1,
  135003. 7,
  135004. 0,
  135005. 8,
  135006. };
  135007. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135008. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135009. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135010. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135011. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0,
  135014. };
  135015. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135016. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135017. };
  135018. static long _vq_quantmap__44c9_s_p3_0[] = {
  135019. 7, 5, 3, 1, 0, 2, 4, 6,
  135020. 8,
  135021. };
  135022. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135023. _vq_quantthresh__44c9_s_p3_0,
  135024. _vq_quantmap__44c9_s_p3_0,
  135025. 9,
  135026. 9
  135027. };
  135028. static static_codebook _44c9_s_p3_0 = {
  135029. 2, 81,
  135030. _vq_lengthlist__44c9_s_p3_0,
  135031. 1, -531628032, 1611661312, 4, 0,
  135032. _vq_quantlist__44c9_s_p3_0,
  135033. NULL,
  135034. &_vq_auxt__44c9_s_p3_0,
  135035. NULL,
  135036. 0
  135037. };
  135038. static long _vq_quantlist__44c9_s_p4_0[] = {
  135039. 8,
  135040. 7,
  135041. 9,
  135042. 6,
  135043. 10,
  135044. 5,
  135045. 11,
  135046. 4,
  135047. 12,
  135048. 3,
  135049. 13,
  135050. 2,
  135051. 14,
  135052. 1,
  135053. 15,
  135054. 0,
  135055. 16,
  135056. };
  135057. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135058. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135059. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135060. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135061. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135062. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135063. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135064. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135065. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135066. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135067. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0,
  135077. };
  135078. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135079. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135080. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135081. };
  135082. static long _vq_quantmap__44c9_s_p4_0[] = {
  135083. 15, 13, 11, 9, 7, 5, 3, 1,
  135084. 0, 2, 4, 6, 8, 10, 12, 14,
  135085. 16,
  135086. };
  135087. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135088. _vq_quantthresh__44c9_s_p4_0,
  135089. _vq_quantmap__44c9_s_p4_0,
  135090. 17,
  135091. 17
  135092. };
  135093. static static_codebook _44c9_s_p4_0 = {
  135094. 2, 289,
  135095. _vq_lengthlist__44c9_s_p4_0,
  135096. 1, -529530880, 1611661312, 5, 0,
  135097. _vq_quantlist__44c9_s_p4_0,
  135098. NULL,
  135099. &_vq_auxt__44c9_s_p4_0,
  135100. NULL,
  135101. 0
  135102. };
  135103. static long _vq_quantlist__44c9_s_p5_0[] = {
  135104. 1,
  135105. 0,
  135106. 2,
  135107. };
  135108. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135109. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135110. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135111. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135112. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135113. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135114. 12,
  135115. };
  135116. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135117. -5.5, 5.5,
  135118. };
  135119. static long _vq_quantmap__44c9_s_p5_0[] = {
  135120. 1, 0, 2,
  135121. };
  135122. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135123. _vq_quantthresh__44c9_s_p5_0,
  135124. _vq_quantmap__44c9_s_p5_0,
  135125. 3,
  135126. 3
  135127. };
  135128. static static_codebook _44c9_s_p5_0 = {
  135129. 4, 81,
  135130. _vq_lengthlist__44c9_s_p5_0,
  135131. 1, -529137664, 1618345984, 2, 0,
  135132. _vq_quantlist__44c9_s_p5_0,
  135133. NULL,
  135134. &_vq_auxt__44c9_s_p5_0,
  135135. NULL,
  135136. 0
  135137. };
  135138. static long _vq_quantlist__44c9_s_p5_1[] = {
  135139. 5,
  135140. 4,
  135141. 6,
  135142. 3,
  135143. 7,
  135144. 2,
  135145. 8,
  135146. 1,
  135147. 9,
  135148. 0,
  135149. 10,
  135150. };
  135151. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135152. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135153. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135154. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135155. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135156. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135157. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135158. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135159. 11,11,11, 7, 7, 7, 7, 7, 7,
  135160. };
  135161. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135162. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135163. 3.5, 4.5,
  135164. };
  135165. static long _vq_quantmap__44c9_s_p5_1[] = {
  135166. 9, 7, 5, 3, 1, 0, 2, 4,
  135167. 6, 8, 10,
  135168. };
  135169. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135170. _vq_quantthresh__44c9_s_p5_1,
  135171. _vq_quantmap__44c9_s_p5_1,
  135172. 11,
  135173. 11
  135174. };
  135175. static static_codebook _44c9_s_p5_1 = {
  135176. 2, 121,
  135177. _vq_lengthlist__44c9_s_p5_1,
  135178. 1, -531365888, 1611661312, 4, 0,
  135179. _vq_quantlist__44c9_s_p5_1,
  135180. NULL,
  135181. &_vq_auxt__44c9_s_p5_1,
  135182. NULL,
  135183. 0
  135184. };
  135185. static long _vq_quantlist__44c9_s_p6_0[] = {
  135186. 6,
  135187. 5,
  135188. 7,
  135189. 4,
  135190. 8,
  135191. 3,
  135192. 9,
  135193. 2,
  135194. 10,
  135195. 1,
  135196. 11,
  135197. 0,
  135198. 12,
  135199. };
  135200. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135201. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135202. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135203. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135204. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135205. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135206. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 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,
  135212. };
  135213. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135214. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135215. 12.5, 17.5, 22.5, 27.5,
  135216. };
  135217. static long _vq_quantmap__44c9_s_p6_0[] = {
  135218. 11, 9, 7, 5, 3, 1, 0, 2,
  135219. 4, 6, 8, 10, 12,
  135220. };
  135221. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135222. _vq_quantthresh__44c9_s_p6_0,
  135223. _vq_quantmap__44c9_s_p6_0,
  135224. 13,
  135225. 13
  135226. };
  135227. static static_codebook _44c9_s_p6_0 = {
  135228. 2, 169,
  135229. _vq_lengthlist__44c9_s_p6_0,
  135230. 1, -526516224, 1616117760, 4, 0,
  135231. _vq_quantlist__44c9_s_p6_0,
  135232. NULL,
  135233. &_vq_auxt__44c9_s_p6_0,
  135234. NULL,
  135235. 0
  135236. };
  135237. static long _vq_quantlist__44c9_s_p6_1[] = {
  135238. 2,
  135239. 1,
  135240. 3,
  135241. 0,
  135242. 4,
  135243. };
  135244. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135245. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135246. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135247. };
  135248. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135249. -1.5, -0.5, 0.5, 1.5,
  135250. };
  135251. static long _vq_quantmap__44c9_s_p6_1[] = {
  135252. 3, 1, 0, 2, 4,
  135253. };
  135254. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135255. _vq_quantthresh__44c9_s_p6_1,
  135256. _vq_quantmap__44c9_s_p6_1,
  135257. 5,
  135258. 5
  135259. };
  135260. static static_codebook _44c9_s_p6_1 = {
  135261. 2, 25,
  135262. _vq_lengthlist__44c9_s_p6_1,
  135263. 1, -533725184, 1611661312, 3, 0,
  135264. _vq_quantlist__44c9_s_p6_1,
  135265. NULL,
  135266. &_vq_auxt__44c9_s_p6_1,
  135267. NULL,
  135268. 0
  135269. };
  135270. static long _vq_quantlist__44c9_s_p7_0[] = {
  135271. 6,
  135272. 5,
  135273. 7,
  135274. 4,
  135275. 8,
  135276. 3,
  135277. 9,
  135278. 2,
  135279. 10,
  135280. 1,
  135281. 11,
  135282. 0,
  135283. 12,
  135284. };
  135285. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135286. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135287. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135288. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135289. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135290. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135291. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135292. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135293. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135294. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135295. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135296. 19,12,12,12,12,13,13,14,14,
  135297. };
  135298. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135299. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135300. 27.5, 38.5, 49.5, 60.5,
  135301. };
  135302. static long _vq_quantmap__44c9_s_p7_0[] = {
  135303. 11, 9, 7, 5, 3, 1, 0, 2,
  135304. 4, 6, 8, 10, 12,
  135305. };
  135306. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135307. _vq_quantthresh__44c9_s_p7_0,
  135308. _vq_quantmap__44c9_s_p7_0,
  135309. 13,
  135310. 13
  135311. };
  135312. static static_codebook _44c9_s_p7_0 = {
  135313. 2, 169,
  135314. _vq_lengthlist__44c9_s_p7_0,
  135315. 1, -523206656, 1618345984, 4, 0,
  135316. _vq_quantlist__44c9_s_p7_0,
  135317. NULL,
  135318. &_vq_auxt__44c9_s_p7_0,
  135319. NULL,
  135320. 0
  135321. };
  135322. static long _vq_quantlist__44c9_s_p7_1[] = {
  135323. 5,
  135324. 4,
  135325. 6,
  135326. 3,
  135327. 7,
  135328. 2,
  135329. 8,
  135330. 1,
  135331. 9,
  135332. 0,
  135333. 10,
  135334. };
  135335. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135336. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135337. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135338. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135339. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135340. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135341. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135342. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135343. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135344. };
  135345. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135346. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135347. 3.5, 4.5,
  135348. };
  135349. static long _vq_quantmap__44c9_s_p7_1[] = {
  135350. 9, 7, 5, 3, 1, 0, 2, 4,
  135351. 6, 8, 10,
  135352. };
  135353. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135354. _vq_quantthresh__44c9_s_p7_1,
  135355. _vq_quantmap__44c9_s_p7_1,
  135356. 11,
  135357. 11
  135358. };
  135359. static static_codebook _44c9_s_p7_1 = {
  135360. 2, 121,
  135361. _vq_lengthlist__44c9_s_p7_1,
  135362. 1, -531365888, 1611661312, 4, 0,
  135363. _vq_quantlist__44c9_s_p7_1,
  135364. NULL,
  135365. &_vq_auxt__44c9_s_p7_1,
  135366. NULL,
  135367. 0
  135368. };
  135369. static long _vq_quantlist__44c9_s_p8_0[] = {
  135370. 7,
  135371. 6,
  135372. 8,
  135373. 5,
  135374. 9,
  135375. 4,
  135376. 10,
  135377. 3,
  135378. 11,
  135379. 2,
  135380. 12,
  135381. 1,
  135382. 13,
  135383. 0,
  135384. 14,
  135385. };
  135386. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135387. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135388. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135389. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135390. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135391. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135392. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135393. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135394. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135395. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135396. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135397. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135398. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135399. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135400. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135401. 14,
  135402. };
  135403. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135404. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135405. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135406. };
  135407. static long _vq_quantmap__44c9_s_p8_0[] = {
  135408. 13, 11, 9, 7, 5, 3, 1, 0,
  135409. 2, 4, 6, 8, 10, 12, 14,
  135410. };
  135411. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135412. _vq_quantthresh__44c9_s_p8_0,
  135413. _vq_quantmap__44c9_s_p8_0,
  135414. 15,
  135415. 15
  135416. };
  135417. static static_codebook _44c9_s_p8_0 = {
  135418. 2, 225,
  135419. _vq_lengthlist__44c9_s_p8_0,
  135420. 1, -520986624, 1620377600, 4, 0,
  135421. _vq_quantlist__44c9_s_p8_0,
  135422. NULL,
  135423. &_vq_auxt__44c9_s_p8_0,
  135424. NULL,
  135425. 0
  135426. };
  135427. static long _vq_quantlist__44c9_s_p8_1[] = {
  135428. 10,
  135429. 9,
  135430. 11,
  135431. 8,
  135432. 12,
  135433. 7,
  135434. 13,
  135435. 6,
  135436. 14,
  135437. 5,
  135438. 15,
  135439. 4,
  135440. 16,
  135441. 3,
  135442. 17,
  135443. 2,
  135444. 18,
  135445. 1,
  135446. 19,
  135447. 0,
  135448. 20,
  135449. };
  135450. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135451. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135452. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135453. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135454. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135455. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135456. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135457. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135458. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135459. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135460. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135461. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135462. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135463. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135464. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135465. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135466. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135467. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135468. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135469. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135470. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135471. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135472. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135473. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135474. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135475. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135476. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135477. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135478. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135479. };
  135480. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135481. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135482. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135483. 6.5, 7.5, 8.5, 9.5,
  135484. };
  135485. static long _vq_quantmap__44c9_s_p8_1[] = {
  135486. 19, 17, 15, 13, 11, 9, 7, 5,
  135487. 3, 1, 0, 2, 4, 6, 8, 10,
  135488. 12, 14, 16, 18, 20,
  135489. };
  135490. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135491. _vq_quantthresh__44c9_s_p8_1,
  135492. _vq_quantmap__44c9_s_p8_1,
  135493. 21,
  135494. 21
  135495. };
  135496. static static_codebook _44c9_s_p8_1 = {
  135497. 2, 441,
  135498. _vq_lengthlist__44c9_s_p8_1,
  135499. 1, -529268736, 1611661312, 5, 0,
  135500. _vq_quantlist__44c9_s_p8_1,
  135501. NULL,
  135502. &_vq_auxt__44c9_s_p8_1,
  135503. NULL,
  135504. 0
  135505. };
  135506. static long _vq_quantlist__44c9_s_p9_0[] = {
  135507. 9,
  135508. 8,
  135509. 10,
  135510. 7,
  135511. 11,
  135512. 6,
  135513. 12,
  135514. 5,
  135515. 13,
  135516. 4,
  135517. 14,
  135518. 3,
  135519. 15,
  135520. 2,
  135521. 16,
  135522. 1,
  135523. 17,
  135524. 0,
  135525. 18,
  135526. };
  135527. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135528. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135529. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135530. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135531. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135532. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135533. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135534. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135535. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135536. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135537. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135538. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135539. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135540. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135541. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135542. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135543. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135544. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135549. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135550. 11,11,11,11,11,11,11,11,11,
  135551. };
  135552. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135553. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135554. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135555. 6982.5, 7913.5,
  135556. };
  135557. static long _vq_quantmap__44c9_s_p9_0[] = {
  135558. 17, 15, 13, 11, 9, 7, 5, 3,
  135559. 1, 0, 2, 4, 6, 8, 10, 12,
  135560. 14, 16, 18,
  135561. };
  135562. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135563. _vq_quantthresh__44c9_s_p9_0,
  135564. _vq_quantmap__44c9_s_p9_0,
  135565. 19,
  135566. 19
  135567. };
  135568. static static_codebook _44c9_s_p9_0 = {
  135569. 2, 361,
  135570. _vq_lengthlist__44c9_s_p9_0,
  135571. 1, -508535424, 1631393792, 5, 0,
  135572. _vq_quantlist__44c9_s_p9_0,
  135573. NULL,
  135574. &_vq_auxt__44c9_s_p9_0,
  135575. NULL,
  135576. 0
  135577. };
  135578. static long _vq_quantlist__44c9_s_p9_1[] = {
  135579. 9,
  135580. 8,
  135581. 10,
  135582. 7,
  135583. 11,
  135584. 6,
  135585. 12,
  135586. 5,
  135587. 13,
  135588. 4,
  135589. 14,
  135590. 3,
  135591. 15,
  135592. 2,
  135593. 16,
  135594. 1,
  135595. 17,
  135596. 0,
  135597. 18,
  135598. };
  135599. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135600. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135601. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135602. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135603. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135604. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135605. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135606. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135607. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135608. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135609. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135610. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135611. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135612. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135613. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135614. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135615. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135616. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135617. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135618. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135619. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135620. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135621. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135622. 13,13,13,14,13,14,15,15,15,
  135623. };
  135624. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135625. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135626. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135627. 367.5, 416.5,
  135628. };
  135629. static long _vq_quantmap__44c9_s_p9_1[] = {
  135630. 17, 15, 13, 11, 9, 7, 5, 3,
  135631. 1, 0, 2, 4, 6, 8, 10, 12,
  135632. 14, 16, 18,
  135633. };
  135634. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135635. _vq_quantthresh__44c9_s_p9_1,
  135636. _vq_quantmap__44c9_s_p9_1,
  135637. 19,
  135638. 19
  135639. };
  135640. static static_codebook _44c9_s_p9_1 = {
  135641. 2, 361,
  135642. _vq_lengthlist__44c9_s_p9_1,
  135643. 1, -518287360, 1622704128, 5, 0,
  135644. _vq_quantlist__44c9_s_p9_1,
  135645. NULL,
  135646. &_vq_auxt__44c9_s_p9_1,
  135647. NULL,
  135648. 0
  135649. };
  135650. static long _vq_quantlist__44c9_s_p9_2[] = {
  135651. 24,
  135652. 23,
  135653. 25,
  135654. 22,
  135655. 26,
  135656. 21,
  135657. 27,
  135658. 20,
  135659. 28,
  135660. 19,
  135661. 29,
  135662. 18,
  135663. 30,
  135664. 17,
  135665. 31,
  135666. 16,
  135667. 32,
  135668. 15,
  135669. 33,
  135670. 14,
  135671. 34,
  135672. 13,
  135673. 35,
  135674. 12,
  135675. 36,
  135676. 11,
  135677. 37,
  135678. 10,
  135679. 38,
  135680. 9,
  135681. 39,
  135682. 8,
  135683. 40,
  135684. 7,
  135685. 41,
  135686. 6,
  135687. 42,
  135688. 5,
  135689. 43,
  135690. 4,
  135691. 44,
  135692. 3,
  135693. 45,
  135694. 2,
  135695. 46,
  135696. 1,
  135697. 47,
  135698. 0,
  135699. 48,
  135700. };
  135701. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135702. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135703. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135704. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135705. 7,
  135706. };
  135707. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135708. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135709. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135710. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135711. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135712. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135713. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135714. };
  135715. static long _vq_quantmap__44c9_s_p9_2[] = {
  135716. 47, 45, 43, 41, 39, 37, 35, 33,
  135717. 31, 29, 27, 25, 23, 21, 19, 17,
  135718. 15, 13, 11, 9, 7, 5, 3, 1,
  135719. 0, 2, 4, 6, 8, 10, 12, 14,
  135720. 16, 18, 20, 22, 24, 26, 28, 30,
  135721. 32, 34, 36, 38, 40, 42, 44, 46,
  135722. 48,
  135723. };
  135724. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135725. _vq_quantthresh__44c9_s_p9_2,
  135726. _vq_quantmap__44c9_s_p9_2,
  135727. 49,
  135728. 49
  135729. };
  135730. static static_codebook _44c9_s_p9_2 = {
  135731. 1, 49,
  135732. _vq_lengthlist__44c9_s_p9_2,
  135733. 1, -526909440, 1611661312, 6, 0,
  135734. _vq_quantlist__44c9_s_p9_2,
  135735. NULL,
  135736. &_vq_auxt__44c9_s_p9_2,
  135737. NULL,
  135738. 0
  135739. };
  135740. static long _huff_lengthlist__44c9_s_short[] = {
  135741. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135742. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135743. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135744. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135745. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135746. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135747. 9, 8,10,13,
  135748. };
  135749. static static_codebook _huff_book__44c9_s_short = {
  135750. 2, 100,
  135751. _huff_lengthlist__44c9_s_short,
  135752. 0, 0, 0, 0, 0,
  135753. NULL,
  135754. NULL,
  135755. NULL,
  135756. NULL,
  135757. 0
  135758. };
  135759. static long _huff_lengthlist__44c0_s_long[] = {
  135760. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135761. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135762. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135763. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135764. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135765. 12,
  135766. };
  135767. static static_codebook _huff_book__44c0_s_long = {
  135768. 2, 81,
  135769. _huff_lengthlist__44c0_s_long,
  135770. 0, 0, 0, 0, 0,
  135771. NULL,
  135772. NULL,
  135773. NULL,
  135774. NULL,
  135775. 0
  135776. };
  135777. static long _vq_quantlist__44c0_s_p1_0[] = {
  135778. 1,
  135779. 0,
  135780. 2,
  135781. };
  135782. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135783. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135784. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135789. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135794. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135829. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135834. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135839. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135875. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135880. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135885. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 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,
  136194. };
  136195. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136196. -0.5, 0.5,
  136197. };
  136198. static long _vq_quantmap__44c0_s_p1_0[] = {
  136199. 1, 0, 2,
  136200. };
  136201. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136202. _vq_quantthresh__44c0_s_p1_0,
  136203. _vq_quantmap__44c0_s_p1_0,
  136204. 3,
  136205. 3
  136206. };
  136207. static static_codebook _44c0_s_p1_0 = {
  136208. 8, 6561,
  136209. _vq_lengthlist__44c0_s_p1_0,
  136210. 1, -535822336, 1611661312, 2, 0,
  136211. _vq_quantlist__44c0_s_p1_0,
  136212. NULL,
  136213. &_vq_auxt__44c0_s_p1_0,
  136214. NULL,
  136215. 0
  136216. };
  136217. static long _vq_quantlist__44c0_s_p2_0[] = {
  136218. 2,
  136219. 1,
  136220. 3,
  136221. 0,
  136222. 4,
  136223. };
  136224. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136225. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  136265. };
  136266. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136267. -1.5, -0.5, 0.5, 1.5,
  136268. };
  136269. static long _vq_quantmap__44c0_s_p2_0[] = {
  136270. 3, 1, 0, 2, 4,
  136271. };
  136272. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136273. _vq_quantthresh__44c0_s_p2_0,
  136274. _vq_quantmap__44c0_s_p2_0,
  136275. 5,
  136276. 5
  136277. };
  136278. static static_codebook _44c0_s_p2_0 = {
  136279. 4, 625,
  136280. _vq_lengthlist__44c0_s_p2_0,
  136281. 1, -533725184, 1611661312, 3, 0,
  136282. _vq_quantlist__44c0_s_p2_0,
  136283. NULL,
  136284. &_vq_auxt__44c0_s_p2_0,
  136285. NULL,
  136286. 0
  136287. };
  136288. static long _vq_quantlist__44c0_s_p3_0[] = {
  136289. 4,
  136290. 3,
  136291. 5,
  136292. 2,
  136293. 6,
  136294. 1,
  136295. 7,
  136296. 0,
  136297. 8,
  136298. };
  136299. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136300. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136301. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136302. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136303. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136304. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0,
  136306. };
  136307. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136308. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136309. };
  136310. static long _vq_quantmap__44c0_s_p3_0[] = {
  136311. 7, 5, 3, 1, 0, 2, 4, 6,
  136312. 8,
  136313. };
  136314. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136315. _vq_quantthresh__44c0_s_p3_0,
  136316. _vq_quantmap__44c0_s_p3_0,
  136317. 9,
  136318. 9
  136319. };
  136320. static static_codebook _44c0_s_p3_0 = {
  136321. 2, 81,
  136322. _vq_lengthlist__44c0_s_p3_0,
  136323. 1, -531628032, 1611661312, 4, 0,
  136324. _vq_quantlist__44c0_s_p3_0,
  136325. NULL,
  136326. &_vq_auxt__44c0_s_p3_0,
  136327. NULL,
  136328. 0
  136329. };
  136330. static long _vq_quantlist__44c0_s_p4_0[] = {
  136331. 4,
  136332. 3,
  136333. 5,
  136334. 2,
  136335. 6,
  136336. 1,
  136337. 7,
  136338. 0,
  136339. 8,
  136340. };
  136341. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136342. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136343. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136344. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136345. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136346. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136347. 10,
  136348. };
  136349. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136350. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136351. };
  136352. static long _vq_quantmap__44c0_s_p4_0[] = {
  136353. 7, 5, 3, 1, 0, 2, 4, 6,
  136354. 8,
  136355. };
  136356. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136357. _vq_quantthresh__44c0_s_p4_0,
  136358. _vq_quantmap__44c0_s_p4_0,
  136359. 9,
  136360. 9
  136361. };
  136362. static static_codebook _44c0_s_p4_0 = {
  136363. 2, 81,
  136364. _vq_lengthlist__44c0_s_p4_0,
  136365. 1, -531628032, 1611661312, 4, 0,
  136366. _vq_quantlist__44c0_s_p4_0,
  136367. NULL,
  136368. &_vq_auxt__44c0_s_p4_0,
  136369. NULL,
  136370. 0
  136371. };
  136372. static long _vq_quantlist__44c0_s_p5_0[] = {
  136373. 8,
  136374. 7,
  136375. 9,
  136376. 6,
  136377. 10,
  136378. 5,
  136379. 11,
  136380. 4,
  136381. 12,
  136382. 3,
  136383. 13,
  136384. 2,
  136385. 14,
  136386. 1,
  136387. 15,
  136388. 0,
  136389. 16,
  136390. };
  136391. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136392. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136393. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136394. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136395. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136396. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136397. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136398. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136399. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136400. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136401. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136402. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136403. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136404. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136405. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136406. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136407. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136408. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136410. 14,
  136411. };
  136412. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136413. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136414. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136415. };
  136416. static long _vq_quantmap__44c0_s_p5_0[] = {
  136417. 15, 13, 11, 9, 7, 5, 3, 1,
  136418. 0, 2, 4, 6, 8, 10, 12, 14,
  136419. 16,
  136420. };
  136421. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136422. _vq_quantthresh__44c0_s_p5_0,
  136423. _vq_quantmap__44c0_s_p5_0,
  136424. 17,
  136425. 17
  136426. };
  136427. static static_codebook _44c0_s_p5_0 = {
  136428. 2, 289,
  136429. _vq_lengthlist__44c0_s_p5_0,
  136430. 1, -529530880, 1611661312, 5, 0,
  136431. _vq_quantlist__44c0_s_p5_0,
  136432. NULL,
  136433. &_vq_auxt__44c0_s_p5_0,
  136434. NULL,
  136435. 0
  136436. };
  136437. static long _vq_quantlist__44c0_s_p6_0[] = {
  136438. 1,
  136439. 0,
  136440. 2,
  136441. };
  136442. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136443. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136444. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136445. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136446. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136447. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136448. 10,
  136449. };
  136450. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136451. -5.5, 5.5,
  136452. };
  136453. static long _vq_quantmap__44c0_s_p6_0[] = {
  136454. 1, 0, 2,
  136455. };
  136456. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136457. _vq_quantthresh__44c0_s_p6_0,
  136458. _vq_quantmap__44c0_s_p6_0,
  136459. 3,
  136460. 3
  136461. };
  136462. static static_codebook _44c0_s_p6_0 = {
  136463. 4, 81,
  136464. _vq_lengthlist__44c0_s_p6_0,
  136465. 1, -529137664, 1618345984, 2, 0,
  136466. _vq_quantlist__44c0_s_p6_0,
  136467. NULL,
  136468. &_vq_auxt__44c0_s_p6_0,
  136469. NULL,
  136470. 0
  136471. };
  136472. static long _vq_quantlist__44c0_s_p6_1[] = {
  136473. 5,
  136474. 4,
  136475. 6,
  136476. 3,
  136477. 7,
  136478. 2,
  136479. 8,
  136480. 1,
  136481. 9,
  136482. 0,
  136483. 10,
  136484. };
  136485. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136486. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136487. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136488. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136489. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136490. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136491. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136492. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136493. 10,10,10, 8, 8, 8, 8, 8, 8,
  136494. };
  136495. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136496. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136497. 3.5, 4.5,
  136498. };
  136499. static long _vq_quantmap__44c0_s_p6_1[] = {
  136500. 9, 7, 5, 3, 1, 0, 2, 4,
  136501. 6, 8, 10,
  136502. };
  136503. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136504. _vq_quantthresh__44c0_s_p6_1,
  136505. _vq_quantmap__44c0_s_p6_1,
  136506. 11,
  136507. 11
  136508. };
  136509. static static_codebook _44c0_s_p6_1 = {
  136510. 2, 121,
  136511. _vq_lengthlist__44c0_s_p6_1,
  136512. 1, -531365888, 1611661312, 4, 0,
  136513. _vq_quantlist__44c0_s_p6_1,
  136514. NULL,
  136515. &_vq_auxt__44c0_s_p6_1,
  136516. NULL,
  136517. 0
  136518. };
  136519. static long _vq_quantlist__44c0_s_p7_0[] = {
  136520. 6,
  136521. 5,
  136522. 7,
  136523. 4,
  136524. 8,
  136525. 3,
  136526. 9,
  136527. 2,
  136528. 10,
  136529. 1,
  136530. 11,
  136531. 0,
  136532. 12,
  136533. };
  136534. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136535. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136536. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136537. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136538. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136539. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136540. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136541. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136542. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136543. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136544. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136545. 0,12,12,11,11,12,12,13,13,
  136546. };
  136547. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136548. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136549. 12.5, 17.5, 22.5, 27.5,
  136550. };
  136551. static long _vq_quantmap__44c0_s_p7_0[] = {
  136552. 11, 9, 7, 5, 3, 1, 0, 2,
  136553. 4, 6, 8, 10, 12,
  136554. };
  136555. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136556. _vq_quantthresh__44c0_s_p7_0,
  136557. _vq_quantmap__44c0_s_p7_0,
  136558. 13,
  136559. 13
  136560. };
  136561. static static_codebook _44c0_s_p7_0 = {
  136562. 2, 169,
  136563. _vq_lengthlist__44c0_s_p7_0,
  136564. 1, -526516224, 1616117760, 4, 0,
  136565. _vq_quantlist__44c0_s_p7_0,
  136566. NULL,
  136567. &_vq_auxt__44c0_s_p7_0,
  136568. NULL,
  136569. 0
  136570. };
  136571. static long _vq_quantlist__44c0_s_p7_1[] = {
  136572. 2,
  136573. 1,
  136574. 3,
  136575. 0,
  136576. 4,
  136577. };
  136578. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136579. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136580. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136581. };
  136582. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136583. -1.5, -0.5, 0.5, 1.5,
  136584. };
  136585. static long _vq_quantmap__44c0_s_p7_1[] = {
  136586. 3, 1, 0, 2, 4,
  136587. };
  136588. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136589. _vq_quantthresh__44c0_s_p7_1,
  136590. _vq_quantmap__44c0_s_p7_1,
  136591. 5,
  136592. 5
  136593. };
  136594. static static_codebook _44c0_s_p7_1 = {
  136595. 2, 25,
  136596. _vq_lengthlist__44c0_s_p7_1,
  136597. 1, -533725184, 1611661312, 3, 0,
  136598. _vq_quantlist__44c0_s_p7_1,
  136599. NULL,
  136600. &_vq_auxt__44c0_s_p7_1,
  136601. NULL,
  136602. 0
  136603. };
  136604. static long _vq_quantlist__44c0_s_p8_0[] = {
  136605. 2,
  136606. 1,
  136607. 3,
  136608. 0,
  136609. 4,
  136610. };
  136611. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136612. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136618. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136619. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136624. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136627. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136651. 11,
  136652. };
  136653. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136654. -331.5, -110.5, 110.5, 331.5,
  136655. };
  136656. static long _vq_quantmap__44c0_s_p8_0[] = {
  136657. 3, 1, 0, 2, 4,
  136658. };
  136659. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136660. _vq_quantthresh__44c0_s_p8_0,
  136661. _vq_quantmap__44c0_s_p8_0,
  136662. 5,
  136663. 5
  136664. };
  136665. static static_codebook _44c0_s_p8_0 = {
  136666. 4, 625,
  136667. _vq_lengthlist__44c0_s_p8_0,
  136668. 1, -518283264, 1627103232, 3, 0,
  136669. _vq_quantlist__44c0_s_p8_0,
  136670. NULL,
  136671. &_vq_auxt__44c0_s_p8_0,
  136672. NULL,
  136673. 0
  136674. };
  136675. static long _vq_quantlist__44c0_s_p8_1[] = {
  136676. 6,
  136677. 5,
  136678. 7,
  136679. 4,
  136680. 8,
  136681. 3,
  136682. 9,
  136683. 2,
  136684. 10,
  136685. 1,
  136686. 11,
  136687. 0,
  136688. 12,
  136689. };
  136690. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136691. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136692. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136693. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136694. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136695. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136696. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136697. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136698. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136699. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136700. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136701. 16,13,13,12,12,14,14,15,13,
  136702. };
  136703. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136704. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136705. 42.5, 59.5, 76.5, 93.5,
  136706. };
  136707. static long _vq_quantmap__44c0_s_p8_1[] = {
  136708. 11, 9, 7, 5, 3, 1, 0, 2,
  136709. 4, 6, 8, 10, 12,
  136710. };
  136711. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136712. _vq_quantthresh__44c0_s_p8_1,
  136713. _vq_quantmap__44c0_s_p8_1,
  136714. 13,
  136715. 13
  136716. };
  136717. static static_codebook _44c0_s_p8_1 = {
  136718. 2, 169,
  136719. _vq_lengthlist__44c0_s_p8_1,
  136720. 1, -522616832, 1620115456, 4, 0,
  136721. _vq_quantlist__44c0_s_p8_1,
  136722. NULL,
  136723. &_vq_auxt__44c0_s_p8_1,
  136724. NULL,
  136725. 0
  136726. };
  136727. static long _vq_quantlist__44c0_s_p8_2[] = {
  136728. 8,
  136729. 7,
  136730. 9,
  136731. 6,
  136732. 10,
  136733. 5,
  136734. 11,
  136735. 4,
  136736. 12,
  136737. 3,
  136738. 13,
  136739. 2,
  136740. 14,
  136741. 1,
  136742. 15,
  136743. 0,
  136744. 16,
  136745. };
  136746. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136747. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136748. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136749. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136750. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136751. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136752. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136753. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136754. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136755. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136756. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136757. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136758. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136759. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136760. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136761. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136762. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136763. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136764. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136765. 10,
  136766. };
  136767. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136768. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136769. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136770. };
  136771. static long _vq_quantmap__44c0_s_p8_2[] = {
  136772. 15, 13, 11, 9, 7, 5, 3, 1,
  136773. 0, 2, 4, 6, 8, 10, 12, 14,
  136774. 16,
  136775. };
  136776. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136777. _vq_quantthresh__44c0_s_p8_2,
  136778. _vq_quantmap__44c0_s_p8_2,
  136779. 17,
  136780. 17
  136781. };
  136782. static static_codebook _44c0_s_p8_2 = {
  136783. 2, 289,
  136784. _vq_lengthlist__44c0_s_p8_2,
  136785. 1, -529530880, 1611661312, 5, 0,
  136786. _vq_quantlist__44c0_s_p8_2,
  136787. NULL,
  136788. &_vq_auxt__44c0_s_p8_2,
  136789. NULL,
  136790. 0
  136791. };
  136792. static long _huff_lengthlist__44c0_s_short[] = {
  136793. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136794. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136795. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136796. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136797. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136798. 12,
  136799. };
  136800. static static_codebook _huff_book__44c0_s_short = {
  136801. 2, 81,
  136802. _huff_lengthlist__44c0_s_short,
  136803. 0, 0, 0, 0, 0,
  136804. NULL,
  136805. NULL,
  136806. NULL,
  136807. NULL,
  136808. 0
  136809. };
  136810. static long _huff_lengthlist__44c0_sm_long[] = {
  136811. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136812. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136813. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136814. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136815. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136816. 13,
  136817. };
  136818. static static_codebook _huff_book__44c0_sm_long = {
  136819. 2, 81,
  136820. _huff_lengthlist__44c0_sm_long,
  136821. 0, 0, 0, 0, 0,
  136822. NULL,
  136823. NULL,
  136824. NULL,
  136825. NULL,
  136826. 0
  136827. };
  136828. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136829. 1,
  136830. 0,
  136831. 2,
  136832. };
  136833. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136834. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136835. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136840. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136845. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136880. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136885. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136890. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136926. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136931. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136936. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 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,
  137245. };
  137246. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137247. -0.5, 0.5,
  137248. };
  137249. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137250. 1, 0, 2,
  137251. };
  137252. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137253. _vq_quantthresh__44c0_sm_p1_0,
  137254. _vq_quantmap__44c0_sm_p1_0,
  137255. 3,
  137256. 3
  137257. };
  137258. static static_codebook _44c0_sm_p1_0 = {
  137259. 8, 6561,
  137260. _vq_lengthlist__44c0_sm_p1_0,
  137261. 1, -535822336, 1611661312, 2, 0,
  137262. _vq_quantlist__44c0_sm_p1_0,
  137263. NULL,
  137264. &_vq_auxt__44c0_sm_p1_0,
  137265. NULL,
  137266. 0
  137267. };
  137268. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137269. 2,
  137270. 1,
  137271. 3,
  137272. 0,
  137273. 4,
  137274. };
  137275. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137276. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137316. };
  137317. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137318. -1.5, -0.5, 0.5, 1.5,
  137319. };
  137320. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137321. 3, 1, 0, 2, 4,
  137322. };
  137323. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137324. _vq_quantthresh__44c0_sm_p2_0,
  137325. _vq_quantmap__44c0_sm_p2_0,
  137326. 5,
  137327. 5
  137328. };
  137329. static static_codebook _44c0_sm_p2_0 = {
  137330. 4, 625,
  137331. _vq_lengthlist__44c0_sm_p2_0,
  137332. 1, -533725184, 1611661312, 3, 0,
  137333. _vq_quantlist__44c0_sm_p2_0,
  137334. NULL,
  137335. &_vq_auxt__44c0_sm_p2_0,
  137336. NULL,
  137337. 0
  137338. };
  137339. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137340. 4,
  137341. 3,
  137342. 5,
  137343. 2,
  137344. 6,
  137345. 1,
  137346. 7,
  137347. 0,
  137348. 8,
  137349. };
  137350. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137351. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137352. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137353. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137354. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137355. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0,
  137357. };
  137358. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137359. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137360. };
  137361. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137362. 7, 5, 3, 1, 0, 2, 4, 6,
  137363. 8,
  137364. };
  137365. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137366. _vq_quantthresh__44c0_sm_p3_0,
  137367. _vq_quantmap__44c0_sm_p3_0,
  137368. 9,
  137369. 9
  137370. };
  137371. static static_codebook _44c0_sm_p3_0 = {
  137372. 2, 81,
  137373. _vq_lengthlist__44c0_sm_p3_0,
  137374. 1, -531628032, 1611661312, 4, 0,
  137375. _vq_quantlist__44c0_sm_p3_0,
  137376. NULL,
  137377. &_vq_auxt__44c0_sm_p3_0,
  137378. NULL,
  137379. 0
  137380. };
  137381. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137382. 4,
  137383. 3,
  137384. 5,
  137385. 2,
  137386. 6,
  137387. 1,
  137388. 7,
  137389. 0,
  137390. 8,
  137391. };
  137392. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137393. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137394. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137395. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137396. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137397. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137398. 11,
  137399. };
  137400. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137401. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137402. };
  137403. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137404. 7, 5, 3, 1, 0, 2, 4, 6,
  137405. 8,
  137406. };
  137407. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137408. _vq_quantthresh__44c0_sm_p4_0,
  137409. _vq_quantmap__44c0_sm_p4_0,
  137410. 9,
  137411. 9
  137412. };
  137413. static static_codebook _44c0_sm_p4_0 = {
  137414. 2, 81,
  137415. _vq_lengthlist__44c0_sm_p4_0,
  137416. 1, -531628032, 1611661312, 4, 0,
  137417. _vq_quantlist__44c0_sm_p4_0,
  137418. NULL,
  137419. &_vq_auxt__44c0_sm_p4_0,
  137420. NULL,
  137421. 0
  137422. };
  137423. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137424. 8,
  137425. 7,
  137426. 9,
  137427. 6,
  137428. 10,
  137429. 5,
  137430. 11,
  137431. 4,
  137432. 12,
  137433. 3,
  137434. 13,
  137435. 2,
  137436. 14,
  137437. 1,
  137438. 15,
  137439. 0,
  137440. 16,
  137441. };
  137442. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137443. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137444. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137445. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137446. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137447. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137448. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137449. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137450. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137451. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137452. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137453. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137454. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137455. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137456. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137457. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137458. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137459. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137461. 14,
  137462. };
  137463. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137464. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137465. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137466. };
  137467. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137468. 15, 13, 11, 9, 7, 5, 3, 1,
  137469. 0, 2, 4, 6, 8, 10, 12, 14,
  137470. 16,
  137471. };
  137472. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137473. _vq_quantthresh__44c0_sm_p5_0,
  137474. _vq_quantmap__44c0_sm_p5_0,
  137475. 17,
  137476. 17
  137477. };
  137478. static static_codebook _44c0_sm_p5_0 = {
  137479. 2, 289,
  137480. _vq_lengthlist__44c0_sm_p5_0,
  137481. 1, -529530880, 1611661312, 5, 0,
  137482. _vq_quantlist__44c0_sm_p5_0,
  137483. NULL,
  137484. &_vq_auxt__44c0_sm_p5_0,
  137485. NULL,
  137486. 0
  137487. };
  137488. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137489. 1,
  137490. 0,
  137491. 2,
  137492. };
  137493. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137494. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137495. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137496. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137497. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137498. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137499. 11,
  137500. };
  137501. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137502. -5.5, 5.5,
  137503. };
  137504. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137505. 1, 0, 2,
  137506. };
  137507. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137508. _vq_quantthresh__44c0_sm_p6_0,
  137509. _vq_quantmap__44c0_sm_p6_0,
  137510. 3,
  137511. 3
  137512. };
  137513. static static_codebook _44c0_sm_p6_0 = {
  137514. 4, 81,
  137515. _vq_lengthlist__44c0_sm_p6_0,
  137516. 1, -529137664, 1618345984, 2, 0,
  137517. _vq_quantlist__44c0_sm_p6_0,
  137518. NULL,
  137519. &_vq_auxt__44c0_sm_p6_0,
  137520. NULL,
  137521. 0
  137522. };
  137523. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137524. 5,
  137525. 4,
  137526. 6,
  137527. 3,
  137528. 7,
  137529. 2,
  137530. 8,
  137531. 1,
  137532. 9,
  137533. 0,
  137534. 10,
  137535. };
  137536. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137537. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137538. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137539. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137540. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137541. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137542. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137543. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137544. 10,10,10, 8, 8, 8, 8, 8, 8,
  137545. };
  137546. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137547. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137548. 3.5, 4.5,
  137549. };
  137550. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137551. 9, 7, 5, 3, 1, 0, 2, 4,
  137552. 6, 8, 10,
  137553. };
  137554. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137555. _vq_quantthresh__44c0_sm_p6_1,
  137556. _vq_quantmap__44c0_sm_p6_1,
  137557. 11,
  137558. 11
  137559. };
  137560. static static_codebook _44c0_sm_p6_1 = {
  137561. 2, 121,
  137562. _vq_lengthlist__44c0_sm_p6_1,
  137563. 1, -531365888, 1611661312, 4, 0,
  137564. _vq_quantlist__44c0_sm_p6_1,
  137565. NULL,
  137566. &_vq_auxt__44c0_sm_p6_1,
  137567. NULL,
  137568. 0
  137569. };
  137570. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137571. 6,
  137572. 5,
  137573. 7,
  137574. 4,
  137575. 8,
  137576. 3,
  137577. 9,
  137578. 2,
  137579. 10,
  137580. 1,
  137581. 11,
  137582. 0,
  137583. 12,
  137584. };
  137585. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137586. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137587. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137588. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137589. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137590. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137591. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137592. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137593. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137594. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137595. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137596. 0,12,12,11,11,13,12,14,14,
  137597. };
  137598. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137599. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137600. 12.5, 17.5, 22.5, 27.5,
  137601. };
  137602. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137603. 11, 9, 7, 5, 3, 1, 0, 2,
  137604. 4, 6, 8, 10, 12,
  137605. };
  137606. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137607. _vq_quantthresh__44c0_sm_p7_0,
  137608. _vq_quantmap__44c0_sm_p7_0,
  137609. 13,
  137610. 13
  137611. };
  137612. static static_codebook _44c0_sm_p7_0 = {
  137613. 2, 169,
  137614. _vq_lengthlist__44c0_sm_p7_0,
  137615. 1, -526516224, 1616117760, 4, 0,
  137616. _vq_quantlist__44c0_sm_p7_0,
  137617. NULL,
  137618. &_vq_auxt__44c0_sm_p7_0,
  137619. NULL,
  137620. 0
  137621. };
  137622. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137623. 2,
  137624. 1,
  137625. 3,
  137626. 0,
  137627. 4,
  137628. };
  137629. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137630. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137631. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137632. };
  137633. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137634. -1.5, -0.5, 0.5, 1.5,
  137635. };
  137636. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137637. 3, 1, 0, 2, 4,
  137638. };
  137639. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137640. _vq_quantthresh__44c0_sm_p7_1,
  137641. _vq_quantmap__44c0_sm_p7_1,
  137642. 5,
  137643. 5
  137644. };
  137645. static static_codebook _44c0_sm_p7_1 = {
  137646. 2, 25,
  137647. _vq_lengthlist__44c0_sm_p7_1,
  137648. 1, -533725184, 1611661312, 3, 0,
  137649. _vq_quantlist__44c0_sm_p7_1,
  137650. NULL,
  137651. &_vq_auxt__44c0_sm_p7_1,
  137652. NULL,
  137653. 0
  137654. };
  137655. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137656. 4,
  137657. 3,
  137658. 5,
  137659. 2,
  137660. 6,
  137661. 1,
  137662. 7,
  137663. 0,
  137664. 8,
  137665. };
  137666. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137667. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137668. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137669. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137670. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137671. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137672. 12,
  137673. };
  137674. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137675. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137676. };
  137677. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137678. 7, 5, 3, 1, 0, 2, 4, 6,
  137679. 8,
  137680. };
  137681. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137682. _vq_quantthresh__44c0_sm_p8_0,
  137683. _vq_quantmap__44c0_sm_p8_0,
  137684. 9,
  137685. 9
  137686. };
  137687. static static_codebook _44c0_sm_p8_0 = {
  137688. 2, 81,
  137689. _vq_lengthlist__44c0_sm_p8_0,
  137690. 1, -516186112, 1627103232, 4, 0,
  137691. _vq_quantlist__44c0_sm_p8_0,
  137692. NULL,
  137693. &_vq_auxt__44c0_sm_p8_0,
  137694. NULL,
  137695. 0
  137696. };
  137697. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137698. 6,
  137699. 5,
  137700. 7,
  137701. 4,
  137702. 8,
  137703. 3,
  137704. 9,
  137705. 2,
  137706. 10,
  137707. 1,
  137708. 11,
  137709. 0,
  137710. 12,
  137711. };
  137712. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137713. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137714. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137715. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137716. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137717. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137718. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137719. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137720. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137721. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137722. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137723. 20,13,13,12,12,16,13,15,13,
  137724. };
  137725. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137726. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137727. 42.5, 59.5, 76.5, 93.5,
  137728. };
  137729. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137730. 11, 9, 7, 5, 3, 1, 0, 2,
  137731. 4, 6, 8, 10, 12,
  137732. };
  137733. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137734. _vq_quantthresh__44c0_sm_p8_1,
  137735. _vq_quantmap__44c0_sm_p8_1,
  137736. 13,
  137737. 13
  137738. };
  137739. static static_codebook _44c0_sm_p8_1 = {
  137740. 2, 169,
  137741. _vq_lengthlist__44c0_sm_p8_1,
  137742. 1, -522616832, 1620115456, 4, 0,
  137743. _vq_quantlist__44c0_sm_p8_1,
  137744. NULL,
  137745. &_vq_auxt__44c0_sm_p8_1,
  137746. NULL,
  137747. 0
  137748. };
  137749. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137750. 8,
  137751. 7,
  137752. 9,
  137753. 6,
  137754. 10,
  137755. 5,
  137756. 11,
  137757. 4,
  137758. 12,
  137759. 3,
  137760. 13,
  137761. 2,
  137762. 14,
  137763. 1,
  137764. 15,
  137765. 0,
  137766. 16,
  137767. };
  137768. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137769. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137770. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137771. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137772. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137773. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137774. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137775. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137776. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137777. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137778. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137779. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137780. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137781. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137782. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137783. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137784. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137785. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137786. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137787. 9,
  137788. };
  137789. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137790. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137791. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137792. };
  137793. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137794. 15, 13, 11, 9, 7, 5, 3, 1,
  137795. 0, 2, 4, 6, 8, 10, 12, 14,
  137796. 16,
  137797. };
  137798. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137799. _vq_quantthresh__44c0_sm_p8_2,
  137800. _vq_quantmap__44c0_sm_p8_2,
  137801. 17,
  137802. 17
  137803. };
  137804. static static_codebook _44c0_sm_p8_2 = {
  137805. 2, 289,
  137806. _vq_lengthlist__44c0_sm_p8_2,
  137807. 1, -529530880, 1611661312, 5, 0,
  137808. _vq_quantlist__44c0_sm_p8_2,
  137809. NULL,
  137810. &_vq_auxt__44c0_sm_p8_2,
  137811. NULL,
  137812. 0
  137813. };
  137814. static long _huff_lengthlist__44c0_sm_short[] = {
  137815. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137816. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137817. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137818. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137819. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137820. 12,
  137821. };
  137822. static static_codebook _huff_book__44c0_sm_short = {
  137823. 2, 81,
  137824. _huff_lengthlist__44c0_sm_short,
  137825. 0, 0, 0, 0, 0,
  137826. NULL,
  137827. NULL,
  137828. NULL,
  137829. NULL,
  137830. 0
  137831. };
  137832. static long _huff_lengthlist__44c1_s_long[] = {
  137833. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137834. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137835. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137836. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137837. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137838. 11,
  137839. };
  137840. static static_codebook _huff_book__44c1_s_long = {
  137841. 2, 81,
  137842. _huff_lengthlist__44c1_s_long,
  137843. 0, 0, 0, 0, 0,
  137844. NULL,
  137845. NULL,
  137846. NULL,
  137847. NULL,
  137848. 0
  137849. };
  137850. static long _vq_quantlist__44c1_s_p1_0[] = {
  137851. 1,
  137852. 0,
  137853. 2,
  137854. };
  137855. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137856. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137857. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137862. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137867. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137902. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137907. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137912. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137948. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137953. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137958. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 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,
  138267. };
  138268. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138269. -0.5, 0.5,
  138270. };
  138271. static long _vq_quantmap__44c1_s_p1_0[] = {
  138272. 1, 0, 2,
  138273. };
  138274. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138275. _vq_quantthresh__44c1_s_p1_0,
  138276. _vq_quantmap__44c1_s_p1_0,
  138277. 3,
  138278. 3
  138279. };
  138280. static static_codebook _44c1_s_p1_0 = {
  138281. 8, 6561,
  138282. _vq_lengthlist__44c1_s_p1_0,
  138283. 1, -535822336, 1611661312, 2, 0,
  138284. _vq_quantlist__44c1_s_p1_0,
  138285. NULL,
  138286. &_vq_auxt__44c1_s_p1_0,
  138287. NULL,
  138288. 0
  138289. };
  138290. static long _vq_quantlist__44c1_s_p2_0[] = {
  138291. 2,
  138292. 1,
  138293. 3,
  138294. 0,
  138295. 4,
  138296. };
  138297. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138298. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138338. };
  138339. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138340. -1.5, -0.5, 0.5, 1.5,
  138341. };
  138342. static long _vq_quantmap__44c1_s_p2_0[] = {
  138343. 3, 1, 0, 2, 4,
  138344. };
  138345. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138346. _vq_quantthresh__44c1_s_p2_0,
  138347. _vq_quantmap__44c1_s_p2_0,
  138348. 5,
  138349. 5
  138350. };
  138351. static static_codebook _44c1_s_p2_0 = {
  138352. 4, 625,
  138353. _vq_lengthlist__44c1_s_p2_0,
  138354. 1, -533725184, 1611661312, 3, 0,
  138355. _vq_quantlist__44c1_s_p2_0,
  138356. NULL,
  138357. &_vq_auxt__44c1_s_p2_0,
  138358. NULL,
  138359. 0
  138360. };
  138361. static long _vq_quantlist__44c1_s_p3_0[] = {
  138362. 4,
  138363. 3,
  138364. 5,
  138365. 2,
  138366. 6,
  138367. 1,
  138368. 7,
  138369. 0,
  138370. 8,
  138371. };
  138372. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138373. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138374. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138375. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138376. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138377. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0,
  138379. };
  138380. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138381. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138382. };
  138383. static long _vq_quantmap__44c1_s_p3_0[] = {
  138384. 7, 5, 3, 1, 0, 2, 4, 6,
  138385. 8,
  138386. };
  138387. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138388. _vq_quantthresh__44c1_s_p3_0,
  138389. _vq_quantmap__44c1_s_p3_0,
  138390. 9,
  138391. 9
  138392. };
  138393. static static_codebook _44c1_s_p3_0 = {
  138394. 2, 81,
  138395. _vq_lengthlist__44c1_s_p3_0,
  138396. 1, -531628032, 1611661312, 4, 0,
  138397. _vq_quantlist__44c1_s_p3_0,
  138398. NULL,
  138399. &_vq_auxt__44c1_s_p3_0,
  138400. NULL,
  138401. 0
  138402. };
  138403. static long _vq_quantlist__44c1_s_p4_0[] = {
  138404. 4,
  138405. 3,
  138406. 5,
  138407. 2,
  138408. 6,
  138409. 1,
  138410. 7,
  138411. 0,
  138412. 8,
  138413. };
  138414. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138415. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138416. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138417. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138418. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138419. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138420. 11,
  138421. };
  138422. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138423. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138424. };
  138425. static long _vq_quantmap__44c1_s_p4_0[] = {
  138426. 7, 5, 3, 1, 0, 2, 4, 6,
  138427. 8,
  138428. };
  138429. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138430. _vq_quantthresh__44c1_s_p4_0,
  138431. _vq_quantmap__44c1_s_p4_0,
  138432. 9,
  138433. 9
  138434. };
  138435. static static_codebook _44c1_s_p4_0 = {
  138436. 2, 81,
  138437. _vq_lengthlist__44c1_s_p4_0,
  138438. 1, -531628032, 1611661312, 4, 0,
  138439. _vq_quantlist__44c1_s_p4_0,
  138440. NULL,
  138441. &_vq_auxt__44c1_s_p4_0,
  138442. NULL,
  138443. 0
  138444. };
  138445. static long _vq_quantlist__44c1_s_p5_0[] = {
  138446. 8,
  138447. 7,
  138448. 9,
  138449. 6,
  138450. 10,
  138451. 5,
  138452. 11,
  138453. 4,
  138454. 12,
  138455. 3,
  138456. 13,
  138457. 2,
  138458. 14,
  138459. 1,
  138460. 15,
  138461. 0,
  138462. 16,
  138463. };
  138464. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138465. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138466. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138467. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138468. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138469. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138470. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138471. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138472. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138473. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138474. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138475. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138476. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138477. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138478. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138479. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138480. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138481. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138483. 14,
  138484. };
  138485. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138488. };
  138489. static long _vq_quantmap__44c1_s_p5_0[] = {
  138490. 15, 13, 11, 9, 7, 5, 3, 1,
  138491. 0, 2, 4, 6, 8, 10, 12, 14,
  138492. 16,
  138493. };
  138494. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138495. _vq_quantthresh__44c1_s_p5_0,
  138496. _vq_quantmap__44c1_s_p5_0,
  138497. 17,
  138498. 17
  138499. };
  138500. static static_codebook _44c1_s_p5_0 = {
  138501. 2, 289,
  138502. _vq_lengthlist__44c1_s_p5_0,
  138503. 1, -529530880, 1611661312, 5, 0,
  138504. _vq_quantlist__44c1_s_p5_0,
  138505. NULL,
  138506. &_vq_auxt__44c1_s_p5_0,
  138507. NULL,
  138508. 0
  138509. };
  138510. static long _vq_quantlist__44c1_s_p6_0[] = {
  138511. 1,
  138512. 0,
  138513. 2,
  138514. };
  138515. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138516. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138517. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138518. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138519. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138520. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138521. 11,
  138522. };
  138523. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138524. -5.5, 5.5,
  138525. };
  138526. static long _vq_quantmap__44c1_s_p6_0[] = {
  138527. 1, 0, 2,
  138528. };
  138529. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138530. _vq_quantthresh__44c1_s_p6_0,
  138531. _vq_quantmap__44c1_s_p6_0,
  138532. 3,
  138533. 3
  138534. };
  138535. static static_codebook _44c1_s_p6_0 = {
  138536. 4, 81,
  138537. _vq_lengthlist__44c1_s_p6_0,
  138538. 1, -529137664, 1618345984, 2, 0,
  138539. _vq_quantlist__44c1_s_p6_0,
  138540. NULL,
  138541. &_vq_auxt__44c1_s_p6_0,
  138542. NULL,
  138543. 0
  138544. };
  138545. static long _vq_quantlist__44c1_s_p6_1[] = {
  138546. 5,
  138547. 4,
  138548. 6,
  138549. 3,
  138550. 7,
  138551. 2,
  138552. 8,
  138553. 1,
  138554. 9,
  138555. 0,
  138556. 10,
  138557. };
  138558. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138559. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138560. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138561. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138562. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138563. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138564. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138565. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138566. 10,10,10, 8, 8, 8, 8, 8, 8,
  138567. };
  138568. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138569. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138570. 3.5, 4.5,
  138571. };
  138572. static long _vq_quantmap__44c1_s_p6_1[] = {
  138573. 9, 7, 5, 3, 1, 0, 2, 4,
  138574. 6, 8, 10,
  138575. };
  138576. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138577. _vq_quantthresh__44c1_s_p6_1,
  138578. _vq_quantmap__44c1_s_p6_1,
  138579. 11,
  138580. 11
  138581. };
  138582. static static_codebook _44c1_s_p6_1 = {
  138583. 2, 121,
  138584. _vq_lengthlist__44c1_s_p6_1,
  138585. 1, -531365888, 1611661312, 4, 0,
  138586. _vq_quantlist__44c1_s_p6_1,
  138587. NULL,
  138588. &_vq_auxt__44c1_s_p6_1,
  138589. NULL,
  138590. 0
  138591. };
  138592. static long _vq_quantlist__44c1_s_p7_0[] = {
  138593. 6,
  138594. 5,
  138595. 7,
  138596. 4,
  138597. 8,
  138598. 3,
  138599. 9,
  138600. 2,
  138601. 10,
  138602. 1,
  138603. 11,
  138604. 0,
  138605. 12,
  138606. };
  138607. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138608. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138609. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138610. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138611. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138612. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138613. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138614. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138615. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138616. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138617. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138618. 0,12,11,11,11,13,10,14,13,
  138619. };
  138620. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138621. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138622. 12.5, 17.5, 22.5, 27.5,
  138623. };
  138624. static long _vq_quantmap__44c1_s_p7_0[] = {
  138625. 11, 9, 7, 5, 3, 1, 0, 2,
  138626. 4, 6, 8, 10, 12,
  138627. };
  138628. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138629. _vq_quantthresh__44c1_s_p7_0,
  138630. _vq_quantmap__44c1_s_p7_0,
  138631. 13,
  138632. 13
  138633. };
  138634. static static_codebook _44c1_s_p7_0 = {
  138635. 2, 169,
  138636. _vq_lengthlist__44c1_s_p7_0,
  138637. 1, -526516224, 1616117760, 4, 0,
  138638. _vq_quantlist__44c1_s_p7_0,
  138639. NULL,
  138640. &_vq_auxt__44c1_s_p7_0,
  138641. NULL,
  138642. 0
  138643. };
  138644. static long _vq_quantlist__44c1_s_p7_1[] = {
  138645. 2,
  138646. 1,
  138647. 3,
  138648. 0,
  138649. 4,
  138650. };
  138651. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138652. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138653. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138654. };
  138655. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138656. -1.5, -0.5, 0.5, 1.5,
  138657. };
  138658. static long _vq_quantmap__44c1_s_p7_1[] = {
  138659. 3, 1, 0, 2, 4,
  138660. };
  138661. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138662. _vq_quantthresh__44c1_s_p7_1,
  138663. _vq_quantmap__44c1_s_p7_1,
  138664. 5,
  138665. 5
  138666. };
  138667. static static_codebook _44c1_s_p7_1 = {
  138668. 2, 25,
  138669. _vq_lengthlist__44c1_s_p7_1,
  138670. 1, -533725184, 1611661312, 3, 0,
  138671. _vq_quantlist__44c1_s_p7_1,
  138672. NULL,
  138673. &_vq_auxt__44c1_s_p7_1,
  138674. NULL,
  138675. 0
  138676. };
  138677. static long _vq_quantlist__44c1_s_p8_0[] = {
  138678. 6,
  138679. 5,
  138680. 7,
  138681. 4,
  138682. 8,
  138683. 3,
  138684. 9,
  138685. 2,
  138686. 10,
  138687. 1,
  138688. 11,
  138689. 0,
  138690. 12,
  138691. };
  138692. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138693. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138694. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138697. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138698. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138699. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138700. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138701. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138703. 10,10,10,10,10,10,10,10,10,
  138704. };
  138705. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138706. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138707. 552.5, 773.5, 994.5, 1215.5,
  138708. };
  138709. static long _vq_quantmap__44c1_s_p8_0[] = {
  138710. 11, 9, 7, 5, 3, 1, 0, 2,
  138711. 4, 6, 8, 10, 12,
  138712. };
  138713. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138714. _vq_quantthresh__44c1_s_p8_0,
  138715. _vq_quantmap__44c1_s_p8_0,
  138716. 13,
  138717. 13
  138718. };
  138719. static static_codebook _44c1_s_p8_0 = {
  138720. 2, 169,
  138721. _vq_lengthlist__44c1_s_p8_0,
  138722. 1, -514541568, 1627103232, 4, 0,
  138723. _vq_quantlist__44c1_s_p8_0,
  138724. NULL,
  138725. &_vq_auxt__44c1_s_p8_0,
  138726. NULL,
  138727. 0
  138728. };
  138729. static long _vq_quantlist__44c1_s_p8_1[] = {
  138730. 6,
  138731. 5,
  138732. 7,
  138733. 4,
  138734. 8,
  138735. 3,
  138736. 9,
  138737. 2,
  138738. 10,
  138739. 1,
  138740. 11,
  138741. 0,
  138742. 12,
  138743. };
  138744. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138745. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138746. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138747. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138748. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138749. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138750. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138751. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138752. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138753. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138754. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138755. 16,13,12,12,11,14,12,15,13,
  138756. };
  138757. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138758. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138759. 42.5, 59.5, 76.5, 93.5,
  138760. };
  138761. static long _vq_quantmap__44c1_s_p8_1[] = {
  138762. 11, 9, 7, 5, 3, 1, 0, 2,
  138763. 4, 6, 8, 10, 12,
  138764. };
  138765. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138766. _vq_quantthresh__44c1_s_p8_1,
  138767. _vq_quantmap__44c1_s_p8_1,
  138768. 13,
  138769. 13
  138770. };
  138771. static static_codebook _44c1_s_p8_1 = {
  138772. 2, 169,
  138773. _vq_lengthlist__44c1_s_p8_1,
  138774. 1, -522616832, 1620115456, 4, 0,
  138775. _vq_quantlist__44c1_s_p8_1,
  138776. NULL,
  138777. &_vq_auxt__44c1_s_p8_1,
  138778. NULL,
  138779. 0
  138780. };
  138781. static long _vq_quantlist__44c1_s_p8_2[] = {
  138782. 8,
  138783. 7,
  138784. 9,
  138785. 6,
  138786. 10,
  138787. 5,
  138788. 11,
  138789. 4,
  138790. 12,
  138791. 3,
  138792. 13,
  138793. 2,
  138794. 14,
  138795. 1,
  138796. 15,
  138797. 0,
  138798. 16,
  138799. };
  138800. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138801. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138802. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138803. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138804. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138805. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138806. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138807. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138808. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138809. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138810. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138811. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138812. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138813. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138814. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138815. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138816. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138817. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138818. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138819. 9,
  138820. };
  138821. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138822. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138823. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138824. };
  138825. static long _vq_quantmap__44c1_s_p8_2[] = {
  138826. 15, 13, 11, 9, 7, 5, 3, 1,
  138827. 0, 2, 4, 6, 8, 10, 12, 14,
  138828. 16,
  138829. };
  138830. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138831. _vq_quantthresh__44c1_s_p8_2,
  138832. _vq_quantmap__44c1_s_p8_2,
  138833. 17,
  138834. 17
  138835. };
  138836. static static_codebook _44c1_s_p8_2 = {
  138837. 2, 289,
  138838. _vq_lengthlist__44c1_s_p8_2,
  138839. 1, -529530880, 1611661312, 5, 0,
  138840. _vq_quantlist__44c1_s_p8_2,
  138841. NULL,
  138842. &_vq_auxt__44c1_s_p8_2,
  138843. NULL,
  138844. 0
  138845. };
  138846. static long _huff_lengthlist__44c1_s_short[] = {
  138847. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138848. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138849. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138850. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138851. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138852. 11,
  138853. };
  138854. static static_codebook _huff_book__44c1_s_short = {
  138855. 2, 81,
  138856. _huff_lengthlist__44c1_s_short,
  138857. 0, 0, 0, 0, 0,
  138858. NULL,
  138859. NULL,
  138860. NULL,
  138861. NULL,
  138862. 0
  138863. };
  138864. static long _huff_lengthlist__44c1_sm_long[] = {
  138865. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138866. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138867. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138868. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138869. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138870. 11,
  138871. };
  138872. static static_codebook _huff_book__44c1_sm_long = {
  138873. 2, 81,
  138874. _huff_lengthlist__44c1_sm_long,
  138875. 0, 0, 0, 0, 0,
  138876. NULL,
  138877. NULL,
  138878. NULL,
  138879. NULL,
  138880. 0
  138881. };
  138882. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138883. 1,
  138884. 0,
  138885. 2,
  138886. };
  138887. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138888. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138889. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138894. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138899. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138934. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138939. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138944. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138980. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138985. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138990. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 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,
  139299. };
  139300. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139301. -0.5, 0.5,
  139302. };
  139303. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139304. 1, 0, 2,
  139305. };
  139306. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139307. _vq_quantthresh__44c1_sm_p1_0,
  139308. _vq_quantmap__44c1_sm_p1_0,
  139309. 3,
  139310. 3
  139311. };
  139312. static static_codebook _44c1_sm_p1_0 = {
  139313. 8, 6561,
  139314. _vq_lengthlist__44c1_sm_p1_0,
  139315. 1, -535822336, 1611661312, 2, 0,
  139316. _vq_quantlist__44c1_sm_p1_0,
  139317. NULL,
  139318. &_vq_auxt__44c1_sm_p1_0,
  139319. NULL,
  139320. 0
  139321. };
  139322. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139323. 2,
  139324. 1,
  139325. 3,
  139326. 0,
  139327. 4,
  139328. };
  139329. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139330. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139370. };
  139371. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139372. -1.5, -0.5, 0.5, 1.5,
  139373. };
  139374. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139375. 3, 1, 0, 2, 4,
  139376. };
  139377. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139378. _vq_quantthresh__44c1_sm_p2_0,
  139379. _vq_quantmap__44c1_sm_p2_0,
  139380. 5,
  139381. 5
  139382. };
  139383. static static_codebook _44c1_sm_p2_0 = {
  139384. 4, 625,
  139385. _vq_lengthlist__44c1_sm_p2_0,
  139386. 1, -533725184, 1611661312, 3, 0,
  139387. _vq_quantlist__44c1_sm_p2_0,
  139388. NULL,
  139389. &_vq_auxt__44c1_sm_p2_0,
  139390. NULL,
  139391. 0
  139392. };
  139393. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139394. 4,
  139395. 3,
  139396. 5,
  139397. 2,
  139398. 6,
  139399. 1,
  139400. 7,
  139401. 0,
  139402. 8,
  139403. };
  139404. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139405. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139406. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139407. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139408. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139409. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0,
  139411. };
  139412. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139413. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139414. };
  139415. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139416. 7, 5, 3, 1, 0, 2, 4, 6,
  139417. 8,
  139418. };
  139419. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139420. _vq_quantthresh__44c1_sm_p3_0,
  139421. _vq_quantmap__44c1_sm_p3_0,
  139422. 9,
  139423. 9
  139424. };
  139425. static static_codebook _44c1_sm_p3_0 = {
  139426. 2, 81,
  139427. _vq_lengthlist__44c1_sm_p3_0,
  139428. 1, -531628032, 1611661312, 4, 0,
  139429. _vq_quantlist__44c1_sm_p3_0,
  139430. NULL,
  139431. &_vq_auxt__44c1_sm_p3_0,
  139432. NULL,
  139433. 0
  139434. };
  139435. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139436. 4,
  139437. 3,
  139438. 5,
  139439. 2,
  139440. 6,
  139441. 1,
  139442. 7,
  139443. 0,
  139444. 8,
  139445. };
  139446. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139447. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139448. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139449. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139450. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139451. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139452. 11,
  139453. };
  139454. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139455. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139456. };
  139457. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139458. 7, 5, 3, 1, 0, 2, 4, 6,
  139459. 8,
  139460. };
  139461. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139462. _vq_quantthresh__44c1_sm_p4_0,
  139463. _vq_quantmap__44c1_sm_p4_0,
  139464. 9,
  139465. 9
  139466. };
  139467. static static_codebook _44c1_sm_p4_0 = {
  139468. 2, 81,
  139469. _vq_lengthlist__44c1_sm_p4_0,
  139470. 1, -531628032, 1611661312, 4, 0,
  139471. _vq_quantlist__44c1_sm_p4_0,
  139472. NULL,
  139473. &_vq_auxt__44c1_sm_p4_0,
  139474. NULL,
  139475. 0
  139476. };
  139477. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139478. 8,
  139479. 7,
  139480. 9,
  139481. 6,
  139482. 10,
  139483. 5,
  139484. 11,
  139485. 4,
  139486. 12,
  139487. 3,
  139488. 13,
  139489. 2,
  139490. 14,
  139491. 1,
  139492. 15,
  139493. 0,
  139494. 16,
  139495. };
  139496. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139497. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139498. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139499. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139500. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139501. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139502. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139503. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139504. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139505. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139506. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139507. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139508. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139509. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139510. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139511. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139512. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139513. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139515. 14,
  139516. };
  139517. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139518. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139519. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139520. };
  139521. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139522. 15, 13, 11, 9, 7, 5, 3, 1,
  139523. 0, 2, 4, 6, 8, 10, 12, 14,
  139524. 16,
  139525. };
  139526. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139527. _vq_quantthresh__44c1_sm_p5_0,
  139528. _vq_quantmap__44c1_sm_p5_0,
  139529. 17,
  139530. 17
  139531. };
  139532. static static_codebook _44c1_sm_p5_0 = {
  139533. 2, 289,
  139534. _vq_lengthlist__44c1_sm_p5_0,
  139535. 1, -529530880, 1611661312, 5, 0,
  139536. _vq_quantlist__44c1_sm_p5_0,
  139537. NULL,
  139538. &_vq_auxt__44c1_sm_p5_0,
  139539. NULL,
  139540. 0
  139541. };
  139542. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139543. 1,
  139544. 0,
  139545. 2,
  139546. };
  139547. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139548. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139549. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139550. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139551. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139552. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139553. 11,
  139554. };
  139555. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139556. -5.5, 5.5,
  139557. };
  139558. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139559. 1, 0, 2,
  139560. };
  139561. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139562. _vq_quantthresh__44c1_sm_p6_0,
  139563. _vq_quantmap__44c1_sm_p6_0,
  139564. 3,
  139565. 3
  139566. };
  139567. static static_codebook _44c1_sm_p6_0 = {
  139568. 4, 81,
  139569. _vq_lengthlist__44c1_sm_p6_0,
  139570. 1, -529137664, 1618345984, 2, 0,
  139571. _vq_quantlist__44c1_sm_p6_0,
  139572. NULL,
  139573. &_vq_auxt__44c1_sm_p6_0,
  139574. NULL,
  139575. 0
  139576. };
  139577. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139578. 5,
  139579. 4,
  139580. 6,
  139581. 3,
  139582. 7,
  139583. 2,
  139584. 8,
  139585. 1,
  139586. 9,
  139587. 0,
  139588. 10,
  139589. };
  139590. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139591. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139592. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139593. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139594. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139595. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139596. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139597. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139598. 10,10,10, 8, 8, 8, 8, 8, 8,
  139599. };
  139600. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139601. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139602. 3.5, 4.5,
  139603. };
  139604. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139605. 9, 7, 5, 3, 1, 0, 2, 4,
  139606. 6, 8, 10,
  139607. };
  139608. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139609. _vq_quantthresh__44c1_sm_p6_1,
  139610. _vq_quantmap__44c1_sm_p6_1,
  139611. 11,
  139612. 11
  139613. };
  139614. static static_codebook _44c1_sm_p6_1 = {
  139615. 2, 121,
  139616. _vq_lengthlist__44c1_sm_p6_1,
  139617. 1, -531365888, 1611661312, 4, 0,
  139618. _vq_quantlist__44c1_sm_p6_1,
  139619. NULL,
  139620. &_vq_auxt__44c1_sm_p6_1,
  139621. NULL,
  139622. 0
  139623. };
  139624. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139625. 6,
  139626. 5,
  139627. 7,
  139628. 4,
  139629. 8,
  139630. 3,
  139631. 9,
  139632. 2,
  139633. 10,
  139634. 1,
  139635. 11,
  139636. 0,
  139637. 12,
  139638. };
  139639. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139640. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139641. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139642. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139643. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139644. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139645. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139646. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139647. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139648. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139649. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139650. 0,12,12,11,11,13,12,14,13,
  139651. };
  139652. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139653. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139654. 12.5, 17.5, 22.5, 27.5,
  139655. };
  139656. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139657. 11, 9, 7, 5, 3, 1, 0, 2,
  139658. 4, 6, 8, 10, 12,
  139659. };
  139660. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139661. _vq_quantthresh__44c1_sm_p7_0,
  139662. _vq_quantmap__44c1_sm_p7_0,
  139663. 13,
  139664. 13
  139665. };
  139666. static static_codebook _44c1_sm_p7_0 = {
  139667. 2, 169,
  139668. _vq_lengthlist__44c1_sm_p7_0,
  139669. 1, -526516224, 1616117760, 4, 0,
  139670. _vq_quantlist__44c1_sm_p7_0,
  139671. NULL,
  139672. &_vq_auxt__44c1_sm_p7_0,
  139673. NULL,
  139674. 0
  139675. };
  139676. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139677. 2,
  139678. 1,
  139679. 3,
  139680. 0,
  139681. 4,
  139682. };
  139683. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139684. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139685. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139686. };
  139687. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139688. -1.5, -0.5, 0.5, 1.5,
  139689. };
  139690. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139691. 3, 1, 0, 2, 4,
  139692. };
  139693. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139694. _vq_quantthresh__44c1_sm_p7_1,
  139695. _vq_quantmap__44c1_sm_p7_1,
  139696. 5,
  139697. 5
  139698. };
  139699. static static_codebook _44c1_sm_p7_1 = {
  139700. 2, 25,
  139701. _vq_lengthlist__44c1_sm_p7_1,
  139702. 1, -533725184, 1611661312, 3, 0,
  139703. _vq_quantlist__44c1_sm_p7_1,
  139704. NULL,
  139705. &_vq_auxt__44c1_sm_p7_1,
  139706. NULL,
  139707. 0
  139708. };
  139709. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139710. 6,
  139711. 5,
  139712. 7,
  139713. 4,
  139714. 8,
  139715. 3,
  139716. 9,
  139717. 2,
  139718. 10,
  139719. 1,
  139720. 11,
  139721. 0,
  139722. 12,
  139723. };
  139724. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139725. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139726. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139727. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139728. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139729. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139730. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139731. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139732. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139733. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139734. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139735. 13,13,13,13,13,13,13,13,13,
  139736. };
  139737. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139738. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139739. 552.5, 773.5, 994.5, 1215.5,
  139740. };
  139741. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139742. 11, 9, 7, 5, 3, 1, 0, 2,
  139743. 4, 6, 8, 10, 12,
  139744. };
  139745. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139746. _vq_quantthresh__44c1_sm_p8_0,
  139747. _vq_quantmap__44c1_sm_p8_0,
  139748. 13,
  139749. 13
  139750. };
  139751. static static_codebook _44c1_sm_p8_0 = {
  139752. 2, 169,
  139753. _vq_lengthlist__44c1_sm_p8_0,
  139754. 1, -514541568, 1627103232, 4, 0,
  139755. _vq_quantlist__44c1_sm_p8_0,
  139756. NULL,
  139757. &_vq_auxt__44c1_sm_p8_0,
  139758. NULL,
  139759. 0
  139760. };
  139761. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139762. 6,
  139763. 5,
  139764. 7,
  139765. 4,
  139766. 8,
  139767. 3,
  139768. 9,
  139769. 2,
  139770. 10,
  139771. 1,
  139772. 11,
  139773. 0,
  139774. 12,
  139775. };
  139776. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139777. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139778. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139779. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139780. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139781. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139782. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139783. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139784. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139785. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139786. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139787. 20,13,12,12,12,14,12,14,13,
  139788. };
  139789. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139790. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139791. 42.5, 59.5, 76.5, 93.5,
  139792. };
  139793. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139794. 11, 9, 7, 5, 3, 1, 0, 2,
  139795. 4, 6, 8, 10, 12,
  139796. };
  139797. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139798. _vq_quantthresh__44c1_sm_p8_1,
  139799. _vq_quantmap__44c1_sm_p8_1,
  139800. 13,
  139801. 13
  139802. };
  139803. static static_codebook _44c1_sm_p8_1 = {
  139804. 2, 169,
  139805. _vq_lengthlist__44c1_sm_p8_1,
  139806. 1, -522616832, 1620115456, 4, 0,
  139807. _vq_quantlist__44c1_sm_p8_1,
  139808. NULL,
  139809. &_vq_auxt__44c1_sm_p8_1,
  139810. NULL,
  139811. 0
  139812. };
  139813. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139814. 8,
  139815. 7,
  139816. 9,
  139817. 6,
  139818. 10,
  139819. 5,
  139820. 11,
  139821. 4,
  139822. 12,
  139823. 3,
  139824. 13,
  139825. 2,
  139826. 14,
  139827. 1,
  139828. 15,
  139829. 0,
  139830. 16,
  139831. };
  139832. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139833. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139834. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139835. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139836. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139837. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139838. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139839. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139840. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139841. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139842. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139843. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139844. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139845. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139846. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139847. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139848. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139849. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139850. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139851. 9,
  139852. };
  139853. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139854. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139855. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139856. };
  139857. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139858. 15, 13, 11, 9, 7, 5, 3, 1,
  139859. 0, 2, 4, 6, 8, 10, 12, 14,
  139860. 16,
  139861. };
  139862. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139863. _vq_quantthresh__44c1_sm_p8_2,
  139864. _vq_quantmap__44c1_sm_p8_2,
  139865. 17,
  139866. 17
  139867. };
  139868. static static_codebook _44c1_sm_p8_2 = {
  139869. 2, 289,
  139870. _vq_lengthlist__44c1_sm_p8_2,
  139871. 1, -529530880, 1611661312, 5, 0,
  139872. _vq_quantlist__44c1_sm_p8_2,
  139873. NULL,
  139874. &_vq_auxt__44c1_sm_p8_2,
  139875. NULL,
  139876. 0
  139877. };
  139878. static long _huff_lengthlist__44c1_sm_short[] = {
  139879. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139880. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139881. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139882. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139883. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139884. 11,
  139885. };
  139886. static static_codebook _huff_book__44c1_sm_short = {
  139887. 2, 81,
  139888. _huff_lengthlist__44c1_sm_short,
  139889. 0, 0, 0, 0, 0,
  139890. NULL,
  139891. NULL,
  139892. NULL,
  139893. NULL,
  139894. 0
  139895. };
  139896. static long _huff_lengthlist__44cn1_s_long[] = {
  139897. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139898. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139899. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139900. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139901. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139902. 20,
  139903. };
  139904. static static_codebook _huff_book__44cn1_s_long = {
  139905. 2, 81,
  139906. _huff_lengthlist__44cn1_s_long,
  139907. 0, 0, 0, 0, 0,
  139908. NULL,
  139909. NULL,
  139910. NULL,
  139911. NULL,
  139912. 0
  139913. };
  139914. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139915. 1,
  139916. 0,
  139917. 2,
  139918. };
  139919. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139920. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139921. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139926. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139931. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139966. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139971. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139976. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140012. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140017. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140022. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 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,
  140331. };
  140332. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140333. -0.5, 0.5,
  140334. };
  140335. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140336. 1, 0, 2,
  140337. };
  140338. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140339. _vq_quantthresh__44cn1_s_p1_0,
  140340. _vq_quantmap__44cn1_s_p1_0,
  140341. 3,
  140342. 3
  140343. };
  140344. static static_codebook _44cn1_s_p1_0 = {
  140345. 8, 6561,
  140346. _vq_lengthlist__44cn1_s_p1_0,
  140347. 1, -535822336, 1611661312, 2, 0,
  140348. _vq_quantlist__44cn1_s_p1_0,
  140349. NULL,
  140350. &_vq_auxt__44cn1_s_p1_0,
  140351. NULL,
  140352. 0
  140353. };
  140354. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140355. 2,
  140356. 1,
  140357. 3,
  140358. 0,
  140359. 4,
  140360. };
  140361. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140362. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140402. };
  140403. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140404. -1.5, -0.5, 0.5, 1.5,
  140405. };
  140406. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140407. 3, 1, 0, 2, 4,
  140408. };
  140409. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140410. _vq_quantthresh__44cn1_s_p2_0,
  140411. _vq_quantmap__44cn1_s_p2_0,
  140412. 5,
  140413. 5
  140414. };
  140415. static static_codebook _44cn1_s_p2_0 = {
  140416. 4, 625,
  140417. _vq_lengthlist__44cn1_s_p2_0,
  140418. 1, -533725184, 1611661312, 3, 0,
  140419. _vq_quantlist__44cn1_s_p2_0,
  140420. NULL,
  140421. &_vq_auxt__44cn1_s_p2_0,
  140422. NULL,
  140423. 0
  140424. };
  140425. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140426. 4,
  140427. 3,
  140428. 5,
  140429. 2,
  140430. 6,
  140431. 1,
  140432. 7,
  140433. 0,
  140434. 8,
  140435. };
  140436. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140437. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140438. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140439. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140440. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140441. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0,
  140443. };
  140444. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140445. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140446. };
  140447. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140448. 7, 5, 3, 1, 0, 2, 4, 6,
  140449. 8,
  140450. };
  140451. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140452. _vq_quantthresh__44cn1_s_p3_0,
  140453. _vq_quantmap__44cn1_s_p3_0,
  140454. 9,
  140455. 9
  140456. };
  140457. static static_codebook _44cn1_s_p3_0 = {
  140458. 2, 81,
  140459. _vq_lengthlist__44cn1_s_p3_0,
  140460. 1, -531628032, 1611661312, 4, 0,
  140461. _vq_quantlist__44cn1_s_p3_0,
  140462. NULL,
  140463. &_vq_auxt__44cn1_s_p3_0,
  140464. NULL,
  140465. 0
  140466. };
  140467. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140468. 4,
  140469. 3,
  140470. 5,
  140471. 2,
  140472. 6,
  140473. 1,
  140474. 7,
  140475. 0,
  140476. 8,
  140477. };
  140478. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140479. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140480. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140481. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140482. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140483. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140484. 11,
  140485. };
  140486. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140487. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140488. };
  140489. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140490. 7, 5, 3, 1, 0, 2, 4, 6,
  140491. 8,
  140492. };
  140493. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140494. _vq_quantthresh__44cn1_s_p4_0,
  140495. _vq_quantmap__44cn1_s_p4_0,
  140496. 9,
  140497. 9
  140498. };
  140499. static static_codebook _44cn1_s_p4_0 = {
  140500. 2, 81,
  140501. _vq_lengthlist__44cn1_s_p4_0,
  140502. 1, -531628032, 1611661312, 4, 0,
  140503. _vq_quantlist__44cn1_s_p4_0,
  140504. NULL,
  140505. &_vq_auxt__44cn1_s_p4_0,
  140506. NULL,
  140507. 0
  140508. };
  140509. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140510. 8,
  140511. 7,
  140512. 9,
  140513. 6,
  140514. 10,
  140515. 5,
  140516. 11,
  140517. 4,
  140518. 12,
  140519. 3,
  140520. 13,
  140521. 2,
  140522. 14,
  140523. 1,
  140524. 15,
  140525. 0,
  140526. 16,
  140527. };
  140528. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140529. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140530. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140531. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140532. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140533. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140534. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140535. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140536. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140537. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140538. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140539. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140540. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140541. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140542. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140543. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140544. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140545. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140547. 14,
  140548. };
  140549. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140550. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140551. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140552. };
  140553. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140554. 15, 13, 11, 9, 7, 5, 3, 1,
  140555. 0, 2, 4, 6, 8, 10, 12, 14,
  140556. 16,
  140557. };
  140558. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140559. _vq_quantthresh__44cn1_s_p5_0,
  140560. _vq_quantmap__44cn1_s_p5_0,
  140561. 17,
  140562. 17
  140563. };
  140564. static static_codebook _44cn1_s_p5_0 = {
  140565. 2, 289,
  140566. _vq_lengthlist__44cn1_s_p5_0,
  140567. 1, -529530880, 1611661312, 5, 0,
  140568. _vq_quantlist__44cn1_s_p5_0,
  140569. NULL,
  140570. &_vq_auxt__44cn1_s_p5_0,
  140571. NULL,
  140572. 0
  140573. };
  140574. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140575. 1,
  140576. 0,
  140577. 2,
  140578. };
  140579. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140580. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140581. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140582. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140583. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140584. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140585. 10,
  140586. };
  140587. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140588. -5.5, 5.5,
  140589. };
  140590. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140591. 1, 0, 2,
  140592. };
  140593. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140594. _vq_quantthresh__44cn1_s_p6_0,
  140595. _vq_quantmap__44cn1_s_p6_0,
  140596. 3,
  140597. 3
  140598. };
  140599. static static_codebook _44cn1_s_p6_0 = {
  140600. 4, 81,
  140601. _vq_lengthlist__44cn1_s_p6_0,
  140602. 1, -529137664, 1618345984, 2, 0,
  140603. _vq_quantlist__44cn1_s_p6_0,
  140604. NULL,
  140605. &_vq_auxt__44cn1_s_p6_0,
  140606. NULL,
  140607. 0
  140608. };
  140609. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140610. 5,
  140611. 4,
  140612. 6,
  140613. 3,
  140614. 7,
  140615. 2,
  140616. 8,
  140617. 1,
  140618. 9,
  140619. 0,
  140620. 10,
  140621. };
  140622. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140623. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140624. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140625. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140626. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140627. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140628. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140629. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140630. 10,10,10, 9, 9, 9, 9, 9, 9,
  140631. };
  140632. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140633. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140634. 3.5, 4.5,
  140635. };
  140636. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140637. 9, 7, 5, 3, 1, 0, 2, 4,
  140638. 6, 8, 10,
  140639. };
  140640. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140641. _vq_quantthresh__44cn1_s_p6_1,
  140642. _vq_quantmap__44cn1_s_p6_1,
  140643. 11,
  140644. 11
  140645. };
  140646. static static_codebook _44cn1_s_p6_1 = {
  140647. 2, 121,
  140648. _vq_lengthlist__44cn1_s_p6_1,
  140649. 1, -531365888, 1611661312, 4, 0,
  140650. _vq_quantlist__44cn1_s_p6_1,
  140651. NULL,
  140652. &_vq_auxt__44cn1_s_p6_1,
  140653. NULL,
  140654. 0
  140655. };
  140656. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140657. 6,
  140658. 5,
  140659. 7,
  140660. 4,
  140661. 8,
  140662. 3,
  140663. 9,
  140664. 2,
  140665. 10,
  140666. 1,
  140667. 11,
  140668. 0,
  140669. 12,
  140670. };
  140671. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140672. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140673. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140674. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140675. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140676. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140677. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140678. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140679. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140680. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140681. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140682. 0,13,13,12,12,13,13,13,14,
  140683. };
  140684. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140685. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140686. 12.5, 17.5, 22.5, 27.5,
  140687. };
  140688. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140689. 11, 9, 7, 5, 3, 1, 0, 2,
  140690. 4, 6, 8, 10, 12,
  140691. };
  140692. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140693. _vq_quantthresh__44cn1_s_p7_0,
  140694. _vq_quantmap__44cn1_s_p7_0,
  140695. 13,
  140696. 13
  140697. };
  140698. static static_codebook _44cn1_s_p7_0 = {
  140699. 2, 169,
  140700. _vq_lengthlist__44cn1_s_p7_0,
  140701. 1, -526516224, 1616117760, 4, 0,
  140702. _vq_quantlist__44cn1_s_p7_0,
  140703. NULL,
  140704. &_vq_auxt__44cn1_s_p7_0,
  140705. NULL,
  140706. 0
  140707. };
  140708. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140709. 2,
  140710. 1,
  140711. 3,
  140712. 0,
  140713. 4,
  140714. };
  140715. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140716. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140717. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140718. };
  140719. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140720. -1.5, -0.5, 0.5, 1.5,
  140721. };
  140722. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140723. 3, 1, 0, 2, 4,
  140724. };
  140725. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140726. _vq_quantthresh__44cn1_s_p7_1,
  140727. _vq_quantmap__44cn1_s_p7_1,
  140728. 5,
  140729. 5
  140730. };
  140731. static static_codebook _44cn1_s_p7_1 = {
  140732. 2, 25,
  140733. _vq_lengthlist__44cn1_s_p7_1,
  140734. 1, -533725184, 1611661312, 3, 0,
  140735. _vq_quantlist__44cn1_s_p7_1,
  140736. NULL,
  140737. &_vq_auxt__44cn1_s_p7_1,
  140738. NULL,
  140739. 0
  140740. };
  140741. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140742. 2,
  140743. 1,
  140744. 3,
  140745. 0,
  140746. 4,
  140747. };
  140748. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140749. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140750. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140752. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140756. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140758. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140764. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140776. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140782. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140783. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140784. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140785. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140786. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140787. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140788. 12,
  140789. };
  140790. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140791. -331.5, -110.5, 110.5, 331.5,
  140792. };
  140793. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140794. 3, 1, 0, 2, 4,
  140795. };
  140796. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140797. _vq_quantthresh__44cn1_s_p8_0,
  140798. _vq_quantmap__44cn1_s_p8_0,
  140799. 5,
  140800. 5
  140801. };
  140802. static static_codebook _44cn1_s_p8_0 = {
  140803. 4, 625,
  140804. _vq_lengthlist__44cn1_s_p8_0,
  140805. 1, -518283264, 1627103232, 3, 0,
  140806. _vq_quantlist__44cn1_s_p8_0,
  140807. NULL,
  140808. &_vq_auxt__44cn1_s_p8_0,
  140809. NULL,
  140810. 0
  140811. };
  140812. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140813. 6,
  140814. 5,
  140815. 7,
  140816. 4,
  140817. 8,
  140818. 3,
  140819. 9,
  140820. 2,
  140821. 10,
  140822. 1,
  140823. 11,
  140824. 0,
  140825. 12,
  140826. };
  140827. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140828. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140829. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140830. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140831. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140832. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140833. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140834. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140835. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140836. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140837. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140838. 15,12,12,11,11,14,12,13,14,
  140839. };
  140840. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140841. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140842. 42.5, 59.5, 76.5, 93.5,
  140843. };
  140844. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140845. 11, 9, 7, 5, 3, 1, 0, 2,
  140846. 4, 6, 8, 10, 12,
  140847. };
  140848. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140849. _vq_quantthresh__44cn1_s_p8_1,
  140850. _vq_quantmap__44cn1_s_p8_1,
  140851. 13,
  140852. 13
  140853. };
  140854. static static_codebook _44cn1_s_p8_1 = {
  140855. 2, 169,
  140856. _vq_lengthlist__44cn1_s_p8_1,
  140857. 1, -522616832, 1620115456, 4, 0,
  140858. _vq_quantlist__44cn1_s_p8_1,
  140859. NULL,
  140860. &_vq_auxt__44cn1_s_p8_1,
  140861. NULL,
  140862. 0
  140863. };
  140864. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140865. 8,
  140866. 7,
  140867. 9,
  140868. 6,
  140869. 10,
  140870. 5,
  140871. 11,
  140872. 4,
  140873. 12,
  140874. 3,
  140875. 13,
  140876. 2,
  140877. 14,
  140878. 1,
  140879. 15,
  140880. 0,
  140881. 16,
  140882. };
  140883. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140884. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140885. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140886. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140887. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140888. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140889. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140890. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140891. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140892. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140893. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140894. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140895. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140896. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140897. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140898. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140899. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140900. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140901. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140902. 9,
  140903. };
  140904. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140905. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140906. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140907. };
  140908. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140909. 15, 13, 11, 9, 7, 5, 3, 1,
  140910. 0, 2, 4, 6, 8, 10, 12, 14,
  140911. 16,
  140912. };
  140913. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140914. _vq_quantthresh__44cn1_s_p8_2,
  140915. _vq_quantmap__44cn1_s_p8_2,
  140916. 17,
  140917. 17
  140918. };
  140919. static static_codebook _44cn1_s_p8_2 = {
  140920. 2, 289,
  140921. _vq_lengthlist__44cn1_s_p8_2,
  140922. 1, -529530880, 1611661312, 5, 0,
  140923. _vq_quantlist__44cn1_s_p8_2,
  140924. NULL,
  140925. &_vq_auxt__44cn1_s_p8_2,
  140926. NULL,
  140927. 0
  140928. };
  140929. static long _huff_lengthlist__44cn1_s_short[] = {
  140930. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140931. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140932. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140933. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140934. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140935. 10,
  140936. };
  140937. static static_codebook _huff_book__44cn1_s_short = {
  140938. 2, 81,
  140939. _huff_lengthlist__44cn1_s_short,
  140940. 0, 0, 0, 0, 0,
  140941. NULL,
  140942. NULL,
  140943. NULL,
  140944. NULL,
  140945. 0
  140946. };
  140947. static long _huff_lengthlist__44cn1_sm_long[] = {
  140948. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140949. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140950. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140951. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140952. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140953. 17,
  140954. };
  140955. static static_codebook _huff_book__44cn1_sm_long = {
  140956. 2, 81,
  140957. _huff_lengthlist__44cn1_sm_long,
  140958. 0, 0, 0, 0, 0,
  140959. NULL,
  140960. NULL,
  140961. NULL,
  140962. NULL,
  140963. 0
  140964. };
  140965. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140966. 1,
  140967. 0,
  140968. 2,
  140969. };
  140970. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140971. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140972. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140977. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140982. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141017. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141022. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141027. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141063. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141068. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141073. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 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,
  141382. };
  141383. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141384. -0.5, 0.5,
  141385. };
  141386. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141387. 1, 0, 2,
  141388. };
  141389. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141390. _vq_quantthresh__44cn1_sm_p1_0,
  141391. _vq_quantmap__44cn1_sm_p1_0,
  141392. 3,
  141393. 3
  141394. };
  141395. static static_codebook _44cn1_sm_p1_0 = {
  141396. 8, 6561,
  141397. _vq_lengthlist__44cn1_sm_p1_0,
  141398. 1, -535822336, 1611661312, 2, 0,
  141399. _vq_quantlist__44cn1_sm_p1_0,
  141400. NULL,
  141401. &_vq_auxt__44cn1_sm_p1_0,
  141402. NULL,
  141403. 0
  141404. };
  141405. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141406. 2,
  141407. 1,
  141408. 3,
  141409. 0,
  141410. 4,
  141411. };
  141412. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141413. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141453. };
  141454. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141455. -1.5, -0.5, 0.5, 1.5,
  141456. };
  141457. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141458. 3, 1, 0, 2, 4,
  141459. };
  141460. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141461. _vq_quantthresh__44cn1_sm_p2_0,
  141462. _vq_quantmap__44cn1_sm_p2_0,
  141463. 5,
  141464. 5
  141465. };
  141466. static static_codebook _44cn1_sm_p2_0 = {
  141467. 4, 625,
  141468. _vq_lengthlist__44cn1_sm_p2_0,
  141469. 1, -533725184, 1611661312, 3, 0,
  141470. _vq_quantlist__44cn1_sm_p2_0,
  141471. NULL,
  141472. &_vq_auxt__44cn1_sm_p2_0,
  141473. NULL,
  141474. 0
  141475. };
  141476. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141477. 4,
  141478. 3,
  141479. 5,
  141480. 2,
  141481. 6,
  141482. 1,
  141483. 7,
  141484. 0,
  141485. 8,
  141486. };
  141487. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141488. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141489. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141490. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141491. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141492. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0,
  141494. };
  141495. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141496. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141497. };
  141498. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141499. 7, 5, 3, 1, 0, 2, 4, 6,
  141500. 8,
  141501. };
  141502. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141503. _vq_quantthresh__44cn1_sm_p3_0,
  141504. _vq_quantmap__44cn1_sm_p3_0,
  141505. 9,
  141506. 9
  141507. };
  141508. static static_codebook _44cn1_sm_p3_0 = {
  141509. 2, 81,
  141510. _vq_lengthlist__44cn1_sm_p3_0,
  141511. 1, -531628032, 1611661312, 4, 0,
  141512. _vq_quantlist__44cn1_sm_p3_0,
  141513. NULL,
  141514. &_vq_auxt__44cn1_sm_p3_0,
  141515. NULL,
  141516. 0
  141517. };
  141518. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141519. 4,
  141520. 3,
  141521. 5,
  141522. 2,
  141523. 6,
  141524. 1,
  141525. 7,
  141526. 0,
  141527. 8,
  141528. };
  141529. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141530. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141531. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141532. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141533. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141534. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141535. 11,
  141536. };
  141537. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141538. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141539. };
  141540. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141541. 7, 5, 3, 1, 0, 2, 4, 6,
  141542. 8,
  141543. };
  141544. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141545. _vq_quantthresh__44cn1_sm_p4_0,
  141546. _vq_quantmap__44cn1_sm_p4_0,
  141547. 9,
  141548. 9
  141549. };
  141550. static static_codebook _44cn1_sm_p4_0 = {
  141551. 2, 81,
  141552. _vq_lengthlist__44cn1_sm_p4_0,
  141553. 1, -531628032, 1611661312, 4, 0,
  141554. _vq_quantlist__44cn1_sm_p4_0,
  141555. NULL,
  141556. &_vq_auxt__44cn1_sm_p4_0,
  141557. NULL,
  141558. 0
  141559. };
  141560. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141561. 8,
  141562. 7,
  141563. 9,
  141564. 6,
  141565. 10,
  141566. 5,
  141567. 11,
  141568. 4,
  141569. 12,
  141570. 3,
  141571. 13,
  141572. 2,
  141573. 14,
  141574. 1,
  141575. 15,
  141576. 0,
  141577. 16,
  141578. };
  141579. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141580. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141581. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141582. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141583. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141584. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141585. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141586. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141587. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141588. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141589. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141590. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141591. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141592. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141593. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141594. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141595. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141596. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141598. 14,
  141599. };
  141600. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141601. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141602. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141603. };
  141604. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141605. 15, 13, 11, 9, 7, 5, 3, 1,
  141606. 0, 2, 4, 6, 8, 10, 12, 14,
  141607. 16,
  141608. };
  141609. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141610. _vq_quantthresh__44cn1_sm_p5_0,
  141611. _vq_quantmap__44cn1_sm_p5_0,
  141612. 17,
  141613. 17
  141614. };
  141615. static static_codebook _44cn1_sm_p5_0 = {
  141616. 2, 289,
  141617. _vq_lengthlist__44cn1_sm_p5_0,
  141618. 1, -529530880, 1611661312, 5, 0,
  141619. _vq_quantlist__44cn1_sm_p5_0,
  141620. NULL,
  141621. &_vq_auxt__44cn1_sm_p5_0,
  141622. NULL,
  141623. 0
  141624. };
  141625. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141626. 1,
  141627. 0,
  141628. 2,
  141629. };
  141630. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141631. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141632. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141633. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141634. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141635. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141636. 10,
  141637. };
  141638. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141639. -5.5, 5.5,
  141640. };
  141641. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141642. 1, 0, 2,
  141643. };
  141644. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141645. _vq_quantthresh__44cn1_sm_p6_0,
  141646. _vq_quantmap__44cn1_sm_p6_0,
  141647. 3,
  141648. 3
  141649. };
  141650. static static_codebook _44cn1_sm_p6_0 = {
  141651. 4, 81,
  141652. _vq_lengthlist__44cn1_sm_p6_0,
  141653. 1, -529137664, 1618345984, 2, 0,
  141654. _vq_quantlist__44cn1_sm_p6_0,
  141655. NULL,
  141656. &_vq_auxt__44cn1_sm_p6_0,
  141657. NULL,
  141658. 0
  141659. };
  141660. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141661. 5,
  141662. 4,
  141663. 6,
  141664. 3,
  141665. 7,
  141666. 2,
  141667. 8,
  141668. 1,
  141669. 9,
  141670. 0,
  141671. 10,
  141672. };
  141673. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141674. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141675. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141676. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141677. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141678. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141679. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141680. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141681. 10,10,10, 8, 9, 8, 8, 9, 8,
  141682. };
  141683. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141684. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141685. 3.5, 4.5,
  141686. };
  141687. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141688. 9, 7, 5, 3, 1, 0, 2, 4,
  141689. 6, 8, 10,
  141690. };
  141691. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141692. _vq_quantthresh__44cn1_sm_p6_1,
  141693. _vq_quantmap__44cn1_sm_p6_1,
  141694. 11,
  141695. 11
  141696. };
  141697. static static_codebook _44cn1_sm_p6_1 = {
  141698. 2, 121,
  141699. _vq_lengthlist__44cn1_sm_p6_1,
  141700. 1, -531365888, 1611661312, 4, 0,
  141701. _vq_quantlist__44cn1_sm_p6_1,
  141702. NULL,
  141703. &_vq_auxt__44cn1_sm_p6_1,
  141704. NULL,
  141705. 0
  141706. };
  141707. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141708. 6,
  141709. 5,
  141710. 7,
  141711. 4,
  141712. 8,
  141713. 3,
  141714. 9,
  141715. 2,
  141716. 10,
  141717. 1,
  141718. 11,
  141719. 0,
  141720. 12,
  141721. };
  141722. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141723. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141724. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141725. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141726. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141727. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141728. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141729. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141730. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141731. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141732. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141733. 0,13,12,12,12,13,13,13,14,
  141734. };
  141735. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141736. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141737. 12.5, 17.5, 22.5, 27.5,
  141738. };
  141739. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141740. 11, 9, 7, 5, 3, 1, 0, 2,
  141741. 4, 6, 8, 10, 12,
  141742. };
  141743. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141744. _vq_quantthresh__44cn1_sm_p7_0,
  141745. _vq_quantmap__44cn1_sm_p7_0,
  141746. 13,
  141747. 13
  141748. };
  141749. static static_codebook _44cn1_sm_p7_0 = {
  141750. 2, 169,
  141751. _vq_lengthlist__44cn1_sm_p7_0,
  141752. 1, -526516224, 1616117760, 4, 0,
  141753. _vq_quantlist__44cn1_sm_p7_0,
  141754. NULL,
  141755. &_vq_auxt__44cn1_sm_p7_0,
  141756. NULL,
  141757. 0
  141758. };
  141759. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141760. 2,
  141761. 1,
  141762. 3,
  141763. 0,
  141764. 4,
  141765. };
  141766. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141767. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141768. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141769. };
  141770. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141771. -1.5, -0.5, 0.5, 1.5,
  141772. };
  141773. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141774. 3, 1, 0, 2, 4,
  141775. };
  141776. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141777. _vq_quantthresh__44cn1_sm_p7_1,
  141778. _vq_quantmap__44cn1_sm_p7_1,
  141779. 5,
  141780. 5
  141781. };
  141782. static static_codebook _44cn1_sm_p7_1 = {
  141783. 2, 25,
  141784. _vq_lengthlist__44cn1_sm_p7_1,
  141785. 1, -533725184, 1611661312, 3, 0,
  141786. _vq_quantlist__44cn1_sm_p7_1,
  141787. NULL,
  141788. &_vq_auxt__44cn1_sm_p7_1,
  141789. NULL,
  141790. 0
  141791. };
  141792. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141793. 4,
  141794. 3,
  141795. 5,
  141796. 2,
  141797. 6,
  141798. 1,
  141799. 7,
  141800. 0,
  141801. 8,
  141802. };
  141803. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141804. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141805. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141806. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141807. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141808. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141809. 14,
  141810. };
  141811. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141812. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141813. };
  141814. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141815. 7, 5, 3, 1, 0, 2, 4, 6,
  141816. 8,
  141817. };
  141818. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141819. _vq_quantthresh__44cn1_sm_p8_0,
  141820. _vq_quantmap__44cn1_sm_p8_0,
  141821. 9,
  141822. 9
  141823. };
  141824. static static_codebook _44cn1_sm_p8_0 = {
  141825. 2, 81,
  141826. _vq_lengthlist__44cn1_sm_p8_0,
  141827. 1, -516186112, 1627103232, 4, 0,
  141828. _vq_quantlist__44cn1_sm_p8_0,
  141829. NULL,
  141830. &_vq_auxt__44cn1_sm_p8_0,
  141831. NULL,
  141832. 0
  141833. };
  141834. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141835. 6,
  141836. 5,
  141837. 7,
  141838. 4,
  141839. 8,
  141840. 3,
  141841. 9,
  141842. 2,
  141843. 10,
  141844. 1,
  141845. 11,
  141846. 0,
  141847. 12,
  141848. };
  141849. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141850. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141851. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141852. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141853. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141854. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141855. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141856. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141857. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141858. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141859. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141860. 17,12,12,11,10,13,11,13,13,
  141861. };
  141862. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141863. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141864. 42.5, 59.5, 76.5, 93.5,
  141865. };
  141866. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141867. 11, 9, 7, 5, 3, 1, 0, 2,
  141868. 4, 6, 8, 10, 12,
  141869. };
  141870. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141871. _vq_quantthresh__44cn1_sm_p8_1,
  141872. _vq_quantmap__44cn1_sm_p8_1,
  141873. 13,
  141874. 13
  141875. };
  141876. static static_codebook _44cn1_sm_p8_1 = {
  141877. 2, 169,
  141878. _vq_lengthlist__44cn1_sm_p8_1,
  141879. 1, -522616832, 1620115456, 4, 0,
  141880. _vq_quantlist__44cn1_sm_p8_1,
  141881. NULL,
  141882. &_vq_auxt__44cn1_sm_p8_1,
  141883. NULL,
  141884. 0
  141885. };
  141886. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141887. 8,
  141888. 7,
  141889. 9,
  141890. 6,
  141891. 10,
  141892. 5,
  141893. 11,
  141894. 4,
  141895. 12,
  141896. 3,
  141897. 13,
  141898. 2,
  141899. 14,
  141900. 1,
  141901. 15,
  141902. 0,
  141903. 16,
  141904. };
  141905. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141906. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141907. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141908. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141909. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141910. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141911. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141912. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141913. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141914. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141915. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141916. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141917. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141918. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141919. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141920. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141921. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141922. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141923. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141924. 9,
  141925. };
  141926. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141927. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141928. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141929. };
  141930. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141931. 15, 13, 11, 9, 7, 5, 3, 1,
  141932. 0, 2, 4, 6, 8, 10, 12, 14,
  141933. 16,
  141934. };
  141935. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141936. _vq_quantthresh__44cn1_sm_p8_2,
  141937. _vq_quantmap__44cn1_sm_p8_2,
  141938. 17,
  141939. 17
  141940. };
  141941. static static_codebook _44cn1_sm_p8_2 = {
  141942. 2, 289,
  141943. _vq_lengthlist__44cn1_sm_p8_2,
  141944. 1, -529530880, 1611661312, 5, 0,
  141945. _vq_quantlist__44cn1_sm_p8_2,
  141946. NULL,
  141947. &_vq_auxt__44cn1_sm_p8_2,
  141948. NULL,
  141949. 0
  141950. };
  141951. static long _huff_lengthlist__44cn1_sm_short[] = {
  141952. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141953. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141954. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141955. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141956. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141957. 9,
  141958. };
  141959. static static_codebook _huff_book__44cn1_sm_short = {
  141960. 2, 81,
  141961. _huff_lengthlist__44cn1_sm_short,
  141962. 0, 0, 0, 0, 0,
  141963. NULL,
  141964. NULL,
  141965. NULL,
  141966. NULL,
  141967. 0
  141968. };
  141969. /*** End of inlined file: res_books_stereo.h ***/
  141970. /***** residue backends *********************************************/
  141971. static vorbis_info_residue0 _residue_44_low={
  141972. 0,-1, -1, 9,-1,
  141973. /* 0 1 2 3 4 5 6 7 */
  141974. {0},
  141975. {-1},
  141976. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141977. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141978. };
  141979. static vorbis_info_residue0 _residue_44_mid={
  141980. 0,-1, -1, 10,-1,
  141981. /* 0 1 2 3 4 5 6 7 8 */
  141982. {0},
  141983. {-1},
  141984. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141985. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141986. };
  141987. static vorbis_info_residue0 _residue_44_high={
  141988. 0,-1, -1, 10,-1,
  141989. /* 0 1 2 3 4 5 6 7 8 */
  141990. {0},
  141991. {-1},
  141992. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141993. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141994. };
  141995. static static_bookblock _resbook_44s_n1={
  141996. {
  141997. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141998. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141999. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142000. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142001. }
  142002. };
  142003. static static_bookblock _resbook_44sm_n1={
  142004. {
  142005. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142006. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142007. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142008. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142009. }
  142010. };
  142011. static static_bookblock _resbook_44s_0={
  142012. {
  142013. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142014. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142015. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142016. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142017. }
  142018. };
  142019. static static_bookblock _resbook_44sm_0={
  142020. {
  142021. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142022. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142023. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142024. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142025. }
  142026. };
  142027. static static_bookblock _resbook_44s_1={
  142028. {
  142029. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142030. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142031. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142032. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142033. }
  142034. };
  142035. static static_bookblock _resbook_44sm_1={
  142036. {
  142037. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142038. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142039. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142040. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142041. }
  142042. };
  142043. static static_bookblock _resbook_44s_2={
  142044. {
  142045. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142046. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142047. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142048. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142049. }
  142050. };
  142051. static static_bookblock _resbook_44s_3={
  142052. {
  142053. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142054. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142055. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142056. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142057. }
  142058. };
  142059. static static_bookblock _resbook_44s_4={
  142060. {
  142061. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142062. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142063. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142064. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142065. }
  142066. };
  142067. static static_bookblock _resbook_44s_5={
  142068. {
  142069. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142070. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142071. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142072. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142073. }
  142074. };
  142075. static static_bookblock _resbook_44s_6={
  142076. {
  142077. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142078. {0,0,&_44c6_s_p4_0},
  142079. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142080. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142081. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142082. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142083. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142084. }
  142085. };
  142086. static static_bookblock _resbook_44s_7={
  142087. {
  142088. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142089. {0,0,&_44c7_s_p4_0},
  142090. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142091. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142092. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142093. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142094. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142095. }
  142096. };
  142097. static static_bookblock _resbook_44s_8={
  142098. {
  142099. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142100. {0,0,&_44c8_s_p4_0},
  142101. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142102. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142103. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142104. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142105. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142106. }
  142107. };
  142108. static static_bookblock _resbook_44s_9={
  142109. {
  142110. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142111. {0,0,&_44c9_s_p4_0},
  142112. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142113. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142114. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142115. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142116. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142117. }
  142118. };
  142119. static vorbis_residue_template _res_44s_n1[]={
  142120. {2,0, &_residue_44_low,
  142121. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142122. &_resbook_44s_n1,&_resbook_44sm_n1},
  142123. {2,0, &_residue_44_low,
  142124. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142125. &_resbook_44s_n1,&_resbook_44sm_n1}
  142126. };
  142127. static vorbis_residue_template _res_44s_0[]={
  142128. {2,0, &_residue_44_low,
  142129. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142130. &_resbook_44s_0,&_resbook_44sm_0},
  142131. {2,0, &_residue_44_low,
  142132. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142133. &_resbook_44s_0,&_resbook_44sm_0}
  142134. };
  142135. static vorbis_residue_template _res_44s_1[]={
  142136. {2,0, &_residue_44_low,
  142137. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142138. &_resbook_44s_1,&_resbook_44sm_1},
  142139. {2,0, &_residue_44_low,
  142140. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142141. &_resbook_44s_1,&_resbook_44sm_1}
  142142. };
  142143. static vorbis_residue_template _res_44s_2[]={
  142144. {2,0, &_residue_44_mid,
  142145. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142146. &_resbook_44s_2,&_resbook_44s_2},
  142147. {2,0, &_residue_44_mid,
  142148. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142149. &_resbook_44s_2,&_resbook_44s_2}
  142150. };
  142151. static vorbis_residue_template _res_44s_3[]={
  142152. {2,0, &_residue_44_mid,
  142153. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142154. &_resbook_44s_3,&_resbook_44s_3},
  142155. {2,0, &_residue_44_mid,
  142156. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142157. &_resbook_44s_3,&_resbook_44s_3}
  142158. };
  142159. static vorbis_residue_template _res_44s_4[]={
  142160. {2,0, &_residue_44_mid,
  142161. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142162. &_resbook_44s_4,&_resbook_44s_4},
  142163. {2,0, &_residue_44_mid,
  142164. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142165. &_resbook_44s_4,&_resbook_44s_4}
  142166. };
  142167. static vorbis_residue_template _res_44s_5[]={
  142168. {2,0, &_residue_44_mid,
  142169. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142170. &_resbook_44s_5,&_resbook_44s_5},
  142171. {2,0, &_residue_44_mid,
  142172. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142173. &_resbook_44s_5,&_resbook_44s_5}
  142174. };
  142175. static vorbis_residue_template _res_44s_6[]={
  142176. {2,0, &_residue_44_high,
  142177. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142178. &_resbook_44s_6,&_resbook_44s_6},
  142179. {2,0, &_residue_44_high,
  142180. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142181. &_resbook_44s_6,&_resbook_44s_6}
  142182. };
  142183. static vorbis_residue_template _res_44s_7[]={
  142184. {2,0, &_residue_44_high,
  142185. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142186. &_resbook_44s_7,&_resbook_44s_7},
  142187. {2,0, &_residue_44_high,
  142188. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142189. &_resbook_44s_7,&_resbook_44s_7}
  142190. };
  142191. static vorbis_residue_template _res_44s_8[]={
  142192. {2,0, &_residue_44_high,
  142193. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142194. &_resbook_44s_8,&_resbook_44s_8},
  142195. {2,0, &_residue_44_high,
  142196. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142197. &_resbook_44s_8,&_resbook_44s_8}
  142198. };
  142199. static vorbis_residue_template _res_44s_9[]={
  142200. {2,0, &_residue_44_high,
  142201. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142202. &_resbook_44s_9,&_resbook_44s_9},
  142203. {2,0, &_residue_44_high,
  142204. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142205. &_resbook_44s_9,&_resbook_44s_9}
  142206. };
  142207. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142208. { _map_nominal, _res_44s_n1 }, /* -1 */
  142209. { _map_nominal, _res_44s_0 }, /* 0 */
  142210. { _map_nominal, _res_44s_1 }, /* 1 */
  142211. { _map_nominal, _res_44s_2 }, /* 2 */
  142212. { _map_nominal, _res_44s_3 }, /* 3 */
  142213. { _map_nominal, _res_44s_4 }, /* 4 */
  142214. { _map_nominal, _res_44s_5 }, /* 5 */
  142215. { _map_nominal, _res_44s_6 }, /* 6 */
  142216. { _map_nominal, _res_44s_7 }, /* 7 */
  142217. { _map_nominal, _res_44s_8 }, /* 8 */
  142218. { _map_nominal, _res_44s_9 }, /* 9 */
  142219. };
  142220. /*** End of inlined file: residue_44.h ***/
  142221. /*** Start of inlined file: psych_44.h ***/
  142222. /* preecho trigger settings *****************************************/
  142223. static vorbis_info_psy_global _psy_global_44[5]={
  142224. {8, /* lines per eighth octave */
  142225. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142226. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142227. -6.f,
  142228. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142229. },
  142230. {8, /* lines per eighth octave */
  142231. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142232. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142233. -6.f,
  142234. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142235. },
  142236. {8, /* lines per eighth octave */
  142237. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142238. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142239. -6.f,
  142240. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142241. },
  142242. {8, /* lines per eighth octave */
  142243. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142244. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142245. -6.f,
  142246. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142247. },
  142248. {8, /* lines per eighth octave */
  142249. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142250. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142251. -6.f,
  142252. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142253. },
  142254. };
  142255. /* noise compander lookups * low, mid, high quality ****************/
  142256. static compandblock _psy_compand_44[6]={
  142257. /* sub-mode Z short */
  142258. {{
  142259. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142260. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142261. 16,17,18,19,20,21,22, 23, /* 23dB */
  142262. 24,25,26,27,28,29,30, 31, /* 31dB */
  142263. 32,33,34,35,36,37,38, 39, /* 39dB */
  142264. }},
  142265. /* mode_Z nominal short */
  142266. {{
  142267. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142268. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142269. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142270. 15,16,17,17,17,18,18, 19, /* 31dB */
  142271. 19,19,20,21,22,23,24, 25, /* 39dB */
  142272. }},
  142273. /* mode A short */
  142274. {{
  142275. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142276. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142277. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142278. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142279. 11,12,13,14,15,16,17, 18, /* 39dB */
  142280. }},
  142281. /* sub-mode Z long */
  142282. {{
  142283. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142284. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142285. 16,17,18,19,20,21,22, 23, /* 23dB */
  142286. 24,25,26,27,28,29,30, 31, /* 31dB */
  142287. 32,33,34,35,36,37,38, 39, /* 39dB */
  142288. }},
  142289. /* mode_Z nominal long */
  142290. {{
  142291. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142292. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142293. 13,14,14,14,15,15,15, 15, /* 23dB */
  142294. 16,16,17,17,17,18,18, 19, /* 31dB */
  142295. 19,19,20,21,22,23,24, 25, /* 39dB */
  142296. }},
  142297. /* mode A long */
  142298. {{
  142299. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142300. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142301. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142302. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142303. 11,12,13,14,15,16,17, 18, /* 39dB */
  142304. }}
  142305. };
  142306. /* tonal masking curve level adjustments *************************/
  142307. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142308. /* 63 125 250 500 1 2 4 8 16 */
  142309. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142310. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142311. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142312. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142313. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142314. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142315. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142316. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142317. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142318. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142319. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142320. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142321. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142322. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142323. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142324. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142325. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142326. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142327. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142328. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142329. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142330. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142331. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142332. };
  142333. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142334. /* 63 125 250 500 1 2 4 8 16 */
  142335. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142336. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142337. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142338. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142339. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142340. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142341. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142342. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142343. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142344. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142345. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142346. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142347. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142348. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142349. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142350. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142351. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142352. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142353. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142354. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142355. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142356. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142357. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142358. };
  142359. /* noise bias (transition block) */
  142360. static noise3 _psy_noisebias_trans[12]={
  142361. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142362. /* -1 */
  142363. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142364. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142365. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142366. /* 0
  142367. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142368. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142369. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142370. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142371. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142372. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142373. /* 1
  142374. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142375. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142376. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142377. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142378. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142379. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142380. /* 2
  142381. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142382. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142383. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142384. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142385. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142386. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142387. /* 3
  142388. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142389. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142390. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142391. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142392. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142393. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142394. /* 4
  142395. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142396. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142397. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142398. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142399. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142400. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142401. /* 5
  142402. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142403. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142404. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142405. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142406. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142407. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142408. /* 6
  142409. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142410. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142411. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142412. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142413. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142414. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142415. /* 7
  142416. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142417. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142418. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142419. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142420. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142421. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142422. /* 8
  142423. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142424. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142425. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142426. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142427. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142428. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142429. /* 9
  142430. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142431. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142432. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142433. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142434. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142435. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142436. /* 10 */
  142437. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142438. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142439. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142440. };
  142441. /* noise bias (long block) */
  142442. static noise3 _psy_noisebias_long[12]={
  142443. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142444. /* -1 */
  142445. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142446. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142447. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142448. /* 0 */
  142449. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142450. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142451. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142452. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142453. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142454. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142455. /* 1 */
  142456. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142457. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142458. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142459. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142460. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142461. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142462. /* 2 */
  142463. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142464. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142465. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142466. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142467. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142468. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142469. /* 3 */
  142470. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142471. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142472. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142473. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142474. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142475. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142476. /* 4 */
  142477. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142478. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142479. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142480. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142481. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142482. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142483. /* 5 */
  142484. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142485. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142486. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142487. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142488. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142489. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142490. /* 6 */
  142491. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142492. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142493. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142494. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142495. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142496. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142497. /* 7 */
  142498. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142499. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142500. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142501. /* 8 */
  142502. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142503. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142504. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142505. /* 9 */
  142506. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142507. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142508. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142509. /* 10 */
  142510. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142511. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142512. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142513. };
  142514. /* noise bias (impulse block) */
  142515. static noise3 _psy_noisebias_impulse[12]={
  142516. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142517. /* -1 */
  142518. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142519. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142520. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142521. /* 0 */
  142522. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142523. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142524. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142525. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142526. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142527. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142528. /* 1 */
  142529. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142530. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142531. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142532. /* 2 */
  142533. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142534. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142535. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142536. /* 3 */
  142537. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142538. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142539. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142540. /* 4 */
  142541. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142542. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142543. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142544. /* 5 */
  142545. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142546. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142547. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142548. /* 6
  142549. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142550. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142551. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142552. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142553. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142554. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142555. /* 7 */
  142556. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142557. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142558. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142559. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142560. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142561. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142562. /* 8 */
  142563. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142564. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142565. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142566. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142567. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142568. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142569. /* 9 */
  142570. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142571. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142572. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142573. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142574. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142575. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142576. /* 10 */
  142577. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142578. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142579. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142580. };
  142581. /* noise bias (padding block) */
  142582. static noise3 _psy_noisebias_padding[12]={
  142583. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142584. /* -1 */
  142585. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142586. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142587. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142588. /* 0 */
  142589. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142590. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142591. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142592. /* 1 */
  142593. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142594. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142595. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142596. /* 2 */
  142597. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142598. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142599. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142600. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142601. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142602. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142603. /* 3 */
  142604. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142605. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142606. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142607. /* 4 */
  142608. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142609. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142610. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142611. /* 5 */
  142612. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142613. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142614. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142615. /* 6 */
  142616. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142617. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142618. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142619. /* 7 */
  142620. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142621. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142622. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142623. /* 8 */
  142624. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142625. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142626. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142627. /* 9 */
  142628. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142629. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142630. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142631. /* 10 */
  142632. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142633. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142634. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142635. };
  142636. static noiseguard _psy_noiseguards_44[4]={
  142637. {3,3,15},
  142638. {3,3,15},
  142639. {10,10,100},
  142640. {10,10,100},
  142641. };
  142642. static int _psy_tone_suppress[12]={
  142643. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142644. };
  142645. static int _psy_tone_0dB[12]={
  142646. 90,90,95,95,95,95,105,105,105,105,105,105,
  142647. };
  142648. static int _psy_noise_suppress[12]={
  142649. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142650. };
  142651. static vorbis_info_psy _psy_info_template={
  142652. /* blockflag */
  142653. -1,
  142654. /* ath_adjatt, ath_maxatt */
  142655. -140.,-140.,
  142656. /* tonemask att boost/decay,suppr,curves */
  142657. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142658. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142659. 1, -0.f, .5f, .5f, 0,0,0,
  142660. /* noiseoffset*3, noisecompand, max_curve_dB */
  142661. {{-1},{-1},{-1}},{-1},105.f,
  142662. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142663. 0,0,-1,-1,0.,
  142664. };
  142665. /* ath ****************/
  142666. static int _psy_ath_floater[12]={
  142667. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142668. };
  142669. static int _psy_ath_abs[12]={
  142670. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142671. };
  142672. /* stereo setup. These don't map directly to quality level, there's
  142673. an additional indirection as several of the below may be used in a
  142674. single bitmanaged stream
  142675. ****************/
  142676. /* various stereo possibilities */
  142677. /* stereo mode by base quality level */
  142678. static adj_stereo _psy_stereo_modes_44[12]={
  142679. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142680. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142681. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142682. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142683. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142684. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142685. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142686. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142687. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142688. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142689. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142690. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142691. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142692. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142693. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142694. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142695. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142696. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142697. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142698. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142699. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142700. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142701. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142702. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142703. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142704. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142705. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142706. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142707. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142708. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142709. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142710. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142711. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142712. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142713. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142714. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142715. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142716. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142717. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142718. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142719. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142720. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142721. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142722. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142723. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142724. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142725. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142726. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142727. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142728. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142729. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142730. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142731. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142732. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142733. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142734. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142735. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142736. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142737. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142738. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142739. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142740. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142741. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142742. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142743. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142744. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142745. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142746. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142747. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142748. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142749. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142750. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142751. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142752. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142753. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142754. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142755. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142756. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142757. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142758. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142759. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142760. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142761. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142762. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142763. };
  142764. /* tone master attenuation by base quality mode and bitrate tweak */
  142765. static att3 _psy_tone_masteratt_44[12]={
  142766. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142767. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142768. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142769. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142770. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142771. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142772. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142773. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142774. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142775. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142776. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142777. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142778. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142779. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142780. };
  142781. /* lowpass by mode **************/
  142782. static double _psy_lowpass_44[12]={
  142783. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142784. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142785. };
  142786. /* noise normalization **********/
  142787. static int _noise_start_short_44[11]={
  142788. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142789. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142790. };
  142791. static int _noise_start_long_44[11]={
  142792. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142793. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142794. };
  142795. static int _noise_part_short_44[11]={
  142796. 8,8,8,8,8,8,8,8,8,8,8
  142797. };
  142798. static int _noise_part_long_44[11]={
  142799. 32,32,32,32,32,32,32,32,32,32,32
  142800. };
  142801. static double _noise_thresh_44[11]={
  142802. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142803. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142804. };
  142805. static double _noise_thresh_5only[2]={
  142806. .5,.5,
  142807. };
  142808. /*** End of inlined file: psych_44.h ***/
  142809. static double rate_mapping_44_stereo[12]={
  142810. 22500.,32000.,40000.,48000.,56000.,64000.,
  142811. 80000.,96000.,112000.,128000.,160000.,250001.
  142812. };
  142813. static double quality_mapping_44[12]={
  142814. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142815. };
  142816. static int blocksize_short_44[11]={
  142817. 512,256,256,256,256,256,256,256,256,256,256
  142818. };
  142819. static int blocksize_long_44[11]={
  142820. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142821. };
  142822. static double _psy_compand_short_mapping[12]={
  142823. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142824. };
  142825. static double _psy_compand_long_mapping[12]={
  142826. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142827. };
  142828. static double _global_mapping_44[12]={
  142829. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142830. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142831. };
  142832. static int _floor_short_mapping_44[11]={
  142833. 1,0,0,2,2,4,5,5,5,5,5
  142834. };
  142835. static int _floor_long_mapping_44[11]={
  142836. 8,7,7,7,7,7,7,7,7,7,7
  142837. };
  142838. ve_setup_data_template ve_setup_44_stereo={
  142839. 11,
  142840. rate_mapping_44_stereo,
  142841. quality_mapping_44,
  142842. 2,
  142843. 40000,
  142844. 50000,
  142845. blocksize_short_44,
  142846. blocksize_long_44,
  142847. _psy_tone_masteratt_44,
  142848. _psy_tone_0dB,
  142849. _psy_tone_suppress,
  142850. _vp_tonemask_adj_otherblock,
  142851. _vp_tonemask_adj_longblock,
  142852. _vp_tonemask_adj_otherblock,
  142853. _psy_noiseguards_44,
  142854. _psy_noisebias_impulse,
  142855. _psy_noisebias_padding,
  142856. _psy_noisebias_trans,
  142857. _psy_noisebias_long,
  142858. _psy_noise_suppress,
  142859. _psy_compand_44,
  142860. _psy_compand_short_mapping,
  142861. _psy_compand_long_mapping,
  142862. {_noise_start_short_44,_noise_start_long_44},
  142863. {_noise_part_short_44,_noise_part_long_44},
  142864. _noise_thresh_44,
  142865. _psy_ath_floater,
  142866. _psy_ath_abs,
  142867. _psy_lowpass_44,
  142868. _psy_global_44,
  142869. _global_mapping_44,
  142870. _psy_stereo_modes_44,
  142871. _floor_books,
  142872. _floor,
  142873. _floor_short_mapping_44,
  142874. _floor_long_mapping_44,
  142875. _mapres_template_44_stereo
  142876. };
  142877. /*** End of inlined file: setup_44.h ***/
  142878. /*** Start of inlined file: setup_44u.h ***/
  142879. /*** Start of inlined file: residue_44u.h ***/
  142880. /*** Start of inlined file: res_books_uncoupled.h ***/
  142881. static long _vq_quantlist__16u0__p1_0[] = {
  142882. 1,
  142883. 0,
  142884. 2,
  142885. };
  142886. static long _vq_lengthlist__16u0__p1_0[] = {
  142887. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142888. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142889. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142890. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142891. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142892. 12,
  142893. };
  142894. static float _vq_quantthresh__16u0__p1_0[] = {
  142895. -0.5, 0.5,
  142896. };
  142897. static long _vq_quantmap__16u0__p1_0[] = {
  142898. 1, 0, 2,
  142899. };
  142900. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142901. _vq_quantthresh__16u0__p1_0,
  142902. _vq_quantmap__16u0__p1_0,
  142903. 3,
  142904. 3
  142905. };
  142906. static static_codebook _16u0__p1_0 = {
  142907. 4, 81,
  142908. _vq_lengthlist__16u0__p1_0,
  142909. 1, -535822336, 1611661312, 2, 0,
  142910. _vq_quantlist__16u0__p1_0,
  142911. NULL,
  142912. &_vq_auxt__16u0__p1_0,
  142913. NULL,
  142914. 0
  142915. };
  142916. static long _vq_quantlist__16u0__p2_0[] = {
  142917. 1,
  142918. 0,
  142919. 2,
  142920. };
  142921. static long _vq_lengthlist__16u0__p2_0[] = {
  142922. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142923. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142924. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142925. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142926. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142927. 8,
  142928. };
  142929. static float _vq_quantthresh__16u0__p2_0[] = {
  142930. -0.5, 0.5,
  142931. };
  142932. static long _vq_quantmap__16u0__p2_0[] = {
  142933. 1, 0, 2,
  142934. };
  142935. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142936. _vq_quantthresh__16u0__p2_0,
  142937. _vq_quantmap__16u0__p2_0,
  142938. 3,
  142939. 3
  142940. };
  142941. static static_codebook _16u0__p2_0 = {
  142942. 4, 81,
  142943. _vq_lengthlist__16u0__p2_0,
  142944. 1, -535822336, 1611661312, 2, 0,
  142945. _vq_quantlist__16u0__p2_0,
  142946. NULL,
  142947. &_vq_auxt__16u0__p2_0,
  142948. NULL,
  142949. 0
  142950. };
  142951. static long _vq_quantlist__16u0__p3_0[] = {
  142952. 2,
  142953. 1,
  142954. 3,
  142955. 0,
  142956. 4,
  142957. };
  142958. static long _vq_lengthlist__16u0__p3_0[] = {
  142959. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142960. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142961. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142962. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142963. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142964. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142965. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142966. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142967. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142968. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142969. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142970. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142971. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142972. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142973. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142974. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142975. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142976. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142977. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142978. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142979. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142980. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142981. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142982. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142983. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142984. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142985. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142986. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142987. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142988. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142989. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142990. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142991. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142992. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142993. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142994. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142995. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142996. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142997. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142998. 18,
  142999. };
  143000. static float _vq_quantthresh__16u0__p3_0[] = {
  143001. -1.5, -0.5, 0.5, 1.5,
  143002. };
  143003. static long _vq_quantmap__16u0__p3_0[] = {
  143004. 3, 1, 0, 2, 4,
  143005. };
  143006. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143007. _vq_quantthresh__16u0__p3_0,
  143008. _vq_quantmap__16u0__p3_0,
  143009. 5,
  143010. 5
  143011. };
  143012. static static_codebook _16u0__p3_0 = {
  143013. 4, 625,
  143014. _vq_lengthlist__16u0__p3_0,
  143015. 1, -533725184, 1611661312, 3, 0,
  143016. _vq_quantlist__16u0__p3_0,
  143017. NULL,
  143018. &_vq_auxt__16u0__p3_0,
  143019. NULL,
  143020. 0
  143021. };
  143022. static long _vq_quantlist__16u0__p4_0[] = {
  143023. 2,
  143024. 1,
  143025. 3,
  143026. 0,
  143027. 4,
  143028. };
  143029. static long _vq_lengthlist__16u0__p4_0[] = {
  143030. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143031. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143032. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143033. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143034. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143035. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143036. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143037. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143038. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143039. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143040. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143041. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143042. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143043. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143044. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143045. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143046. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143047. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143048. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143049. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143050. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143051. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143052. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143053. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143054. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143055. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143056. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143057. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143058. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143059. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143060. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143061. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143062. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143063. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143064. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143065. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143066. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143067. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143068. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143069. 11,
  143070. };
  143071. static float _vq_quantthresh__16u0__p4_0[] = {
  143072. -1.5, -0.5, 0.5, 1.5,
  143073. };
  143074. static long _vq_quantmap__16u0__p4_0[] = {
  143075. 3, 1, 0, 2, 4,
  143076. };
  143077. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143078. _vq_quantthresh__16u0__p4_0,
  143079. _vq_quantmap__16u0__p4_0,
  143080. 5,
  143081. 5
  143082. };
  143083. static static_codebook _16u0__p4_0 = {
  143084. 4, 625,
  143085. _vq_lengthlist__16u0__p4_0,
  143086. 1, -533725184, 1611661312, 3, 0,
  143087. _vq_quantlist__16u0__p4_0,
  143088. NULL,
  143089. &_vq_auxt__16u0__p4_0,
  143090. NULL,
  143091. 0
  143092. };
  143093. static long _vq_quantlist__16u0__p5_0[] = {
  143094. 4,
  143095. 3,
  143096. 5,
  143097. 2,
  143098. 6,
  143099. 1,
  143100. 7,
  143101. 0,
  143102. 8,
  143103. };
  143104. static long _vq_lengthlist__16u0__p5_0[] = {
  143105. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143106. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143107. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143108. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143109. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143110. 12,
  143111. };
  143112. static float _vq_quantthresh__16u0__p5_0[] = {
  143113. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143114. };
  143115. static long _vq_quantmap__16u0__p5_0[] = {
  143116. 7, 5, 3, 1, 0, 2, 4, 6,
  143117. 8,
  143118. };
  143119. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143120. _vq_quantthresh__16u0__p5_0,
  143121. _vq_quantmap__16u0__p5_0,
  143122. 9,
  143123. 9
  143124. };
  143125. static static_codebook _16u0__p5_0 = {
  143126. 2, 81,
  143127. _vq_lengthlist__16u0__p5_0,
  143128. 1, -531628032, 1611661312, 4, 0,
  143129. _vq_quantlist__16u0__p5_0,
  143130. NULL,
  143131. &_vq_auxt__16u0__p5_0,
  143132. NULL,
  143133. 0
  143134. };
  143135. static long _vq_quantlist__16u0__p6_0[] = {
  143136. 6,
  143137. 5,
  143138. 7,
  143139. 4,
  143140. 8,
  143141. 3,
  143142. 9,
  143143. 2,
  143144. 10,
  143145. 1,
  143146. 11,
  143147. 0,
  143148. 12,
  143149. };
  143150. static long _vq_lengthlist__16u0__p6_0[] = {
  143151. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143152. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143153. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143154. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143155. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143156. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143157. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143158. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143159. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143160. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143161. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143162. };
  143163. static float _vq_quantthresh__16u0__p6_0[] = {
  143164. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143165. 12.5, 17.5, 22.5, 27.5,
  143166. };
  143167. static long _vq_quantmap__16u0__p6_0[] = {
  143168. 11, 9, 7, 5, 3, 1, 0, 2,
  143169. 4, 6, 8, 10, 12,
  143170. };
  143171. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143172. _vq_quantthresh__16u0__p6_0,
  143173. _vq_quantmap__16u0__p6_0,
  143174. 13,
  143175. 13
  143176. };
  143177. static static_codebook _16u0__p6_0 = {
  143178. 2, 169,
  143179. _vq_lengthlist__16u0__p6_0,
  143180. 1, -526516224, 1616117760, 4, 0,
  143181. _vq_quantlist__16u0__p6_0,
  143182. NULL,
  143183. &_vq_auxt__16u0__p6_0,
  143184. NULL,
  143185. 0
  143186. };
  143187. static long _vq_quantlist__16u0__p6_1[] = {
  143188. 2,
  143189. 1,
  143190. 3,
  143191. 0,
  143192. 4,
  143193. };
  143194. static long _vq_lengthlist__16u0__p6_1[] = {
  143195. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143196. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143197. };
  143198. static float _vq_quantthresh__16u0__p6_1[] = {
  143199. -1.5, -0.5, 0.5, 1.5,
  143200. };
  143201. static long _vq_quantmap__16u0__p6_1[] = {
  143202. 3, 1, 0, 2, 4,
  143203. };
  143204. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143205. _vq_quantthresh__16u0__p6_1,
  143206. _vq_quantmap__16u0__p6_1,
  143207. 5,
  143208. 5
  143209. };
  143210. static static_codebook _16u0__p6_1 = {
  143211. 2, 25,
  143212. _vq_lengthlist__16u0__p6_1,
  143213. 1, -533725184, 1611661312, 3, 0,
  143214. _vq_quantlist__16u0__p6_1,
  143215. NULL,
  143216. &_vq_auxt__16u0__p6_1,
  143217. NULL,
  143218. 0
  143219. };
  143220. static long _vq_quantlist__16u0__p7_0[] = {
  143221. 1,
  143222. 0,
  143223. 2,
  143224. };
  143225. static long _vq_lengthlist__16u0__p7_0[] = {
  143226. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143227. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143228. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143229. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143230. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143231. 7,
  143232. };
  143233. static float _vq_quantthresh__16u0__p7_0[] = {
  143234. -157.5, 157.5,
  143235. };
  143236. static long _vq_quantmap__16u0__p7_0[] = {
  143237. 1, 0, 2,
  143238. };
  143239. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143240. _vq_quantthresh__16u0__p7_0,
  143241. _vq_quantmap__16u0__p7_0,
  143242. 3,
  143243. 3
  143244. };
  143245. static static_codebook _16u0__p7_0 = {
  143246. 4, 81,
  143247. _vq_lengthlist__16u0__p7_0,
  143248. 1, -518803456, 1628680192, 2, 0,
  143249. _vq_quantlist__16u0__p7_0,
  143250. NULL,
  143251. &_vq_auxt__16u0__p7_0,
  143252. NULL,
  143253. 0
  143254. };
  143255. static long _vq_quantlist__16u0__p7_1[] = {
  143256. 7,
  143257. 6,
  143258. 8,
  143259. 5,
  143260. 9,
  143261. 4,
  143262. 10,
  143263. 3,
  143264. 11,
  143265. 2,
  143266. 12,
  143267. 1,
  143268. 13,
  143269. 0,
  143270. 14,
  143271. };
  143272. static long _vq_lengthlist__16u0__p7_1[] = {
  143273. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143274. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143275. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143276. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143277. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143278. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143281. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143283. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143286. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143287. 10,
  143288. };
  143289. static float _vq_quantthresh__16u0__p7_1[] = {
  143290. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143291. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143292. };
  143293. static long _vq_quantmap__16u0__p7_1[] = {
  143294. 13, 11, 9, 7, 5, 3, 1, 0,
  143295. 2, 4, 6, 8, 10, 12, 14,
  143296. };
  143297. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143298. _vq_quantthresh__16u0__p7_1,
  143299. _vq_quantmap__16u0__p7_1,
  143300. 15,
  143301. 15
  143302. };
  143303. static static_codebook _16u0__p7_1 = {
  143304. 2, 225,
  143305. _vq_lengthlist__16u0__p7_1,
  143306. 1, -520986624, 1620377600, 4, 0,
  143307. _vq_quantlist__16u0__p7_1,
  143308. NULL,
  143309. &_vq_auxt__16u0__p7_1,
  143310. NULL,
  143311. 0
  143312. };
  143313. static long _vq_quantlist__16u0__p7_2[] = {
  143314. 10,
  143315. 9,
  143316. 11,
  143317. 8,
  143318. 12,
  143319. 7,
  143320. 13,
  143321. 6,
  143322. 14,
  143323. 5,
  143324. 15,
  143325. 4,
  143326. 16,
  143327. 3,
  143328. 17,
  143329. 2,
  143330. 18,
  143331. 1,
  143332. 19,
  143333. 0,
  143334. 20,
  143335. };
  143336. static long _vq_lengthlist__16u0__p7_2[] = {
  143337. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143338. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143339. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143340. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143341. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143342. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143343. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143344. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143345. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143346. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143347. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143348. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143349. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143350. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143351. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143352. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143353. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143354. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143355. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143356. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143357. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143358. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143359. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143360. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143361. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143362. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143363. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143364. 10,10,12,11,10,11,11,11,10,
  143365. };
  143366. static float _vq_quantthresh__16u0__p7_2[] = {
  143367. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143368. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143369. 6.5, 7.5, 8.5, 9.5,
  143370. };
  143371. static long _vq_quantmap__16u0__p7_2[] = {
  143372. 19, 17, 15, 13, 11, 9, 7, 5,
  143373. 3, 1, 0, 2, 4, 6, 8, 10,
  143374. 12, 14, 16, 18, 20,
  143375. };
  143376. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143377. _vq_quantthresh__16u0__p7_2,
  143378. _vq_quantmap__16u0__p7_2,
  143379. 21,
  143380. 21
  143381. };
  143382. static static_codebook _16u0__p7_2 = {
  143383. 2, 441,
  143384. _vq_lengthlist__16u0__p7_2,
  143385. 1, -529268736, 1611661312, 5, 0,
  143386. _vq_quantlist__16u0__p7_2,
  143387. NULL,
  143388. &_vq_auxt__16u0__p7_2,
  143389. NULL,
  143390. 0
  143391. };
  143392. static long _huff_lengthlist__16u0__single[] = {
  143393. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143394. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143395. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143396. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143397. };
  143398. static static_codebook _huff_book__16u0__single = {
  143399. 2, 64,
  143400. _huff_lengthlist__16u0__single,
  143401. 0, 0, 0, 0, 0,
  143402. NULL,
  143403. NULL,
  143404. NULL,
  143405. NULL,
  143406. 0
  143407. };
  143408. static long _huff_lengthlist__16u1__long[] = {
  143409. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143410. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143411. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143412. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143413. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143414. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143415. 16,13,16,18,
  143416. };
  143417. static static_codebook _huff_book__16u1__long = {
  143418. 2, 100,
  143419. _huff_lengthlist__16u1__long,
  143420. 0, 0, 0, 0, 0,
  143421. NULL,
  143422. NULL,
  143423. NULL,
  143424. NULL,
  143425. 0
  143426. };
  143427. static long _vq_quantlist__16u1__p1_0[] = {
  143428. 1,
  143429. 0,
  143430. 2,
  143431. };
  143432. static long _vq_lengthlist__16u1__p1_0[] = {
  143433. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143434. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143435. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143436. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143437. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143438. 11,
  143439. };
  143440. static float _vq_quantthresh__16u1__p1_0[] = {
  143441. -0.5, 0.5,
  143442. };
  143443. static long _vq_quantmap__16u1__p1_0[] = {
  143444. 1, 0, 2,
  143445. };
  143446. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143447. _vq_quantthresh__16u1__p1_0,
  143448. _vq_quantmap__16u1__p1_0,
  143449. 3,
  143450. 3
  143451. };
  143452. static static_codebook _16u1__p1_0 = {
  143453. 4, 81,
  143454. _vq_lengthlist__16u1__p1_0,
  143455. 1, -535822336, 1611661312, 2, 0,
  143456. _vq_quantlist__16u1__p1_0,
  143457. NULL,
  143458. &_vq_auxt__16u1__p1_0,
  143459. NULL,
  143460. 0
  143461. };
  143462. static long _vq_quantlist__16u1__p2_0[] = {
  143463. 1,
  143464. 0,
  143465. 2,
  143466. };
  143467. static long _vq_lengthlist__16u1__p2_0[] = {
  143468. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143469. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143470. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143471. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143472. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143473. 8,
  143474. };
  143475. static float _vq_quantthresh__16u1__p2_0[] = {
  143476. -0.5, 0.5,
  143477. };
  143478. static long _vq_quantmap__16u1__p2_0[] = {
  143479. 1, 0, 2,
  143480. };
  143481. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143482. _vq_quantthresh__16u1__p2_0,
  143483. _vq_quantmap__16u1__p2_0,
  143484. 3,
  143485. 3
  143486. };
  143487. static static_codebook _16u1__p2_0 = {
  143488. 4, 81,
  143489. _vq_lengthlist__16u1__p2_0,
  143490. 1, -535822336, 1611661312, 2, 0,
  143491. _vq_quantlist__16u1__p2_0,
  143492. NULL,
  143493. &_vq_auxt__16u1__p2_0,
  143494. NULL,
  143495. 0
  143496. };
  143497. static long _vq_quantlist__16u1__p3_0[] = {
  143498. 2,
  143499. 1,
  143500. 3,
  143501. 0,
  143502. 4,
  143503. };
  143504. static long _vq_lengthlist__16u1__p3_0[] = {
  143505. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143506. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143507. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143508. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143509. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143510. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143511. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143512. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143513. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143514. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143515. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143516. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143517. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143518. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143519. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143520. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143521. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143522. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143523. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143524. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143525. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143526. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143527. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143528. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143529. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143530. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143531. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143532. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143533. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143534. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143535. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143536. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143537. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143538. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143539. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143540. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143541. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143542. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143543. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143544. 16,
  143545. };
  143546. static float _vq_quantthresh__16u1__p3_0[] = {
  143547. -1.5, -0.5, 0.5, 1.5,
  143548. };
  143549. static long _vq_quantmap__16u1__p3_0[] = {
  143550. 3, 1, 0, 2, 4,
  143551. };
  143552. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143553. _vq_quantthresh__16u1__p3_0,
  143554. _vq_quantmap__16u1__p3_0,
  143555. 5,
  143556. 5
  143557. };
  143558. static static_codebook _16u1__p3_0 = {
  143559. 4, 625,
  143560. _vq_lengthlist__16u1__p3_0,
  143561. 1, -533725184, 1611661312, 3, 0,
  143562. _vq_quantlist__16u1__p3_0,
  143563. NULL,
  143564. &_vq_auxt__16u1__p3_0,
  143565. NULL,
  143566. 0
  143567. };
  143568. static long _vq_quantlist__16u1__p4_0[] = {
  143569. 2,
  143570. 1,
  143571. 3,
  143572. 0,
  143573. 4,
  143574. };
  143575. static long _vq_lengthlist__16u1__p4_0[] = {
  143576. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143577. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143578. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143579. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143580. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143581. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143582. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143583. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143584. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143585. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143586. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143587. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143588. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143589. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143590. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143591. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143592. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143593. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143594. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143595. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143596. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143597. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143598. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143599. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143600. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143601. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143602. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143603. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143604. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143605. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143606. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143607. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143608. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143609. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143610. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143611. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143612. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143613. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143614. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143615. 11,
  143616. };
  143617. static float _vq_quantthresh__16u1__p4_0[] = {
  143618. -1.5, -0.5, 0.5, 1.5,
  143619. };
  143620. static long _vq_quantmap__16u1__p4_0[] = {
  143621. 3, 1, 0, 2, 4,
  143622. };
  143623. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143624. _vq_quantthresh__16u1__p4_0,
  143625. _vq_quantmap__16u1__p4_0,
  143626. 5,
  143627. 5
  143628. };
  143629. static static_codebook _16u1__p4_0 = {
  143630. 4, 625,
  143631. _vq_lengthlist__16u1__p4_0,
  143632. 1, -533725184, 1611661312, 3, 0,
  143633. _vq_quantlist__16u1__p4_0,
  143634. NULL,
  143635. &_vq_auxt__16u1__p4_0,
  143636. NULL,
  143637. 0
  143638. };
  143639. static long _vq_quantlist__16u1__p5_0[] = {
  143640. 4,
  143641. 3,
  143642. 5,
  143643. 2,
  143644. 6,
  143645. 1,
  143646. 7,
  143647. 0,
  143648. 8,
  143649. };
  143650. static long _vq_lengthlist__16u1__p5_0[] = {
  143651. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143652. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143653. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143654. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143655. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143656. 13,
  143657. };
  143658. static float _vq_quantthresh__16u1__p5_0[] = {
  143659. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143660. };
  143661. static long _vq_quantmap__16u1__p5_0[] = {
  143662. 7, 5, 3, 1, 0, 2, 4, 6,
  143663. 8,
  143664. };
  143665. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143666. _vq_quantthresh__16u1__p5_0,
  143667. _vq_quantmap__16u1__p5_0,
  143668. 9,
  143669. 9
  143670. };
  143671. static static_codebook _16u1__p5_0 = {
  143672. 2, 81,
  143673. _vq_lengthlist__16u1__p5_0,
  143674. 1, -531628032, 1611661312, 4, 0,
  143675. _vq_quantlist__16u1__p5_0,
  143676. NULL,
  143677. &_vq_auxt__16u1__p5_0,
  143678. NULL,
  143679. 0
  143680. };
  143681. static long _vq_quantlist__16u1__p6_0[] = {
  143682. 4,
  143683. 3,
  143684. 5,
  143685. 2,
  143686. 6,
  143687. 1,
  143688. 7,
  143689. 0,
  143690. 8,
  143691. };
  143692. static long _vq_lengthlist__16u1__p6_0[] = {
  143693. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143694. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143695. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143696. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143697. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143698. 11,
  143699. };
  143700. static float _vq_quantthresh__16u1__p6_0[] = {
  143701. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143702. };
  143703. static long _vq_quantmap__16u1__p6_0[] = {
  143704. 7, 5, 3, 1, 0, 2, 4, 6,
  143705. 8,
  143706. };
  143707. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143708. _vq_quantthresh__16u1__p6_0,
  143709. _vq_quantmap__16u1__p6_0,
  143710. 9,
  143711. 9
  143712. };
  143713. static static_codebook _16u1__p6_0 = {
  143714. 2, 81,
  143715. _vq_lengthlist__16u1__p6_0,
  143716. 1, -531628032, 1611661312, 4, 0,
  143717. _vq_quantlist__16u1__p6_0,
  143718. NULL,
  143719. &_vq_auxt__16u1__p6_0,
  143720. NULL,
  143721. 0
  143722. };
  143723. static long _vq_quantlist__16u1__p7_0[] = {
  143724. 1,
  143725. 0,
  143726. 2,
  143727. };
  143728. static long _vq_lengthlist__16u1__p7_0[] = {
  143729. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143730. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143731. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143732. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143733. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143734. 13,
  143735. };
  143736. static float _vq_quantthresh__16u1__p7_0[] = {
  143737. -5.5, 5.5,
  143738. };
  143739. static long _vq_quantmap__16u1__p7_0[] = {
  143740. 1, 0, 2,
  143741. };
  143742. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143743. _vq_quantthresh__16u1__p7_0,
  143744. _vq_quantmap__16u1__p7_0,
  143745. 3,
  143746. 3
  143747. };
  143748. static static_codebook _16u1__p7_0 = {
  143749. 4, 81,
  143750. _vq_lengthlist__16u1__p7_0,
  143751. 1, -529137664, 1618345984, 2, 0,
  143752. _vq_quantlist__16u1__p7_0,
  143753. NULL,
  143754. &_vq_auxt__16u1__p7_0,
  143755. NULL,
  143756. 0
  143757. };
  143758. static long _vq_quantlist__16u1__p7_1[] = {
  143759. 5,
  143760. 4,
  143761. 6,
  143762. 3,
  143763. 7,
  143764. 2,
  143765. 8,
  143766. 1,
  143767. 9,
  143768. 0,
  143769. 10,
  143770. };
  143771. static long _vq_lengthlist__16u1__p7_1[] = {
  143772. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143773. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143774. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143775. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143776. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143777. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143778. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143779. 8, 9, 9,10,10,10,10,10,10,
  143780. };
  143781. static float _vq_quantthresh__16u1__p7_1[] = {
  143782. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143783. 3.5, 4.5,
  143784. };
  143785. static long _vq_quantmap__16u1__p7_1[] = {
  143786. 9, 7, 5, 3, 1, 0, 2, 4,
  143787. 6, 8, 10,
  143788. };
  143789. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143790. _vq_quantthresh__16u1__p7_1,
  143791. _vq_quantmap__16u1__p7_1,
  143792. 11,
  143793. 11
  143794. };
  143795. static static_codebook _16u1__p7_1 = {
  143796. 2, 121,
  143797. _vq_lengthlist__16u1__p7_1,
  143798. 1, -531365888, 1611661312, 4, 0,
  143799. _vq_quantlist__16u1__p7_1,
  143800. NULL,
  143801. &_vq_auxt__16u1__p7_1,
  143802. NULL,
  143803. 0
  143804. };
  143805. static long _vq_quantlist__16u1__p8_0[] = {
  143806. 5,
  143807. 4,
  143808. 6,
  143809. 3,
  143810. 7,
  143811. 2,
  143812. 8,
  143813. 1,
  143814. 9,
  143815. 0,
  143816. 10,
  143817. };
  143818. static long _vq_lengthlist__16u1__p8_0[] = {
  143819. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143820. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143821. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143822. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143823. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143824. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143825. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143826. 13,14,14,15,15,16,16,15,16,
  143827. };
  143828. static float _vq_quantthresh__16u1__p8_0[] = {
  143829. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143830. 38.5, 49.5,
  143831. };
  143832. static long _vq_quantmap__16u1__p8_0[] = {
  143833. 9, 7, 5, 3, 1, 0, 2, 4,
  143834. 6, 8, 10,
  143835. };
  143836. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143837. _vq_quantthresh__16u1__p8_0,
  143838. _vq_quantmap__16u1__p8_0,
  143839. 11,
  143840. 11
  143841. };
  143842. static static_codebook _16u1__p8_0 = {
  143843. 2, 121,
  143844. _vq_lengthlist__16u1__p8_0,
  143845. 1, -524582912, 1618345984, 4, 0,
  143846. _vq_quantlist__16u1__p8_0,
  143847. NULL,
  143848. &_vq_auxt__16u1__p8_0,
  143849. NULL,
  143850. 0
  143851. };
  143852. static long _vq_quantlist__16u1__p8_1[] = {
  143853. 5,
  143854. 4,
  143855. 6,
  143856. 3,
  143857. 7,
  143858. 2,
  143859. 8,
  143860. 1,
  143861. 9,
  143862. 0,
  143863. 10,
  143864. };
  143865. static long _vq_lengthlist__16u1__p8_1[] = {
  143866. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143867. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143868. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143869. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143870. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143871. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143872. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143873. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143874. };
  143875. static float _vq_quantthresh__16u1__p8_1[] = {
  143876. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143877. 3.5, 4.5,
  143878. };
  143879. static long _vq_quantmap__16u1__p8_1[] = {
  143880. 9, 7, 5, 3, 1, 0, 2, 4,
  143881. 6, 8, 10,
  143882. };
  143883. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143884. _vq_quantthresh__16u1__p8_1,
  143885. _vq_quantmap__16u1__p8_1,
  143886. 11,
  143887. 11
  143888. };
  143889. static static_codebook _16u1__p8_1 = {
  143890. 2, 121,
  143891. _vq_lengthlist__16u1__p8_1,
  143892. 1, -531365888, 1611661312, 4, 0,
  143893. _vq_quantlist__16u1__p8_1,
  143894. NULL,
  143895. &_vq_auxt__16u1__p8_1,
  143896. NULL,
  143897. 0
  143898. };
  143899. static long _vq_quantlist__16u1__p9_0[] = {
  143900. 7,
  143901. 6,
  143902. 8,
  143903. 5,
  143904. 9,
  143905. 4,
  143906. 10,
  143907. 3,
  143908. 11,
  143909. 2,
  143910. 12,
  143911. 1,
  143912. 13,
  143913. 0,
  143914. 14,
  143915. };
  143916. static long _vq_lengthlist__16u1__p9_0[] = {
  143917. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143918. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143919. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143920. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143921. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143922. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143923. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143924. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143925. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143926. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143927. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143928. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143929. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143930. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143931. 8,
  143932. };
  143933. static float _vq_quantthresh__16u1__p9_0[] = {
  143934. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143935. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143936. };
  143937. static long _vq_quantmap__16u1__p9_0[] = {
  143938. 13, 11, 9, 7, 5, 3, 1, 0,
  143939. 2, 4, 6, 8, 10, 12, 14,
  143940. };
  143941. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143942. _vq_quantthresh__16u1__p9_0,
  143943. _vq_quantmap__16u1__p9_0,
  143944. 15,
  143945. 15
  143946. };
  143947. static static_codebook _16u1__p9_0 = {
  143948. 2, 225,
  143949. _vq_lengthlist__16u1__p9_0,
  143950. 1, -514071552, 1627381760, 4, 0,
  143951. _vq_quantlist__16u1__p9_0,
  143952. NULL,
  143953. &_vq_auxt__16u1__p9_0,
  143954. NULL,
  143955. 0
  143956. };
  143957. static long _vq_quantlist__16u1__p9_1[] = {
  143958. 7,
  143959. 6,
  143960. 8,
  143961. 5,
  143962. 9,
  143963. 4,
  143964. 10,
  143965. 3,
  143966. 11,
  143967. 2,
  143968. 12,
  143969. 1,
  143970. 13,
  143971. 0,
  143972. 14,
  143973. };
  143974. static long _vq_lengthlist__16u1__p9_1[] = {
  143975. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143976. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143977. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143978. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143979. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143980. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143981. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143982. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143983. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143984. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143985. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143986. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143987. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143988. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143989. 9,
  143990. };
  143991. static float _vq_quantthresh__16u1__p9_1[] = {
  143992. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143993. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143994. };
  143995. static long _vq_quantmap__16u1__p9_1[] = {
  143996. 13, 11, 9, 7, 5, 3, 1, 0,
  143997. 2, 4, 6, 8, 10, 12, 14,
  143998. };
  143999. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144000. _vq_quantthresh__16u1__p9_1,
  144001. _vq_quantmap__16u1__p9_1,
  144002. 15,
  144003. 15
  144004. };
  144005. static static_codebook _16u1__p9_1 = {
  144006. 2, 225,
  144007. _vq_lengthlist__16u1__p9_1,
  144008. 1, -522338304, 1620115456, 4, 0,
  144009. _vq_quantlist__16u1__p9_1,
  144010. NULL,
  144011. &_vq_auxt__16u1__p9_1,
  144012. NULL,
  144013. 0
  144014. };
  144015. static long _vq_quantlist__16u1__p9_2[] = {
  144016. 8,
  144017. 7,
  144018. 9,
  144019. 6,
  144020. 10,
  144021. 5,
  144022. 11,
  144023. 4,
  144024. 12,
  144025. 3,
  144026. 13,
  144027. 2,
  144028. 14,
  144029. 1,
  144030. 15,
  144031. 0,
  144032. 16,
  144033. };
  144034. static long _vq_lengthlist__16u1__p9_2[] = {
  144035. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144036. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144037. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144038. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144039. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144040. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144041. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144042. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144043. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144044. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144045. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144046. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144047. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144048. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144049. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144050. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144051. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144052. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144053. 10,
  144054. };
  144055. static float _vq_quantthresh__16u1__p9_2[] = {
  144056. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144057. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144058. };
  144059. static long _vq_quantmap__16u1__p9_2[] = {
  144060. 15, 13, 11, 9, 7, 5, 3, 1,
  144061. 0, 2, 4, 6, 8, 10, 12, 14,
  144062. 16,
  144063. };
  144064. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144065. _vq_quantthresh__16u1__p9_2,
  144066. _vq_quantmap__16u1__p9_2,
  144067. 17,
  144068. 17
  144069. };
  144070. static static_codebook _16u1__p9_2 = {
  144071. 2, 289,
  144072. _vq_lengthlist__16u1__p9_2,
  144073. 1, -529530880, 1611661312, 5, 0,
  144074. _vq_quantlist__16u1__p9_2,
  144075. NULL,
  144076. &_vq_auxt__16u1__p9_2,
  144077. NULL,
  144078. 0
  144079. };
  144080. static long _huff_lengthlist__16u1__short[] = {
  144081. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144082. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144083. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144084. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144085. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144086. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144087. 16,16,16,16,
  144088. };
  144089. static static_codebook _huff_book__16u1__short = {
  144090. 2, 100,
  144091. _huff_lengthlist__16u1__short,
  144092. 0, 0, 0, 0, 0,
  144093. NULL,
  144094. NULL,
  144095. NULL,
  144096. NULL,
  144097. 0
  144098. };
  144099. static long _huff_lengthlist__16u2__long[] = {
  144100. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144101. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144102. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144103. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144104. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144105. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144106. 13,14,18,18,
  144107. };
  144108. static static_codebook _huff_book__16u2__long = {
  144109. 2, 100,
  144110. _huff_lengthlist__16u2__long,
  144111. 0, 0, 0, 0, 0,
  144112. NULL,
  144113. NULL,
  144114. NULL,
  144115. NULL,
  144116. 0
  144117. };
  144118. static long _huff_lengthlist__16u2__short[] = {
  144119. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144120. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144121. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144122. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144123. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144124. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144125. 16,16,16,16,
  144126. };
  144127. static static_codebook _huff_book__16u2__short = {
  144128. 2, 100,
  144129. _huff_lengthlist__16u2__short,
  144130. 0, 0, 0, 0, 0,
  144131. NULL,
  144132. NULL,
  144133. NULL,
  144134. NULL,
  144135. 0
  144136. };
  144137. static long _vq_quantlist__16u2_p1_0[] = {
  144138. 1,
  144139. 0,
  144140. 2,
  144141. };
  144142. static long _vq_lengthlist__16u2_p1_0[] = {
  144143. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144144. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144145. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144146. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144147. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144148. 10,
  144149. };
  144150. static float _vq_quantthresh__16u2_p1_0[] = {
  144151. -0.5, 0.5,
  144152. };
  144153. static long _vq_quantmap__16u2_p1_0[] = {
  144154. 1, 0, 2,
  144155. };
  144156. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144157. _vq_quantthresh__16u2_p1_0,
  144158. _vq_quantmap__16u2_p1_0,
  144159. 3,
  144160. 3
  144161. };
  144162. static static_codebook _16u2_p1_0 = {
  144163. 4, 81,
  144164. _vq_lengthlist__16u2_p1_0,
  144165. 1, -535822336, 1611661312, 2, 0,
  144166. _vq_quantlist__16u2_p1_0,
  144167. NULL,
  144168. &_vq_auxt__16u2_p1_0,
  144169. NULL,
  144170. 0
  144171. };
  144172. static long _vq_quantlist__16u2_p2_0[] = {
  144173. 2,
  144174. 1,
  144175. 3,
  144176. 0,
  144177. 4,
  144178. };
  144179. static long _vq_lengthlist__16u2_p2_0[] = {
  144180. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144181. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144182. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144183. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144184. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144185. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144186. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144187. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144188. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144189. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144190. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144191. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144192. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144193. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144194. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144195. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144196. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144197. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144198. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144199. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144200. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144201. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144202. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144203. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144204. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144205. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144206. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144207. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144208. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144209. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144210. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144211. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144212. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144213. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144214. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144215. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144216. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144217. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144218. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144219. 13,
  144220. };
  144221. static float _vq_quantthresh__16u2_p2_0[] = {
  144222. -1.5, -0.5, 0.5, 1.5,
  144223. };
  144224. static long _vq_quantmap__16u2_p2_0[] = {
  144225. 3, 1, 0, 2, 4,
  144226. };
  144227. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144228. _vq_quantthresh__16u2_p2_0,
  144229. _vq_quantmap__16u2_p2_0,
  144230. 5,
  144231. 5
  144232. };
  144233. static static_codebook _16u2_p2_0 = {
  144234. 4, 625,
  144235. _vq_lengthlist__16u2_p2_0,
  144236. 1, -533725184, 1611661312, 3, 0,
  144237. _vq_quantlist__16u2_p2_0,
  144238. NULL,
  144239. &_vq_auxt__16u2_p2_0,
  144240. NULL,
  144241. 0
  144242. };
  144243. static long _vq_quantlist__16u2_p3_0[] = {
  144244. 4,
  144245. 3,
  144246. 5,
  144247. 2,
  144248. 6,
  144249. 1,
  144250. 7,
  144251. 0,
  144252. 8,
  144253. };
  144254. static long _vq_lengthlist__16u2_p3_0[] = {
  144255. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144256. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144257. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144258. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144259. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144260. 11,
  144261. };
  144262. static float _vq_quantthresh__16u2_p3_0[] = {
  144263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144264. };
  144265. static long _vq_quantmap__16u2_p3_0[] = {
  144266. 7, 5, 3, 1, 0, 2, 4, 6,
  144267. 8,
  144268. };
  144269. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144270. _vq_quantthresh__16u2_p3_0,
  144271. _vq_quantmap__16u2_p3_0,
  144272. 9,
  144273. 9
  144274. };
  144275. static static_codebook _16u2_p3_0 = {
  144276. 2, 81,
  144277. _vq_lengthlist__16u2_p3_0,
  144278. 1, -531628032, 1611661312, 4, 0,
  144279. _vq_quantlist__16u2_p3_0,
  144280. NULL,
  144281. &_vq_auxt__16u2_p3_0,
  144282. NULL,
  144283. 0
  144284. };
  144285. static long _vq_quantlist__16u2_p4_0[] = {
  144286. 8,
  144287. 7,
  144288. 9,
  144289. 6,
  144290. 10,
  144291. 5,
  144292. 11,
  144293. 4,
  144294. 12,
  144295. 3,
  144296. 13,
  144297. 2,
  144298. 14,
  144299. 1,
  144300. 15,
  144301. 0,
  144302. 16,
  144303. };
  144304. static long _vq_lengthlist__16u2_p4_0[] = {
  144305. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144306. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144307. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144308. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144309. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144310. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144311. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144312. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144313. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144314. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144315. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144316. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144317. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144318. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144319. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144320. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144321. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144322. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144323. 14,
  144324. };
  144325. static float _vq_quantthresh__16u2_p4_0[] = {
  144326. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144327. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144328. };
  144329. static long _vq_quantmap__16u2_p4_0[] = {
  144330. 15, 13, 11, 9, 7, 5, 3, 1,
  144331. 0, 2, 4, 6, 8, 10, 12, 14,
  144332. 16,
  144333. };
  144334. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144335. _vq_quantthresh__16u2_p4_0,
  144336. _vq_quantmap__16u2_p4_0,
  144337. 17,
  144338. 17
  144339. };
  144340. static static_codebook _16u2_p4_0 = {
  144341. 2, 289,
  144342. _vq_lengthlist__16u2_p4_0,
  144343. 1, -529530880, 1611661312, 5, 0,
  144344. _vq_quantlist__16u2_p4_0,
  144345. NULL,
  144346. &_vq_auxt__16u2_p4_0,
  144347. NULL,
  144348. 0
  144349. };
  144350. static long _vq_quantlist__16u2_p5_0[] = {
  144351. 1,
  144352. 0,
  144353. 2,
  144354. };
  144355. static long _vq_lengthlist__16u2_p5_0[] = {
  144356. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144357. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144358. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144359. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144360. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144361. 10,
  144362. };
  144363. static float _vq_quantthresh__16u2_p5_0[] = {
  144364. -5.5, 5.5,
  144365. };
  144366. static long _vq_quantmap__16u2_p5_0[] = {
  144367. 1, 0, 2,
  144368. };
  144369. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144370. _vq_quantthresh__16u2_p5_0,
  144371. _vq_quantmap__16u2_p5_0,
  144372. 3,
  144373. 3
  144374. };
  144375. static static_codebook _16u2_p5_0 = {
  144376. 4, 81,
  144377. _vq_lengthlist__16u2_p5_0,
  144378. 1, -529137664, 1618345984, 2, 0,
  144379. _vq_quantlist__16u2_p5_0,
  144380. NULL,
  144381. &_vq_auxt__16u2_p5_0,
  144382. NULL,
  144383. 0
  144384. };
  144385. static long _vq_quantlist__16u2_p5_1[] = {
  144386. 5,
  144387. 4,
  144388. 6,
  144389. 3,
  144390. 7,
  144391. 2,
  144392. 8,
  144393. 1,
  144394. 9,
  144395. 0,
  144396. 10,
  144397. };
  144398. static long _vq_lengthlist__16u2_p5_1[] = {
  144399. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144400. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144401. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144402. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144403. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144404. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144405. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144406. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144407. };
  144408. static float _vq_quantthresh__16u2_p5_1[] = {
  144409. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144410. 3.5, 4.5,
  144411. };
  144412. static long _vq_quantmap__16u2_p5_1[] = {
  144413. 9, 7, 5, 3, 1, 0, 2, 4,
  144414. 6, 8, 10,
  144415. };
  144416. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144417. _vq_quantthresh__16u2_p5_1,
  144418. _vq_quantmap__16u2_p5_1,
  144419. 11,
  144420. 11
  144421. };
  144422. static static_codebook _16u2_p5_1 = {
  144423. 2, 121,
  144424. _vq_lengthlist__16u2_p5_1,
  144425. 1, -531365888, 1611661312, 4, 0,
  144426. _vq_quantlist__16u2_p5_1,
  144427. NULL,
  144428. &_vq_auxt__16u2_p5_1,
  144429. NULL,
  144430. 0
  144431. };
  144432. static long _vq_quantlist__16u2_p6_0[] = {
  144433. 6,
  144434. 5,
  144435. 7,
  144436. 4,
  144437. 8,
  144438. 3,
  144439. 9,
  144440. 2,
  144441. 10,
  144442. 1,
  144443. 11,
  144444. 0,
  144445. 12,
  144446. };
  144447. static long _vq_lengthlist__16u2_p6_0[] = {
  144448. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144449. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144450. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144451. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144452. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144453. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144454. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144455. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144456. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144457. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144458. 12,13,13,14,14,14,14,15,15,
  144459. };
  144460. static float _vq_quantthresh__16u2_p6_0[] = {
  144461. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144462. 12.5, 17.5, 22.5, 27.5,
  144463. };
  144464. static long _vq_quantmap__16u2_p6_0[] = {
  144465. 11, 9, 7, 5, 3, 1, 0, 2,
  144466. 4, 6, 8, 10, 12,
  144467. };
  144468. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144469. _vq_quantthresh__16u2_p6_0,
  144470. _vq_quantmap__16u2_p6_0,
  144471. 13,
  144472. 13
  144473. };
  144474. static static_codebook _16u2_p6_0 = {
  144475. 2, 169,
  144476. _vq_lengthlist__16u2_p6_0,
  144477. 1, -526516224, 1616117760, 4, 0,
  144478. _vq_quantlist__16u2_p6_0,
  144479. NULL,
  144480. &_vq_auxt__16u2_p6_0,
  144481. NULL,
  144482. 0
  144483. };
  144484. static long _vq_quantlist__16u2_p6_1[] = {
  144485. 2,
  144486. 1,
  144487. 3,
  144488. 0,
  144489. 4,
  144490. };
  144491. static long _vq_lengthlist__16u2_p6_1[] = {
  144492. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144493. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144494. };
  144495. static float _vq_quantthresh__16u2_p6_1[] = {
  144496. -1.5, -0.5, 0.5, 1.5,
  144497. };
  144498. static long _vq_quantmap__16u2_p6_1[] = {
  144499. 3, 1, 0, 2, 4,
  144500. };
  144501. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144502. _vq_quantthresh__16u2_p6_1,
  144503. _vq_quantmap__16u2_p6_1,
  144504. 5,
  144505. 5
  144506. };
  144507. static static_codebook _16u2_p6_1 = {
  144508. 2, 25,
  144509. _vq_lengthlist__16u2_p6_1,
  144510. 1, -533725184, 1611661312, 3, 0,
  144511. _vq_quantlist__16u2_p6_1,
  144512. NULL,
  144513. &_vq_auxt__16u2_p6_1,
  144514. NULL,
  144515. 0
  144516. };
  144517. static long _vq_quantlist__16u2_p7_0[] = {
  144518. 6,
  144519. 5,
  144520. 7,
  144521. 4,
  144522. 8,
  144523. 3,
  144524. 9,
  144525. 2,
  144526. 10,
  144527. 1,
  144528. 11,
  144529. 0,
  144530. 12,
  144531. };
  144532. static long _vq_lengthlist__16u2_p7_0[] = {
  144533. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144534. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144535. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144536. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144537. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144538. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144539. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144540. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144541. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144542. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144543. 12,13,13,13,14,14,14,15,14,
  144544. };
  144545. static float _vq_quantthresh__16u2_p7_0[] = {
  144546. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144547. 27.5, 38.5, 49.5, 60.5,
  144548. };
  144549. static long _vq_quantmap__16u2_p7_0[] = {
  144550. 11, 9, 7, 5, 3, 1, 0, 2,
  144551. 4, 6, 8, 10, 12,
  144552. };
  144553. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144554. _vq_quantthresh__16u2_p7_0,
  144555. _vq_quantmap__16u2_p7_0,
  144556. 13,
  144557. 13
  144558. };
  144559. static static_codebook _16u2_p7_0 = {
  144560. 2, 169,
  144561. _vq_lengthlist__16u2_p7_0,
  144562. 1, -523206656, 1618345984, 4, 0,
  144563. _vq_quantlist__16u2_p7_0,
  144564. NULL,
  144565. &_vq_auxt__16u2_p7_0,
  144566. NULL,
  144567. 0
  144568. };
  144569. static long _vq_quantlist__16u2_p7_1[] = {
  144570. 5,
  144571. 4,
  144572. 6,
  144573. 3,
  144574. 7,
  144575. 2,
  144576. 8,
  144577. 1,
  144578. 9,
  144579. 0,
  144580. 10,
  144581. };
  144582. static long _vq_lengthlist__16u2_p7_1[] = {
  144583. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144584. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144585. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144586. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144587. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144588. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144589. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144590. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144591. };
  144592. static float _vq_quantthresh__16u2_p7_1[] = {
  144593. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144594. 3.5, 4.5,
  144595. };
  144596. static long _vq_quantmap__16u2_p7_1[] = {
  144597. 9, 7, 5, 3, 1, 0, 2, 4,
  144598. 6, 8, 10,
  144599. };
  144600. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144601. _vq_quantthresh__16u2_p7_1,
  144602. _vq_quantmap__16u2_p7_1,
  144603. 11,
  144604. 11
  144605. };
  144606. static static_codebook _16u2_p7_1 = {
  144607. 2, 121,
  144608. _vq_lengthlist__16u2_p7_1,
  144609. 1, -531365888, 1611661312, 4, 0,
  144610. _vq_quantlist__16u2_p7_1,
  144611. NULL,
  144612. &_vq_auxt__16u2_p7_1,
  144613. NULL,
  144614. 0
  144615. };
  144616. static long _vq_quantlist__16u2_p8_0[] = {
  144617. 7,
  144618. 6,
  144619. 8,
  144620. 5,
  144621. 9,
  144622. 4,
  144623. 10,
  144624. 3,
  144625. 11,
  144626. 2,
  144627. 12,
  144628. 1,
  144629. 13,
  144630. 0,
  144631. 14,
  144632. };
  144633. static long _vq_lengthlist__16u2_p8_0[] = {
  144634. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144635. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144636. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144637. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144638. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144639. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144640. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144641. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144642. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144643. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144644. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144645. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144646. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144647. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144648. 14,
  144649. };
  144650. static float _vq_quantthresh__16u2_p8_0[] = {
  144651. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144652. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144653. };
  144654. static long _vq_quantmap__16u2_p8_0[] = {
  144655. 13, 11, 9, 7, 5, 3, 1, 0,
  144656. 2, 4, 6, 8, 10, 12, 14,
  144657. };
  144658. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144659. _vq_quantthresh__16u2_p8_0,
  144660. _vq_quantmap__16u2_p8_0,
  144661. 15,
  144662. 15
  144663. };
  144664. static static_codebook _16u2_p8_0 = {
  144665. 2, 225,
  144666. _vq_lengthlist__16u2_p8_0,
  144667. 1, -520986624, 1620377600, 4, 0,
  144668. _vq_quantlist__16u2_p8_0,
  144669. NULL,
  144670. &_vq_auxt__16u2_p8_0,
  144671. NULL,
  144672. 0
  144673. };
  144674. static long _vq_quantlist__16u2_p8_1[] = {
  144675. 10,
  144676. 9,
  144677. 11,
  144678. 8,
  144679. 12,
  144680. 7,
  144681. 13,
  144682. 6,
  144683. 14,
  144684. 5,
  144685. 15,
  144686. 4,
  144687. 16,
  144688. 3,
  144689. 17,
  144690. 2,
  144691. 18,
  144692. 1,
  144693. 19,
  144694. 0,
  144695. 20,
  144696. };
  144697. static long _vq_lengthlist__16u2_p8_1[] = {
  144698. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144699. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144700. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144701. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144702. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144703. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144704. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144705. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144706. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144707. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144708. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144709. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144710. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144711. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144712. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144713. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144714. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144715. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144716. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144717. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144718. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144719. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144720. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144721. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144723. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144724. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144725. 11,11,10,11,11,11,10,11,11,
  144726. };
  144727. static float _vq_quantthresh__16u2_p8_1[] = {
  144728. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144729. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144730. 6.5, 7.5, 8.5, 9.5,
  144731. };
  144732. static long _vq_quantmap__16u2_p8_1[] = {
  144733. 19, 17, 15, 13, 11, 9, 7, 5,
  144734. 3, 1, 0, 2, 4, 6, 8, 10,
  144735. 12, 14, 16, 18, 20,
  144736. };
  144737. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144738. _vq_quantthresh__16u2_p8_1,
  144739. _vq_quantmap__16u2_p8_1,
  144740. 21,
  144741. 21
  144742. };
  144743. static static_codebook _16u2_p8_1 = {
  144744. 2, 441,
  144745. _vq_lengthlist__16u2_p8_1,
  144746. 1, -529268736, 1611661312, 5, 0,
  144747. _vq_quantlist__16u2_p8_1,
  144748. NULL,
  144749. &_vq_auxt__16u2_p8_1,
  144750. NULL,
  144751. 0
  144752. };
  144753. static long _vq_quantlist__16u2_p9_0[] = {
  144754. 5586,
  144755. 4655,
  144756. 6517,
  144757. 3724,
  144758. 7448,
  144759. 2793,
  144760. 8379,
  144761. 1862,
  144762. 9310,
  144763. 931,
  144764. 10241,
  144765. 0,
  144766. 11172,
  144767. 5521,
  144768. 5651,
  144769. };
  144770. static long _vq_lengthlist__16u2_p9_0[] = {
  144771. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144783. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144784. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144785. 5,
  144786. };
  144787. static float _vq_quantthresh__16u2_p9_0[] = {
  144788. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144789. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144790. };
  144791. static long _vq_quantmap__16u2_p9_0[] = {
  144792. 11, 9, 7, 5, 3, 1, 13, 0,
  144793. 14, 2, 4, 6, 8, 10, 12,
  144794. };
  144795. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144796. _vq_quantthresh__16u2_p9_0,
  144797. _vq_quantmap__16u2_p9_0,
  144798. 15,
  144799. 15
  144800. };
  144801. static static_codebook _16u2_p9_0 = {
  144802. 2, 225,
  144803. _vq_lengthlist__16u2_p9_0,
  144804. 1, -510275072, 1611661312, 14, 0,
  144805. _vq_quantlist__16u2_p9_0,
  144806. NULL,
  144807. &_vq_auxt__16u2_p9_0,
  144808. NULL,
  144809. 0
  144810. };
  144811. static long _vq_quantlist__16u2_p9_1[] = {
  144812. 392,
  144813. 343,
  144814. 441,
  144815. 294,
  144816. 490,
  144817. 245,
  144818. 539,
  144819. 196,
  144820. 588,
  144821. 147,
  144822. 637,
  144823. 98,
  144824. 686,
  144825. 49,
  144826. 735,
  144827. 0,
  144828. 784,
  144829. 388,
  144830. 396,
  144831. };
  144832. static long _vq_lengthlist__16u2_p9_1[] = {
  144833. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144834. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144835. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144836. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144837. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144838. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144839. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144840. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144841. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144842. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144843. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144844. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144845. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144846. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144847. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144853. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144854. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144855. 11,11,11,11,11,11,11, 5, 4,
  144856. };
  144857. static float _vq_quantthresh__16u2_p9_1[] = {
  144858. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144859. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144860. 318.5, 367.5,
  144861. };
  144862. static long _vq_quantmap__16u2_p9_1[] = {
  144863. 15, 13, 11, 9, 7, 5, 3, 1,
  144864. 17, 0, 18, 2, 4, 6, 8, 10,
  144865. 12, 14, 16,
  144866. };
  144867. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144868. _vq_quantthresh__16u2_p9_1,
  144869. _vq_quantmap__16u2_p9_1,
  144870. 19,
  144871. 19
  144872. };
  144873. static static_codebook _16u2_p9_1 = {
  144874. 2, 361,
  144875. _vq_lengthlist__16u2_p9_1,
  144876. 1, -518488064, 1611661312, 10, 0,
  144877. _vq_quantlist__16u2_p9_1,
  144878. NULL,
  144879. &_vq_auxt__16u2_p9_1,
  144880. NULL,
  144881. 0
  144882. };
  144883. static long _vq_quantlist__16u2_p9_2[] = {
  144884. 24,
  144885. 23,
  144886. 25,
  144887. 22,
  144888. 26,
  144889. 21,
  144890. 27,
  144891. 20,
  144892. 28,
  144893. 19,
  144894. 29,
  144895. 18,
  144896. 30,
  144897. 17,
  144898. 31,
  144899. 16,
  144900. 32,
  144901. 15,
  144902. 33,
  144903. 14,
  144904. 34,
  144905. 13,
  144906. 35,
  144907. 12,
  144908. 36,
  144909. 11,
  144910. 37,
  144911. 10,
  144912. 38,
  144913. 9,
  144914. 39,
  144915. 8,
  144916. 40,
  144917. 7,
  144918. 41,
  144919. 6,
  144920. 42,
  144921. 5,
  144922. 43,
  144923. 4,
  144924. 44,
  144925. 3,
  144926. 45,
  144927. 2,
  144928. 46,
  144929. 1,
  144930. 47,
  144931. 0,
  144932. 48,
  144933. };
  144934. static long _vq_lengthlist__16u2_p9_2[] = {
  144935. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144936. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144937. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144938. 11,
  144939. };
  144940. static float _vq_quantthresh__16u2_p9_2[] = {
  144941. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144942. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144943. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144944. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144945. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144946. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144947. };
  144948. static long _vq_quantmap__16u2_p9_2[] = {
  144949. 47, 45, 43, 41, 39, 37, 35, 33,
  144950. 31, 29, 27, 25, 23, 21, 19, 17,
  144951. 15, 13, 11, 9, 7, 5, 3, 1,
  144952. 0, 2, 4, 6, 8, 10, 12, 14,
  144953. 16, 18, 20, 22, 24, 26, 28, 30,
  144954. 32, 34, 36, 38, 40, 42, 44, 46,
  144955. 48,
  144956. };
  144957. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144958. _vq_quantthresh__16u2_p9_2,
  144959. _vq_quantmap__16u2_p9_2,
  144960. 49,
  144961. 49
  144962. };
  144963. static static_codebook _16u2_p9_2 = {
  144964. 1, 49,
  144965. _vq_lengthlist__16u2_p9_2,
  144966. 1, -526909440, 1611661312, 6, 0,
  144967. _vq_quantlist__16u2_p9_2,
  144968. NULL,
  144969. &_vq_auxt__16u2_p9_2,
  144970. NULL,
  144971. 0
  144972. };
  144973. static long _vq_quantlist__8u0__p1_0[] = {
  144974. 1,
  144975. 0,
  144976. 2,
  144977. };
  144978. static long _vq_lengthlist__8u0__p1_0[] = {
  144979. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144980. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144981. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144982. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144983. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144984. 11,
  144985. };
  144986. static float _vq_quantthresh__8u0__p1_0[] = {
  144987. -0.5, 0.5,
  144988. };
  144989. static long _vq_quantmap__8u0__p1_0[] = {
  144990. 1, 0, 2,
  144991. };
  144992. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144993. _vq_quantthresh__8u0__p1_0,
  144994. _vq_quantmap__8u0__p1_0,
  144995. 3,
  144996. 3
  144997. };
  144998. static static_codebook _8u0__p1_0 = {
  144999. 4, 81,
  145000. _vq_lengthlist__8u0__p1_0,
  145001. 1, -535822336, 1611661312, 2, 0,
  145002. _vq_quantlist__8u0__p1_0,
  145003. NULL,
  145004. &_vq_auxt__8u0__p1_0,
  145005. NULL,
  145006. 0
  145007. };
  145008. static long _vq_quantlist__8u0__p2_0[] = {
  145009. 1,
  145010. 0,
  145011. 2,
  145012. };
  145013. static long _vq_lengthlist__8u0__p2_0[] = {
  145014. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145015. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145016. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145017. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145018. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145019. 8,
  145020. };
  145021. static float _vq_quantthresh__8u0__p2_0[] = {
  145022. -0.5, 0.5,
  145023. };
  145024. static long _vq_quantmap__8u0__p2_0[] = {
  145025. 1, 0, 2,
  145026. };
  145027. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145028. _vq_quantthresh__8u0__p2_0,
  145029. _vq_quantmap__8u0__p2_0,
  145030. 3,
  145031. 3
  145032. };
  145033. static static_codebook _8u0__p2_0 = {
  145034. 4, 81,
  145035. _vq_lengthlist__8u0__p2_0,
  145036. 1, -535822336, 1611661312, 2, 0,
  145037. _vq_quantlist__8u0__p2_0,
  145038. NULL,
  145039. &_vq_auxt__8u0__p2_0,
  145040. NULL,
  145041. 0
  145042. };
  145043. static long _vq_quantlist__8u0__p3_0[] = {
  145044. 2,
  145045. 1,
  145046. 3,
  145047. 0,
  145048. 4,
  145049. };
  145050. static long _vq_lengthlist__8u0__p3_0[] = {
  145051. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145052. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145053. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145054. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145055. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145056. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145057. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145058. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145059. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145060. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145061. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145062. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145063. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145064. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145065. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145066. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145067. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145068. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145069. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145070. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145071. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145072. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145073. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145074. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145075. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145076. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145077. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145078. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145079. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145080. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145081. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145082. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145083. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145084. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145085. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145086. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145087. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145088. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145089. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145090. 16,
  145091. };
  145092. static float _vq_quantthresh__8u0__p3_0[] = {
  145093. -1.5, -0.5, 0.5, 1.5,
  145094. };
  145095. static long _vq_quantmap__8u0__p3_0[] = {
  145096. 3, 1, 0, 2, 4,
  145097. };
  145098. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145099. _vq_quantthresh__8u0__p3_0,
  145100. _vq_quantmap__8u0__p3_0,
  145101. 5,
  145102. 5
  145103. };
  145104. static static_codebook _8u0__p3_0 = {
  145105. 4, 625,
  145106. _vq_lengthlist__8u0__p3_0,
  145107. 1, -533725184, 1611661312, 3, 0,
  145108. _vq_quantlist__8u0__p3_0,
  145109. NULL,
  145110. &_vq_auxt__8u0__p3_0,
  145111. NULL,
  145112. 0
  145113. };
  145114. static long _vq_quantlist__8u0__p4_0[] = {
  145115. 2,
  145116. 1,
  145117. 3,
  145118. 0,
  145119. 4,
  145120. };
  145121. static long _vq_lengthlist__8u0__p4_0[] = {
  145122. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145123. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145124. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145125. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145126. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145127. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145128. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145129. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145130. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145131. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145132. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145133. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145134. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145135. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145136. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145137. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145138. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145139. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145140. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145141. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145142. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145143. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145144. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145145. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145146. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145147. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145148. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145149. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145150. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145151. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145152. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145153. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145154. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145155. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145156. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145157. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145158. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145159. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145160. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145161. 12,
  145162. };
  145163. static float _vq_quantthresh__8u0__p4_0[] = {
  145164. -1.5, -0.5, 0.5, 1.5,
  145165. };
  145166. static long _vq_quantmap__8u0__p4_0[] = {
  145167. 3, 1, 0, 2, 4,
  145168. };
  145169. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145170. _vq_quantthresh__8u0__p4_0,
  145171. _vq_quantmap__8u0__p4_0,
  145172. 5,
  145173. 5
  145174. };
  145175. static static_codebook _8u0__p4_0 = {
  145176. 4, 625,
  145177. _vq_lengthlist__8u0__p4_0,
  145178. 1, -533725184, 1611661312, 3, 0,
  145179. _vq_quantlist__8u0__p4_0,
  145180. NULL,
  145181. &_vq_auxt__8u0__p4_0,
  145182. NULL,
  145183. 0
  145184. };
  145185. static long _vq_quantlist__8u0__p5_0[] = {
  145186. 4,
  145187. 3,
  145188. 5,
  145189. 2,
  145190. 6,
  145191. 1,
  145192. 7,
  145193. 0,
  145194. 8,
  145195. };
  145196. static long _vq_lengthlist__8u0__p5_0[] = {
  145197. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145198. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145199. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145200. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145201. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145202. 12,
  145203. };
  145204. static float _vq_quantthresh__8u0__p5_0[] = {
  145205. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145206. };
  145207. static long _vq_quantmap__8u0__p5_0[] = {
  145208. 7, 5, 3, 1, 0, 2, 4, 6,
  145209. 8,
  145210. };
  145211. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145212. _vq_quantthresh__8u0__p5_0,
  145213. _vq_quantmap__8u0__p5_0,
  145214. 9,
  145215. 9
  145216. };
  145217. static static_codebook _8u0__p5_0 = {
  145218. 2, 81,
  145219. _vq_lengthlist__8u0__p5_0,
  145220. 1, -531628032, 1611661312, 4, 0,
  145221. _vq_quantlist__8u0__p5_0,
  145222. NULL,
  145223. &_vq_auxt__8u0__p5_0,
  145224. NULL,
  145225. 0
  145226. };
  145227. static long _vq_quantlist__8u0__p6_0[] = {
  145228. 6,
  145229. 5,
  145230. 7,
  145231. 4,
  145232. 8,
  145233. 3,
  145234. 9,
  145235. 2,
  145236. 10,
  145237. 1,
  145238. 11,
  145239. 0,
  145240. 12,
  145241. };
  145242. static long _vq_lengthlist__8u0__p6_0[] = {
  145243. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145244. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145245. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145246. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145247. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145248. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145249. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145250. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145251. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145252. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145253. 16, 0,15, 0,17, 0, 0, 0, 0,
  145254. };
  145255. static float _vq_quantthresh__8u0__p6_0[] = {
  145256. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145257. 12.5, 17.5, 22.5, 27.5,
  145258. };
  145259. static long _vq_quantmap__8u0__p6_0[] = {
  145260. 11, 9, 7, 5, 3, 1, 0, 2,
  145261. 4, 6, 8, 10, 12,
  145262. };
  145263. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145264. _vq_quantthresh__8u0__p6_0,
  145265. _vq_quantmap__8u0__p6_0,
  145266. 13,
  145267. 13
  145268. };
  145269. static static_codebook _8u0__p6_0 = {
  145270. 2, 169,
  145271. _vq_lengthlist__8u0__p6_0,
  145272. 1, -526516224, 1616117760, 4, 0,
  145273. _vq_quantlist__8u0__p6_0,
  145274. NULL,
  145275. &_vq_auxt__8u0__p6_0,
  145276. NULL,
  145277. 0
  145278. };
  145279. static long _vq_quantlist__8u0__p6_1[] = {
  145280. 2,
  145281. 1,
  145282. 3,
  145283. 0,
  145284. 4,
  145285. };
  145286. static long _vq_lengthlist__8u0__p6_1[] = {
  145287. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145288. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145289. };
  145290. static float _vq_quantthresh__8u0__p6_1[] = {
  145291. -1.5, -0.5, 0.5, 1.5,
  145292. };
  145293. static long _vq_quantmap__8u0__p6_1[] = {
  145294. 3, 1, 0, 2, 4,
  145295. };
  145296. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145297. _vq_quantthresh__8u0__p6_1,
  145298. _vq_quantmap__8u0__p6_1,
  145299. 5,
  145300. 5
  145301. };
  145302. static static_codebook _8u0__p6_1 = {
  145303. 2, 25,
  145304. _vq_lengthlist__8u0__p6_1,
  145305. 1, -533725184, 1611661312, 3, 0,
  145306. _vq_quantlist__8u0__p6_1,
  145307. NULL,
  145308. &_vq_auxt__8u0__p6_1,
  145309. NULL,
  145310. 0
  145311. };
  145312. static long _vq_quantlist__8u0__p7_0[] = {
  145313. 1,
  145314. 0,
  145315. 2,
  145316. };
  145317. static long _vq_lengthlist__8u0__p7_0[] = {
  145318. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145319. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145320. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145321. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145322. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145323. 7,
  145324. };
  145325. static float _vq_quantthresh__8u0__p7_0[] = {
  145326. -157.5, 157.5,
  145327. };
  145328. static long _vq_quantmap__8u0__p7_0[] = {
  145329. 1, 0, 2,
  145330. };
  145331. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145332. _vq_quantthresh__8u0__p7_0,
  145333. _vq_quantmap__8u0__p7_0,
  145334. 3,
  145335. 3
  145336. };
  145337. static static_codebook _8u0__p7_0 = {
  145338. 4, 81,
  145339. _vq_lengthlist__8u0__p7_0,
  145340. 1, -518803456, 1628680192, 2, 0,
  145341. _vq_quantlist__8u0__p7_0,
  145342. NULL,
  145343. &_vq_auxt__8u0__p7_0,
  145344. NULL,
  145345. 0
  145346. };
  145347. static long _vq_quantlist__8u0__p7_1[] = {
  145348. 7,
  145349. 6,
  145350. 8,
  145351. 5,
  145352. 9,
  145353. 4,
  145354. 10,
  145355. 3,
  145356. 11,
  145357. 2,
  145358. 12,
  145359. 1,
  145360. 13,
  145361. 0,
  145362. 14,
  145363. };
  145364. static long _vq_lengthlist__8u0__p7_1[] = {
  145365. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145366. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145367. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145368. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145369. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145370. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145377. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145378. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145379. 10,
  145380. };
  145381. static float _vq_quantthresh__8u0__p7_1[] = {
  145382. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145383. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145384. };
  145385. static long _vq_quantmap__8u0__p7_1[] = {
  145386. 13, 11, 9, 7, 5, 3, 1, 0,
  145387. 2, 4, 6, 8, 10, 12, 14,
  145388. };
  145389. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145390. _vq_quantthresh__8u0__p7_1,
  145391. _vq_quantmap__8u0__p7_1,
  145392. 15,
  145393. 15
  145394. };
  145395. static static_codebook _8u0__p7_1 = {
  145396. 2, 225,
  145397. _vq_lengthlist__8u0__p7_1,
  145398. 1, -520986624, 1620377600, 4, 0,
  145399. _vq_quantlist__8u0__p7_1,
  145400. NULL,
  145401. &_vq_auxt__8u0__p7_1,
  145402. NULL,
  145403. 0
  145404. };
  145405. static long _vq_quantlist__8u0__p7_2[] = {
  145406. 10,
  145407. 9,
  145408. 11,
  145409. 8,
  145410. 12,
  145411. 7,
  145412. 13,
  145413. 6,
  145414. 14,
  145415. 5,
  145416. 15,
  145417. 4,
  145418. 16,
  145419. 3,
  145420. 17,
  145421. 2,
  145422. 18,
  145423. 1,
  145424. 19,
  145425. 0,
  145426. 20,
  145427. };
  145428. static long _vq_lengthlist__8u0__p7_2[] = {
  145429. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145430. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145431. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145432. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145433. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145434. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145435. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145436. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145437. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145438. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145439. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145440. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145441. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145442. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145443. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145444. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145445. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145446. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145447. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145448. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145449. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145450. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145451. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145452. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145453. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145454. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145455. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145456. 11,12,11,11,11,10,10,11,11,
  145457. };
  145458. static float _vq_quantthresh__8u0__p7_2[] = {
  145459. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145460. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145461. 6.5, 7.5, 8.5, 9.5,
  145462. };
  145463. static long _vq_quantmap__8u0__p7_2[] = {
  145464. 19, 17, 15, 13, 11, 9, 7, 5,
  145465. 3, 1, 0, 2, 4, 6, 8, 10,
  145466. 12, 14, 16, 18, 20,
  145467. };
  145468. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145469. _vq_quantthresh__8u0__p7_2,
  145470. _vq_quantmap__8u0__p7_2,
  145471. 21,
  145472. 21
  145473. };
  145474. static static_codebook _8u0__p7_2 = {
  145475. 2, 441,
  145476. _vq_lengthlist__8u0__p7_2,
  145477. 1, -529268736, 1611661312, 5, 0,
  145478. _vq_quantlist__8u0__p7_2,
  145479. NULL,
  145480. &_vq_auxt__8u0__p7_2,
  145481. NULL,
  145482. 0
  145483. };
  145484. static long _huff_lengthlist__8u0__single[] = {
  145485. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145486. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145487. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145488. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145489. };
  145490. static static_codebook _huff_book__8u0__single = {
  145491. 2, 64,
  145492. _huff_lengthlist__8u0__single,
  145493. 0, 0, 0, 0, 0,
  145494. NULL,
  145495. NULL,
  145496. NULL,
  145497. NULL,
  145498. 0
  145499. };
  145500. static long _vq_quantlist__8u1__p1_0[] = {
  145501. 1,
  145502. 0,
  145503. 2,
  145504. };
  145505. static long _vq_lengthlist__8u1__p1_0[] = {
  145506. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145507. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145508. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145509. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145510. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145511. 10,
  145512. };
  145513. static float _vq_quantthresh__8u1__p1_0[] = {
  145514. -0.5, 0.5,
  145515. };
  145516. static long _vq_quantmap__8u1__p1_0[] = {
  145517. 1, 0, 2,
  145518. };
  145519. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145520. _vq_quantthresh__8u1__p1_0,
  145521. _vq_quantmap__8u1__p1_0,
  145522. 3,
  145523. 3
  145524. };
  145525. static static_codebook _8u1__p1_0 = {
  145526. 4, 81,
  145527. _vq_lengthlist__8u1__p1_0,
  145528. 1, -535822336, 1611661312, 2, 0,
  145529. _vq_quantlist__8u1__p1_0,
  145530. NULL,
  145531. &_vq_auxt__8u1__p1_0,
  145532. NULL,
  145533. 0
  145534. };
  145535. static long _vq_quantlist__8u1__p2_0[] = {
  145536. 1,
  145537. 0,
  145538. 2,
  145539. };
  145540. static long _vq_lengthlist__8u1__p2_0[] = {
  145541. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145542. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145543. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145544. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145545. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145546. 7,
  145547. };
  145548. static float _vq_quantthresh__8u1__p2_0[] = {
  145549. -0.5, 0.5,
  145550. };
  145551. static long _vq_quantmap__8u1__p2_0[] = {
  145552. 1, 0, 2,
  145553. };
  145554. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145555. _vq_quantthresh__8u1__p2_0,
  145556. _vq_quantmap__8u1__p2_0,
  145557. 3,
  145558. 3
  145559. };
  145560. static static_codebook _8u1__p2_0 = {
  145561. 4, 81,
  145562. _vq_lengthlist__8u1__p2_0,
  145563. 1, -535822336, 1611661312, 2, 0,
  145564. _vq_quantlist__8u1__p2_0,
  145565. NULL,
  145566. &_vq_auxt__8u1__p2_0,
  145567. NULL,
  145568. 0
  145569. };
  145570. static long _vq_quantlist__8u1__p3_0[] = {
  145571. 2,
  145572. 1,
  145573. 3,
  145574. 0,
  145575. 4,
  145576. };
  145577. static long _vq_lengthlist__8u1__p3_0[] = {
  145578. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145579. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145580. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145581. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145582. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145583. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145584. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145585. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145586. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145587. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145588. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145589. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145590. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145591. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145592. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145593. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145594. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145595. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145596. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145597. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145598. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145599. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145600. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145601. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145602. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145603. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145604. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145605. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145606. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145607. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145608. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145609. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145610. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145611. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145612. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145613. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145614. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145615. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145616. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145617. 16,
  145618. };
  145619. static float _vq_quantthresh__8u1__p3_0[] = {
  145620. -1.5, -0.5, 0.5, 1.5,
  145621. };
  145622. static long _vq_quantmap__8u1__p3_0[] = {
  145623. 3, 1, 0, 2, 4,
  145624. };
  145625. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145626. _vq_quantthresh__8u1__p3_0,
  145627. _vq_quantmap__8u1__p3_0,
  145628. 5,
  145629. 5
  145630. };
  145631. static static_codebook _8u1__p3_0 = {
  145632. 4, 625,
  145633. _vq_lengthlist__8u1__p3_0,
  145634. 1, -533725184, 1611661312, 3, 0,
  145635. _vq_quantlist__8u1__p3_0,
  145636. NULL,
  145637. &_vq_auxt__8u1__p3_0,
  145638. NULL,
  145639. 0
  145640. };
  145641. static long _vq_quantlist__8u1__p4_0[] = {
  145642. 2,
  145643. 1,
  145644. 3,
  145645. 0,
  145646. 4,
  145647. };
  145648. static long _vq_lengthlist__8u1__p4_0[] = {
  145649. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145650. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145651. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145652. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145653. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145654. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145655. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145656. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145657. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145658. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145659. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145660. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145661. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145662. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145663. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145664. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145665. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145666. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145667. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145668. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145669. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145670. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145671. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145672. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145673. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145674. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145675. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145676. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145677. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145678. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145679. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145680. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145681. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145682. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145683. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145684. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145685. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145686. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145687. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145688. 10,
  145689. };
  145690. static float _vq_quantthresh__8u1__p4_0[] = {
  145691. -1.5, -0.5, 0.5, 1.5,
  145692. };
  145693. static long _vq_quantmap__8u1__p4_0[] = {
  145694. 3, 1, 0, 2, 4,
  145695. };
  145696. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145697. _vq_quantthresh__8u1__p4_0,
  145698. _vq_quantmap__8u1__p4_0,
  145699. 5,
  145700. 5
  145701. };
  145702. static static_codebook _8u1__p4_0 = {
  145703. 4, 625,
  145704. _vq_lengthlist__8u1__p4_0,
  145705. 1, -533725184, 1611661312, 3, 0,
  145706. _vq_quantlist__8u1__p4_0,
  145707. NULL,
  145708. &_vq_auxt__8u1__p4_0,
  145709. NULL,
  145710. 0
  145711. };
  145712. static long _vq_quantlist__8u1__p5_0[] = {
  145713. 4,
  145714. 3,
  145715. 5,
  145716. 2,
  145717. 6,
  145718. 1,
  145719. 7,
  145720. 0,
  145721. 8,
  145722. };
  145723. static long _vq_lengthlist__8u1__p5_0[] = {
  145724. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145725. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145726. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145727. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145728. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145729. 13,
  145730. };
  145731. static float _vq_quantthresh__8u1__p5_0[] = {
  145732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145733. };
  145734. static long _vq_quantmap__8u1__p5_0[] = {
  145735. 7, 5, 3, 1, 0, 2, 4, 6,
  145736. 8,
  145737. };
  145738. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145739. _vq_quantthresh__8u1__p5_0,
  145740. _vq_quantmap__8u1__p5_0,
  145741. 9,
  145742. 9
  145743. };
  145744. static static_codebook _8u1__p5_0 = {
  145745. 2, 81,
  145746. _vq_lengthlist__8u1__p5_0,
  145747. 1, -531628032, 1611661312, 4, 0,
  145748. _vq_quantlist__8u1__p5_0,
  145749. NULL,
  145750. &_vq_auxt__8u1__p5_0,
  145751. NULL,
  145752. 0
  145753. };
  145754. static long _vq_quantlist__8u1__p6_0[] = {
  145755. 4,
  145756. 3,
  145757. 5,
  145758. 2,
  145759. 6,
  145760. 1,
  145761. 7,
  145762. 0,
  145763. 8,
  145764. };
  145765. static long _vq_lengthlist__8u1__p6_0[] = {
  145766. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145767. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145768. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145769. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145770. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145771. 10,
  145772. };
  145773. static float _vq_quantthresh__8u1__p6_0[] = {
  145774. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145775. };
  145776. static long _vq_quantmap__8u1__p6_0[] = {
  145777. 7, 5, 3, 1, 0, 2, 4, 6,
  145778. 8,
  145779. };
  145780. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145781. _vq_quantthresh__8u1__p6_0,
  145782. _vq_quantmap__8u1__p6_0,
  145783. 9,
  145784. 9
  145785. };
  145786. static static_codebook _8u1__p6_0 = {
  145787. 2, 81,
  145788. _vq_lengthlist__8u1__p6_0,
  145789. 1, -531628032, 1611661312, 4, 0,
  145790. _vq_quantlist__8u1__p6_0,
  145791. NULL,
  145792. &_vq_auxt__8u1__p6_0,
  145793. NULL,
  145794. 0
  145795. };
  145796. static long _vq_quantlist__8u1__p7_0[] = {
  145797. 1,
  145798. 0,
  145799. 2,
  145800. };
  145801. static long _vq_lengthlist__8u1__p7_0[] = {
  145802. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145803. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145804. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145805. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145806. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145807. 11,
  145808. };
  145809. static float _vq_quantthresh__8u1__p7_0[] = {
  145810. -5.5, 5.5,
  145811. };
  145812. static long _vq_quantmap__8u1__p7_0[] = {
  145813. 1, 0, 2,
  145814. };
  145815. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145816. _vq_quantthresh__8u1__p7_0,
  145817. _vq_quantmap__8u1__p7_0,
  145818. 3,
  145819. 3
  145820. };
  145821. static static_codebook _8u1__p7_0 = {
  145822. 4, 81,
  145823. _vq_lengthlist__8u1__p7_0,
  145824. 1, -529137664, 1618345984, 2, 0,
  145825. _vq_quantlist__8u1__p7_0,
  145826. NULL,
  145827. &_vq_auxt__8u1__p7_0,
  145828. NULL,
  145829. 0
  145830. };
  145831. static long _vq_quantlist__8u1__p7_1[] = {
  145832. 5,
  145833. 4,
  145834. 6,
  145835. 3,
  145836. 7,
  145837. 2,
  145838. 8,
  145839. 1,
  145840. 9,
  145841. 0,
  145842. 10,
  145843. };
  145844. static long _vq_lengthlist__8u1__p7_1[] = {
  145845. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145846. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145847. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145848. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145849. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145850. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145851. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145852. 9, 9, 9, 9, 9,10,10,10,10,
  145853. };
  145854. static float _vq_quantthresh__8u1__p7_1[] = {
  145855. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145856. 3.5, 4.5,
  145857. };
  145858. static long _vq_quantmap__8u1__p7_1[] = {
  145859. 9, 7, 5, 3, 1, 0, 2, 4,
  145860. 6, 8, 10,
  145861. };
  145862. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145863. _vq_quantthresh__8u1__p7_1,
  145864. _vq_quantmap__8u1__p7_1,
  145865. 11,
  145866. 11
  145867. };
  145868. static static_codebook _8u1__p7_1 = {
  145869. 2, 121,
  145870. _vq_lengthlist__8u1__p7_1,
  145871. 1, -531365888, 1611661312, 4, 0,
  145872. _vq_quantlist__8u1__p7_1,
  145873. NULL,
  145874. &_vq_auxt__8u1__p7_1,
  145875. NULL,
  145876. 0
  145877. };
  145878. static long _vq_quantlist__8u1__p8_0[] = {
  145879. 5,
  145880. 4,
  145881. 6,
  145882. 3,
  145883. 7,
  145884. 2,
  145885. 8,
  145886. 1,
  145887. 9,
  145888. 0,
  145889. 10,
  145890. };
  145891. static long _vq_lengthlist__8u1__p8_0[] = {
  145892. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145893. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145894. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145895. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145896. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145897. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145898. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145899. 12,13,13,14,14,15,15,15,15,
  145900. };
  145901. static float _vq_quantthresh__8u1__p8_0[] = {
  145902. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145903. 38.5, 49.5,
  145904. };
  145905. static long _vq_quantmap__8u1__p8_0[] = {
  145906. 9, 7, 5, 3, 1, 0, 2, 4,
  145907. 6, 8, 10,
  145908. };
  145909. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145910. _vq_quantthresh__8u1__p8_0,
  145911. _vq_quantmap__8u1__p8_0,
  145912. 11,
  145913. 11
  145914. };
  145915. static static_codebook _8u1__p8_0 = {
  145916. 2, 121,
  145917. _vq_lengthlist__8u1__p8_0,
  145918. 1, -524582912, 1618345984, 4, 0,
  145919. _vq_quantlist__8u1__p8_0,
  145920. NULL,
  145921. &_vq_auxt__8u1__p8_0,
  145922. NULL,
  145923. 0
  145924. };
  145925. static long _vq_quantlist__8u1__p8_1[] = {
  145926. 5,
  145927. 4,
  145928. 6,
  145929. 3,
  145930. 7,
  145931. 2,
  145932. 8,
  145933. 1,
  145934. 9,
  145935. 0,
  145936. 10,
  145937. };
  145938. static long _vq_lengthlist__8u1__p8_1[] = {
  145939. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145940. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145941. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145942. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145943. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145944. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145945. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145946. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145947. };
  145948. static float _vq_quantthresh__8u1__p8_1[] = {
  145949. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145950. 3.5, 4.5,
  145951. };
  145952. static long _vq_quantmap__8u1__p8_1[] = {
  145953. 9, 7, 5, 3, 1, 0, 2, 4,
  145954. 6, 8, 10,
  145955. };
  145956. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145957. _vq_quantthresh__8u1__p8_1,
  145958. _vq_quantmap__8u1__p8_1,
  145959. 11,
  145960. 11
  145961. };
  145962. static static_codebook _8u1__p8_1 = {
  145963. 2, 121,
  145964. _vq_lengthlist__8u1__p8_1,
  145965. 1, -531365888, 1611661312, 4, 0,
  145966. _vq_quantlist__8u1__p8_1,
  145967. NULL,
  145968. &_vq_auxt__8u1__p8_1,
  145969. NULL,
  145970. 0
  145971. };
  145972. static long _vq_quantlist__8u1__p9_0[] = {
  145973. 7,
  145974. 6,
  145975. 8,
  145976. 5,
  145977. 9,
  145978. 4,
  145979. 10,
  145980. 3,
  145981. 11,
  145982. 2,
  145983. 12,
  145984. 1,
  145985. 13,
  145986. 0,
  145987. 14,
  145988. };
  145989. static long _vq_lengthlist__8u1__p9_0[] = {
  145990. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145991. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145992. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146002. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146004. 10,
  146005. };
  146006. static float _vq_quantthresh__8u1__p9_0[] = {
  146007. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146008. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146009. };
  146010. static long _vq_quantmap__8u1__p9_0[] = {
  146011. 13, 11, 9, 7, 5, 3, 1, 0,
  146012. 2, 4, 6, 8, 10, 12, 14,
  146013. };
  146014. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146015. _vq_quantthresh__8u1__p9_0,
  146016. _vq_quantmap__8u1__p9_0,
  146017. 15,
  146018. 15
  146019. };
  146020. static static_codebook _8u1__p9_0 = {
  146021. 2, 225,
  146022. _vq_lengthlist__8u1__p9_0,
  146023. 1, -514071552, 1627381760, 4, 0,
  146024. _vq_quantlist__8u1__p9_0,
  146025. NULL,
  146026. &_vq_auxt__8u1__p9_0,
  146027. NULL,
  146028. 0
  146029. };
  146030. static long _vq_quantlist__8u1__p9_1[] = {
  146031. 7,
  146032. 6,
  146033. 8,
  146034. 5,
  146035. 9,
  146036. 4,
  146037. 10,
  146038. 3,
  146039. 11,
  146040. 2,
  146041. 12,
  146042. 1,
  146043. 13,
  146044. 0,
  146045. 14,
  146046. };
  146047. static long _vq_lengthlist__8u1__p9_1[] = {
  146048. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146049. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146050. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146051. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146052. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146053. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146054. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146055. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146056. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146057. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146058. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146059. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146060. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146061. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146062. 13,
  146063. };
  146064. static float _vq_quantthresh__8u1__p9_1[] = {
  146065. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146066. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146067. };
  146068. static long _vq_quantmap__8u1__p9_1[] = {
  146069. 13, 11, 9, 7, 5, 3, 1, 0,
  146070. 2, 4, 6, 8, 10, 12, 14,
  146071. };
  146072. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146073. _vq_quantthresh__8u1__p9_1,
  146074. _vq_quantmap__8u1__p9_1,
  146075. 15,
  146076. 15
  146077. };
  146078. static static_codebook _8u1__p9_1 = {
  146079. 2, 225,
  146080. _vq_lengthlist__8u1__p9_1,
  146081. 1, -522338304, 1620115456, 4, 0,
  146082. _vq_quantlist__8u1__p9_1,
  146083. NULL,
  146084. &_vq_auxt__8u1__p9_1,
  146085. NULL,
  146086. 0
  146087. };
  146088. static long _vq_quantlist__8u1__p9_2[] = {
  146089. 8,
  146090. 7,
  146091. 9,
  146092. 6,
  146093. 10,
  146094. 5,
  146095. 11,
  146096. 4,
  146097. 12,
  146098. 3,
  146099. 13,
  146100. 2,
  146101. 14,
  146102. 1,
  146103. 15,
  146104. 0,
  146105. 16,
  146106. };
  146107. static long _vq_lengthlist__8u1__p9_2[] = {
  146108. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146109. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146110. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146111. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146112. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146113. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146114. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146115. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146116. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146117. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146118. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146119. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146120. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146121. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146122. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146123. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146124. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146125. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146126. 10,
  146127. };
  146128. static float _vq_quantthresh__8u1__p9_2[] = {
  146129. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146130. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146131. };
  146132. static long _vq_quantmap__8u1__p9_2[] = {
  146133. 15, 13, 11, 9, 7, 5, 3, 1,
  146134. 0, 2, 4, 6, 8, 10, 12, 14,
  146135. 16,
  146136. };
  146137. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146138. _vq_quantthresh__8u1__p9_2,
  146139. _vq_quantmap__8u1__p9_2,
  146140. 17,
  146141. 17
  146142. };
  146143. static static_codebook _8u1__p9_2 = {
  146144. 2, 289,
  146145. _vq_lengthlist__8u1__p9_2,
  146146. 1, -529530880, 1611661312, 5, 0,
  146147. _vq_quantlist__8u1__p9_2,
  146148. NULL,
  146149. &_vq_auxt__8u1__p9_2,
  146150. NULL,
  146151. 0
  146152. };
  146153. static long _huff_lengthlist__8u1__single[] = {
  146154. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146155. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146156. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146157. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146158. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146159. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146160. 13, 8, 8,15,
  146161. };
  146162. static static_codebook _huff_book__8u1__single = {
  146163. 2, 100,
  146164. _huff_lengthlist__8u1__single,
  146165. 0, 0, 0, 0, 0,
  146166. NULL,
  146167. NULL,
  146168. NULL,
  146169. NULL,
  146170. 0
  146171. };
  146172. static long _huff_lengthlist__44u0__long[] = {
  146173. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146174. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146175. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146176. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146177. };
  146178. static static_codebook _huff_book__44u0__long = {
  146179. 2, 64,
  146180. _huff_lengthlist__44u0__long,
  146181. 0, 0, 0, 0, 0,
  146182. NULL,
  146183. NULL,
  146184. NULL,
  146185. NULL,
  146186. 0
  146187. };
  146188. static long _vq_quantlist__44u0__p1_0[] = {
  146189. 1,
  146190. 0,
  146191. 2,
  146192. };
  146193. static long _vq_lengthlist__44u0__p1_0[] = {
  146194. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146195. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146196. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146197. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146198. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146199. 13,
  146200. };
  146201. static float _vq_quantthresh__44u0__p1_0[] = {
  146202. -0.5, 0.5,
  146203. };
  146204. static long _vq_quantmap__44u0__p1_0[] = {
  146205. 1, 0, 2,
  146206. };
  146207. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146208. _vq_quantthresh__44u0__p1_0,
  146209. _vq_quantmap__44u0__p1_0,
  146210. 3,
  146211. 3
  146212. };
  146213. static static_codebook _44u0__p1_0 = {
  146214. 4, 81,
  146215. _vq_lengthlist__44u0__p1_0,
  146216. 1, -535822336, 1611661312, 2, 0,
  146217. _vq_quantlist__44u0__p1_0,
  146218. NULL,
  146219. &_vq_auxt__44u0__p1_0,
  146220. NULL,
  146221. 0
  146222. };
  146223. static long _vq_quantlist__44u0__p2_0[] = {
  146224. 1,
  146225. 0,
  146226. 2,
  146227. };
  146228. static long _vq_lengthlist__44u0__p2_0[] = {
  146229. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146230. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146231. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146232. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146233. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146234. 9,
  146235. };
  146236. static float _vq_quantthresh__44u0__p2_0[] = {
  146237. -0.5, 0.5,
  146238. };
  146239. static long _vq_quantmap__44u0__p2_0[] = {
  146240. 1, 0, 2,
  146241. };
  146242. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146243. _vq_quantthresh__44u0__p2_0,
  146244. _vq_quantmap__44u0__p2_0,
  146245. 3,
  146246. 3
  146247. };
  146248. static static_codebook _44u0__p2_0 = {
  146249. 4, 81,
  146250. _vq_lengthlist__44u0__p2_0,
  146251. 1, -535822336, 1611661312, 2, 0,
  146252. _vq_quantlist__44u0__p2_0,
  146253. NULL,
  146254. &_vq_auxt__44u0__p2_0,
  146255. NULL,
  146256. 0
  146257. };
  146258. static long _vq_quantlist__44u0__p3_0[] = {
  146259. 2,
  146260. 1,
  146261. 3,
  146262. 0,
  146263. 4,
  146264. };
  146265. static long _vq_lengthlist__44u0__p3_0[] = {
  146266. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146267. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146268. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146269. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146270. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146271. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146272. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146273. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146274. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146275. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146276. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146277. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146278. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146279. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146280. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146281. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146282. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146283. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146284. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146285. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146286. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146287. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146288. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146289. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146290. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146291. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146292. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146293. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146294. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146295. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146296. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146297. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146298. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146299. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146300. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146301. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146302. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146303. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146304. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146305. 19,
  146306. };
  146307. static float _vq_quantthresh__44u0__p3_0[] = {
  146308. -1.5, -0.5, 0.5, 1.5,
  146309. };
  146310. static long _vq_quantmap__44u0__p3_0[] = {
  146311. 3, 1, 0, 2, 4,
  146312. };
  146313. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146314. _vq_quantthresh__44u0__p3_0,
  146315. _vq_quantmap__44u0__p3_0,
  146316. 5,
  146317. 5
  146318. };
  146319. static static_codebook _44u0__p3_0 = {
  146320. 4, 625,
  146321. _vq_lengthlist__44u0__p3_0,
  146322. 1, -533725184, 1611661312, 3, 0,
  146323. _vq_quantlist__44u0__p3_0,
  146324. NULL,
  146325. &_vq_auxt__44u0__p3_0,
  146326. NULL,
  146327. 0
  146328. };
  146329. static long _vq_quantlist__44u0__p4_0[] = {
  146330. 2,
  146331. 1,
  146332. 3,
  146333. 0,
  146334. 4,
  146335. };
  146336. static long _vq_lengthlist__44u0__p4_0[] = {
  146337. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146338. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146339. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146340. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146341. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146342. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146343. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146344. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146345. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146346. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146347. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146348. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146349. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146350. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146351. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146352. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146353. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146354. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146355. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146356. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146357. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146358. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146359. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146360. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146361. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146362. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146363. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146364. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146365. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146366. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146367. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146368. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146369. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146370. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146371. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146372. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146373. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146374. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146375. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146376. 12,
  146377. };
  146378. static float _vq_quantthresh__44u0__p4_0[] = {
  146379. -1.5, -0.5, 0.5, 1.5,
  146380. };
  146381. static long _vq_quantmap__44u0__p4_0[] = {
  146382. 3, 1, 0, 2, 4,
  146383. };
  146384. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146385. _vq_quantthresh__44u0__p4_0,
  146386. _vq_quantmap__44u0__p4_0,
  146387. 5,
  146388. 5
  146389. };
  146390. static static_codebook _44u0__p4_0 = {
  146391. 4, 625,
  146392. _vq_lengthlist__44u0__p4_0,
  146393. 1, -533725184, 1611661312, 3, 0,
  146394. _vq_quantlist__44u0__p4_0,
  146395. NULL,
  146396. &_vq_auxt__44u0__p4_0,
  146397. NULL,
  146398. 0
  146399. };
  146400. static long _vq_quantlist__44u0__p5_0[] = {
  146401. 4,
  146402. 3,
  146403. 5,
  146404. 2,
  146405. 6,
  146406. 1,
  146407. 7,
  146408. 0,
  146409. 8,
  146410. };
  146411. static long _vq_lengthlist__44u0__p5_0[] = {
  146412. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146413. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146414. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146415. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146416. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146417. 12,
  146418. };
  146419. static float _vq_quantthresh__44u0__p5_0[] = {
  146420. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146421. };
  146422. static long _vq_quantmap__44u0__p5_0[] = {
  146423. 7, 5, 3, 1, 0, 2, 4, 6,
  146424. 8,
  146425. };
  146426. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146427. _vq_quantthresh__44u0__p5_0,
  146428. _vq_quantmap__44u0__p5_0,
  146429. 9,
  146430. 9
  146431. };
  146432. static static_codebook _44u0__p5_0 = {
  146433. 2, 81,
  146434. _vq_lengthlist__44u0__p5_0,
  146435. 1, -531628032, 1611661312, 4, 0,
  146436. _vq_quantlist__44u0__p5_0,
  146437. NULL,
  146438. &_vq_auxt__44u0__p5_0,
  146439. NULL,
  146440. 0
  146441. };
  146442. static long _vq_quantlist__44u0__p6_0[] = {
  146443. 6,
  146444. 5,
  146445. 7,
  146446. 4,
  146447. 8,
  146448. 3,
  146449. 9,
  146450. 2,
  146451. 10,
  146452. 1,
  146453. 11,
  146454. 0,
  146455. 12,
  146456. };
  146457. static long _vq_lengthlist__44u0__p6_0[] = {
  146458. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146459. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146460. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146461. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146462. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146463. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146464. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146465. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146466. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146467. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146468. 15,17,16,17,18,17,17,18, 0,
  146469. };
  146470. static float _vq_quantthresh__44u0__p6_0[] = {
  146471. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146472. 12.5, 17.5, 22.5, 27.5,
  146473. };
  146474. static long _vq_quantmap__44u0__p6_0[] = {
  146475. 11, 9, 7, 5, 3, 1, 0, 2,
  146476. 4, 6, 8, 10, 12,
  146477. };
  146478. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146479. _vq_quantthresh__44u0__p6_0,
  146480. _vq_quantmap__44u0__p6_0,
  146481. 13,
  146482. 13
  146483. };
  146484. static static_codebook _44u0__p6_0 = {
  146485. 2, 169,
  146486. _vq_lengthlist__44u0__p6_0,
  146487. 1, -526516224, 1616117760, 4, 0,
  146488. _vq_quantlist__44u0__p6_0,
  146489. NULL,
  146490. &_vq_auxt__44u0__p6_0,
  146491. NULL,
  146492. 0
  146493. };
  146494. static long _vq_quantlist__44u0__p6_1[] = {
  146495. 2,
  146496. 1,
  146497. 3,
  146498. 0,
  146499. 4,
  146500. };
  146501. static long _vq_lengthlist__44u0__p6_1[] = {
  146502. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146503. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146504. };
  146505. static float _vq_quantthresh__44u0__p6_1[] = {
  146506. -1.5, -0.5, 0.5, 1.5,
  146507. };
  146508. static long _vq_quantmap__44u0__p6_1[] = {
  146509. 3, 1, 0, 2, 4,
  146510. };
  146511. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146512. _vq_quantthresh__44u0__p6_1,
  146513. _vq_quantmap__44u0__p6_1,
  146514. 5,
  146515. 5
  146516. };
  146517. static static_codebook _44u0__p6_1 = {
  146518. 2, 25,
  146519. _vq_lengthlist__44u0__p6_1,
  146520. 1, -533725184, 1611661312, 3, 0,
  146521. _vq_quantlist__44u0__p6_1,
  146522. NULL,
  146523. &_vq_auxt__44u0__p6_1,
  146524. NULL,
  146525. 0
  146526. };
  146527. static long _vq_quantlist__44u0__p7_0[] = {
  146528. 2,
  146529. 1,
  146530. 3,
  146531. 0,
  146532. 4,
  146533. };
  146534. static long _vq_lengthlist__44u0__p7_0[] = {
  146535. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146538. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146542. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146549. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146559. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146565. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146568. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146569. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146570. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146571. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146572. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146573. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146574. 10,
  146575. };
  146576. static float _vq_quantthresh__44u0__p7_0[] = {
  146577. -253.5, -84.5, 84.5, 253.5,
  146578. };
  146579. static long _vq_quantmap__44u0__p7_0[] = {
  146580. 3, 1, 0, 2, 4,
  146581. };
  146582. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146583. _vq_quantthresh__44u0__p7_0,
  146584. _vq_quantmap__44u0__p7_0,
  146585. 5,
  146586. 5
  146587. };
  146588. static static_codebook _44u0__p7_0 = {
  146589. 4, 625,
  146590. _vq_lengthlist__44u0__p7_0,
  146591. 1, -518709248, 1626677248, 3, 0,
  146592. _vq_quantlist__44u0__p7_0,
  146593. NULL,
  146594. &_vq_auxt__44u0__p7_0,
  146595. NULL,
  146596. 0
  146597. };
  146598. static long _vq_quantlist__44u0__p7_1[] = {
  146599. 6,
  146600. 5,
  146601. 7,
  146602. 4,
  146603. 8,
  146604. 3,
  146605. 9,
  146606. 2,
  146607. 10,
  146608. 1,
  146609. 11,
  146610. 0,
  146611. 12,
  146612. };
  146613. static long _vq_lengthlist__44u0__p7_1[] = {
  146614. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146615. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146616. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146617. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146618. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146619. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146620. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146621. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146622. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146623. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146624. 15,15,15,15,15,15,15,15,15,
  146625. };
  146626. static float _vq_quantthresh__44u0__p7_1[] = {
  146627. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146628. 32.5, 45.5, 58.5, 71.5,
  146629. };
  146630. static long _vq_quantmap__44u0__p7_1[] = {
  146631. 11, 9, 7, 5, 3, 1, 0, 2,
  146632. 4, 6, 8, 10, 12,
  146633. };
  146634. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146635. _vq_quantthresh__44u0__p7_1,
  146636. _vq_quantmap__44u0__p7_1,
  146637. 13,
  146638. 13
  146639. };
  146640. static static_codebook _44u0__p7_1 = {
  146641. 2, 169,
  146642. _vq_lengthlist__44u0__p7_1,
  146643. 1, -523010048, 1618608128, 4, 0,
  146644. _vq_quantlist__44u0__p7_1,
  146645. NULL,
  146646. &_vq_auxt__44u0__p7_1,
  146647. NULL,
  146648. 0
  146649. };
  146650. static long _vq_quantlist__44u0__p7_2[] = {
  146651. 6,
  146652. 5,
  146653. 7,
  146654. 4,
  146655. 8,
  146656. 3,
  146657. 9,
  146658. 2,
  146659. 10,
  146660. 1,
  146661. 11,
  146662. 0,
  146663. 12,
  146664. };
  146665. static long _vq_lengthlist__44u0__p7_2[] = {
  146666. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146667. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146668. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146669. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146670. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146671. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146672. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146673. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146674. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146675. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146676. 9, 9, 9,10, 9, 9,10,10, 9,
  146677. };
  146678. static float _vq_quantthresh__44u0__p7_2[] = {
  146679. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146680. 2.5, 3.5, 4.5, 5.5,
  146681. };
  146682. static long _vq_quantmap__44u0__p7_2[] = {
  146683. 11, 9, 7, 5, 3, 1, 0, 2,
  146684. 4, 6, 8, 10, 12,
  146685. };
  146686. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146687. _vq_quantthresh__44u0__p7_2,
  146688. _vq_quantmap__44u0__p7_2,
  146689. 13,
  146690. 13
  146691. };
  146692. static static_codebook _44u0__p7_2 = {
  146693. 2, 169,
  146694. _vq_lengthlist__44u0__p7_2,
  146695. 1, -531103744, 1611661312, 4, 0,
  146696. _vq_quantlist__44u0__p7_2,
  146697. NULL,
  146698. &_vq_auxt__44u0__p7_2,
  146699. NULL,
  146700. 0
  146701. };
  146702. static long _huff_lengthlist__44u0__short[] = {
  146703. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146704. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146705. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146706. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146707. };
  146708. static static_codebook _huff_book__44u0__short = {
  146709. 2, 64,
  146710. _huff_lengthlist__44u0__short,
  146711. 0, 0, 0, 0, 0,
  146712. NULL,
  146713. NULL,
  146714. NULL,
  146715. NULL,
  146716. 0
  146717. };
  146718. static long _huff_lengthlist__44u1__long[] = {
  146719. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146720. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146721. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146722. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146723. };
  146724. static static_codebook _huff_book__44u1__long = {
  146725. 2, 64,
  146726. _huff_lengthlist__44u1__long,
  146727. 0, 0, 0, 0, 0,
  146728. NULL,
  146729. NULL,
  146730. NULL,
  146731. NULL,
  146732. 0
  146733. };
  146734. static long _vq_quantlist__44u1__p1_0[] = {
  146735. 1,
  146736. 0,
  146737. 2,
  146738. };
  146739. static long _vq_lengthlist__44u1__p1_0[] = {
  146740. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146741. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146742. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146743. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146744. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146745. 13,
  146746. };
  146747. static float _vq_quantthresh__44u1__p1_0[] = {
  146748. -0.5, 0.5,
  146749. };
  146750. static long _vq_quantmap__44u1__p1_0[] = {
  146751. 1, 0, 2,
  146752. };
  146753. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146754. _vq_quantthresh__44u1__p1_0,
  146755. _vq_quantmap__44u1__p1_0,
  146756. 3,
  146757. 3
  146758. };
  146759. static static_codebook _44u1__p1_0 = {
  146760. 4, 81,
  146761. _vq_lengthlist__44u1__p1_0,
  146762. 1, -535822336, 1611661312, 2, 0,
  146763. _vq_quantlist__44u1__p1_0,
  146764. NULL,
  146765. &_vq_auxt__44u1__p1_0,
  146766. NULL,
  146767. 0
  146768. };
  146769. static long _vq_quantlist__44u1__p2_0[] = {
  146770. 1,
  146771. 0,
  146772. 2,
  146773. };
  146774. static long _vq_lengthlist__44u1__p2_0[] = {
  146775. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146776. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146777. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146778. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146779. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146780. 9,
  146781. };
  146782. static float _vq_quantthresh__44u1__p2_0[] = {
  146783. -0.5, 0.5,
  146784. };
  146785. static long _vq_quantmap__44u1__p2_0[] = {
  146786. 1, 0, 2,
  146787. };
  146788. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146789. _vq_quantthresh__44u1__p2_0,
  146790. _vq_quantmap__44u1__p2_0,
  146791. 3,
  146792. 3
  146793. };
  146794. static static_codebook _44u1__p2_0 = {
  146795. 4, 81,
  146796. _vq_lengthlist__44u1__p2_0,
  146797. 1, -535822336, 1611661312, 2, 0,
  146798. _vq_quantlist__44u1__p2_0,
  146799. NULL,
  146800. &_vq_auxt__44u1__p2_0,
  146801. NULL,
  146802. 0
  146803. };
  146804. static long _vq_quantlist__44u1__p3_0[] = {
  146805. 2,
  146806. 1,
  146807. 3,
  146808. 0,
  146809. 4,
  146810. };
  146811. static long _vq_lengthlist__44u1__p3_0[] = {
  146812. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146813. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146814. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146815. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146816. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146817. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146818. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146819. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146820. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146821. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146822. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146823. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146824. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146825. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146826. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146827. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146828. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146829. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146830. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146831. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146832. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146833. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146834. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146835. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146836. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146837. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146838. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146839. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146840. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146841. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146842. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146843. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146844. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146845. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146846. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146847. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146848. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146849. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146850. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146851. 19,
  146852. };
  146853. static float _vq_quantthresh__44u1__p3_0[] = {
  146854. -1.5, -0.5, 0.5, 1.5,
  146855. };
  146856. static long _vq_quantmap__44u1__p3_0[] = {
  146857. 3, 1, 0, 2, 4,
  146858. };
  146859. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146860. _vq_quantthresh__44u1__p3_0,
  146861. _vq_quantmap__44u1__p3_0,
  146862. 5,
  146863. 5
  146864. };
  146865. static static_codebook _44u1__p3_0 = {
  146866. 4, 625,
  146867. _vq_lengthlist__44u1__p3_0,
  146868. 1, -533725184, 1611661312, 3, 0,
  146869. _vq_quantlist__44u1__p3_0,
  146870. NULL,
  146871. &_vq_auxt__44u1__p3_0,
  146872. NULL,
  146873. 0
  146874. };
  146875. static long _vq_quantlist__44u1__p4_0[] = {
  146876. 2,
  146877. 1,
  146878. 3,
  146879. 0,
  146880. 4,
  146881. };
  146882. static long _vq_lengthlist__44u1__p4_0[] = {
  146883. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146884. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146885. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146886. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146887. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146888. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146889. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146890. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146891. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146892. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146893. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146894. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146895. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146896. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146897. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146898. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146899. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146900. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146901. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146902. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146903. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146904. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146905. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146906. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146907. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146908. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146909. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146910. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146911. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146912. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146913. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146914. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146915. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146916. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146917. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146918. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146919. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146920. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146921. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146922. 12,
  146923. };
  146924. static float _vq_quantthresh__44u1__p4_0[] = {
  146925. -1.5, -0.5, 0.5, 1.5,
  146926. };
  146927. static long _vq_quantmap__44u1__p4_0[] = {
  146928. 3, 1, 0, 2, 4,
  146929. };
  146930. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146931. _vq_quantthresh__44u1__p4_0,
  146932. _vq_quantmap__44u1__p4_0,
  146933. 5,
  146934. 5
  146935. };
  146936. static static_codebook _44u1__p4_0 = {
  146937. 4, 625,
  146938. _vq_lengthlist__44u1__p4_0,
  146939. 1, -533725184, 1611661312, 3, 0,
  146940. _vq_quantlist__44u1__p4_0,
  146941. NULL,
  146942. &_vq_auxt__44u1__p4_0,
  146943. NULL,
  146944. 0
  146945. };
  146946. static long _vq_quantlist__44u1__p5_0[] = {
  146947. 4,
  146948. 3,
  146949. 5,
  146950. 2,
  146951. 6,
  146952. 1,
  146953. 7,
  146954. 0,
  146955. 8,
  146956. };
  146957. static long _vq_lengthlist__44u1__p5_0[] = {
  146958. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146959. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146960. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146961. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146962. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146963. 12,
  146964. };
  146965. static float _vq_quantthresh__44u1__p5_0[] = {
  146966. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146967. };
  146968. static long _vq_quantmap__44u1__p5_0[] = {
  146969. 7, 5, 3, 1, 0, 2, 4, 6,
  146970. 8,
  146971. };
  146972. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146973. _vq_quantthresh__44u1__p5_0,
  146974. _vq_quantmap__44u1__p5_0,
  146975. 9,
  146976. 9
  146977. };
  146978. static static_codebook _44u1__p5_0 = {
  146979. 2, 81,
  146980. _vq_lengthlist__44u1__p5_0,
  146981. 1, -531628032, 1611661312, 4, 0,
  146982. _vq_quantlist__44u1__p5_0,
  146983. NULL,
  146984. &_vq_auxt__44u1__p5_0,
  146985. NULL,
  146986. 0
  146987. };
  146988. static long _vq_quantlist__44u1__p6_0[] = {
  146989. 6,
  146990. 5,
  146991. 7,
  146992. 4,
  146993. 8,
  146994. 3,
  146995. 9,
  146996. 2,
  146997. 10,
  146998. 1,
  146999. 11,
  147000. 0,
  147001. 12,
  147002. };
  147003. static long _vq_lengthlist__44u1__p6_0[] = {
  147004. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147005. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147006. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147007. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147008. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147009. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147010. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147011. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147012. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147013. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147014. 15,17,16,17,18,17,17,18, 0,
  147015. };
  147016. static float _vq_quantthresh__44u1__p6_0[] = {
  147017. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147018. 12.5, 17.5, 22.5, 27.5,
  147019. };
  147020. static long _vq_quantmap__44u1__p6_0[] = {
  147021. 11, 9, 7, 5, 3, 1, 0, 2,
  147022. 4, 6, 8, 10, 12,
  147023. };
  147024. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147025. _vq_quantthresh__44u1__p6_0,
  147026. _vq_quantmap__44u1__p6_0,
  147027. 13,
  147028. 13
  147029. };
  147030. static static_codebook _44u1__p6_0 = {
  147031. 2, 169,
  147032. _vq_lengthlist__44u1__p6_0,
  147033. 1, -526516224, 1616117760, 4, 0,
  147034. _vq_quantlist__44u1__p6_0,
  147035. NULL,
  147036. &_vq_auxt__44u1__p6_0,
  147037. NULL,
  147038. 0
  147039. };
  147040. static long _vq_quantlist__44u1__p6_1[] = {
  147041. 2,
  147042. 1,
  147043. 3,
  147044. 0,
  147045. 4,
  147046. };
  147047. static long _vq_lengthlist__44u1__p6_1[] = {
  147048. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147049. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147050. };
  147051. static float _vq_quantthresh__44u1__p6_1[] = {
  147052. -1.5, -0.5, 0.5, 1.5,
  147053. };
  147054. static long _vq_quantmap__44u1__p6_1[] = {
  147055. 3, 1, 0, 2, 4,
  147056. };
  147057. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147058. _vq_quantthresh__44u1__p6_1,
  147059. _vq_quantmap__44u1__p6_1,
  147060. 5,
  147061. 5
  147062. };
  147063. static static_codebook _44u1__p6_1 = {
  147064. 2, 25,
  147065. _vq_lengthlist__44u1__p6_1,
  147066. 1, -533725184, 1611661312, 3, 0,
  147067. _vq_quantlist__44u1__p6_1,
  147068. NULL,
  147069. &_vq_auxt__44u1__p6_1,
  147070. NULL,
  147071. 0
  147072. };
  147073. static long _vq_quantlist__44u1__p7_0[] = {
  147074. 3,
  147075. 2,
  147076. 4,
  147077. 1,
  147078. 5,
  147079. 0,
  147080. 6,
  147081. };
  147082. static long _vq_lengthlist__44u1__p7_0[] = {
  147083. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147084. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147085. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147086. 8,
  147087. };
  147088. static float _vq_quantthresh__44u1__p7_0[] = {
  147089. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147090. };
  147091. static long _vq_quantmap__44u1__p7_0[] = {
  147092. 5, 3, 1, 0, 2, 4, 6,
  147093. };
  147094. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147095. _vq_quantthresh__44u1__p7_0,
  147096. _vq_quantmap__44u1__p7_0,
  147097. 7,
  147098. 7
  147099. };
  147100. static static_codebook _44u1__p7_0 = {
  147101. 2, 49,
  147102. _vq_lengthlist__44u1__p7_0,
  147103. 1, -518017024, 1626677248, 3, 0,
  147104. _vq_quantlist__44u1__p7_0,
  147105. NULL,
  147106. &_vq_auxt__44u1__p7_0,
  147107. NULL,
  147108. 0
  147109. };
  147110. static long _vq_quantlist__44u1__p7_1[] = {
  147111. 6,
  147112. 5,
  147113. 7,
  147114. 4,
  147115. 8,
  147116. 3,
  147117. 9,
  147118. 2,
  147119. 10,
  147120. 1,
  147121. 11,
  147122. 0,
  147123. 12,
  147124. };
  147125. static long _vq_lengthlist__44u1__p7_1[] = {
  147126. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147127. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147128. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147129. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147130. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147131. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147132. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147133. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147134. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147135. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147136. 15,15,15,15,15,15,15,15,15,
  147137. };
  147138. static float _vq_quantthresh__44u1__p7_1[] = {
  147139. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147140. 32.5, 45.5, 58.5, 71.5,
  147141. };
  147142. static long _vq_quantmap__44u1__p7_1[] = {
  147143. 11, 9, 7, 5, 3, 1, 0, 2,
  147144. 4, 6, 8, 10, 12,
  147145. };
  147146. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147147. _vq_quantthresh__44u1__p7_1,
  147148. _vq_quantmap__44u1__p7_1,
  147149. 13,
  147150. 13
  147151. };
  147152. static static_codebook _44u1__p7_1 = {
  147153. 2, 169,
  147154. _vq_lengthlist__44u1__p7_1,
  147155. 1, -523010048, 1618608128, 4, 0,
  147156. _vq_quantlist__44u1__p7_1,
  147157. NULL,
  147158. &_vq_auxt__44u1__p7_1,
  147159. NULL,
  147160. 0
  147161. };
  147162. static long _vq_quantlist__44u1__p7_2[] = {
  147163. 6,
  147164. 5,
  147165. 7,
  147166. 4,
  147167. 8,
  147168. 3,
  147169. 9,
  147170. 2,
  147171. 10,
  147172. 1,
  147173. 11,
  147174. 0,
  147175. 12,
  147176. };
  147177. static long _vq_lengthlist__44u1__p7_2[] = {
  147178. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147179. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147180. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147181. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147182. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147183. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147184. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147185. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147186. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147187. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147188. 9, 9, 9,10, 9, 9,10,10, 9,
  147189. };
  147190. static float _vq_quantthresh__44u1__p7_2[] = {
  147191. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147192. 2.5, 3.5, 4.5, 5.5,
  147193. };
  147194. static long _vq_quantmap__44u1__p7_2[] = {
  147195. 11, 9, 7, 5, 3, 1, 0, 2,
  147196. 4, 6, 8, 10, 12,
  147197. };
  147198. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147199. _vq_quantthresh__44u1__p7_2,
  147200. _vq_quantmap__44u1__p7_2,
  147201. 13,
  147202. 13
  147203. };
  147204. static static_codebook _44u1__p7_2 = {
  147205. 2, 169,
  147206. _vq_lengthlist__44u1__p7_2,
  147207. 1, -531103744, 1611661312, 4, 0,
  147208. _vq_quantlist__44u1__p7_2,
  147209. NULL,
  147210. &_vq_auxt__44u1__p7_2,
  147211. NULL,
  147212. 0
  147213. };
  147214. static long _huff_lengthlist__44u1__short[] = {
  147215. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147216. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147217. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147218. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147219. };
  147220. static static_codebook _huff_book__44u1__short = {
  147221. 2, 64,
  147222. _huff_lengthlist__44u1__short,
  147223. 0, 0, 0, 0, 0,
  147224. NULL,
  147225. NULL,
  147226. NULL,
  147227. NULL,
  147228. 0
  147229. };
  147230. static long _huff_lengthlist__44u2__long[] = {
  147231. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147232. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147233. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147234. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147235. };
  147236. static static_codebook _huff_book__44u2__long = {
  147237. 2, 64,
  147238. _huff_lengthlist__44u2__long,
  147239. 0, 0, 0, 0, 0,
  147240. NULL,
  147241. NULL,
  147242. NULL,
  147243. NULL,
  147244. 0
  147245. };
  147246. static long _vq_quantlist__44u2__p1_0[] = {
  147247. 1,
  147248. 0,
  147249. 2,
  147250. };
  147251. static long _vq_lengthlist__44u2__p1_0[] = {
  147252. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147253. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147254. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147255. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147256. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147257. 13,
  147258. };
  147259. static float _vq_quantthresh__44u2__p1_0[] = {
  147260. -0.5, 0.5,
  147261. };
  147262. static long _vq_quantmap__44u2__p1_0[] = {
  147263. 1, 0, 2,
  147264. };
  147265. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147266. _vq_quantthresh__44u2__p1_0,
  147267. _vq_quantmap__44u2__p1_0,
  147268. 3,
  147269. 3
  147270. };
  147271. static static_codebook _44u2__p1_0 = {
  147272. 4, 81,
  147273. _vq_lengthlist__44u2__p1_0,
  147274. 1, -535822336, 1611661312, 2, 0,
  147275. _vq_quantlist__44u2__p1_0,
  147276. NULL,
  147277. &_vq_auxt__44u2__p1_0,
  147278. NULL,
  147279. 0
  147280. };
  147281. static long _vq_quantlist__44u2__p2_0[] = {
  147282. 1,
  147283. 0,
  147284. 2,
  147285. };
  147286. static long _vq_lengthlist__44u2__p2_0[] = {
  147287. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147288. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147289. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147290. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147291. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147292. 9,
  147293. };
  147294. static float _vq_quantthresh__44u2__p2_0[] = {
  147295. -0.5, 0.5,
  147296. };
  147297. static long _vq_quantmap__44u2__p2_0[] = {
  147298. 1, 0, 2,
  147299. };
  147300. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147301. _vq_quantthresh__44u2__p2_0,
  147302. _vq_quantmap__44u2__p2_0,
  147303. 3,
  147304. 3
  147305. };
  147306. static static_codebook _44u2__p2_0 = {
  147307. 4, 81,
  147308. _vq_lengthlist__44u2__p2_0,
  147309. 1, -535822336, 1611661312, 2, 0,
  147310. _vq_quantlist__44u2__p2_0,
  147311. NULL,
  147312. &_vq_auxt__44u2__p2_0,
  147313. NULL,
  147314. 0
  147315. };
  147316. static long _vq_quantlist__44u2__p3_0[] = {
  147317. 2,
  147318. 1,
  147319. 3,
  147320. 0,
  147321. 4,
  147322. };
  147323. static long _vq_lengthlist__44u2__p3_0[] = {
  147324. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147325. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147326. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147327. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147328. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147329. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147330. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147331. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147332. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147333. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147334. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147335. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147336. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147337. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147338. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147339. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147340. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147341. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147342. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147343. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147344. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147345. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147346. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147347. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147348. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147349. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147350. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147351. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147352. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147353. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147354. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147355. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147356. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147357. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147358. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147359. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147360. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147361. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147362. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147363. 0,
  147364. };
  147365. static float _vq_quantthresh__44u2__p3_0[] = {
  147366. -1.5, -0.5, 0.5, 1.5,
  147367. };
  147368. static long _vq_quantmap__44u2__p3_0[] = {
  147369. 3, 1, 0, 2, 4,
  147370. };
  147371. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147372. _vq_quantthresh__44u2__p3_0,
  147373. _vq_quantmap__44u2__p3_0,
  147374. 5,
  147375. 5
  147376. };
  147377. static static_codebook _44u2__p3_0 = {
  147378. 4, 625,
  147379. _vq_lengthlist__44u2__p3_0,
  147380. 1, -533725184, 1611661312, 3, 0,
  147381. _vq_quantlist__44u2__p3_0,
  147382. NULL,
  147383. &_vq_auxt__44u2__p3_0,
  147384. NULL,
  147385. 0
  147386. };
  147387. static long _vq_quantlist__44u2__p4_0[] = {
  147388. 2,
  147389. 1,
  147390. 3,
  147391. 0,
  147392. 4,
  147393. };
  147394. static long _vq_lengthlist__44u2__p4_0[] = {
  147395. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147396. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147397. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147398. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147399. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147400. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147401. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147402. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147403. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147404. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147405. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147406. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147407. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147408. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147409. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147410. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147411. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147412. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147413. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147414. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147415. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147416. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147417. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147418. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147419. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147420. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147421. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147422. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147423. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147424. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147425. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147426. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147427. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147428. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147429. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147430. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147431. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147432. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147433. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147434. 13,
  147435. };
  147436. static float _vq_quantthresh__44u2__p4_0[] = {
  147437. -1.5, -0.5, 0.5, 1.5,
  147438. };
  147439. static long _vq_quantmap__44u2__p4_0[] = {
  147440. 3, 1, 0, 2, 4,
  147441. };
  147442. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147443. _vq_quantthresh__44u2__p4_0,
  147444. _vq_quantmap__44u2__p4_0,
  147445. 5,
  147446. 5
  147447. };
  147448. static static_codebook _44u2__p4_0 = {
  147449. 4, 625,
  147450. _vq_lengthlist__44u2__p4_0,
  147451. 1, -533725184, 1611661312, 3, 0,
  147452. _vq_quantlist__44u2__p4_0,
  147453. NULL,
  147454. &_vq_auxt__44u2__p4_0,
  147455. NULL,
  147456. 0
  147457. };
  147458. static long _vq_quantlist__44u2__p5_0[] = {
  147459. 4,
  147460. 3,
  147461. 5,
  147462. 2,
  147463. 6,
  147464. 1,
  147465. 7,
  147466. 0,
  147467. 8,
  147468. };
  147469. static long _vq_lengthlist__44u2__p5_0[] = {
  147470. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147471. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147472. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147473. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147474. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147475. 13,
  147476. };
  147477. static float _vq_quantthresh__44u2__p5_0[] = {
  147478. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147479. };
  147480. static long _vq_quantmap__44u2__p5_0[] = {
  147481. 7, 5, 3, 1, 0, 2, 4, 6,
  147482. 8,
  147483. };
  147484. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147485. _vq_quantthresh__44u2__p5_0,
  147486. _vq_quantmap__44u2__p5_0,
  147487. 9,
  147488. 9
  147489. };
  147490. static static_codebook _44u2__p5_0 = {
  147491. 2, 81,
  147492. _vq_lengthlist__44u2__p5_0,
  147493. 1, -531628032, 1611661312, 4, 0,
  147494. _vq_quantlist__44u2__p5_0,
  147495. NULL,
  147496. &_vq_auxt__44u2__p5_0,
  147497. NULL,
  147498. 0
  147499. };
  147500. static long _vq_quantlist__44u2__p6_0[] = {
  147501. 6,
  147502. 5,
  147503. 7,
  147504. 4,
  147505. 8,
  147506. 3,
  147507. 9,
  147508. 2,
  147509. 10,
  147510. 1,
  147511. 11,
  147512. 0,
  147513. 12,
  147514. };
  147515. static long _vq_lengthlist__44u2__p6_0[] = {
  147516. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147517. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147518. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147519. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147520. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147521. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147522. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147523. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147524. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147525. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147526. 15,17,17,16,18,17,18, 0, 0,
  147527. };
  147528. static float _vq_quantthresh__44u2__p6_0[] = {
  147529. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147530. 12.5, 17.5, 22.5, 27.5,
  147531. };
  147532. static long _vq_quantmap__44u2__p6_0[] = {
  147533. 11, 9, 7, 5, 3, 1, 0, 2,
  147534. 4, 6, 8, 10, 12,
  147535. };
  147536. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147537. _vq_quantthresh__44u2__p6_0,
  147538. _vq_quantmap__44u2__p6_0,
  147539. 13,
  147540. 13
  147541. };
  147542. static static_codebook _44u2__p6_0 = {
  147543. 2, 169,
  147544. _vq_lengthlist__44u2__p6_0,
  147545. 1, -526516224, 1616117760, 4, 0,
  147546. _vq_quantlist__44u2__p6_0,
  147547. NULL,
  147548. &_vq_auxt__44u2__p6_0,
  147549. NULL,
  147550. 0
  147551. };
  147552. static long _vq_quantlist__44u2__p6_1[] = {
  147553. 2,
  147554. 1,
  147555. 3,
  147556. 0,
  147557. 4,
  147558. };
  147559. static long _vq_lengthlist__44u2__p6_1[] = {
  147560. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147561. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147562. };
  147563. static float _vq_quantthresh__44u2__p6_1[] = {
  147564. -1.5, -0.5, 0.5, 1.5,
  147565. };
  147566. static long _vq_quantmap__44u2__p6_1[] = {
  147567. 3, 1, 0, 2, 4,
  147568. };
  147569. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147570. _vq_quantthresh__44u2__p6_1,
  147571. _vq_quantmap__44u2__p6_1,
  147572. 5,
  147573. 5
  147574. };
  147575. static static_codebook _44u2__p6_1 = {
  147576. 2, 25,
  147577. _vq_lengthlist__44u2__p6_1,
  147578. 1, -533725184, 1611661312, 3, 0,
  147579. _vq_quantlist__44u2__p6_1,
  147580. NULL,
  147581. &_vq_auxt__44u2__p6_1,
  147582. NULL,
  147583. 0
  147584. };
  147585. static long _vq_quantlist__44u2__p7_0[] = {
  147586. 4,
  147587. 3,
  147588. 5,
  147589. 2,
  147590. 6,
  147591. 1,
  147592. 7,
  147593. 0,
  147594. 8,
  147595. };
  147596. static long _vq_lengthlist__44u2__p7_0[] = {
  147597. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147598. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147602. 11,
  147603. };
  147604. static float _vq_quantthresh__44u2__p7_0[] = {
  147605. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147606. };
  147607. static long _vq_quantmap__44u2__p7_0[] = {
  147608. 7, 5, 3, 1, 0, 2, 4, 6,
  147609. 8,
  147610. };
  147611. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147612. _vq_quantthresh__44u2__p7_0,
  147613. _vq_quantmap__44u2__p7_0,
  147614. 9,
  147615. 9
  147616. };
  147617. static static_codebook _44u2__p7_0 = {
  147618. 2, 81,
  147619. _vq_lengthlist__44u2__p7_0,
  147620. 1, -516612096, 1626677248, 4, 0,
  147621. _vq_quantlist__44u2__p7_0,
  147622. NULL,
  147623. &_vq_auxt__44u2__p7_0,
  147624. NULL,
  147625. 0
  147626. };
  147627. static long _vq_quantlist__44u2__p7_1[] = {
  147628. 6,
  147629. 5,
  147630. 7,
  147631. 4,
  147632. 8,
  147633. 3,
  147634. 9,
  147635. 2,
  147636. 10,
  147637. 1,
  147638. 11,
  147639. 0,
  147640. 12,
  147641. };
  147642. static long _vq_lengthlist__44u2__p7_1[] = {
  147643. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147644. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147645. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147646. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147647. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147648. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147649. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147650. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147651. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147652. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147653. 14,14,14,17,15,17,17,17,17,
  147654. };
  147655. static float _vq_quantthresh__44u2__p7_1[] = {
  147656. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147657. 32.5, 45.5, 58.5, 71.5,
  147658. };
  147659. static long _vq_quantmap__44u2__p7_1[] = {
  147660. 11, 9, 7, 5, 3, 1, 0, 2,
  147661. 4, 6, 8, 10, 12,
  147662. };
  147663. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147664. _vq_quantthresh__44u2__p7_1,
  147665. _vq_quantmap__44u2__p7_1,
  147666. 13,
  147667. 13
  147668. };
  147669. static static_codebook _44u2__p7_1 = {
  147670. 2, 169,
  147671. _vq_lengthlist__44u2__p7_1,
  147672. 1, -523010048, 1618608128, 4, 0,
  147673. _vq_quantlist__44u2__p7_1,
  147674. NULL,
  147675. &_vq_auxt__44u2__p7_1,
  147676. NULL,
  147677. 0
  147678. };
  147679. static long _vq_quantlist__44u2__p7_2[] = {
  147680. 6,
  147681. 5,
  147682. 7,
  147683. 4,
  147684. 8,
  147685. 3,
  147686. 9,
  147687. 2,
  147688. 10,
  147689. 1,
  147690. 11,
  147691. 0,
  147692. 12,
  147693. };
  147694. static long _vq_lengthlist__44u2__p7_2[] = {
  147695. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147696. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147697. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147698. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147699. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147700. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147701. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147702. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147703. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147705. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147706. };
  147707. static float _vq_quantthresh__44u2__p7_2[] = {
  147708. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147709. 2.5, 3.5, 4.5, 5.5,
  147710. };
  147711. static long _vq_quantmap__44u2__p7_2[] = {
  147712. 11, 9, 7, 5, 3, 1, 0, 2,
  147713. 4, 6, 8, 10, 12,
  147714. };
  147715. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147716. _vq_quantthresh__44u2__p7_2,
  147717. _vq_quantmap__44u2__p7_2,
  147718. 13,
  147719. 13
  147720. };
  147721. static static_codebook _44u2__p7_2 = {
  147722. 2, 169,
  147723. _vq_lengthlist__44u2__p7_2,
  147724. 1, -531103744, 1611661312, 4, 0,
  147725. _vq_quantlist__44u2__p7_2,
  147726. NULL,
  147727. &_vq_auxt__44u2__p7_2,
  147728. NULL,
  147729. 0
  147730. };
  147731. static long _huff_lengthlist__44u2__short[] = {
  147732. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147733. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147734. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147735. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147736. };
  147737. static static_codebook _huff_book__44u2__short = {
  147738. 2, 64,
  147739. _huff_lengthlist__44u2__short,
  147740. 0, 0, 0, 0, 0,
  147741. NULL,
  147742. NULL,
  147743. NULL,
  147744. NULL,
  147745. 0
  147746. };
  147747. static long _huff_lengthlist__44u3__long[] = {
  147748. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147749. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147750. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147751. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147752. };
  147753. static static_codebook _huff_book__44u3__long = {
  147754. 2, 64,
  147755. _huff_lengthlist__44u3__long,
  147756. 0, 0, 0, 0, 0,
  147757. NULL,
  147758. NULL,
  147759. NULL,
  147760. NULL,
  147761. 0
  147762. };
  147763. static long _vq_quantlist__44u3__p1_0[] = {
  147764. 1,
  147765. 0,
  147766. 2,
  147767. };
  147768. static long _vq_lengthlist__44u3__p1_0[] = {
  147769. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147770. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147771. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147772. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147773. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147774. 13,
  147775. };
  147776. static float _vq_quantthresh__44u3__p1_0[] = {
  147777. -0.5, 0.5,
  147778. };
  147779. static long _vq_quantmap__44u3__p1_0[] = {
  147780. 1, 0, 2,
  147781. };
  147782. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147783. _vq_quantthresh__44u3__p1_0,
  147784. _vq_quantmap__44u3__p1_0,
  147785. 3,
  147786. 3
  147787. };
  147788. static static_codebook _44u3__p1_0 = {
  147789. 4, 81,
  147790. _vq_lengthlist__44u3__p1_0,
  147791. 1, -535822336, 1611661312, 2, 0,
  147792. _vq_quantlist__44u3__p1_0,
  147793. NULL,
  147794. &_vq_auxt__44u3__p1_0,
  147795. NULL,
  147796. 0
  147797. };
  147798. static long _vq_quantlist__44u3__p2_0[] = {
  147799. 1,
  147800. 0,
  147801. 2,
  147802. };
  147803. static long _vq_lengthlist__44u3__p2_0[] = {
  147804. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147805. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147806. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147807. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147808. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147809. 9,
  147810. };
  147811. static float _vq_quantthresh__44u3__p2_0[] = {
  147812. -0.5, 0.5,
  147813. };
  147814. static long _vq_quantmap__44u3__p2_0[] = {
  147815. 1, 0, 2,
  147816. };
  147817. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147818. _vq_quantthresh__44u3__p2_0,
  147819. _vq_quantmap__44u3__p2_0,
  147820. 3,
  147821. 3
  147822. };
  147823. static static_codebook _44u3__p2_0 = {
  147824. 4, 81,
  147825. _vq_lengthlist__44u3__p2_0,
  147826. 1, -535822336, 1611661312, 2, 0,
  147827. _vq_quantlist__44u3__p2_0,
  147828. NULL,
  147829. &_vq_auxt__44u3__p2_0,
  147830. NULL,
  147831. 0
  147832. };
  147833. static long _vq_quantlist__44u3__p3_0[] = {
  147834. 2,
  147835. 1,
  147836. 3,
  147837. 0,
  147838. 4,
  147839. };
  147840. static long _vq_lengthlist__44u3__p3_0[] = {
  147841. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147842. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147843. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147844. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147845. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147846. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147847. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147848. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147849. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147850. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147851. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147852. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147853. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147854. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147855. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147856. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147857. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147858. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147859. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147860. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147861. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147862. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147863. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147864. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147865. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147866. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147867. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147868. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147869. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147870. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147871. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147872. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147873. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147874. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147875. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147876. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147877. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147878. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147879. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147880. 0,
  147881. };
  147882. static float _vq_quantthresh__44u3__p3_0[] = {
  147883. -1.5, -0.5, 0.5, 1.5,
  147884. };
  147885. static long _vq_quantmap__44u3__p3_0[] = {
  147886. 3, 1, 0, 2, 4,
  147887. };
  147888. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147889. _vq_quantthresh__44u3__p3_0,
  147890. _vq_quantmap__44u3__p3_0,
  147891. 5,
  147892. 5
  147893. };
  147894. static static_codebook _44u3__p3_0 = {
  147895. 4, 625,
  147896. _vq_lengthlist__44u3__p3_0,
  147897. 1, -533725184, 1611661312, 3, 0,
  147898. _vq_quantlist__44u3__p3_0,
  147899. NULL,
  147900. &_vq_auxt__44u3__p3_0,
  147901. NULL,
  147902. 0
  147903. };
  147904. static long _vq_quantlist__44u3__p4_0[] = {
  147905. 2,
  147906. 1,
  147907. 3,
  147908. 0,
  147909. 4,
  147910. };
  147911. static long _vq_lengthlist__44u3__p4_0[] = {
  147912. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147913. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147914. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147915. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147916. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147917. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147918. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147919. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147920. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147921. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147922. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147923. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147924. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147925. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147926. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147927. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147928. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147929. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147930. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147931. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147932. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147933. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147934. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147935. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147936. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147937. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147938. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147939. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147940. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147941. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147942. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147943. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147944. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147945. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147946. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147947. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147948. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147949. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147950. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147951. 13,
  147952. };
  147953. static float _vq_quantthresh__44u3__p4_0[] = {
  147954. -1.5, -0.5, 0.5, 1.5,
  147955. };
  147956. static long _vq_quantmap__44u3__p4_0[] = {
  147957. 3, 1, 0, 2, 4,
  147958. };
  147959. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147960. _vq_quantthresh__44u3__p4_0,
  147961. _vq_quantmap__44u3__p4_0,
  147962. 5,
  147963. 5
  147964. };
  147965. static static_codebook _44u3__p4_0 = {
  147966. 4, 625,
  147967. _vq_lengthlist__44u3__p4_0,
  147968. 1, -533725184, 1611661312, 3, 0,
  147969. _vq_quantlist__44u3__p4_0,
  147970. NULL,
  147971. &_vq_auxt__44u3__p4_0,
  147972. NULL,
  147973. 0
  147974. };
  147975. static long _vq_quantlist__44u3__p5_0[] = {
  147976. 4,
  147977. 3,
  147978. 5,
  147979. 2,
  147980. 6,
  147981. 1,
  147982. 7,
  147983. 0,
  147984. 8,
  147985. };
  147986. static long _vq_lengthlist__44u3__p5_0[] = {
  147987. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147988. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147989. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147990. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147991. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147992. 12,
  147993. };
  147994. static float _vq_quantthresh__44u3__p5_0[] = {
  147995. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147996. };
  147997. static long _vq_quantmap__44u3__p5_0[] = {
  147998. 7, 5, 3, 1, 0, 2, 4, 6,
  147999. 8,
  148000. };
  148001. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148002. _vq_quantthresh__44u3__p5_0,
  148003. _vq_quantmap__44u3__p5_0,
  148004. 9,
  148005. 9
  148006. };
  148007. static static_codebook _44u3__p5_0 = {
  148008. 2, 81,
  148009. _vq_lengthlist__44u3__p5_0,
  148010. 1, -531628032, 1611661312, 4, 0,
  148011. _vq_quantlist__44u3__p5_0,
  148012. NULL,
  148013. &_vq_auxt__44u3__p5_0,
  148014. NULL,
  148015. 0
  148016. };
  148017. static long _vq_quantlist__44u3__p6_0[] = {
  148018. 6,
  148019. 5,
  148020. 7,
  148021. 4,
  148022. 8,
  148023. 3,
  148024. 9,
  148025. 2,
  148026. 10,
  148027. 1,
  148028. 11,
  148029. 0,
  148030. 12,
  148031. };
  148032. static long _vq_lengthlist__44u3__p6_0[] = {
  148033. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148034. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148035. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148036. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148037. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148038. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148039. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148040. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148041. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148042. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148043. 15,16,16,16,17,18,16,20,18,
  148044. };
  148045. static float _vq_quantthresh__44u3__p6_0[] = {
  148046. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148047. 12.5, 17.5, 22.5, 27.5,
  148048. };
  148049. static long _vq_quantmap__44u3__p6_0[] = {
  148050. 11, 9, 7, 5, 3, 1, 0, 2,
  148051. 4, 6, 8, 10, 12,
  148052. };
  148053. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148054. _vq_quantthresh__44u3__p6_0,
  148055. _vq_quantmap__44u3__p6_0,
  148056. 13,
  148057. 13
  148058. };
  148059. static static_codebook _44u3__p6_0 = {
  148060. 2, 169,
  148061. _vq_lengthlist__44u3__p6_0,
  148062. 1, -526516224, 1616117760, 4, 0,
  148063. _vq_quantlist__44u3__p6_0,
  148064. NULL,
  148065. &_vq_auxt__44u3__p6_0,
  148066. NULL,
  148067. 0
  148068. };
  148069. static long _vq_quantlist__44u3__p6_1[] = {
  148070. 2,
  148071. 1,
  148072. 3,
  148073. 0,
  148074. 4,
  148075. };
  148076. static long _vq_lengthlist__44u3__p6_1[] = {
  148077. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148078. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148079. };
  148080. static float _vq_quantthresh__44u3__p6_1[] = {
  148081. -1.5, -0.5, 0.5, 1.5,
  148082. };
  148083. static long _vq_quantmap__44u3__p6_1[] = {
  148084. 3, 1, 0, 2, 4,
  148085. };
  148086. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148087. _vq_quantthresh__44u3__p6_1,
  148088. _vq_quantmap__44u3__p6_1,
  148089. 5,
  148090. 5
  148091. };
  148092. static static_codebook _44u3__p6_1 = {
  148093. 2, 25,
  148094. _vq_lengthlist__44u3__p6_1,
  148095. 1, -533725184, 1611661312, 3, 0,
  148096. _vq_quantlist__44u3__p6_1,
  148097. NULL,
  148098. &_vq_auxt__44u3__p6_1,
  148099. NULL,
  148100. 0
  148101. };
  148102. static long _vq_quantlist__44u3__p7_0[] = {
  148103. 4,
  148104. 3,
  148105. 5,
  148106. 2,
  148107. 6,
  148108. 1,
  148109. 7,
  148110. 0,
  148111. 8,
  148112. };
  148113. static long _vq_lengthlist__44u3__p7_0[] = {
  148114. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148115. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148116. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148117. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148118. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148119. 9,
  148120. };
  148121. static float _vq_quantthresh__44u3__p7_0[] = {
  148122. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148123. };
  148124. static long _vq_quantmap__44u3__p7_0[] = {
  148125. 7, 5, 3, 1, 0, 2, 4, 6,
  148126. 8,
  148127. };
  148128. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148129. _vq_quantthresh__44u3__p7_0,
  148130. _vq_quantmap__44u3__p7_0,
  148131. 9,
  148132. 9
  148133. };
  148134. static static_codebook _44u3__p7_0 = {
  148135. 2, 81,
  148136. _vq_lengthlist__44u3__p7_0,
  148137. 1, -515907584, 1627381760, 4, 0,
  148138. _vq_quantlist__44u3__p7_0,
  148139. NULL,
  148140. &_vq_auxt__44u3__p7_0,
  148141. NULL,
  148142. 0
  148143. };
  148144. static long _vq_quantlist__44u3__p7_1[] = {
  148145. 7,
  148146. 6,
  148147. 8,
  148148. 5,
  148149. 9,
  148150. 4,
  148151. 10,
  148152. 3,
  148153. 11,
  148154. 2,
  148155. 12,
  148156. 1,
  148157. 13,
  148158. 0,
  148159. 14,
  148160. };
  148161. static long _vq_lengthlist__44u3__p7_1[] = {
  148162. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148163. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148164. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148165. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148166. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148167. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148168. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148169. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148170. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148171. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148172. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148173. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148174. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148175. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148176. 17,
  148177. };
  148178. static float _vq_quantthresh__44u3__p7_1[] = {
  148179. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148180. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148181. };
  148182. static long _vq_quantmap__44u3__p7_1[] = {
  148183. 13, 11, 9, 7, 5, 3, 1, 0,
  148184. 2, 4, 6, 8, 10, 12, 14,
  148185. };
  148186. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148187. _vq_quantthresh__44u3__p7_1,
  148188. _vq_quantmap__44u3__p7_1,
  148189. 15,
  148190. 15
  148191. };
  148192. static static_codebook _44u3__p7_1 = {
  148193. 2, 225,
  148194. _vq_lengthlist__44u3__p7_1,
  148195. 1, -522338304, 1620115456, 4, 0,
  148196. _vq_quantlist__44u3__p7_1,
  148197. NULL,
  148198. &_vq_auxt__44u3__p7_1,
  148199. NULL,
  148200. 0
  148201. };
  148202. static long _vq_quantlist__44u3__p7_2[] = {
  148203. 8,
  148204. 7,
  148205. 9,
  148206. 6,
  148207. 10,
  148208. 5,
  148209. 11,
  148210. 4,
  148211. 12,
  148212. 3,
  148213. 13,
  148214. 2,
  148215. 14,
  148216. 1,
  148217. 15,
  148218. 0,
  148219. 16,
  148220. };
  148221. static long _vq_lengthlist__44u3__p7_2[] = {
  148222. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148223. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148224. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148225. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148226. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148227. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148228. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148229. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148230. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148231. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148232. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148233. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148234. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148235. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148236. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148239. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148240. 11,
  148241. };
  148242. static float _vq_quantthresh__44u3__p7_2[] = {
  148243. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148244. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148245. };
  148246. static long _vq_quantmap__44u3__p7_2[] = {
  148247. 15, 13, 11, 9, 7, 5, 3, 1,
  148248. 0, 2, 4, 6, 8, 10, 12, 14,
  148249. 16,
  148250. };
  148251. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148252. _vq_quantthresh__44u3__p7_2,
  148253. _vq_quantmap__44u3__p7_2,
  148254. 17,
  148255. 17
  148256. };
  148257. static static_codebook _44u3__p7_2 = {
  148258. 2, 289,
  148259. _vq_lengthlist__44u3__p7_2,
  148260. 1, -529530880, 1611661312, 5, 0,
  148261. _vq_quantlist__44u3__p7_2,
  148262. NULL,
  148263. &_vq_auxt__44u3__p7_2,
  148264. NULL,
  148265. 0
  148266. };
  148267. static long _huff_lengthlist__44u3__short[] = {
  148268. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148269. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148270. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148271. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148272. };
  148273. static static_codebook _huff_book__44u3__short = {
  148274. 2, 64,
  148275. _huff_lengthlist__44u3__short,
  148276. 0, 0, 0, 0, 0,
  148277. NULL,
  148278. NULL,
  148279. NULL,
  148280. NULL,
  148281. 0
  148282. };
  148283. static long _huff_lengthlist__44u4__long[] = {
  148284. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148285. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148286. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148287. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148288. };
  148289. static static_codebook _huff_book__44u4__long = {
  148290. 2, 64,
  148291. _huff_lengthlist__44u4__long,
  148292. 0, 0, 0, 0, 0,
  148293. NULL,
  148294. NULL,
  148295. NULL,
  148296. NULL,
  148297. 0
  148298. };
  148299. static long _vq_quantlist__44u4__p1_0[] = {
  148300. 1,
  148301. 0,
  148302. 2,
  148303. };
  148304. static long _vq_lengthlist__44u4__p1_0[] = {
  148305. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148306. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148307. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148308. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148309. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148310. 13,
  148311. };
  148312. static float _vq_quantthresh__44u4__p1_0[] = {
  148313. -0.5, 0.5,
  148314. };
  148315. static long _vq_quantmap__44u4__p1_0[] = {
  148316. 1, 0, 2,
  148317. };
  148318. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148319. _vq_quantthresh__44u4__p1_0,
  148320. _vq_quantmap__44u4__p1_0,
  148321. 3,
  148322. 3
  148323. };
  148324. static static_codebook _44u4__p1_0 = {
  148325. 4, 81,
  148326. _vq_lengthlist__44u4__p1_0,
  148327. 1, -535822336, 1611661312, 2, 0,
  148328. _vq_quantlist__44u4__p1_0,
  148329. NULL,
  148330. &_vq_auxt__44u4__p1_0,
  148331. NULL,
  148332. 0
  148333. };
  148334. static long _vq_quantlist__44u4__p2_0[] = {
  148335. 1,
  148336. 0,
  148337. 2,
  148338. };
  148339. static long _vq_lengthlist__44u4__p2_0[] = {
  148340. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148341. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148342. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148343. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148344. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148345. 9,
  148346. };
  148347. static float _vq_quantthresh__44u4__p2_0[] = {
  148348. -0.5, 0.5,
  148349. };
  148350. static long _vq_quantmap__44u4__p2_0[] = {
  148351. 1, 0, 2,
  148352. };
  148353. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148354. _vq_quantthresh__44u4__p2_0,
  148355. _vq_quantmap__44u4__p2_0,
  148356. 3,
  148357. 3
  148358. };
  148359. static static_codebook _44u4__p2_0 = {
  148360. 4, 81,
  148361. _vq_lengthlist__44u4__p2_0,
  148362. 1, -535822336, 1611661312, 2, 0,
  148363. _vq_quantlist__44u4__p2_0,
  148364. NULL,
  148365. &_vq_auxt__44u4__p2_0,
  148366. NULL,
  148367. 0
  148368. };
  148369. static long _vq_quantlist__44u4__p3_0[] = {
  148370. 2,
  148371. 1,
  148372. 3,
  148373. 0,
  148374. 4,
  148375. };
  148376. static long _vq_lengthlist__44u4__p3_0[] = {
  148377. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148378. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148379. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148380. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148381. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148382. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148383. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148384. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148385. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148386. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148387. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148388. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148389. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148390. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148391. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148392. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148393. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148394. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148395. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148396. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148397. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148398. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148399. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148400. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148401. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148402. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148403. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148404. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148405. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148406. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148407. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148408. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148409. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148410. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148411. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148412. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148413. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148414. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148415. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148416. 0,
  148417. };
  148418. static float _vq_quantthresh__44u4__p3_0[] = {
  148419. -1.5, -0.5, 0.5, 1.5,
  148420. };
  148421. static long _vq_quantmap__44u4__p3_0[] = {
  148422. 3, 1, 0, 2, 4,
  148423. };
  148424. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148425. _vq_quantthresh__44u4__p3_0,
  148426. _vq_quantmap__44u4__p3_0,
  148427. 5,
  148428. 5
  148429. };
  148430. static static_codebook _44u4__p3_0 = {
  148431. 4, 625,
  148432. _vq_lengthlist__44u4__p3_0,
  148433. 1, -533725184, 1611661312, 3, 0,
  148434. _vq_quantlist__44u4__p3_0,
  148435. NULL,
  148436. &_vq_auxt__44u4__p3_0,
  148437. NULL,
  148438. 0
  148439. };
  148440. static long _vq_quantlist__44u4__p4_0[] = {
  148441. 2,
  148442. 1,
  148443. 3,
  148444. 0,
  148445. 4,
  148446. };
  148447. static long _vq_lengthlist__44u4__p4_0[] = {
  148448. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148449. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148450. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148451. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148452. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148453. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148454. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148455. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148456. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148457. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148458. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148459. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148460. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148461. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148462. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148463. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148464. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148465. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148466. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148467. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148468. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148469. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148470. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148471. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148472. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148473. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148474. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148475. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148476. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148477. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148478. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148479. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148480. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148481. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148482. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148483. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148484. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148485. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148486. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148487. 13,
  148488. };
  148489. static float _vq_quantthresh__44u4__p4_0[] = {
  148490. -1.5, -0.5, 0.5, 1.5,
  148491. };
  148492. static long _vq_quantmap__44u4__p4_0[] = {
  148493. 3, 1, 0, 2, 4,
  148494. };
  148495. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148496. _vq_quantthresh__44u4__p4_0,
  148497. _vq_quantmap__44u4__p4_0,
  148498. 5,
  148499. 5
  148500. };
  148501. static static_codebook _44u4__p4_0 = {
  148502. 4, 625,
  148503. _vq_lengthlist__44u4__p4_0,
  148504. 1, -533725184, 1611661312, 3, 0,
  148505. _vq_quantlist__44u4__p4_0,
  148506. NULL,
  148507. &_vq_auxt__44u4__p4_0,
  148508. NULL,
  148509. 0
  148510. };
  148511. static long _vq_quantlist__44u4__p5_0[] = {
  148512. 4,
  148513. 3,
  148514. 5,
  148515. 2,
  148516. 6,
  148517. 1,
  148518. 7,
  148519. 0,
  148520. 8,
  148521. };
  148522. static long _vq_lengthlist__44u4__p5_0[] = {
  148523. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148524. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148525. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148526. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148527. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148528. 12,
  148529. };
  148530. static float _vq_quantthresh__44u4__p5_0[] = {
  148531. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148532. };
  148533. static long _vq_quantmap__44u4__p5_0[] = {
  148534. 7, 5, 3, 1, 0, 2, 4, 6,
  148535. 8,
  148536. };
  148537. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148538. _vq_quantthresh__44u4__p5_0,
  148539. _vq_quantmap__44u4__p5_0,
  148540. 9,
  148541. 9
  148542. };
  148543. static static_codebook _44u4__p5_0 = {
  148544. 2, 81,
  148545. _vq_lengthlist__44u4__p5_0,
  148546. 1, -531628032, 1611661312, 4, 0,
  148547. _vq_quantlist__44u4__p5_0,
  148548. NULL,
  148549. &_vq_auxt__44u4__p5_0,
  148550. NULL,
  148551. 0
  148552. };
  148553. static long _vq_quantlist__44u4__p6_0[] = {
  148554. 6,
  148555. 5,
  148556. 7,
  148557. 4,
  148558. 8,
  148559. 3,
  148560. 9,
  148561. 2,
  148562. 10,
  148563. 1,
  148564. 11,
  148565. 0,
  148566. 12,
  148567. };
  148568. static long _vq_lengthlist__44u4__p6_0[] = {
  148569. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148570. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148571. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148572. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148573. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148574. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148575. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148576. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148577. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148578. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148579. 16,16,16,17,17,18,17,20,21,
  148580. };
  148581. static float _vq_quantthresh__44u4__p6_0[] = {
  148582. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148583. 12.5, 17.5, 22.5, 27.5,
  148584. };
  148585. static long _vq_quantmap__44u4__p6_0[] = {
  148586. 11, 9, 7, 5, 3, 1, 0, 2,
  148587. 4, 6, 8, 10, 12,
  148588. };
  148589. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148590. _vq_quantthresh__44u4__p6_0,
  148591. _vq_quantmap__44u4__p6_0,
  148592. 13,
  148593. 13
  148594. };
  148595. static static_codebook _44u4__p6_0 = {
  148596. 2, 169,
  148597. _vq_lengthlist__44u4__p6_0,
  148598. 1, -526516224, 1616117760, 4, 0,
  148599. _vq_quantlist__44u4__p6_0,
  148600. NULL,
  148601. &_vq_auxt__44u4__p6_0,
  148602. NULL,
  148603. 0
  148604. };
  148605. static long _vq_quantlist__44u4__p6_1[] = {
  148606. 2,
  148607. 1,
  148608. 3,
  148609. 0,
  148610. 4,
  148611. };
  148612. static long _vq_lengthlist__44u4__p6_1[] = {
  148613. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148614. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148615. };
  148616. static float _vq_quantthresh__44u4__p6_1[] = {
  148617. -1.5, -0.5, 0.5, 1.5,
  148618. };
  148619. static long _vq_quantmap__44u4__p6_1[] = {
  148620. 3, 1, 0, 2, 4,
  148621. };
  148622. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148623. _vq_quantthresh__44u4__p6_1,
  148624. _vq_quantmap__44u4__p6_1,
  148625. 5,
  148626. 5
  148627. };
  148628. static static_codebook _44u4__p6_1 = {
  148629. 2, 25,
  148630. _vq_lengthlist__44u4__p6_1,
  148631. 1, -533725184, 1611661312, 3, 0,
  148632. _vq_quantlist__44u4__p6_1,
  148633. NULL,
  148634. &_vq_auxt__44u4__p6_1,
  148635. NULL,
  148636. 0
  148637. };
  148638. static long _vq_quantlist__44u4__p7_0[] = {
  148639. 6,
  148640. 5,
  148641. 7,
  148642. 4,
  148643. 8,
  148644. 3,
  148645. 9,
  148646. 2,
  148647. 10,
  148648. 1,
  148649. 11,
  148650. 0,
  148651. 12,
  148652. };
  148653. static long _vq_lengthlist__44u4__p7_0[] = {
  148654. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148655. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148656. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148657. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148658. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148659. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148664. 11,11,11,11,11,11,11,11,11,
  148665. };
  148666. static float _vq_quantthresh__44u4__p7_0[] = {
  148667. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148668. 637.5, 892.5, 1147.5, 1402.5,
  148669. };
  148670. static long _vq_quantmap__44u4__p7_0[] = {
  148671. 11, 9, 7, 5, 3, 1, 0, 2,
  148672. 4, 6, 8, 10, 12,
  148673. };
  148674. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148675. _vq_quantthresh__44u4__p7_0,
  148676. _vq_quantmap__44u4__p7_0,
  148677. 13,
  148678. 13
  148679. };
  148680. static static_codebook _44u4__p7_0 = {
  148681. 2, 169,
  148682. _vq_lengthlist__44u4__p7_0,
  148683. 1, -514332672, 1627381760, 4, 0,
  148684. _vq_quantlist__44u4__p7_0,
  148685. NULL,
  148686. &_vq_auxt__44u4__p7_0,
  148687. NULL,
  148688. 0
  148689. };
  148690. static long _vq_quantlist__44u4__p7_1[] = {
  148691. 7,
  148692. 6,
  148693. 8,
  148694. 5,
  148695. 9,
  148696. 4,
  148697. 10,
  148698. 3,
  148699. 11,
  148700. 2,
  148701. 12,
  148702. 1,
  148703. 13,
  148704. 0,
  148705. 14,
  148706. };
  148707. static long _vq_lengthlist__44u4__p7_1[] = {
  148708. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148709. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148710. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148711. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148712. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148713. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148714. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148715. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148716. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148717. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148718. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148719. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148720. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148721. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148722. 16,
  148723. };
  148724. static float _vq_quantthresh__44u4__p7_1[] = {
  148725. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148726. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148727. };
  148728. static long _vq_quantmap__44u4__p7_1[] = {
  148729. 13, 11, 9, 7, 5, 3, 1, 0,
  148730. 2, 4, 6, 8, 10, 12, 14,
  148731. };
  148732. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148733. _vq_quantthresh__44u4__p7_1,
  148734. _vq_quantmap__44u4__p7_1,
  148735. 15,
  148736. 15
  148737. };
  148738. static static_codebook _44u4__p7_1 = {
  148739. 2, 225,
  148740. _vq_lengthlist__44u4__p7_1,
  148741. 1, -522338304, 1620115456, 4, 0,
  148742. _vq_quantlist__44u4__p7_1,
  148743. NULL,
  148744. &_vq_auxt__44u4__p7_1,
  148745. NULL,
  148746. 0
  148747. };
  148748. static long _vq_quantlist__44u4__p7_2[] = {
  148749. 8,
  148750. 7,
  148751. 9,
  148752. 6,
  148753. 10,
  148754. 5,
  148755. 11,
  148756. 4,
  148757. 12,
  148758. 3,
  148759. 13,
  148760. 2,
  148761. 14,
  148762. 1,
  148763. 15,
  148764. 0,
  148765. 16,
  148766. };
  148767. static long _vq_lengthlist__44u4__p7_2[] = {
  148768. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148769. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148770. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148771. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148772. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148773. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148774. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148775. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148776. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148777. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148778. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148779. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148780. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148781. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148783. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148784. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148785. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148786. 10,
  148787. };
  148788. static float _vq_quantthresh__44u4__p7_2[] = {
  148789. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148790. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148791. };
  148792. static long _vq_quantmap__44u4__p7_2[] = {
  148793. 15, 13, 11, 9, 7, 5, 3, 1,
  148794. 0, 2, 4, 6, 8, 10, 12, 14,
  148795. 16,
  148796. };
  148797. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148798. _vq_quantthresh__44u4__p7_2,
  148799. _vq_quantmap__44u4__p7_2,
  148800. 17,
  148801. 17
  148802. };
  148803. static static_codebook _44u4__p7_2 = {
  148804. 2, 289,
  148805. _vq_lengthlist__44u4__p7_2,
  148806. 1, -529530880, 1611661312, 5, 0,
  148807. _vq_quantlist__44u4__p7_2,
  148808. NULL,
  148809. &_vq_auxt__44u4__p7_2,
  148810. NULL,
  148811. 0
  148812. };
  148813. static long _huff_lengthlist__44u4__short[] = {
  148814. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148815. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148816. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148817. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148818. };
  148819. static static_codebook _huff_book__44u4__short = {
  148820. 2, 64,
  148821. _huff_lengthlist__44u4__short,
  148822. 0, 0, 0, 0, 0,
  148823. NULL,
  148824. NULL,
  148825. NULL,
  148826. NULL,
  148827. 0
  148828. };
  148829. static long _huff_lengthlist__44u5__long[] = {
  148830. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148831. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148832. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148833. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148834. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148835. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148836. 14, 8, 7, 8,
  148837. };
  148838. static static_codebook _huff_book__44u5__long = {
  148839. 2, 100,
  148840. _huff_lengthlist__44u5__long,
  148841. 0, 0, 0, 0, 0,
  148842. NULL,
  148843. NULL,
  148844. NULL,
  148845. NULL,
  148846. 0
  148847. };
  148848. static long _vq_quantlist__44u5__p1_0[] = {
  148849. 1,
  148850. 0,
  148851. 2,
  148852. };
  148853. static long _vq_lengthlist__44u5__p1_0[] = {
  148854. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148855. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148856. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148857. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148858. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148859. 12,
  148860. };
  148861. static float _vq_quantthresh__44u5__p1_0[] = {
  148862. -0.5, 0.5,
  148863. };
  148864. static long _vq_quantmap__44u5__p1_0[] = {
  148865. 1, 0, 2,
  148866. };
  148867. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148868. _vq_quantthresh__44u5__p1_0,
  148869. _vq_quantmap__44u5__p1_0,
  148870. 3,
  148871. 3
  148872. };
  148873. static static_codebook _44u5__p1_0 = {
  148874. 4, 81,
  148875. _vq_lengthlist__44u5__p1_0,
  148876. 1, -535822336, 1611661312, 2, 0,
  148877. _vq_quantlist__44u5__p1_0,
  148878. NULL,
  148879. &_vq_auxt__44u5__p1_0,
  148880. NULL,
  148881. 0
  148882. };
  148883. static long _vq_quantlist__44u5__p2_0[] = {
  148884. 1,
  148885. 0,
  148886. 2,
  148887. };
  148888. static long _vq_lengthlist__44u5__p2_0[] = {
  148889. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148890. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148891. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148892. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148893. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148894. 9,
  148895. };
  148896. static float _vq_quantthresh__44u5__p2_0[] = {
  148897. -0.5, 0.5,
  148898. };
  148899. static long _vq_quantmap__44u5__p2_0[] = {
  148900. 1, 0, 2,
  148901. };
  148902. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148903. _vq_quantthresh__44u5__p2_0,
  148904. _vq_quantmap__44u5__p2_0,
  148905. 3,
  148906. 3
  148907. };
  148908. static static_codebook _44u5__p2_0 = {
  148909. 4, 81,
  148910. _vq_lengthlist__44u5__p2_0,
  148911. 1, -535822336, 1611661312, 2, 0,
  148912. _vq_quantlist__44u5__p2_0,
  148913. NULL,
  148914. &_vq_auxt__44u5__p2_0,
  148915. NULL,
  148916. 0
  148917. };
  148918. static long _vq_quantlist__44u5__p3_0[] = {
  148919. 2,
  148920. 1,
  148921. 3,
  148922. 0,
  148923. 4,
  148924. };
  148925. static long _vq_lengthlist__44u5__p3_0[] = {
  148926. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148927. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148928. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148929. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148930. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148931. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148932. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148933. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148934. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148935. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148936. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148937. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148938. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148939. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148940. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148941. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148942. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148943. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148944. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148945. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148946. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148947. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148948. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148949. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148950. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148951. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148952. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148953. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148954. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148955. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148956. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148957. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148958. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148959. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148960. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148961. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148962. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148963. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148964. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148965. 0,
  148966. };
  148967. static float _vq_quantthresh__44u5__p3_0[] = {
  148968. -1.5, -0.5, 0.5, 1.5,
  148969. };
  148970. static long _vq_quantmap__44u5__p3_0[] = {
  148971. 3, 1, 0, 2, 4,
  148972. };
  148973. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148974. _vq_quantthresh__44u5__p3_0,
  148975. _vq_quantmap__44u5__p3_0,
  148976. 5,
  148977. 5
  148978. };
  148979. static static_codebook _44u5__p3_0 = {
  148980. 4, 625,
  148981. _vq_lengthlist__44u5__p3_0,
  148982. 1, -533725184, 1611661312, 3, 0,
  148983. _vq_quantlist__44u5__p3_0,
  148984. NULL,
  148985. &_vq_auxt__44u5__p3_0,
  148986. NULL,
  148987. 0
  148988. };
  148989. static long _vq_quantlist__44u5__p4_0[] = {
  148990. 2,
  148991. 1,
  148992. 3,
  148993. 0,
  148994. 4,
  148995. };
  148996. static long _vq_lengthlist__44u5__p4_0[] = {
  148997. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148998. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148999. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149000. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149001. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149002. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149003. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149004. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149005. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149006. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149007. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149008. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149009. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149010. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149011. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149012. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149013. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149014. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149015. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149016. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149017. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149018. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149019. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149020. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149021. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149022. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149023. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149024. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149025. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149026. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149027. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149028. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149029. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149030. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149031. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149032. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149033. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149034. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149035. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149036. 12,
  149037. };
  149038. static float _vq_quantthresh__44u5__p4_0[] = {
  149039. -1.5, -0.5, 0.5, 1.5,
  149040. };
  149041. static long _vq_quantmap__44u5__p4_0[] = {
  149042. 3, 1, 0, 2, 4,
  149043. };
  149044. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149045. _vq_quantthresh__44u5__p4_0,
  149046. _vq_quantmap__44u5__p4_0,
  149047. 5,
  149048. 5
  149049. };
  149050. static static_codebook _44u5__p4_0 = {
  149051. 4, 625,
  149052. _vq_lengthlist__44u5__p4_0,
  149053. 1, -533725184, 1611661312, 3, 0,
  149054. _vq_quantlist__44u5__p4_0,
  149055. NULL,
  149056. &_vq_auxt__44u5__p4_0,
  149057. NULL,
  149058. 0
  149059. };
  149060. static long _vq_quantlist__44u5__p5_0[] = {
  149061. 4,
  149062. 3,
  149063. 5,
  149064. 2,
  149065. 6,
  149066. 1,
  149067. 7,
  149068. 0,
  149069. 8,
  149070. };
  149071. static long _vq_lengthlist__44u5__p5_0[] = {
  149072. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149073. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149074. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149075. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149076. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149077. 14,
  149078. };
  149079. static float _vq_quantthresh__44u5__p5_0[] = {
  149080. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149081. };
  149082. static long _vq_quantmap__44u5__p5_0[] = {
  149083. 7, 5, 3, 1, 0, 2, 4, 6,
  149084. 8,
  149085. };
  149086. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149087. _vq_quantthresh__44u5__p5_0,
  149088. _vq_quantmap__44u5__p5_0,
  149089. 9,
  149090. 9
  149091. };
  149092. static static_codebook _44u5__p5_0 = {
  149093. 2, 81,
  149094. _vq_lengthlist__44u5__p5_0,
  149095. 1, -531628032, 1611661312, 4, 0,
  149096. _vq_quantlist__44u5__p5_0,
  149097. NULL,
  149098. &_vq_auxt__44u5__p5_0,
  149099. NULL,
  149100. 0
  149101. };
  149102. static long _vq_quantlist__44u5__p6_0[] = {
  149103. 4,
  149104. 3,
  149105. 5,
  149106. 2,
  149107. 6,
  149108. 1,
  149109. 7,
  149110. 0,
  149111. 8,
  149112. };
  149113. static long _vq_lengthlist__44u5__p6_0[] = {
  149114. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149115. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149116. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149117. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149118. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149119. 11,
  149120. };
  149121. static float _vq_quantthresh__44u5__p6_0[] = {
  149122. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149123. };
  149124. static long _vq_quantmap__44u5__p6_0[] = {
  149125. 7, 5, 3, 1, 0, 2, 4, 6,
  149126. 8,
  149127. };
  149128. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149129. _vq_quantthresh__44u5__p6_0,
  149130. _vq_quantmap__44u5__p6_0,
  149131. 9,
  149132. 9
  149133. };
  149134. static static_codebook _44u5__p6_0 = {
  149135. 2, 81,
  149136. _vq_lengthlist__44u5__p6_0,
  149137. 1, -531628032, 1611661312, 4, 0,
  149138. _vq_quantlist__44u5__p6_0,
  149139. NULL,
  149140. &_vq_auxt__44u5__p6_0,
  149141. NULL,
  149142. 0
  149143. };
  149144. static long _vq_quantlist__44u5__p7_0[] = {
  149145. 1,
  149146. 0,
  149147. 2,
  149148. };
  149149. static long _vq_lengthlist__44u5__p7_0[] = {
  149150. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149151. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149152. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149153. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149154. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149155. 12,
  149156. };
  149157. static float _vq_quantthresh__44u5__p7_0[] = {
  149158. -5.5, 5.5,
  149159. };
  149160. static long _vq_quantmap__44u5__p7_0[] = {
  149161. 1, 0, 2,
  149162. };
  149163. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149164. _vq_quantthresh__44u5__p7_0,
  149165. _vq_quantmap__44u5__p7_0,
  149166. 3,
  149167. 3
  149168. };
  149169. static static_codebook _44u5__p7_0 = {
  149170. 4, 81,
  149171. _vq_lengthlist__44u5__p7_0,
  149172. 1, -529137664, 1618345984, 2, 0,
  149173. _vq_quantlist__44u5__p7_0,
  149174. NULL,
  149175. &_vq_auxt__44u5__p7_0,
  149176. NULL,
  149177. 0
  149178. };
  149179. static long _vq_quantlist__44u5__p7_1[] = {
  149180. 5,
  149181. 4,
  149182. 6,
  149183. 3,
  149184. 7,
  149185. 2,
  149186. 8,
  149187. 1,
  149188. 9,
  149189. 0,
  149190. 10,
  149191. };
  149192. static long _vq_lengthlist__44u5__p7_1[] = {
  149193. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149194. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149195. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149196. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149197. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149198. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149199. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149200. 9, 9, 9, 9, 9,10,10,10,10,
  149201. };
  149202. static float _vq_quantthresh__44u5__p7_1[] = {
  149203. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149204. 3.5, 4.5,
  149205. };
  149206. static long _vq_quantmap__44u5__p7_1[] = {
  149207. 9, 7, 5, 3, 1, 0, 2, 4,
  149208. 6, 8, 10,
  149209. };
  149210. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149211. _vq_quantthresh__44u5__p7_1,
  149212. _vq_quantmap__44u5__p7_1,
  149213. 11,
  149214. 11
  149215. };
  149216. static static_codebook _44u5__p7_1 = {
  149217. 2, 121,
  149218. _vq_lengthlist__44u5__p7_1,
  149219. 1, -531365888, 1611661312, 4, 0,
  149220. _vq_quantlist__44u5__p7_1,
  149221. NULL,
  149222. &_vq_auxt__44u5__p7_1,
  149223. NULL,
  149224. 0
  149225. };
  149226. static long _vq_quantlist__44u5__p8_0[] = {
  149227. 5,
  149228. 4,
  149229. 6,
  149230. 3,
  149231. 7,
  149232. 2,
  149233. 8,
  149234. 1,
  149235. 9,
  149236. 0,
  149237. 10,
  149238. };
  149239. static long _vq_lengthlist__44u5__p8_0[] = {
  149240. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149241. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149242. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149243. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149244. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149245. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149246. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149247. 12,13,13,14,14,14,14,15,15,
  149248. };
  149249. static float _vq_quantthresh__44u5__p8_0[] = {
  149250. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149251. 38.5, 49.5,
  149252. };
  149253. static long _vq_quantmap__44u5__p8_0[] = {
  149254. 9, 7, 5, 3, 1, 0, 2, 4,
  149255. 6, 8, 10,
  149256. };
  149257. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149258. _vq_quantthresh__44u5__p8_0,
  149259. _vq_quantmap__44u5__p8_0,
  149260. 11,
  149261. 11
  149262. };
  149263. static static_codebook _44u5__p8_0 = {
  149264. 2, 121,
  149265. _vq_lengthlist__44u5__p8_0,
  149266. 1, -524582912, 1618345984, 4, 0,
  149267. _vq_quantlist__44u5__p8_0,
  149268. NULL,
  149269. &_vq_auxt__44u5__p8_0,
  149270. NULL,
  149271. 0
  149272. };
  149273. static long _vq_quantlist__44u5__p8_1[] = {
  149274. 5,
  149275. 4,
  149276. 6,
  149277. 3,
  149278. 7,
  149279. 2,
  149280. 8,
  149281. 1,
  149282. 9,
  149283. 0,
  149284. 10,
  149285. };
  149286. static long _vq_lengthlist__44u5__p8_1[] = {
  149287. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149288. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149289. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149290. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149291. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149292. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149293. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149294. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149295. };
  149296. static float _vq_quantthresh__44u5__p8_1[] = {
  149297. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149298. 3.5, 4.5,
  149299. };
  149300. static long _vq_quantmap__44u5__p8_1[] = {
  149301. 9, 7, 5, 3, 1, 0, 2, 4,
  149302. 6, 8, 10,
  149303. };
  149304. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149305. _vq_quantthresh__44u5__p8_1,
  149306. _vq_quantmap__44u5__p8_1,
  149307. 11,
  149308. 11
  149309. };
  149310. static static_codebook _44u5__p8_1 = {
  149311. 2, 121,
  149312. _vq_lengthlist__44u5__p8_1,
  149313. 1, -531365888, 1611661312, 4, 0,
  149314. _vq_quantlist__44u5__p8_1,
  149315. NULL,
  149316. &_vq_auxt__44u5__p8_1,
  149317. NULL,
  149318. 0
  149319. };
  149320. static long _vq_quantlist__44u5__p9_0[] = {
  149321. 6,
  149322. 5,
  149323. 7,
  149324. 4,
  149325. 8,
  149326. 3,
  149327. 9,
  149328. 2,
  149329. 10,
  149330. 1,
  149331. 11,
  149332. 0,
  149333. 12,
  149334. };
  149335. static long _vq_lengthlist__44u5__p9_0[] = {
  149336. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149337. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149338. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149339. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149340. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149341. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149342. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149343. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149344. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149345. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149346. 12,12,12,12,12,12,12,12,12,
  149347. };
  149348. static float _vq_quantthresh__44u5__p9_0[] = {
  149349. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149350. 637.5, 892.5, 1147.5, 1402.5,
  149351. };
  149352. static long _vq_quantmap__44u5__p9_0[] = {
  149353. 11, 9, 7, 5, 3, 1, 0, 2,
  149354. 4, 6, 8, 10, 12,
  149355. };
  149356. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149357. _vq_quantthresh__44u5__p9_0,
  149358. _vq_quantmap__44u5__p9_0,
  149359. 13,
  149360. 13
  149361. };
  149362. static static_codebook _44u5__p9_0 = {
  149363. 2, 169,
  149364. _vq_lengthlist__44u5__p9_0,
  149365. 1, -514332672, 1627381760, 4, 0,
  149366. _vq_quantlist__44u5__p9_0,
  149367. NULL,
  149368. &_vq_auxt__44u5__p9_0,
  149369. NULL,
  149370. 0
  149371. };
  149372. static long _vq_quantlist__44u5__p9_1[] = {
  149373. 7,
  149374. 6,
  149375. 8,
  149376. 5,
  149377. 9,
  149378. 4,
  149379. 10,
  149380. 3,
  149381. 11,
  149382. 2,
  149383. 12,
  149384. 1,
  149385. 13,
  149386. 0,
  149387. 14,
  149388. };
  149389. static long _vq_lengthlist__44u5__p9_1[] = {
  149390. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149391. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149392. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149393. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149394. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149395. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149396. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149397. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149398. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149399. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149400. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149401. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149402. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149403. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149404. 14,
  149405. };
  149406. static float _vq_quantthresh__44u5__p9_1[] = {
  149407. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149408. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149409. };
  149410. static long _vq_quantmap__44u5__p9_1[] = {
  149411. 13, 11, 9, 7, 5, 3, 1, 0,
  149412. 2, 4, 6, 8, 10, 12, 14,
  149413. };
  149414. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149415. _vq_quantthresh__44u5__p9_1,
  149416. _vq_quantmap__44u5__p9_1,
  149417. 15,
  149418. 15
  149419. };
  149420. static static_codebook _44u5__p9_1 = {
  149421. 2, 225,
  149422. _vq_lengthlist__44u5__p9_1,
  149423. 1, -522338304, 1620115456, 4, 0,
  149424. _vq_quantlist__44u5__p9_1,
  149425. NULL,
  149426. &_vq_auxt__44u5__p9_1,
  149427. NULL,
  149428. 0
  149429. };
  149430. static long _vq_quantlist__44u5__p9_2[] = {
  149431. 8,
  149432. 7,
  149433. 9,
  149434. 6,
  149435. 10,
  149436. 5,
  149437. 11,
  149438. 4,
  149439. 12,
  149440. 3,
  149441. 13,
  149442. 2,
  149443. 14,
  149444. 1,
  149445. 15,
  149446. 0,
  149447. 16,
  149448. };
  149449. static long _vq_lengthlist__44u5__p9_2[] = {
  149450. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149451. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149452. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149453. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149454. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149455. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149456. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149457. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149458. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149459. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149460. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149461. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149462. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149463. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149464. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149465. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149466. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149467. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149468. 10,
  149469. };
  149470. static float _vq_quantthresh__44u5__p9_2[] = {
  149471. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149472. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149473. };
  149474. static long _vq_quantmap__44u5__p9_2[] = {
  149475. 15, 13, 11, 9, 7, 5, 3, 1,
  149476. 0, 2, 4, 6, 8, 10, 12, 14,
  149477. 16,
  149478. };
  149479. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149480. _vq_quantthresh__44u5__p9_2,
  149481. _vq_quantmap__44u5__p9_2,
  149482. 17,
  149483. 17
  149484. };
  149485. static static_codebook _44u5__p9_2 = {
  149486. 2, 289,
  149487. _vq_lengthlist__44u5__p9_2,
  149488. 1, -529530880, 1611661312, 5, 0,
  149489. _vq_quantlist__44u5__p9_2,
  149490. NULL,
  149491. &_vq_auxt__44u5__p9_2,
  149492. NULL,
  149493. 0
  149494. };
  149495. static long _huff_lengthlist__44u5__short[] = {
  149496. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149497. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149498. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149499. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149500. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149501. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149502. 6, 8,15,17,
  149503. };
  149504. static static_codebook _huff_book__44u5__short = {
  149505. 2, 100,
  149506. _huff_lengthlist__44u5__short,
  149507. 0, 0, 0, 0, 0,
  149508. NULL,
  149509. NULL,
  149510. NULL,
  149511. NULL,
  149512. 0
  149513. };
  149514. static long _huff_lengthlist__44u6__long[] = {
  149515. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149516. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149517. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149518. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149519. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149520. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149521. 13, 8, 7, 7,
  149522. };
  149523. static static_codebook _huff_book__44u6__long = {
  149524. 2, 100,
  149525. _huff_lengthlist__44u6__long,
  149526. 0, 0, 0, 0, 0,
  149527. NULL,
  149528. NULL,
  149529. NULL,
  149530. NULL,
  149531. 0
  149532. };
  149533. static long _vq_quantlist__44u6__p1_0[] = {
  149534. 1,
  149535. 0,
  149536. 2,
  149537. };
  149538. static long _vq_lengthlist__44u6__p1_0[] = {
  149539. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149540. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149541. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149542. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149543. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149544. 12,
  149545. };
  149546. static float _vq_quantthresh__44u6__p1_0[] = {
  149547. -0.5, 0.5,
  149548. };
  149549. static long _vq_quantmap__44u6__p1_0[] = {
  149550. 1, 0, 2,
  149551. };
  149552. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149553. _vq_quantthresh__44u6__p1_0,
  149554. _vq_quantmap__44u6__p1_0,
  149555. 3,
  149556. 3
  149557. };
  149558. static static_codebook _44u6__p1_0 = {
  149559. 4, 81,
  149560. _vq_lengthlist__44u6__p1_0,
  149561. 1, -535822336, 1611661312, 2, 0,
  149562. _vq_quantlist__44u6__p1_0,
  149563. NULL,
  149564. &_vq_auxt__44u6__p1_0,
  149565. NULL,
  149566. 0
  149567. };
  149568. static long _vq_quantlist__44u6__p2_0[] = {
  149569. 1,
  149570. 0,
  149571. 2,
  149572. };
  149573. static long _vq_lengthlist__44u6__p2_0[] = {
  149574. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149575. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149576. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149577. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149578. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149579. 9,
  149580. };
  149581. static float _vq_quantthresh__44u6__p2_0[] = {
  149582. -0.5, 0.5,
  149583. };
  149584. static long _vq_quantmap__44u6__p2_0[] = {
  149585. 1, 0, 2,
  149586. };
  149587. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149588. _vq_quantthresh__44u6__p2_0,
  149589. _vq_quantmap__44u6__p2_0,
  149590. 3,
  149591. 3
  149592. };
  149593. static static_codebook _44u6__p2_0 = {
  149594. 4, 81,
  149595. _vq_lengthlist__44u6__p2_0,
  149596. 1, -535822336, 1611661312, 2, 0,
  149597. _vq_quantlist__44u6__p2_0,
  149598. NULL,
  149599. &_vq_auxt__44u6__p2_0,
  149600. NULL,
  149601. 0
  149602. };
  149603. static long _vq_quantlist__44u6__p3_0[] = {
  149604. 2,
  149605. 1,
  149606. 3,
  149607. 0,
  149608. 4,
  149609. };
  149610. static long _vq_lengthlist__44u6__p3_0[] = {
  149611. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149612. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149613. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149614. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149615. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149616. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149617. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149618. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149619. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149620. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149621. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149622. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149623. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149624. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149625. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149626. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149627. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149628. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149629. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149630. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149631. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149632. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149633. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149634. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149635. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149636. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149637. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149638. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149639. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149640. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149641. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149642. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149643. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149644. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149645. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149646. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149647. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149648. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149649. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149650. 19,
  149651. };
  149652. static float _vq_quantthresh__44u6__p3_0[] = {
  149653. -1.5, -0.5, 0.5, 1.5,
  149654. };
  149655. static long _vq_quantmap__44u6__p3_0[] = {
  149656. 3, 1, 0, 2, 4,
  149657. };
  149658. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149659. _vq_quantthresh__44u6__p3_0,
  149660. _vq_quantmap__44u6__p3_0,
  149661. 5,
  149662. 5
  149663. };
  149664. static static_codebook _44u6__p3_0 = {
  149665. 4, 625,
  149666. _vq_lengthlist__44u6__p3_0,
  149667. 1, -533725184, 1611661312, 3, 0,
  149668. _vq_quantlist__44u6__p3_0,
  149669. NULL,
  149670. &_vq_auxt__44u6__p3_0,
  149671. NULL,
  149672. 0
  149673. };
  149674. static long _vq_quantlist__44u6__p4_0[] = {
  149675. 2,
  149676. 1,
  149677. 3,
  149678. 0,
  149679. 4,
  149680. };
  149681. static long _vq_lengthlist__44u6__p4_0[] = {
  149682. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149683. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149684. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149685. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149686. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149687. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149688. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149689. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149690. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149691. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149692. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149693. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149694. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149695. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149696. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149697. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149698. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149699. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149700. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149701. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149702. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149703. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149704. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149705. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149706. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149707. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149708. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149709. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149710. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149711. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149712. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149713. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149714. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149715. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149716. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149717. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149718. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149719. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149720. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149721. 13,
  149722. };
  149723. static float _vq_quantthresh__44u6__p4_0[] = {
  149724. -1.5, -0.5, 0.5, 1.5,
  149725. };
  149726. static long _vq_quantmap__44u6__p4_0[] = {
  149727. 3, 1, 0, 2, 4,
  149728. };
  149729. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149730. _vq_quantthresh__44u6__p4_0,
  149731. _vq_quantmap__44u6__p4_0,
  149732. 5,
  149733. 5
  149734. };
  149735. static static_codebook _44u6__p4_0 = {
  149736. 4, 625,
  149737. _vq_lengthlist__44u6__p4_0,
  149738. 1, -533725184, 1611661312, 3, 0,
  149739. _vq_quantlist__44u6__p4_0,
  149740. NULL,
  149741. &_vq_auxt__44u6__p4_0,
  149742. NULL,
  149743. 0
  149744. };
  149745. static long _vq_quantlist__44u6__p5_0[] = {
  149746. 4,
  149747. 3,
  149748. 5,
  149749. 2,
  149750. 6,
  149751. 1,
  149752. 7,
  149753. 0,
  149754. 8,
  149755. };
  149756. static long _vq_lengthlist__44u6__p5_0[] = {
  149757. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149758. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149759. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149760. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149761. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149762. 14,
  149763. };
  149764. static float _vq_quantthresh__44u6__p5_0[] = {
  149765. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149766. };
  149767. static long _vq_quantmap__44u6__p5_0[] = {
  149768. 7, 5, 3, 1, 0, 2, 4, 6,
  149769. 8,
  149770. };
  149771. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149772. _vq_quantthresh__44u6__p5_0,
  149773. _vq_quantmap__44u6__p5_0,
  149774. 9,
  149775. 9
  149776. };
  149777. static static_codebook _44u6__p5_0 = {
  149778. 2, 81,
  149779. _vq_lengthlist__44u6__p5_0,
  149780. 1, -531628032, 1611661312, 4, 0,
  149781. _vq_quantlist__44u6__p5_0,
  149782. NULL,
  149783. &_vq_auxt__44u6__p5_0,
  149784. NULL,
  149785. 0
  149786. };
  149787. static long _vq_quantlist__44u6__p6_0[] = {
  149788. 4,
  149789. 3,
  149790. 5,
  149791. 2,
  149792. 6,
  149793. 1,
  149794. 7,
  149795. 0,
  149796. 8,
  149797. };
  149798. static long _vq_lengthlist__44u6__p6_0[] = {
  149799. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149800. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149801. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149802. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149803. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149804. 12,
  149805. };
  149806. static float _vq_quantthresh__44u6__p6_0[] = {
  149807. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149808. };
  149809. static long _vq_quantmap__44u6__p6_0[] = {
  149810. 7, 5, 3, 1, 0, 2, 4, 6,
  149811. 8,
  149812. };
  149813. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149814. _vq_quantthresh__44u6__p6_0,
  149815. _vq_quantmap__44u6__p6_0,
  149816. 9,
  149817. 9
  149818. };
  149819. static static_codebook _44u6__p6_0 = {
  149820. 2, 81,
  149821. _vq_lengthlist__44u6__p6_0,
  149822. 1, -531628032, 1611661312, 4, 0,
  149823. _vq_quantlist__44u6__p6_0,
  149824. NULL,
  149825. &_vq_auxt__44u6__p6_0,
  149826. NULL,
  149827. 0
  149828. };
  149829. static long _vq_quantlist__44u6__p7_0[] = {
  149830. 1,
  149831. 0,
  149832. 2,
  149833. };
  149834. static long _vq_lengthlist__44u6__p7_0[] = {
  149835. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149836. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149837. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149838. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149839. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149840. 10,
  149841. };
  149842. static float _vq_quantthresh__44u6__p7_0[] = {
  149843. -5.5, 5.5,
  149844. };
  149845. static long _vq_quantmap__44u6__p7_0[] = {
  149846. 1, 0, 2,
  149847. };
  149848. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149849. _vq_quantthresh__44u6__p7_0,
  149850. _vq_quantmap__44u6__p7_0,
  149851. 3,
  149852. 3
  149853. };
  149854. static static_codebook _44u6__p7_0 = {
  149855. 4, 81,
  149856. _vq_lengthlist__44u6__p7_0,
  149857. 1, -529137664, 1618345984, 2, 0,
  149858. _vq_quantlist__44u6__p7_0,
  149859. NULL,
  149860. &_vq_auxt__44u6__p7_0,
  149861. NULL,
  149862. 0
  149863. };
  149864. static long _vq_quantlist__44u6__p7_1[] = {
  149865. 5,
  149866. 4,
  149867. 6,
  149868. 3,
  149869. 7,
  149870. 2,
  149871. 8,
  149872. 1,
  149873. 9,
  149874. 0,
  149875. 10,
  149876. };
  149877. static long _vq_lengthlist__44u6__p7_1[] = {
  149878. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149879. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149880. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149881. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149882. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149883. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149884. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149885. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149886. };
  149887. static float _vq_quantthresh__44u6__p7_1[] = {
  149888. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149889. 3.5, 4.5,
  149890. };
  149891. static long _vq_quantmap__44u6__p7_1[] = {
  149892. 9, 7, 5, 3, 1, 0, 2, 4,
  149893. 6, 8, 10,
  149894. };
  149895. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149896. _vq_quantthresh__44u6__p7_1,
  149897. _vq_quantmap__44u6__p7_1,
  149898. 11,
  149899. 11
  149900. };
  149901. static static_codebook _44u6__p7_1 = {
  149902. 2, 121,
  149903. _vq_lengthlist__44u6__p7_1,
  149904. 1, -531365888, 1611661312, 4, 0,
  149905. _vq_quantlist__44u6__p7_1,
  149906. NULL,
  149907. &_vq_auxt__44u6__p7_1,
  149908. NULL,
  149909. 0
  149910. };
  149911. static long _vq_quantlist__44u6__p8_0[] = {
  149912. 5,
  149913. 4,
  149914. 6,
  149915. 3,
  149916. 7,
  149917. 2,
  149918. 8,
  149919. 1,
  149920. 9,
  149921. 0,
  149922. 10,
  149923. };
  149924. static long _vq_lengthlist__44u6__p8_0[] = {
  149925. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149926. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149927. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149928. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149929. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149930. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149931. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149932. 12,13,13,14,14,14,15,15,15,
  149933. };
  149934. static float _vq_quantthresh__44u6__p8_0[] = {
  149935. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149936. 38.5, 49.5,
  149937. };
  149938. static long _vq_quantmap__44u6__p8_0[] = {
  149939. 9, 7, 5, 3, 1, 0, 2, 4,
  149940. 6, 8, 10,
  149941. };
  149942. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149943. _vq_quantthresh__44u6__p8_0,
  149944. _vq_quantmap__44u6__p8_0,
  149945. 11,
  149946. 11
  149947. };
  149948. static static_codebook _44u6__p8_0 = {
  149949. 2, 121,
  149950. _vq_lengthlist__44u6__p8_0,
  149951. 1, -524582912, 1618345984, 4, 0,
  149952. _vq_quantlist__44u6__p8_0,
  149953. NULL,
  149954. &_vq_auxt__44u6__p8_0,
  149955. NULL,
  149956. 0
  149957. };
  149958. static long _vq_quantlist__44u6__p8_1[] = {
  149959. 5,
  149960. 4,
  149961. 6,
  149962. 3,
  149963. 7,
  149964. 2,
  149965. 8,
  149966. 1,
  149967. 9,
  149968. 0,
  149969. 10,
  149970. };
  149971. static long _vq_lengthlist__44u6__p8_1[] = {
  149972. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149973. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149974. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149975. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149976. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149977. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149978. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149979. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149980. };
  149981. static float _vq_quantthresh__44u6__p8_1[] = {
  149982. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149983. 3.5, 4.5,
  149984. };
  149985. static long _vq_quantmap__44u6__p8_1[] = {
  149986. 9, 7, 5, 3, 1, 0, 2, 4,
  149987. 6, 8, 10,
  149988. };
  149989. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149990. _vq_quantthresh__44u6__p8_1,
  149991. _vq_quantmap__44u6__p8_1,
  149992. 11,
  149993. 11
  149994. };
  149995. static static_codebook _44u6__p8_1 = {
  149996. 2, 121,
  149997. _vq_lengthlist__44u6__p8_1,
  149998. 1, -531365888, 1611661312, 4, 0,
  149999. _vq_quantlist__44u6__p8_1,
  150000. NULL,
  150001. &_vq_auxt__44u6__p8_1,
  150002. NULL,
  150003. 0
  150004. };
  150005. static long _vq_quantlist__44u6__p9_0[] = {
  150006. 7,
  150007. 6,
  150008. 8,
  150009. 5,
  150010. 9,
  150011. 4,
  150012. 10,
  150013. 3,
  150014. 11,
  150015. 2,
  150016. 12,
  150017. 1,
  150018. 13,
  150019. 0,
  150020. 14,
  150021. };
  150022. static long _vq_lengthlist__44u6__p9_0[] = {
  150023. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150024. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150025. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150026. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150027. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150028. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150029. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150030. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150031. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150032. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150033. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150034. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150035. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150036. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150037. 14,
  150038. };
  150039. static float _vq_quantthresh__44u6__p9_0[] = {
  150040. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150041. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150042. };
  150043. static long _vq_quantmap__44u6__p9_0[] = {
  150044. 13, 11, 9, 7, 5, 3, 1, 0,
  150045. 2, 4, 6, 8, 10, 12, 14,
  150046. };
  150047. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150048. _vq_quantthresh__44u6__p9_0,
  150049. _vq_quantmap__44u6__p9_0,
  150050. 15,
  150051. 15
  150052. };
  150053. static static_codebook _44u6__p9_0 = {
  150054. 2, 225,
  150055. _vq_lengthlist__44u6__p9_0,
  150056. 1, -514071552, 1627381760, 4, 0,
  150057. _vq_quantlist__44u6__p9_0,
  150058. NULL,
  150059. &_vq_auxt__44u6__p9_0,
  150060. NULL,
  150061. 0
  150062. };
  150063. static long _vq_quantlist__44u6__p9_1[] = {
  150064. 7,
  150065. 6,
  150066. 8,
  150067. 5,
  150068. 9,
  150069. 4,
  150070. 10,
  150071. 3,
  150072. 11,
  150073. 2,
  150074. 12,
  150075. 1,
  150076. 13,
  150077. 0,
  150078. 14,
  150079. };
  150080. static long _vq_lengthlist__44u6__p9_1[] = {
  150081. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150082. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150083. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150084. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150085. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150086. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150087. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150088. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150089. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150090. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150091. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150092. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150093. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150094. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150095. 13,
  150096. };
  150097. static float _vq_quantthresh__44u6__p9_1[] = {
  150098. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150099. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150100. };
  150101. static long _vq_quantmap__44u6__p9_1[] = {
  150102. 13, 11, 9, 7, 5, 3, 1, 0,
  150103. 2, 4, 6, 8, 10, 12, 14,
  150104. };
  150105. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150106. _vq_quantthresh__44u6__p9_1,
  150107. _vq_quantmap__44u6__p9_1,
  150108. 15,
  150109. 15
  150110. };
  150111. static static_codebook _44u6__p9_1 = {
  150112. 2, 225,
  150113. _vq_lengthlist__44u6__p9_1,
  150114. 1, -522338304, 1620115456, 4, 0,
  150115. _vq_quantlist__44u6__p9_1,
  150116. NULL,
  150117. &_vq_auxt__44u6__p9_1,
  150118. NULL,
  150119. 0
  150120. };
  150121. static long _vq_quantlist__44u6__p9_2[] = {
  150122. 8,
  150123. 7,
  150124. 9,
  150125. 6,
  150126. 10,
  150127. 5,
  150128. 11,
  150129. 4,
  150130. 12,
  150131. 3,
  150132. 13,
  150133. 2,
  150134. 14,
  150135. 1,
  150136. 15,
  150137. 0,
  150138. 16,
  150139. };
  150140. static long _vq_lengthlist__44u6__p9_2[] = {
  150141. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150142. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150143. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150144. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150145. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150146. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150147. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150148. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150149. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150150. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150151. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150153. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150154. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150155. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150156. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150157. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150158. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150159. 10,
  150160. };
  150161. static float _vq_quantthresh__44u6__p9_2[] = {
  150162. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150163. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150164. };
  150165. static long _vq_quantmap__44u6__p9_2[] = {
  150166. 15, 13, 11, 9, 7, 5, 3, 1,
  150167. 0, 2, 4, 6, 8, 10, 12, 14,
  150168. 16,
  150169. };
  150170. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150171. _vq_quantthresh__44u6__p9_2,
  150172. _vq_quantmap__44u6__p9_2,
  150173. 17,
  150174. 17
  150175. };
  150176. static static_codebook _44u6__p9_2 = {
  150177. 2, 289,
  150178. _vq_lengthlist__44u6__p9_2,
  150179. 1, -529530880, 1611661312, 5, 0,
  150180. _vq_quantlist__44u6__p9_2,
  150181. NULL,
  150182. &_vq_auxt__44u6__p9_2,
  150183. NULL,
  150184. 0
  150185. };
  150186. static long _huff_lengthlist__44u6__short[] = {
  150187. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150188. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150189. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150190. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150191. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150192. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150193. 7, 6, 9,16,
  150194. };
  150195. static static_codebook _huff_book__44u6__short = {
  150196. 2, 100,
  150197. _huff_lengthlist__44u6__short,
  150198. 0, 0, 0, 0, 0,
  150199. NULL,
  150200. NULL,
  150201. NULL,
  150202. NULL,
  150203. 0
  150204. };
  150205. static long _huff_lengthlist__44u7__long[] = {
  150206. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150207. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150208. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150209. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150210. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150211. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150212. 12, 8, 6, 7,
  150213. };
  150214. static static_codebook _huff_book__44u7__long = {
  150215. 2, 100,
  150216. _huff_lengthlist__44u7__long,
  150217. 0, 0, 0, 0, 0,
  150218. NULL,
  150219. NULL,
  150220. NULL,
  150221. NULL,
  150222. 0
  150223. };
  150224. static long _vq_quantlist__44u7__p1_0[] = {
  150225. 1,
  150226. 0,
  150227. 2,
  150228. };
  150229. static long _vq_lengthlist__44u7__p1_0[] = {
  150230. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150231. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150232. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150233. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150234. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150235. 12,
  150236. };
  150237. static float _vq_quantthresh__44u7__p1_0[] = {
  150238. -0.5, 0.5,
  150239. };
  150240. static long _vq_quantmap__44u7__p1_0[] = {
  150241. 1, 0, 2,
  150242. };
  150243. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150244. _vq_quantthresh__44u7__p1_0,
  150245. _vq_quantmap__44u7__p1_0,
  150246. 3,
  150247. 3
  150248. };
  150249. static static_codebook _44u7__p1_0 = {
  150250. 4, 81,
  150251. _vq_lengthlist__44u7__p1_0,
  150252. 1, -535822336, 1611661312, 2, 0,
  150253. _vq_quantlist__44u7__p1_0,
  150254. NULL,
  150255. &_vq_auxt__44u7__p1_0,
  150256. NULL,
  150257. 0
  150258. };
  150259. static long _vq_quantlist__44u7__p2_0[] = {
  150260. 1,
  150261. 0,
  150262. 2,
  150263. };
  150264. static long _vq_lengthlist__44u7__p2_0[] = {
  150265. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150266. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150267. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150268. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150269. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150270. 9,
  150271. };
  150272. static float _vq_quantthresh__44u7__p2_0[] = {
  150273. -0.5, 0.5,
  150274. };
  150275. static long _vq_quantmap__44u7__p2_0[] = {
  150276. 1, 0, 2,
  150277. };
  150278. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150279. _vq_quantthresh__44u7__p2_0,
  150280. _vq_quantmap__44u7__p2_0,
  150281. 3,
  150282. 3
  150283. };
  150284. static static_codebook _44u7__p2_0 = {
  150285. 4, 81,
  150286. _vq_lengthlist__44u7__p2_0,
  150287. 1, -535822336, 1611661312, 2, 0,
  150288. _vq_quantlist__44u7__p2_0,
  150289. NULL,
  150290. &_vq_auxt__44u7__p2_0,
  150291. NULL,
  150292. 0
  150293. };
  150294. static long _vq_quantlist__44u7__p3_0[] = {
  150295. 2,
  150296. 1,
  150297. 3,
  150298. 0,
  150299. 4,
  150300. };
  150301. static long _vq_lengthlist__44u7__p3_0[] = {
  150302. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150303. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150304. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150305. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150306. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150307. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150308. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150309. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150310. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150311. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150312. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150313. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150314. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150315. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150316. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150317. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150318. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150319. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150320. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150321. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150322. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150323. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150324. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150325. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150326. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150327. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150328. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150329. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150330. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150331. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150332. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150333. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150334. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150335. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150336. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150337. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150338. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150339. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150340. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150341. 0,
  150342. };
  150343. static float _vq_quantthresh__44u7__p3_0[] = {
  150344. -1.5, -0.5, 0.5, 1.5,
  150345. };
  150346. static long _vq_quantmap__44u7__p3_0[] = {
  150347. 3, 1, 0, 2, 4,
  150348. };
  150349. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150350. _vq_quantthresh__44u7__p3_0,
  150351. _vq_quantmap__44u7__p3_0,
  150352. 5,
  150353. 5
  150354. };
  150355. static static_codebook _44u7__p3_0 = {
  150356. 4, 625,
  150357. _vq_lengthlist__44u7__p3_0,
  150358. 1, -533725184, 1611661312, 3, 0,
  150359. _vq_quantlist__44u7__p3_0,
  150360. NULL,
  150361. &_vq_auxt__44u7__p3_0,
  150362. NULL,
  150363. 0
  150364. };
  150365. static long _vq_quantlist__44u7__p4_0[] = {
  150366. 2,
  150367. 1,
  150368. 3,
  150369. 0,
  150370. 4,
  150371. };
  150372. static long _vq_lengthlist__44u7__p4_0[] = {
  150373. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150374. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150375. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150376. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150377. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150378. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150379. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150380. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150381. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150382. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150383. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150384. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150385. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150386. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150387. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150388. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150389. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150390. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150391. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150392. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150393. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150394. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150395. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150396. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150397. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150398. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150399. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150400. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150401. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150402. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150403. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150404. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150405. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150406. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150407. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150408. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150409. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150410. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150411. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150412. 14,
  150413. };
  150414. static float _vq_quantthresh__44u7__p4_0[] = {
  150415. -1.5, -0.5, 0.5, 1.5,
  150416. };
  150417. static long _vq_quantmap__44u7__p4_0[] = {
  150418. 3, 1, 0, 2, 4,
  150419. };
  150420. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150421. _vq_quantthresh__44u7__p4_0,
  150422. _vq_quantmap__44u7__p4_0,
  150423. 5,
  150424. 5
  150425. };
  150426. static static_codebook _44u7__p4_0 = {
  150427. 4, 625,
  150428. _vq_lengthlist__44u7__p4_0,
  150429. 1, -533725184, 1611661312, 3, 0,
  150430. _vq_quantlist__44u7__p4_0,
  150431. NULL,
  150432. &_vq_auxt__44u7__p4_0,
  150433. NULL,
  150434. 0
  150435. };
  150436. static long _vq_quantlist__44u7__p5_0[] = {
  150437. 4,
  150438. 3,
  150439. 5,
  150440. 2,
  150441. 6,
  150442. 1,
  150443. 7,
  150444. 0,
  150445. 8,
  150446. };
  150447. static long _vq_lengthlist__44u7__p5_0[] = {
  150448. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150449. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150450. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150451. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150452. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150453. 14,
  150454. };
  150455. static float _vq_quantthresh__44u7__p5_0[] = {
  150456. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150457. };
  150458. static long _vq_quantmap__44u7__p5_0[] = {
  150459. 7, 5, 3, 1, 0, 2, 4, 6,
  150460. 8,
  150461. };
  150462. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150463. _vq_quantthresh__44u7__p5_0,
  150464. _vq_quantmap__44u7__p5_0,
  150465. 9,
  150466. 9
  150467. };
  150468. static static_codebook _44u7__p5_0 = {
  150469. 2, 81,
  150470. _vq_lengthlist__44u7__p5_0,
  150471. 1, -531628032, 1611661312, 4, 0,
  150472. _vq_quantlist__44u7__p5_0,
  150473. NULL,
  150474. &_vq_auxt__44u7__p5_0,
  150475. NULL,
  150476. 0
  150477. };
  150478. static long _vq_quantlist__44u7__p6_0[] = {
  150479. 4,
  150480. 3,
  150481. 5,
  150482. 2,
  150483. 6,
  150484. 1,
  150485. 7,
  150486. 0,
  150487. 8,
  150488. };
  150489. static long _vq_lengthlist__44u7__p6_0[] = {
  150490. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150491. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150492. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150493. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150494. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150495. 12,
  150496. };
  150497. static float _vq_quantthresh__44u7__p6_0[] = {
  150498. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150499. };
  150500. static long _vq_quantmap__44u7__p6_0[] = {
  150501. 7, 5, 3, 1, 0, 2, 4, 6,
  150502. 8,
  150503. };
  150504. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150505. _vq_quantthresh__44u7__p6_0,
  150506. _vq_quantmap__44u7__p6_0,
  150507. 9,
  150508. 9
  150509. };
  150510. static static_codebook _44u7__p6_0 = {
  150511. 2, 81,
  150512. _vq_lengthlist__44u7__p6_0,
  150513. 1, -531628032, 1611661312, 4, 0,
  150514. _vq_quantlist__44u7__p6_0,
  150515. NULL,
  150516. &_vq_auxt__44u7__p6_0,
  150517. NULL,
  150518. 0
  150519. };
  150520. static long _vq_quantlist__44u7__p7_0[] = {
  150521. 1,
  150522. 0,
  150523. 2,
  150524. };
  150525. static long _vq_lengthlist__44u7__p7_0[] = {
  150526. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150527. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150528. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150529. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150530. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150531. 10,
  150532. };
  150533. static float _vq_quantthresh__44u7__p7_0[] = {
  150534. -5.5, 5.5,
  150535. };
  150536. static long _vq_quantmap__44u7__p7_0[] = {
  150537. 1, 0, 2,
  150538. };
  150539. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150540. _vq_quantthresh__44u7__p7_0,
  150541. _vq_quantmap__44u7__p7_0,
  150542. 3,
  150543. 3
  150544. };
  150545. static static_codebook _44u7__p7_0 = {
  150546. 4, 81,
  150547. _vq_lengthlist__44u7__p7_0,
  150548. 1, -529137664, 1618345984, 2, 0,
  150549. _vq_quantlist__44u7__p7_0,
  150550. NULL,
  150551. &_vq_auxt__44u7__p7_0,
  150552. NULL,
  150553. 0
  150554. };
  150555. static long _vq_quantlist__44u7__p7_1[] = {
  150556. 5,
  150557. 4,
  150558. 6,
  150559. 3,
  150560. 7,
  150561. 2,
  150562. 8,
  150563. 1,
  150564. 9,
  150565. 0,
  150566. 10,
  150567. };
  150568. static long _vq_lengthlist__44u7__p7_1[] = {
  150569. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150570. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150571. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150572. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150573. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150574. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150575. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150576. 8, 9, 9, 9, 9, 9,10,10,10,
  150577. };
  150578. static float _vq_quantthresh__44u7__p7_1[] = {
  150579. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150580. 3.5, 4.5,
  150581. };
  150582. static long _vq_quantmap__44u7__p7_1[] = {
  150583. 9, 7, 5, 3, 1, 0, 2, 4,
  150584. 6, 8, 10,
  150585. };
  150586. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150587. _vq_quantthresh__44u7__p7_1,
  150588. _vq_quantmap__44u7__p7_1,
  150589. 11,
  150590. 11
  150591. };
  150592. static static_codebook _44u7__p7_1 = {
  150593. 2, 121,
  150594. _vq_lengthlist__44u7__p7_1,
  150595. 1, -531365888, 1611661312, 4, 0,
  150596. _vq_quantlist__44u7__p7_1,
  150597. NULL,
  150598. &_vq_auxt__44u7__p7_1,
  150599. NULL,
  150600. 0
  150601. };
  150602. static long _vq_quantlist__44u7__p8_0[] = {
  150603. 5,
  150604. 4,
  150605. 6,
  150606. 3,
  150607. 7,
  150608. 2,
  150609. 8,
  150610. 1,
  150611. 9,
  150612. 0,
  150613. 10,
  150614. };
  150615. static long _vq_lengthlist__44u7__p8_0[] = {
  150616. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150617. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150618. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150619. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150620. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150621. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150622. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150623. 12,13,13,14,14,15,15,15,16,
  150624. };
  150625. static float _vq_quantthresh__44u7__p8_0[] = {
  150626. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150627. 38.5, 49.5,
  150628. };
  150629. static long _vq_quantmap__44u7__p8_0[] = {
  150630. 9, 7, 5, 3, 1, 0, 2, 4,
  150631. 6, 8, 10,
  150632. };
  150633. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150634. _vq_quantthresh__44u7__p8_0,
  150635. _vq_quantmap__44u7__p8_0,
  150636. 11,
  150637. 11
  150638. };
  150639. static static_codebook _44u7__p8_0 = {
  150640. 2, 121,
  150641. _vq_lengthlist__44u7__p8_0,
  150642. 1, -524582912, 1618345984, 4, 0,
  150643. _vq_quantlist__44u7__p8_0,
  150644. NULL,
  150645. &_vq_auxt__44u7__p8_0,
  150646. NULL,
  150647. 0
  150648. };
  150649. static long _vq_quantlist__44u7__p8_1[] = {
  150650. 5,
  150651. 4,
  150652. 6,
  150653. 3,
  150654. 7,
  150655. 2,
  150656. 8,
  150657. 1,
  150658. 9,
  150659. 0,
  150660. 10,
  150661. };
  150662. static long _vq_lengthlist__44u7__p8_1[] = {
  150663. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150664. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150665. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150666. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150667. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150668. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150669. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150670. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150671. };
  150672. static float _vq_quantthresh__44u7__p8_1[] = {
  150673. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150674. 3.5, 4.5,
  150675. };
  150676. static long _vq_quantmap__44u7__p8_1[] = {
  150677. 9, 7, 5, 3, 1, 0, 2, 4,
  150678. 6, 8, 10,
  150679. };
  150680. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150681. _vq_quantthresh__44u7__p8_1,
  150682. _vq_quantmap__44u7__p8_1,
  150683. 11,
  150684. 11
  150685. };
  150686. static static_codebook _44u7__p8_1 = {
  150687. 2, 121,
  150688. _vq_lengthlist__44u7__p8_1,
  150689. 1, -531365888, 1611661312, 4, 0,
  150690. _vq_quantlist__44u7__p8_1,
  150691. NULL,
  150692. &_vq_auxt__44u7__p8_1,
  150693. NULL,
  150694. 0
  150695. };
  150696. static long _vq_quantlist__44u7__p9_0[] = {
  150697. 5,
  150698. 4,
  150699. 6,
  150700. 3,
  150701. 7,
  150702. 2,
  150703. 8,
  150704. 1,
  150705. 9,
  150706. 0,
  150707. 10,
  150708. };
  150709. static long _vq_lengthlist__44u7__p9_0[] = {
  150710. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150711. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150716. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150717. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150718. };
  150719. static float _vq_quantthresh__44u7__p9_0[] = {
  150720. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150721. 2229.5, 2866.5,
  150722. };
  150723. static long _vq_quantmap__44u7__p9_0[] = {
  150724. 9, 7, 5, 3, 1, 0, 2, 4,
  150725. 6, 8, 10,
  150726. };
  150727. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150728. _vq_quantthresh__44u7__p9_0,
  150729. _vq_quantmap__44u7__p9_0,
  150730. 11,
  150731. 11
  150732. };
  150733. static static_codebook _44u7__p9_0 = {
  150734. 2, 121,
  150735. _vq_lengthlist__44u7__p9_0,
  150736. 1, -512171520, 1630791680, 4, 0,
  150737. _vq_quantlist__44u7__p9_0,
  150738. NULL,
  150739. &_vq_auxt__44u7__p9_0,
  150740. NULL,
  150741. 0
  150742. };
  150743. static long _vq_quantlist__44u7__p9_1[] = {
  150744. 6,
  150745. 5,
  150746. 7,
  150747. 4,
  150748. 8,
  150749. 3,
  150750. 9,
  150751. 2,
  150752. 10,
  150753. 1,
  150754. 11,
  150755. 0,
  150756. 12,
  150757. };
  150758. static long _vq_lengthlist__44u7__p9_1[] = {
  150759. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150760. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150761. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150762. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150763. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150764. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150765. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150766. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150767. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150768. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150769. 15,15,15,15,17,17,16,17,16,
  150770. };
  150771. static float _vq_quantthresh__44u7__p9_1[] = {
  150772. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150773. 122.5, 171.5, 220.5, 269.5,
  150774. };
  150775. static long _vq_quantmap__44u7__p9_1[] = {
  150776. 11, 9, 7, 5, 3, 1, 0, 2,
  150777. 4, 6, 8, 10, 12,
  150778. };
  150779. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150780. _vq_quantthresh__44u7__p9_1,
  150781. _vq_quantmap__44u7__p9_1,
  150782. 13,
  150783. 13
  150784. };
  150785. static static_codebook _44u7__p9_1 = {
  150786. 2, 169,
  150787. _vq_lengthlist__44u7__p9_1,
  150788. 1, -518889472, 1622704128, 4, 0,
  150789. _vq_quantlist__44u7__p9_1,
  150790. NULL,
  150791. &_vq_auxt__44u7__p9_1,
  150792. NULL,
  150793. 0
  150794. };
  150795. static long _vq_quantlist__44u7__p9_2[] = {
  150796. 24,
  150797. 23,
  150798. 25,
  150799. 22,
  150800. 26,
  150801. 21,
  150802. 27,
  150803. 20,
  150804. 28,
  150805. 19,
  150806. 29,
  150807. 18,
  150808. 30,
  150809. 17,
  150810. 31,
  150811. 16,
  150812. 32,
  150813. 15,
  150814. 33,
  150815. 14,
  150816. 34,
  150817. 13,
  150818. 35,
  150819. 12,
  150820. 36,
  150821. 11,
  150822. 37,
  150823. 10,
  150824. 38,
  150825. 9,
  150826. 39,
  150827. 8,
  150828. 40,
  150829. 7,
  150830. 41,
  150831. 6,
  150832. 42,
  150833. 5,
  150834. 43,
  150835. 4,
  150836. 44,
  150837. 3,
  150838. 45,
  150839. 2,
  150840. 46,
  150841. 1,
  150842. 47,
  150843. 0,
  150844. 48,
  150845. };
  150846. static long _vq_lengthlist__44u7__p9_2[] = {
  150847. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150848. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150849. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150850. 8,
  150851. };
  150852. static float _vq_quantthresh__44u7__p9_2[] = {
  150853. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150854. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150855. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150856. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150857. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150858. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150859. };
  150860. static long _vq_quantmap__44u7__p9_2[] = {
  150861. 47, 45, 43, 41, 39, 37, 35, 33,
  150862. 31, 29, 27, 25, 23, 21, 19, 17,
  150863. 15, 13, 11, 9, 7, 5, 3, 1,
  150864. 0, 2, 4, 6, 8, 10, 12, 14,
  150865. 16, 18, 20, 22, 24, 26, 28, 30,
  150866. 32, 34, 36, 38, 40, 42, 44, 46,
  150867. 48,
  150868. };
  150869. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150870. _vq_quantthresh__44u7__p9_2,
  150871. _vq_quantmap__44u7__p9_2,
  150872. 49,
  150873. 49
  150874. };
  150875. static static_codebook _44u7__p9_2 = {
  150876. 1, 49,
  150877. _vq_lengthlist__44u7__p9_2,
  150878. 1, -526909440, 1611661312, 6, 0,
  150879. _vq_quantlist__44u7__p9_2,
  150880. NULL,
  150881. &_vq_auxt__44u7__p9_2,
  150882. NULL,
  150883. 0
  150884. };
  150885. static long _huff_lengthlist__44u7__short[] = {
  150886. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150887. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150888. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150889. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150890. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150891. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150892. 6, 8, 5, 9,
  150893. };
  150894. static static_codebook _huff_book__44u7__short = {
  150895. 2, 100,
  150896. _huff_lengthlist__44u7__short,
  150897. 0, 0, 0, 0, 0,
  150898. NULL,
  150899. NULL,
  150900. NULL,
  150901. NULL,
  150902. 0
  150903. };
  150904. static long _huff_lengthlist__44u8__long[] = {
  150905. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150906. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150907. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150908. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150909. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150910. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150911. 10, 8, 8, 9,
  150912. };
  150913. static static_codebook _huff_book__44u8__long = {
  150914. 2, 100,
  150915. _huff_lengthlist__44u8__long,
  150916. 0, 0, 0, 0, 0,
  150917. NULL,
  150918. NULL,
  150919. NULL,
  150920. NULL,
  150921. 0
  150922. };
  150923. static long _huff_lengthlist__44u8__short[] = {
  150924. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150925. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150926. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150927. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150928. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150929. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150930. 10,10,15,17,
  150931. };
  150932. static static_codebook _huff_book__44u8__short = {
  150933. 2, 100,
  150934. _huff_lengthlist__44u8__short,
  150935. 0, 0, 0, 0, 0,
  150936. NULL,
  150937. NULL,
  150938. NULL,
  150939. NULL,
  150940. 0
  150941. };
  150942. static long _vq_quantlist__44u8_p1_0[] = {
  150943. 1,
  150944. 0,
  150945. 2,
  150946. };
  150947. static long _vq_lengthlist__44u8_p1_0[] = {
  150948. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150949. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150950. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150951. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150952. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150953. 10,
  150954. };
  150955. static float _vq_quantthresh__44u8_p1_0[] = {
  150956. -0.5, 0.5,
  150957. };
  150958. static long _vq_quantmap__44u8_p1_0[] = {
  150959. 1, 0, 2,
  150960. };
  150961. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150962. _vq_quantthresh__44u8_p1_0,
  150963. _vq_quantmap__44u8_p1_0,
  150964. 3,
  150965. 3
  150966. };
  150967. static static_codebook _44u8_p1_0 = {
  150968. 4, 81,
  150969. _vq_lengthlist__44u8_p1_0,
  150970. 1, -535822336, 1611661312, 2, 0,
  150971. _vq_quantlist__44u8_p1_0,
  150972. NULL,
  150973. &_vq_auxt__44u8_p1_0,
  150974. NULL,
  150975. 0
  150976. };
  150977. static long _vq_quantlist__44u8_p2_0[] = {
  150978. 2,
  150979. 1,
  150980. 3,
  150981. 0,
  150982. 4,
  150983. };
  150984. static long _vq_lengthlist__44u8_p2_0[] = {
  150985. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150986. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150987. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150988. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150989. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150990. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150991. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150992. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150993. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150994. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150995. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150996. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150997. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150998. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150999. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151000. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151001. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151002. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151003. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151004. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151005. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151006. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151007. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151008. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151009. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151010. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151011. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151012. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151013. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151014. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151015. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151016. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151017. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151018. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151019. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151020. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151021. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151022. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151023. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151024. 14,
  151025. };
  151026. static float _vq_quantthresh__44u8_p2_0[] = {
  151027. -1.5, -0.5, 0.5, 1.5,
  151028. };
  151029. static long _vq_quantmap__44u8_p2_0[] = {
  151030. 3, 1, 0, 2, 4,
  151031. };
  151032. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151033. _vq_quantthresh__44u8_p2_0,
  151034. _vq_quantmap__44u8_p2_0,
  151035. 5,
  151036. 5
  151037. };
  151038. static static_codebook _44u8_p2_0 = {
  151039. 4, 625,
  151040. _vq_lengthlist__44u8_p2_0,
  151041. 1, -533725184, 1611661312, 3, 0,
  151042. _vq_quantlist__44u8_p2_0,
  151043. NULL,
  151044. &_vq_auxt__44u8_p2_0,
  151045. NULL,
  151046. 0
  151047. };
  151048. static long _vq_quantlist__44u8_p3_0[] = {
  151049. 4,
  151050. 3,
  151051. 5,
  151052. 2,
  151053. 6,
  151054. 1,
  151055. 7,
  151056. 0,
  151057. 8,
  151058. };
  151059. static long _vq_lengthlist__44u8_p3_0[] = {
  151060. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151061. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151062. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151063. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151064. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151065. 12,
  151066. };
  151067. static float _vq_quantthresh__44u8_p3_0[] = {
  151068. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151069. };
  151070. static long _vq_quantmap__44u8_p3_0[] = {
  151071. 7, 5, 3, 1, 0, 2, 4, 6,
  151072. 8,
  151073. };
  151074. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151075. _vq_quantthresh__44u8_p3_0,
  151076. _vq_quantmap__44u8_p3_0,
  151077. 9,
  151078. 9
  151079. };
  151080. static static_codebook _44u8_p3_0 = {
  151081. 2, 81,
  151082. _vq_lengthlist__44u8_p3_0,
  151083. 1, -531628032, 1611661312, 4, 0,
  151084. _vq_quantlist__44u8_p3_0,
  151085. NULL,
  151086. &_vq_auxt__44u8_p3_0,
  151087. NULL,
  151088. 0
  151089. };
  151090. static long _vq_quantlist__44u8_p4_0[] = {
  151091. 8,
  151092. 7,
  151093. 9,
  151094. 6,
  151095. 10,
  151096. 5,
  151097. 11,
  151098. 4,
  151099. 12,
  151100. 3,
  151101. 13,
  151102. 2,
  151103. 14,
  151104. 1,
  151105. 15,
  151106. 0,
  151107. 16,
  151108. };
  151109. static long _vq_lengthlist__44u8_p4_0[] = {
  151110. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151111. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151112. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151113. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151114. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151115. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151116. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151117. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151118. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151119. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151120. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151121. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151122. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151123. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151124. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151125. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151126. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151127. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151128. 14,
  151129. };
  151130. static float _vq_quantthresh__44u8_p4_0[] = {
  151131. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151132. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151133. };
  151134. static long _vq_quantmap__44u8_p4_0[] = {
  151135. 15, 13, 11, 9, 7, 5, 3, 1,
  151136. 0, 2, 4, 6, 8, 10, 12, 14,
  151137. 16,
  151138. };
  151139. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151140. _vq_quantthresh__44u8_p4_0,
  151141. _vq_quantmap__44u8_p4_0,
  151142. 17,
  151143. 17
  151144. };
  151145. static static_codebook _44u8_p4_0 = {
  151146. 2, 289,
  151147. _vq_lengthlist__44u8_p4_0,
  151148. 1, -529530880, 1611661312, 5, 0,
  151149. _vq_quantlist__44u8_p4_0,
  151150. NULL,
  151151. &_vq_auxt__44u8_p4_0,
  151152. NULL,
  151153. 0
  151154. };
  151155. static long _vq_quantlist__44u8_p5_0[] = {
  151156. 1,
  151157. 0,
  151158. 2,
  151159. };
  151160. static long _vq_lengthlist__44u8_p5_0[] = {
  151161. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151162. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151163. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151164. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151165. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151166. 10,
  151167. };
  151168. static float _vq_quantthresh__44u8_p5_0[] = {
  151169. -5.5, 5.5,
  151170. };
  151171. static long _vq_quantmap__44u8_p5_0[] = {
  151172. 1, 0, 2,
  151173. };
  151174. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151175. _vq_quantthresh__44u8_p5_0,
  151176. _vq_quantmap__44u8_p5_0,
  151177. 3,
  151178. 3
  151179. };
  151180. static static_codebook _44u8_p5_0 = {
  151181. 4, 81,
  151182. _vq_lengthlist__44u8_p5_0,
  151183. 1, -529137664, 1618345984, 2, 0,
  151184. _vq_quantlist__44u8_p5_0,
  151185. NULL,
  151186. &_vq_auxt__44u8_p5_0,
  151187. NULL,
  151188. 0
  151189. };
  151190. static long _vq_quantlist__44u8_p5_1[] = {
  151191. 5,
  151192. 4,
  151193. 6,
  151194. 3,
  151195. 7,
  151196. 2,
  151197. 8,
  151198. 1,
  151199. 9,
  151200. 0,
  151201. 10,
  151202. };
  151203. static long _vq_lengthlist__44u8_p5_1[] = {
  151204. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151205. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151206. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151207. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151208. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151209. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151210. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151211. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151212. };
  151213. static float _vq_quantthresh__44u8_p5_1[] = {
  151214. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151215. 3.5, 4.5,
  151216. };
  151217. static long _vq_quantmap__44u8_p5_1[] = {
  151218. 9, 7, 5, 3, 1, 0, 2, 4,
  151219. 6, 8, 10,
  151220. };
  151221. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151222. _vq_quantthresh__44u8_p5_1,
  151223. _vq_quantmap__44u8_p5_1,
  151224. 11,
  151225. 11
  151226. };
  151227. static static_codebook _44u8_p5_1 = {
  151228. 2, 121,
  151229. _vq_lengthlist__44u8_p5_1,
  151230. 1, -531365888, 1611661312, 4, 0,
  151231. _vq_quantlist__44u8_p5_1,
  151232. NULL,
  151233. &_vq_auxt__44u8_p5_1,
  151234. NULL,
  151235. 0
  151236. };
  151237. static long _vq_quantlist__44u8_p6_0[] = {
  151238. 6,
  151239. 5,
  151240. 7,
  151241. 4,
  151242. 8,
  151243. 3,
  151244. 9,
  151245. 2,
  151246. 10,
  151247. 1,
  151248. 11,
  151249. 0,
  151250. 12,
  151251. };
  151252. static long _vq_lengthlist__44u8_p6_0[] = {
  151253. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151254. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151255. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151256. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151257. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151258. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151259. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151260. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151261. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151262. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151263. 11,11,11,11,11,12,11,12,12,
  151264. };
  151265. static float _vq_quantthresh__44u8_p6_0[] = {
  151266. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151267. 12.5, 17.5, 22.5, 27.5,
  151268. };
  151269. static long _vq_quantmap__44u8_p6_0[] = {
  151270. 11, 9, 7, 5, 3, 1, 0, 2,
  151271. 4, 6, 8, 10, 12,
  151272. };
  151273. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151274. _vq_quantthresh__44u8_p6_0,
  151275. _vq_quantmap__44u8_p6_0,
  151276. 13,
  151277. 13
  151278. };
  151279. static static_codebook _44u8_p6_0 = {
  151280. 2, 169,
  151281. _vq_lengthlist__44u8_p6_0,
  151282. 1, -526516224, 1616117760, 4, 0,
  151283. _vq_quantlist__44u8_p6_0,
  151284. NULL,
  151285. &_vq_auxt__44u8_p6_0,
  151286. NULL,
  151287. 0
  151288. };
  151289. static long _vq_quantlist__44u8_p6_1[] = {
  151290. 2,
  151291. 1,
  151292. 3,
  151293. 0,
  151294. 4,
  151295. };
  151296. static long _vq_lengthlist__44u8_p6_1[] = {
  151297. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151298. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151299. };
  151300. static float _vq_quantthresh__44u8_p6_1[] = {
  151301. -1.5, -0.5, 0.5, 1.5,
  151302. };
  151303. static long _vq_quantmap__44u8_p6_1[] = {
  151304. 3, 1, 0, 2, 4,
  151305. };
  151306. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151307. _vq_quantthresh__44u8_p6_1,
  151308. _vq_quantmap__44u8_p6_1,
  151309. 5,
  151310. 5
  151311. };
  151312. static static_codebook _44u8_p6_1 = {
  151313. 2, 25,
  151314. _vq_lengthlist__44u8_p6_1,
  151315. 1, -533725184, 1611661312, 3, 0,
  151316. _vq_quantlist__44u8_p6_1,
  151317. NULL,
  151318. &_vq_auxt__44u8_p6_1,
  151319. NULL,
  151320. 0
  151321. };
  151322. static long _vq_quantlist__44u8_p7_0[] = {
  151323. 6,
  151324. 5,
  151325. 7,
  151326. 4,
  151327. 8,
  151328. 3,
  151329. 9,
  151330. 2,
  151331. 10,
  151332. 1,
  151333. 11,
  151334. 0,
  151335. 12,
  151336. };
  151337. static long _vq_lengthlist__44u8_p7_0[] = {
  151338. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151339. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151340. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151341. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151342. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151343. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151344. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151345. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151346. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151347. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151348. 13,13,14,14,14,15,15,15,16,
  151349. };
  151350. static float _vq_quantthresh__44u8_p7_0[] = {
  151351. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151352. 27.5, 38.5, 49.5, 60.5,
  151353. };
  151354. static long _vq_quantmap__44u8_p7_0[] = {
  151355. 11, 9, 7, 5, 3, 1, 0, 2,
  151356. 4, 6, 8, 10, 12,
  151357. };
  151358. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151359. _vq_quantthresh__44u8_p7_0,
  151360. _vq_quantmap__44u8_p7_0,
  151361. 13,
  151362. 13
  151363. };
  151364. static static_codebook _44u8_p7_0 = {
  151365. 2, 169,
  151366. _vq_lengthlist__44u8_p7_0,
  151367. 1, -523206656, 1618345984, 4, 0,
  151368. _vq_quantlist__44u8_p7_0,
  151369. NULL,
  151370. &_vq_auxt__44u8_p7_0,
  151371. NULL,
  151372. 0
  151373. };
  151374. static long _vq_quantlist__44u8_p7_1[] = {
  151375. 5,
  151376. 4,
  151377. 6,
  151378. 3,
  151379. 7,
  151380. 2,
  151381. 8,
  151382. 1,
  151383. 9,
  151384. 0,
  151385. 10,
  151386. };
  151387. static long _vq_lengthlist__44u8_p7_1[] = {
  151388. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151389. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151390. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151391. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151392. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151393. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151394. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151395. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151396. };
  151397. static float _vq_quantthresh__44u8_p7_1[] = {
  151398. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151399. 3.5, 4.5,
  151400. };
  151401. static long _vq_quantmap__44u8_p7_1[] = {
  151402. 9, 7, 5, 3, 1, 0, 2, 4,
  151403. 6, 8, 10,
  151404. };
  151405. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151406. _vq_quantthresh__44u8_p7_1,
  151407. _vq_quantmap__44u8_p7_1,
  151408. 11,
  151409. 11
  151410. };
  151411. static static_codebook _44u8_p7_1 = {
  151412. 2, 121,
  151413. _vq_lengthlist__44u8_p7_1,
  151414. 1, -531365888, 1611661312, 4, 0,
  151415. _vq_quantlist__44u8_p7_1,
  151416. NULL,
  151417. &_vq_auxt__44u8_p7_1,
  151418. NULL,
  151419. 0
  151420. };
  151421. static long _vq_quantlist__44u8_p8_0[] = {
  151422. 7,
  151423. 6,
  151424. 8,
  151425. 5,
  151426. 9,
  151427. 4,
  151428. 10,
  151429. 3,
  151430. 11,
  151431. 2,
  151432. 12,
  151433. 1,
  151434. 13,
  151435. 0,
  151436. 14,
  151437. };
  151438. static long _vq_lengthlist__44u8_p8_0[] = {
  151439. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151440. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151441. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151442. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151443. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151444. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151445. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151446. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151447. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151448. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151449. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151450. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151451. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151452. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151453. 17,
  151454. };
  151455. static float _vq_quantthresh__44u8_p8_0[] = {
  151456. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151457. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151458. };
  151459. static long _vq_quantmap__44u8_p8_0[] = {
  151460. 13, 11, 9, 7, 5, 3, 1, 0,
  151461. 2, 4, 6, 8, 10, 12, 14,
  151462. };
  151463. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151464. _vq_quantthresh__44u8_p8_0,
  151465. _vq_quantmap__44u8_p8_0,
  151466. 15,
  151467. 15
  151468. };
  151469. static static_codebook _44u8_p8_0 = {
  151470. 2, 225,
  151471. _vq_lengthlist__44u8_p8_0,
  151472. 1, -520986624, 1620377600, 4, 0,
  151473. _vq_quantlist__44u8_p8_0,
  151474. NULL,
  151475. &_vq_auxt__44u8_p8_0,
  151476. NULL,
  151477. 0
  151478. };
  151479. static long _vq_quantlist__44u8_p8_1[] = {
  151480. 10,
  151481. 9,
  151482. 11,
  151483. 8,
  151484. 12,
  151485. 7,
  151486. 13,
  151487. 6,
  151488. 14,
  151489. 5,
  151490. 15,
  151491. 4,
  151492. 16,
  151493. 3,
  151494. 17,
  151495. 2,
  151496. 18,
  151497. 1,
  151498. 19,
  151499. 0,
  151500. 20,
  151501. };
  151502. static long _vq_lengthlist__44u8_p8_1[] = {
  151503. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151504. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151505. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151506. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151507. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151508. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151510. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151511. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151512. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151513. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151514. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151515. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151516. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151517. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151518. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151519. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151520. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151521. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151522. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151523. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151524. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151525. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151526. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151527. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151528. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151529. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151530. 10,10,10,10,10,10,10,10,10,
  151531. };
  151532. static float _vq_quantthresh__44u8_p8_1[] = {
  151533. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151534. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151535. 6.5, 7.5, 8.5, 9.5,
  151536. };
  151537. static long _vq_quantmap__44u8_p8_1[] = {
  151538. 19, 17, 15, 13, 11, 9, 7, 5,
  151539. 3, 1, 0, 2, 4, 6, 8, 10,
  151540. 12, 14, 16, 18, 20,
  151541. };
  151542. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151543. _vq_quantthresh__44u8_p8_1,
  151544. _vq_quantmap__44u8_p8_1,
  151545. 21,
  151546. 21
  151547. };
  151548. static static_codebook _44u8_p8_1 = {
  151549. 2, 441,
  151550. _vq_lengthlist__44u8_p8_1,
  151551. 1, -529268736, 1611661312, 5, 0,
  151552. _vq_quantlist__44u8_p8_1,
  151553. NULL,
  151554. &_vq_auxt__44u8_p8_1,
  151555. NULL,
  151556. 0
  151557. };
  151558. static long _vq_quantlist__44u8_p9_0[] = {
  151559. 4,
  151560. 3,
  151561. 5,
  151562. 2,
  151563. 6,
  151564. 1,
  151565. 7,
  151566. 0,
  151567. 8,
  151568. };
  151569. static long _vq_lengthlist__44u8_p9_0[] = {
  151570. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151571. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151572. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151573. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151574. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151575. 8,
  151576. };
  151577. static float _vq_quantthresh__44u8_p9_0[] = {
  151578. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151579. };
  151580. static long _vq_quantmap__44u8_p9_0[] = {
  151581. 7, 5, 3, 1, 0, 2, 4, 6,
  151582. 8,
  151583. };
  151584. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151585. _vq_quantthresh__44u8_p9_0,
  151586. _vq_quantmap__44u8_p9_0,
  151587. 9,
  151588. 9
  151589. };
  151590. static static_codebook _44u8_p9_0 = {
  151591. 2, 81,
  151592. _vq_lengthlist__44u8_p9_0,
  151593. 1, -511895552, 1631393792, 4, 0,
  151594. _vq_quantlist__44u8_p9_0,
  151595. NULL,
  151596. &_vq_auxt__44u8_p9_0,
  151597. NULL,
  151598. 0
  151599. };
  151600. static long _vq_quantlist__44u8_p9_1[] = {
  151601. 9,
  151602. 8,
  151603. 10,
  151604. 7,
  151605. 11,
  151606. 6,
  151607. 12,
  151608. 5,
  151609. 13,
  151610. 4,
  151611. 14,
  151612. 3,
  151613. 15,
  151614. 2,
  151615. 16,
  151616. 1,
  151617. 17,
  151618. 0,
  151619. 18,
  151620. };
  151621. static long _vq_lengthlist__44u8_p9_1[] = {
  151622. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151623. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151624. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151625. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151626. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151627. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151628. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151629. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151630. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151631. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151632. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151633. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151634. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151635. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151636. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151637. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151638. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151639. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151640. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151641. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151642. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151643. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151644. 16,15,16,16,16,16,16,16,16,
  151645. };
  151646. static float _vq_quantthresh__44u8_p9_1[] = {
  151647. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151648. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151649. 367.5, 416.5,
  151650. };
  151651. static long _vq_quantmap__44u8_p9_1[] = {
  151652. 17, 15, 13, 11, 9, 7, 5, 3,
  151653. 1, 0, 2, 4, 6, 8, 10, 12,
  151654. 14, 16, 18,
  151655. };
  151656. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151657. _vq_quantthresh__44u8_p9_1,
  151658. _vq_quantmap__44u8_p9_1,
  151659. 19,
  151660. 19
  151661. };
  151662. static static_codebook _44u8_p9_1 = {
  151663. 2, 361,
  151664. _vq_lengthlist__44u8_p9_1,
  151665. 1, -518287360, 1622704128, 5, 0,
  151666. _vq_quantlist__44u8_p9_1,
  151667. NULL,
  151668. &_vq_auxt__44u8_p9_1,
  151669. NULL,
  151670. 0
  151671. };
  151672. static long _vq_quantlist__44u8_p9_2[] = {
  151673. 24,
  151674. 23,
  151675. 25,
  151676. 22,
  151677. 26,
  151678. 21,
  151679. 27,
  151680. 20,
  151681. 28,
  151682. 19,
  151683. 29,
  151684. 18,
  151685. 30,
  151686. 17,
  151687. 31,
  151688. 16,
  151689. 32,
  151690. 15,
  151691. 33,
  151692. 14,
  151693. 34,
  151694. 13,
  151695. 35,
  151696. 12,
  151697. 36,
  151698. 11,
  151699. 37,
  151700. 10,
  151701. 38,
  151702. 9,
  151703. 39,
  151704. 8,
  151705. 40,
  151706. 7,
  151707. 41,
  151708. 6,
  151709. 42,
  151710. 5,
  151711. 43,
  151712. 4,
  151713. 44,
  151714. 3,
  151715. 45,
  151716. 2,
  151717. 46,
  151718. 1,
  151719. 47,
  151720. 0,
  151721. 48,
  151722. };
  151723. static long _vq_lengthlist__44u8_p9_2[] = {
  151724. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151725. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151726. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151727. 7,
  151728. };
  151729. static float _vq_quantthresh__44u8_p9_2[] = {
  151730. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151731. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151732. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151733. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151734. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151735. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151736. };
  151737. static long _vq_quantmap__44u8_p9_2[] = {
  151738. 47, 45, 43, 41, 39, 37, 35, 33,
  151739. 31, 29, 27, 25, 23, 21, 19, 17,
  151740. 15, 13, 11, 9, 7, 5, 3, 1,
  151741. 0, 2, 4, 6, 8, 10, 12, 14,
  151742. 16, 18, 20, 22, 24, 26, 28, 30,
  151743. 32, 34, 36, 38, 40, 42, 44, 46,
  151744. 48,
  151745. };
  151746. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151747. _vq_quantthresh__44u8_p9_2,
  151748. _vq_quantmap__44u8_p9_2,
  151749. 49,
  151750. 49
  151751. };
  151752. static static_codebook _44u8_p9_2 = {
  151753. 1, 49,
  151754. _vq_lengthlist__44u8_p9_2,
  151755. 1, -526909440, 1611661312, 6, 0,
  151756. _vq_quantlist__44u8_p9_2,
  151757. NULL,
  151758. &_vq_auxt__44u8_p9_2,
  151759. NULL,
  151760. 0
  151761. };
  151762. static long _huff_lengthlist__44u9__long[] = {
  151763. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151764. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151765. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151766. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151767. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151768. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151769. 10, 8, 8, 9,
  151770. };
  151771. static static_codebook _huff_book__44u9__long = {
  151772. 2, 100,
  151773. _huff_lengthlist__44u9__long,
  151774. 0, 0, 0, 0, 0,
  151775. NULL,
  151776. NULL,
  151777. NULL,
  151778. NULL,
  151779. 0
  151780. };
  151781. static long _huff_lengthlist__44u9__short[] = {
  151782. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151783. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151784. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151785. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151786. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151787. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151788. 9, 9,12,15,
  151789. };
  151790. static static_codebook _huff_book__44u9__short = {
  151791. 2, 100,
  151792. _huff_lengthlist__44u9__short,
  151793. 0, 0, 0, 0, 0,
  151794. NULL,
  151795. NULL,
  151796. NULL,
  151797. NULL,
  151798. 0
  151799. };
  151800. static long _vq_quantlist__44u9_p1_0[] = {
  151801. 1,
  151802. 0,
  151803. 2,
  151804. };
  151805. static long _vq_lengthlist__44u9_p1_0[] = {
  151806. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151807. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151808. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151809. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151810. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151811. 10,
  151812. };
  151813. static float _vq_quantthresh__44u9_p1_0[] = {
  151814. -0.5, 0.5,
  151815. };
  151816. static long _vq_quantmap__44u9_p1_0[] = {
  151817. 1, 0, 2,
  151818. };
  151819. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151820. _vq_quantthresh__44u9_p1_0,
  151821. _vq_quantmap__44u9_p1_0,
  151822. 3,
  151823. 3
  151824. };
  151825. static static_codebook _44u9_p1_0 = {
  151826. 4, 81,
  151827. _vq_lengthlist__44u9_p1_0,
  151828. 1, -535822336, 1611661312, 2, 0,
  151829. _vq_quantlist__44u9_p1_0,
  151830. NULL,
  151831. &_vq_auxt__44u9_p1_0,
  151832. NULL,
  151833. 0
  151834. };
  151835. static long _vq_quantlist__44u9_p2_0[] = {
  151836. 2,
  151837. 1,
  151838. 3,
  151839. 0,
  151840. 4,
  151841. };
  151842. static long _vq_lengthlist__44u9_p2_0[] = {
  151843. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151844. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151845. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151846. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151847. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151848. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151849. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151850. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151851. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151852. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151853. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151854. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151855. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151856. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151857. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151858. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151859. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151860. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151861. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151862. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151863. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151864. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151865. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151866. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151867. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151868. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151869. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151870. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151871. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151872. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151873. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151874. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151875. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151876. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151877. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151878. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151879. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151880. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151881. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151882. 14,
  151883. };
  151884. static float _vq_quantthresh__44u9_p2_0[] = {
  151885. -1.5, -0.5, 0.5, 1.5,
  151886. };
  151887. static long _vq_quantmap__44u9_p2_0[] = {
  151888. 3, 1, 0, 2, 4,
  151889. };
  151890. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151891. _vq_quantthresh__44u9_p2_0,
  151892. _vq_quantmap__44u9_p2_0,
  151893. 5,
  151894. 5
  151895. };
  151896. static static_codebook _44u9_p2_0 = {
  151897. 4, 625,
  151898. _vq_lengthlist__44u9_p2_0,
  151899. 1, -533725184, 1611661312, 3, 0,
  151900. _vq_quantlist__44u9_p2_0,
  151901. NULL,
  151902. &_vq_auxt__44u9_p2_0,
  151903. NULL,
  151904. 0
  151905. };
  151906. static long _vq_quantlist__44u9_p3_0[] = {
  151907. 4,
  151908. 3,
  151909. 5,
  151910. 2,
  151911. 6,
  151912. 1,
  151913. 7,
  151914. 0,
  151915. 8,
  151916. };
  151917. static long _vq_lengthlist__44u9_p3_0[] = {
  151918. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151919. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151920. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151921. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151922. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151923. 11,
  151924. };
  151925. static float _vq_quantthresh__44u9_p3_0[] = {
  151926. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151927. };
  151928. static long _vq_quantmap__44u9_p3_0[] = {
  151929. 7, 5, 3, 1, 0, 2, 4, 6,
  151930. 8,
  151931. };
  151932. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151933. _vq_quantthresh__44u9_p3_0,
  151934. _vq_quantmap__44u9_p3_0,
  151935. 9,
  151936. 9
  151937. };
  151938. static static_codebook _44u9_p3_0 = {
  151939. 2, 81,
  151940. _vq_lengthlist__44u9_p3_0,
  151941. 1, -531628032, 1611661312, 4, 0,
  151942. _vq_quantlist__44u9_p3_0,
  151943. NULL,
  151944. &_vq_auxt__44u9_p3_0,
  151945. NULL,
  151946. 0
  151947. };
  151948. static long _vq_quantlist__44u9_p4_0[] = {
  151949. 8,
  151950. 7,
  151951. 9,
  151952. 6,
  151953. 10,
  151954. 5,
  151955. 11,
  151956. 4,
  151957. 12,
  151958. 3,
  151959. 13,
  151960. 2,
  151961. 14,
  151962. 1,
  151963. 15,
  151964. 0,
  151965. 16,
  151966. };
  151967. static long _vq_lengthlist__44u9_p4_0[] = {
  151968. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151969. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151970. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151971. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151972. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151973. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151974. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151975. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151976. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151977. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151978. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151979. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151980. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151981. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151982. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151983. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151984. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151985. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151986. 14,
  151987. };
  151988. static float _vq_quantthresh__44u9_p4_0[] = {
  151989. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151990. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151991. };
  151992. static long _vq_quantmap__44u9_p4_0[] = {
  151993. 15, 13, 11, 9, 7, 5, 3, 1,
  151994. 0, 2, 4, 6, 8, 10, 12, 14,
  151995. 16,
  151996. };
  151997. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151998. _vq_quantthresh__44u9_p4_0,
  151999. _vq_quantmap__44u9_p4_0,
  152000. 17,
  152001. 17
  152002. };
  152003. static static_codebook _44u9_p4_0 = {
  152004. 2, 289,
  152005. _vq_lengthlist__44u9_p4_0,
  152006. 1, -529530880, 1611661312, 5, 0,
  152007. _vq_quantlist__44u9_p4_0,
  152008. NULL,
  152009. &_vq_auxt__44u9_p4_0,
  152010. NULL,
  152011. 0
  152012. };
  152013. static long _vq_quantlist__44u9_p5_0[] = {
  152014. 1,
  152015. 0,
  152016. 2,
  152017. };
  152018. static long _vq_lengthlist__44u9_p5_0[] = {
  152019. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152020. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152021. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152022. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152023. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152024. 10,
  152025. };
  152026. static float _vq_quantthresh__44u9_p5_0[] = {
  152027. -5.5, 5.5,
  152028. };
  152029. static long _vq_quantmap__44u9_p5_0[] = {
  152030. 1, 0, 2,
  152031. };
  152032. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152033. _vq_quantthresh__44u9_p5_0,
  152034. _vq_quantmap__44u9_p5_0,
  152035. 3,
  152036. 3
  152037. };
  152038. static static_codebook _44u9_p5_0 = {
  152039. 4, 81,
  152040. _vq_lengthlist__44u9_p5_0,
  152041. 1, -529137664, 1618345984, 2, 0,
  152042. _vq_quantlist__44u9_p5_0,
  152043. NULL,
  152044. &_vq_auxt__44u9_p5_0,
  152045. NULL,
  152046. 0
  152047. };
  152048. static long _vq_quantlist__44u9_p5_1[] = {
  152049. 5,
  152050. 4,
  152051. 6,
  152052. 3,
  152053. 7,
  152054. 2,
  152055. 8,
  152056. 1,
  152057. 9,
  152058. 0,
  152059. 10,
  152060. };
  152061. static long _vq_lengthlist__44u9_p5_1[] = {
  152062. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152063. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152064. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152065. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152066. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152067. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152068. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152069. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152070. };
  152071. static float _vq_quantthresh__44u9_p5_1[] = {
  152072. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152073. 3.5, 4.5,
  152074. };
  152075. static long _vq_quantmap__44u9_p5_1[] = {
  152076. 9, 7, 5, 3, 1, 0, 2, 4,
  152077. 6, 8, 10,
  152078. };
  152079. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152080. _vq_quantthresh__44u9_p5_1,
  152081. _vq_quantmap__44u9_p5_1,
  152082. 11,
  152083. 11
  152084. };
  152085. static static_codebook _44u9_p5_1 = {
  152086. 2, 121,
  152087. _vq_lengthlist__44u9_p5_1,
  152088. 1, -531365888, 1611661312, 4, 0,
  152089. _vq_quantlist__44u9_p5_1,
  152090. NULL,
  152091. &_vq_auxt__44u9_p5_1,
  152092. NULL,
  152093. 0
  152094. };
  152095. static long _vq_quantlist__44u9_p6_0[] = {
  152096. 6,
  152097. 5,
  152098. 7,
  152099. 4,
  152100. 8,
  152101. 3,
  152102. 9,
  152103. 2,
  152104. 10,
  152105. 1,
  152106. 11,
  152107. 0,
  152108. 12,
  152109. };
  152110. static long _vq_lengthlist__44u9_p6_0[] = {
  152111. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152112. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152113. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152114. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152115. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152116. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152117. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152118. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152119. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152120. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152121. 10,11,11,11,11,12,11,12,12,
  152122. };
  152123. static float _vq_quantthresh__44u9_p6_0[] = {
  152124. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152125. 12.5, 17.5, 22.5, 27.5,
  152126. };
  152127. static long _vq_quantmap__44u9_p6_0[] = {
  152128. 11, 9, 7, 5, 3, 1, 0, 2,
  152129. 4, 6, 8, 10, 12,
  152130. };
  152131. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152132. _vq_quantthresh__44u9_p6_0,
  152133. _vq_quantmap__44u9_p6_0,
  152134. 13,
  152135. 13
  152136. };
  152137. static static_codebook _44u9_p6_0 = {
  152138. 2, 169,
  152139. _vq_lengthlist__44u9_p6_0,
  152140. 1, -526516224, 1616117760, 4, 0,
  152141. _vq_quantlist__44u9_p6_0,
  152142. NULL,
  152143. &_vq_auxt__44u9_p6_0,
  152144. NULL,
  152145. 0
  152146. };
  152147. static long _vq_quantlist__44u9_p6_1[] = {
  152148. 2,
  152149. 1,
  152150. 3,
  152151. 0,
  152152. 4,
  152153. };
  152154. static long _vq_lengthlist__44u9_p6_1[] = {
  152155. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152156. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152157. };
  152158. static float _vq_quantthresh__44u9_p6_1[] = {
  152159. -1.5, -0.5, 0.5, 1.5,
  152160. };
  152161. static long _vq_quantmap__44u9_p6_1[] = {
  152162. 3, 1, 0, 2, 4,
  152163. };
  152164. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152165. _vq_quantthresh__44u9_p6_1,
  152166. _vq_quantmap__44u9_p6_1,
  152167. 5,
  152168. 5
  152169. };
  152170. static static_codebook _44u9_p6_1 = {
  152171. 2, 25,
  152172. _vq_lengthlist__44u9_p6_1,
  152173. 1, -533725184, 1611661312, 3, 0,
  152174. _vq_quantlist__44u9_p6_1,
  152175. NULL,
  152176. &_vq_auxt__44u9_p6_1,
  152177. NULL,
  152178. 0
  152179. };
  152180. static long _vq_quantlist__44u9_p7_0[] = {
  152181. 6,
  152182. 5,
  152183. 7,
  152184. 4,
  152185. 8,
  152186. 3,
  152187. 9,
  152188. 2,
  152189. 10,
  152190. 1,
  152191. 11,
  152192. 0,
  152193. 12,
  152194. };
  152195. static long _vq_lengthlist__44u9_p7_0[] = {
  152196. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152197. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152198. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152199. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152200. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152201. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152202. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152203. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152204. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152205. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152206. 12,13,13,14,14,14,15,15,15,
  152207. };
  152208. static float _vq_quantthresh__44u9_p7_0[] = {
  152209. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152210. 27.5, 38.5, 49.5, 60.5,
  152211. };
  152212. static long _vq_quantmap__44u9_p7_0[] = {
  152213. 11, 9, 7, 5, 3, 1, 0, 2,
  152214. 4, 6, 8, 10, 12,
  152215. };
  152216. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152217. _vq_quantthresh__44u9_p7_0,
  152218. _vq_quantmap__44u9_p7_0,
  152219. 13,
  152220. 13
  152221. };
  152222. static static_codebook _44u9_p7_0 = {
  152223. 2, 169,
  152224. _vq_lengthlist__44u9_p7_0,
  152225. 1, -523206656, 1618345984, 4, 0,
  152226. _vq_quantlist__44u9_p7_0,
  152227. NULL,
  152228. &_vq_auxt__44u9_p7_0,
  152229. NULL,
  152230. 0
  152231. };
  152232. static long _vq_quantlist__44u9_p7_1[] = {
  152233. 5,
  152234. 4,
  152235. 6,
  152236. 3,
  152237. 7,
  152238. 2,
  152239. 8,
  152240. 1,
  152241. 9,
  152242. 0,
  152243. 10,
  152244. };
  152245. static long _vq_lengthlist__44u9_p7_1[] = {
  152246. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152247. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152248. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152249. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152250. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152251. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152252. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152253. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152254. };
  152255. static float _vq_quantthresh__44u9_p7_1[] = {
  152256. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152257. 3.5, 4.5,
  152258. };
  152259. static long _vq_quantmap__44u9_p7_1[] = {
  152260. 9, 7, 5, 3, 1, 0, 2, 4,
  152261. 6, 8, 10,
  152262. };
  152263. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152264. _vq_quantthresh__44u9_p7_1,
  152265. _vq_quantmap__44u9_p7_1,
  152266. 11,
  152267. 11
  152268. };
  152269. static static_codebook _44u9_p7_1 = {
  152270. 2, 121,
  152271. _vq_lengthlist__44u9_p7_1,
  152272. 1, -531365888, 1611661312, 4, 0,
  152273. _vq_quantlist__44u9_p7_1,
  152274. NULL,
  152275. &_vq_auxt__44u9_p7_1,
  152276. NULL,
  152277. 0
  152278. };
  152279. static long _vq_quantlist__44u9_p8_0[] = {
  152280. 7,
  152281. 6,
  152282. 8,
  152283. 5,
  152284. 9,
  152285. 4,
  152286. 10,
  152287. 3,
  152288. 11,
  152289. 2,
  152290. 12,
  152291. 1,
  152292. 13,
  152293. 0,
  152294. 14,
  152295. };
  152296. static long _vq_lengthlist__44u9_p8_0[] = {
  152297. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152298. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152299. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152300. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152301. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152302. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152303. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152304. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152305. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152306. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152307. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152308. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152309. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152310. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152311. 15,
  152312. };
  152313. static float _vq_quantthresh__44u9_p8_0[] = {
  152314. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152315. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152316. };
  152317. static long _vq_quantmap__44u9_p8_0[] = {
  152318. 13, 11, 9, 7, 5, 3, 1, 0,
  152319. 2, 4, 6, 8, 10, 12, 14,
  152320. };
  152321. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152322. _vq_quantthresh__44u9_p8_0,
  152323. _vq_quantmap__44u9_p8_0,
  152324. 15,
  152325. 15
  152326. };
  152327. static static_codebook _44u9_p8_0 = {
  152328. 2, 225,
  152329. _vq_lengthlist__44u9_p8_0,
  152330. 1, -520986624, 1620377600, 4, 0,
  152331. _vq_quantlist__44u9_p8_0,
  152332. NULL,
  152333. &_vq_auxt__44u9_p8_0,
  152334. NULL,
  152335. 0
  152336. };
  152337. static long _vq_quantlist__44u9_p8_1[] = {
  152338. 10,
  152339. 9,
  152340. 11,
  152341. 8,
  152342. 12,
  152343. 7,
  152344. 13,
  152345. 6,
  152346. 14,
  152347. 5,
  152348. 15,
  152349. 4,
  152350. 16,
  152351. 3,
  152352. 17,
  152353. 2,
  152354. 18,
  152355. 1,
  152356. 19,
  152357. 0,
  152358. 20,
  152359. };
  152360. static long _vq_lengthlist__44u9_p8_1[] = {
  152361. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152362. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152363. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152364. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152365. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152366. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152367. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152368. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152369. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152370. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152371. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152372. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152373. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152374. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152375. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152376. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152377. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152378. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152379. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152380. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152381. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152382. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152383. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152384. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152385. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152386. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152387. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152388. 10,10,10,10,10,10,10,10,10,
  152389. };
  152390. static float _vq_quantthresh__44u9_p8_1[] = {
  152391. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152392. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152393. 6.5, 7.5, 8.5, 9.5,
  152394. };
  152395. static long _vq_quantmap__44u9_p8_1[] = {
  152396. 19, 17, 15, 13, 11, 9, 7, 5,
  152397. 3, 1, 0, 2, 4, 6, 8, 10,
  152398. 12, 14, 16, 18, 20,
  152399. };
  152400. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152401. _vq_quantthresh__44u9_p8_1,
  152402. _vq_quantmap__44u9_p8_1,
  152403. 21,
  152404. 21
  152405. };
  152406. static static_codebook _44u9_p8_1 = {
  152407. 2, 441,
  152408. _vq_lengthlist__44u9_p8_1,
  152409. 1, -529268736, 1611661312, 5, 0,
  152410. _vq_quantlist__44u9_p8_1,
  152411. NULL,
  152412. &_vq_auxt__44u9_p8_1,
  152413. NULL,
  152414. 0
  152415. };
  152416. static long _vq_quantlist__44u9_p9_0[] = {
  152417. 7,
  152418. 6,
  152419. 8,
  152420. 5,
  152421. 9,
  152422. 4,
  152423. 10,
  152424. 3,
  152425. 11,
  152426. 2,
  152427. 12,
  152428. 1,
  152429. 13,
  152430. 0,
  152431. 14,
  152432. };
  152433. static long _vq_lengthlist__44u9_p9_0[] = {
  152434. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152435. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152436. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152437. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152439. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152440. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152441. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152442. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152443. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152444. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152445. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152447. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152448. 10,
  152449. };
  152450. static float _vq_quantthresh__44u9_p9_0[] = {
  152451. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152452. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152453. };
  152454. static long _vq_quantmap__44u9_p9_0[] = {
  152455. 13, 11, 9, 7, 5, 3, 1, 0,
  152456. 2, 4, 6, 8, 10, 12, 14,
  152457. };
  152458. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152459. _vq_quantthresh__44u9_p9_0,
  152460. _vq_quantmap__44u9_p9_0,
  152461. 15,
  152462. 15
  152463. };
  152464. static static_codebook _44u9_p9_0 = {
  152465. 2, 225,
  152466. _vq_lengthlist__44u9_p9_0,
  152467. 1, -510036736, 1631393792, 4, 0,
  152468. _vq_quantlist__44u9_p9_0,
  152469. NULL,
  152470. &_vq_auxt__44u9_p9_0,
  152471. NULL,
  152472. 0
  152473. };
  152474. static long _vq_quantlist__44u9_p9_1[] = {
  152475. 9,
  152476. 8,
  152477. 10,
  152478. 7,
  152479. 11,
  152480. 6,
  152481. 12,
  152482. 5,
  152483. 13,
  152484. 4,
  152485. 14,
  152486. 3,
  152487. 15,
  152488. 2,
  152489. 16,
  152490. 1,
  152491. 17,
  152492. 0,
  152493. 18,
  152494. };
  152495. static long _vq_lengthlist__44u9_p9_1[] = {
  152496. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152497. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152498. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152499. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152500. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152501. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152502. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152503. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152504. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152505. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152506. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152507. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152508. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152509. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152510. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152511. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152512. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152513. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152514. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152515. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152516. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152517. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152518. 17,17,15,17,15,17,16,16,17,
  152519. };
  152520. static float _vq_quantthresh__44u9_p9_1[] = {
  152521. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152522. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152523. 367.5, 416.5,
  152524. };
  152525. static long _vq_quantmap__44u9_p9_1[] = {
  152526. 17, 15, 13, 11, 9, 7, 5, 3,
  152527. 1, 0, 2, 4, 6, 8, 10, 12,
  152528. 14, 16, 18,
  152529. };
  152530. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152531. _vq_quantthresh__44u9_p9_1,
  152532. _vq_quantmap__44u9_p9_1,
  152533. 19,
  152534. 19
  152535. };
  152536. static static_codebook _44u9_p9_1 = {
  152537. 2, 361,
  152538. _vq_lengthlist__44u9_p9_1,
  152539. 1, -518287360, 1622704128, 5, 0,
  152540. _vq_quantlist__44u9_p9_1,
  152541. NULL,
  152542. &_vq_auxt__44u9_p9_1,
  152543. NULL,
  152544. 0
  152545. };
  152546. static long _vq_quantlist__44u9_p9_2[] = {
  152547. 24,
  152548. 23,
  152549. 25,
  152550. 22,
  152551. 26,
  152552. 21,
  152553. 27,
  152554. 20,
  152555. 28,
  152556. 19,
  152557. 29,
  152558. 18,
  152559. 30,
  152560. 17,
  152561. 31,
  152562. 16,
  152563. 32,
  152564. 15,
  152565. 33,
  152566. 14,
  152567. 34,
  152568. 13,
  152569. 35,
  152570. 12,
  152571. 36,
  152572. 11,
  152573. 37,
  152574. 10,
  152575. 38,
  152576. 9,
  152577. 39,
  152578. 8,
  152579. 40,
  152580. 7,
  152581. 41,
  152582. 6,
  152583. 42,
  152584. 5,
  152585. 43,
  152586. 4,
  152587. 44,
  152588. 3,
  152589. 45,
  152590. 2,
  152591. 46,
  152592. 1,
  152593. 47,
  152594. 0,
  152595. 48,
  152596. };
  152597. static long _vq_lengthlist__44u9_p9_2[] = {
  152598. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152599. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152600. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152601. 7,
  152602. };
  152603. static float _vq_quantthresh__44u9_p9_2[] = {
  152604. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152605. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152608. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152609. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152610. };
  152611. static long _vq_quantmap__44u9_p9_2[] = {
  152612. 47, 45, 43, 41, 39, 37, 35, 33,
  152613. 31, 29, 27, 25, 23, 21, 19, 17,
  152614. 15, 13, 11, 9, 7, 5, 3, 1,
  152615. 0, 2, 4, 6, 8, 10, 12, 14,
  152616. 16, 18, 20, 22, 24, 26, 28, 30,
  152617. 32, 34, 36, 38, 40, 42, 44, 46,
  152618. 48,
  152619. };
  152620. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152621. _vq_quantthresh__44u9_p9_2,
  152622. _vq_quantmap__44u9_p9_2,
  152623. 49,
  152624. 49
  152625. };
  152626. static static_codebook _44u9_p9_2 = {
  152627. 1, 49,
  152628. _vq_lengthlist__44u9_p9_2,
  152629. 1, -526909440, 1611661312, 6, 0,
  152630. _vq_quantlist__44u9_p9_2,
  152631. NULL,
  152632. &_vq_auxt__44u9_p9_2,
  152633. NULL,
  152634. 0
  152635. };
  152636. static long _huff_lengthlist__44un1__long[] = {
  152637. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152638. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152639. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152640. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152641. };
  152642. static static_codebook _huff_book__44un1__long = {
  152643. 2, 64,
  152644. _huff_lengthlist__44un1__long,
  152645. 0, 0, 0, 0, 0,
  152646. NULL,
  152647. NULL,
  152648. NULL,
  152649. NULL,
  152650. 0
  152651. };
  152652. static long _vq_quantlist__44un1__p1_0[] = {
  152653. 1,
  152654. 0,
  152655. 2,
  152656. };
  152657. static long _vq_lengthlist__44un1__p1_0[] = {
  152658. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152659. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152660. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152661. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152662. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152663. 12,
  152664. };
  152665. static float _vq_quantthresh__44un1__p1_0[] = {
  152666. -0.5, 0.5,
  152667. };
  152668. static long _vq_quantmap__44un1__p1_0[] = {
  152669. 1, 0, 2,
  152670. };
  152671. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152672. _vq_quantthresh__44un1__p1_0,
  152673. _vq_quantmap__44un1__p1_0,
  152674. 3,
  152675. 3
  152676. };
  152677. static static_codebook _44un1__p1_0 = {
  152678. 4, 81,
  152679. _vq_lengthlist__44un1__p1_0,
  152680. 1, -535822336, 1611661312, 2, 0,
  152681. _vq_quantlist__44un1__p1_0,
  152682. NULL,
  152683. &_vq_auxt__44un1__p1_0,
  152684. NULL,
  152685. 0
  152686. };
  152687. static long _vq_quantlist__44un1__p2_0[] = {
  152688. 1,
  152689. 0,
  152690. 2,
  152691. };
  152692. static long _vq_lengthlist__44un1__p2_0[] = {
  152693. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152694. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152695. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152696. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152697. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152698. 8,
  152699. };
  152700. static float _vq_quantthresh__44un1__p2_0[] = {
  152701. -0.5, 0.5,
  152702. };
  152703. static long _vq_quantmap__44un1__p2_0[] = {
  152704. 1, 0, 2,
  152705. };
  152706. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152707. _vq_quantthresh__44un1__p2_0,
  152708. _vq_quantmap__44un1__p2_0,
  152709. 3,
  152710. 3
  152711. };
  152712. static static_codebook _44un1__p2_0 = {
  152713. 4, 81,
  152714. _vq_lengthlist__44un1__p2_0,
  152715. 1, -535822336, 1611661312, 2, 0,
  152716. _vq_quantlist__44un1__p2_0,
  152717. NULL,
  152718. &_vq_auxt__44un1__p2_0,
  152719. NULL,
  152720. 0
  152721. };
  152722. static long _vq_quantlist__44un1__p3_0[] = {
  152723. 2,
  152724. 1,
  152725. 3,
  152726. 0,
  152727. 4,
  152728. };
  152729. static long _vq_lengthlist__44un1__p3_0[] = {
  152730. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152731. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152732. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152733. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152734. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152735. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152736. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152737. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152738. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152739. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152740. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152741. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152742. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152743. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152744. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152745. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152746. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152747. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152748. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152749. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152750. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152751. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152752. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152753. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152754. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152755. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152756. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152757. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152758. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152759. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152760. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152761. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152762. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152763. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152764. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152765. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152766. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152767. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152768. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152769. 17,
  152770. };
  152771. static float _vq_quantthresh__44un1__p3_0[] = {
  152772. -1.5, -0.5, 0.5, 1.5,
  152773. };
  152774. static long _vq_quantmap__44un1__p3_0[] = {
  152775. 3, 1, 0, 2, 4,
  152776. };
  152777. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152778. _vq_quantthresh__44un1__p3_0,
  152779. _vq_quantmap__44un1__p3_0,
  152780. 5,
  152781. 5
  152782. };
  152783. static static_codebook _44un1__p3_0 = {
  152784. 4, 625,
  152785. _vq_lengthlist__44un1__p3_0,
  152786. 1, -533725184, 1611661312, 3, 0,
  152787. _vq_quantlist__44un1__p3_0,
  152788. NULL,
  152789. &_vq_auxt__44un1__p3_0,
  152790. NULL,
  152791. 0
  152792. };
  152793. static long _vq_quantlist__44un1__p4_0[] = {
  152794. 2,
  152795. 1,
  152796. 3,
  152797. 0,
  152798. 4,
  152799. };
  152800. static long _vq_lengthlist__44un1__p4_0[] = {
  152801. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152802. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152803. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152804. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152805. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152806. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152807. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152808. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152809. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152810. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152811. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152812. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152813. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152814. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152815. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152816. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152817. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152818. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152819. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152820. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152821. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152822. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152823. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152824. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152825. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152826. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152827. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152828. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152829. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152830. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152831. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152832. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152833. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152834. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152835. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152836. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152837. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152838. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152839. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152840. 12,
  152841. };
  152842. static float _vq_quantthresh__44un1__p4_0[] = {
  152843. -1.5, -0.5, 0.5, 1.5,
  152844. };
  152845. static long _vq_quantmap__44un1__p4_0[] = {
  152846. 3, 1, 0, 2, 4,
  152847. };
  152848. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152849. _vq_quantthresh__44un1__p4_0,
  152850. _vq_quantmap__44un1__p4_0,
  152851. 5,
  152852. 5
  152853. };
  152854. static static_codebook _44un1__p4_0 = {
  152855. 4, 625,
  152856. _vq_lengthlist__44un1__p4_0,
  152857. 1, -533725184, 1611661312, 3, 0,
  152858. _vq_quantlist__44un1__p4_0,
  152859. NULL,
  152860. &_vq_auxt__44un1__p4_0,
  152861. NULL,
  152862. 0
  152863. };
  152864. static long _vq_quantlist__44un1__p5_0[] = {
  152865. 4,
  152866. 3,
  152867. 5,
  152868. 2,
  152869. 6,
  152870. 1,
  152871. 7,
  152872. 0,
  152873. 8,
  152874. };
  152875. static long _vq_lengthlist__44un1__p5_0[] = {
  152876. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152877. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152878. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152879. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152880. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152881. 12,
  152882. };
  152883. static float _vq_quantthresh__44un1__p5_0[] = {
  152884. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152885. };
  152886. static long _vq_quantmap__44un1__p5_0[] = {
  152887. 7, 5, 3, 1, 0, 2, 4, 6,
  152888. 8,
  152889. };
  152890. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152891. _vq_quantthresh__44un1__p5_0,
  152892. _vq_quantmap__44un1__p5_0,
  152893. 9,
  152894. 9
  152895. };
  152896. static static_codebook _44un1__p5_0 = {
  152897. 2, 81,
  152898. _vq_lengthlist__44un1__p5_0,
  152899. 1, -531628032, 1611661312, 4, 0,
  152900. _vq_quantlist__44un1__p5_0,
  152901. NULL,
  152902. &_vq_auxt__44un1__p5_0,
  152903. NULL,
  152904. 0
  152905. };
  152906. static long _vq_quantlist__44un1__p6_0[] = {
  152907. 6,
  152908. 5,
  152909. 7,
  152910. 4,
  152911. 8,
  152912. 3,
  152913. 9,
  152914. 2,
  152915. 10,
  152916. 1,
  152917. 11,
  152918. 0,
  152919. 12,
  152920. };
  152921. static long _vq_lengthlist__44un1__p6_0[] = {
  152922. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152923. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152924. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152925. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152926. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152927. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152928. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152929. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152930. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152931. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152932. 16, 0,15,18,18, 0,16, 0, 0,
  152933. };
  152934. static float _vq_quantthresh__44un1__p6_0[] = {
  152935. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152936. 12.5, 17.5, 22.5, 27.5,
  152937. };
  152938. static long _vq_quantmap__44un1__p6_0[] = {
  152939. 11, 9, 7, 5, 3, 1, 0, 2,
  152940. 4, 6, 8, 10, 12,
  152941. };
  152942. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152943. _vq_quantthresh__44un1__p6_0,
  152944. _vq_quantmap__44un1__p6_0,
  152945. 13,
  152946. 13
  152947. };
  152948. static static_codebook _44un1__p6_0 = {
  152949. 2, 169,
  152950. _vq_lengthlist__44un1__p6_0,
  152951. 1, -526516224, 1616117760, 4, 0,
  152952. _vq_quantlist__44un1__p6_0,
  152953. NULL,
  152954. &_vq_auxt__44un1__p6_0,
  152955. NULL,
  152956. 0
  152957. };
  152958. static long _vq_quantlist__44un1__p6_1[] = {
  152959. 2,
  152960. 1,
  152961. 3,
  152962. 0,
  152963. 4,
  152964. };
  152965. static long _vq_lengthlist__44un1__p6_1[] = {
  152966. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152967. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152968. };
  152969. static float _vq_quantthresh__44un1__p6_1[] = {
  152970. -1.5, -0.5, 0.5, 1.5,
  152971. };
  152972. static long _vq_quantmap__44un1__p6_1[] = {
  152973. 3, 1, 0, 2, 4,
  152974. };
  152975. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152976. _vq_quantthresh__44un1__p6_1,
  152977. _vq_quantmap__44un1__p6_1,
  152978. 5,
  152979. 5
  152980. };
  152981. static static_codebook _44un1__p6_1 = {
  152982. 2, 25,
  152983. _vq_lengthlist__44un1__p6_1,
  152984. 1, -533725184, 1611661312, 3, 0,
  152985. _vq_quantlist__44un1__p6_1,
  152986. NULL,
  152987. &_vq_auxt__44un1__p6_1,
  152988. NULL,
  152989. 0
  152990. };
  152991. static long _vq_quantlist__44un1__p7_0[] = {
  152992. 2,
  152993. 1,
  152994. 3,
  152995. 0,
  152996. 4,
  152997. };
  152998. static long _vq_lengthlist__44un1__p7_0[] = {
  152999. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153000. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153002. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153006. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153014. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153016. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153035. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153038. 10,
  153039. };
  153040. static float _vq_quantthresh__44un1__p7_0[] = {
  153041. -253.5, -84.5, 84.5, 253.5,
  153042. };
  153043. static long _vq_quantmap__44un1__p7_0[] = {
  153044. 3, 1, 0, 2, 4,
  153045. };
  153046. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153047. _vq_quantthresh__44un1__p7_0,
  153048. _vq_quantmap__44un1__p7_0,
  153049. 5,
  153050. 5
  153051. };
  153052. static static_codebook _44un1__p7_0 = {
  153053. 4, 625,
  153054. _vq_lengthlist__44un1__p7_0,
  153055. 1, -518709248, 1626677248, 3, 0,
  153056. _vq_quantlist__44un1__p7_0,
  153057. NULL,
  153058. &_vq_auxt__44un1__p7_0,
  153059. NULL,
  153060. 0
  153061. };
  153062. static long _vq_quantlist__44un1__p7_1[] = {
  153063. 6,
  153064. 5,
  153065. 7,
  153066. 4,
  153067. 8,
  153068. 3,
  153069. 9,
  153070. 2,
  153071. 10,
  153072. 1,
  153073. 11,
  153074. 0,
  153075. 12,
  153076. };
  153077. static long _vq_lengthlist__44un1__p7_1[] = {
  153078. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153079. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153080. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153081. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153082. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153083. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153084. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153085. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153086. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153087. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153088. 12,13,13,12,13,13,14,14,14,
  153089. };
  153090. static float _vq_quantthresh__44un1__p7_1[] = {
  153091. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153092. 32.5, 45.5, 58.5, 71.5,
  153093. };
  153094. static long _vq_quantmap__44un1__p7_1[] = {
  153095. 11, 9, 7, 5, 3, 1, 0, 2,
  153096. 4, 6, 8, 10, 12,
  153097. };
  153098. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153099. _vq_quantthresh__44un1__p7_1,
  153100. _vq_quantmap__44un1__p7_1,
  153101. 13,
  153102. 13
  153103. };
  153104. static static_codebook _44un1__p7_1 = {
  153105. 2, 169,
  153106. _vq_lengthlist__44un1__p7_1,
  153107. 1, -523010048, 1618608128, 4, 0,
  153108. _vq_quantlist__44un1__p7_1,
  153109. NULL,
  153110. &_vq_auxt__44un1__p7_1,
  153111. NULL,
  153112. 0
  153113. };
  153114. static long _vq_quantlist__44un1__p7_2[] = {
  153115. 6,
  153116. 5,
  153117. 7,
  153118. 4,
  153119. 8,
  153120. 3,
  153121. 9,
  153122. 2,
  153123. 10,
  153124. 1,
  153125. 11,
  153126. 0,
  153127. 12,
  153128. };
  153129. static long _vq_lengthlist__44un1__p7_2[] = {
  153130. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153131. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153132. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153133. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153134. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153135. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153136. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153137. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153138. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153139. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153140. 9, 9, 9,10,10,10,10,10,10,
  153141. };
  153142. static float _vq_quantthresh__44un1__p7_2[] = {
  153143. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153144. 2.5, 3.5, 4.5, 5.5,
  153145. };
  153146. static long _vq_quantmap__44un1__p7_2[] = {
  153147. 11, 9, 7, 5, 3, 1, 0, 2,
  153148. 4, 6, 8, 10, 12,
  153149. };
  153150. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153151. _vq_quantthresh__44un1__p7_2,
  153152. _vq_quantmap__44un1__p7_2,
  153153. 13,
  153154. 13
  153155. };
  153156. static static_codebook _44un1__p7_2 = {
  153157. 2, 169,
  153158. _vq_lengthlist__44un1__p7_2,
  153159. 1, -531103744, 1611661312, 4, 0,
  153160. _vq_quantlist__44un1__p7_2,
  153161. NULL,
  153162. &_vq_auxt__44un1__p7_2,
  153163. NULL,
  153164. 0
  153165. };
  153166. static long _huff_lengthlist__44un1__short[] = {
  153167. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153168. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153169. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153170. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153171. };
  153172. static static_codebook _huff_book__44un1__short = {
  153173. 2, 64,
  153174. _huff_lengthlist__44un1__short,
  153175. 0, 0, 0, 0, 0,
  153176. NULL,
  153177. NULL,
  153178. NULL,
  153179. NULL,
  153180. 0
  153181. };
  153182. /*** End of inlined file: res_books_uncoupled.h ***/
  153183. /***** residue backends *********************************************/
  153184. static vorbis_info_residue0 _residue_44_low_un={
  153185. 0,-1, -1, 8,-1,
  153186. {0},
  153187. {-1},
  153188. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153189. { -1, 25, -1, 45, -1, -1, -1}
  153190. };
  153191. static vorbis_info_residue0 _residue_44_mid_un={
  153192. 0,-1, -1, 10,-1,
  153193. /* 0 1 2 3 4 5 6 7 8 9 */
  153194. {0},
  153195. {-1},
  153196. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153197. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153198. };
  153199. static vorbis_info_residue0 _residue_44_hi_un={
  153200. 0,-1, -1, 10,-1,
  153201. /* 0 1 2 3 4 5 6 7 8 9 */
  153202. {0},
  153203. {-1},
  153204. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153205. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153206. };
  153207. /* mapping conventions:
  153208. only one submap (this would change for efficient 5.1 support for example)*/
  153209. /* Four psychoacoustic profiles are used, one for each blocktype */
  153210. static vorbis_info_mapping0 _map_nominal_u[2]={
  153211. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153212. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153213. };
  153214. static static_bookblock _resbook_44u_n1={
  153215. {
  153216. {0},
  153217. {0,0,&_44un1__p1_0},
  153218. {0,0,&_44un1__p2_0},
  153219. {0,0,&_44un1__p3_0},
  153220. {0,0,&_44un1__p4_0},
  153221. {0,0,&_44un1__p5_0},
  153222. {&_44un1__p6_0,&_44un1__p6_1},
  153223. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153224. }
  153225. };
  153226. static static_bookblock _resbook_44u_0={
  153227. {
  153228. {0},
  153229. {0,0,&_44u0__p1_0},
  153230. {0,0,&_44u0__p2_0},
  153231. {0,0,&_44u0__p3_0},
  153232. {0,0,&_44u0__p4_0},
  153233. {0,0,&_44u0__p5_0},
  153234. {&_44u0__p6_0,&_44u0__p6_1},
  153235. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153236. }
  153237. };
  153238. static static_bookblock _resbook_44u_1={
  153239. {
  153240. {0},
  153241. {0,0,&_44u1__p1_0},
  153242. {0,0,&_44u1__p2_0},
  153243. {0,0,&_44u1__p3_0},
  153244. {0,0,&_44u1__p4_0},
  153245. {0,0,&_44u1__p5_0},
  153246. {&_44u1__p6_0,&_44u1__p6_1},
  153247. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153248. }
  153249. };
  153250. static static_bookblock _resbook_44u_2={
  153251. {
  153252. {0},
  153253. {0,0,&_44u2__p1_0},
  153254. {0,0,&_44u2__p2_0},
  153255. {0,0,&_44u2__p3_0},
  153256. {0,0,&_44u2__p4_0},
  153257. {0,0,&_44u2__p5_0},
  153258. {&_44u2__p6_0,&_44u2__p6_1},
  153259. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153260. }
  153261. };
  153262. static static_bookblock _resbook_44u_3={
  153263. {
  153264. {0},
  153265. {0,0,&_44u3__p1_0},
  153266. {0,0,&_44u3__p2_0},
  153267. {0,0,&_44u3__p3_0},
  153268. {0,0,&_44u3__p4_0},
  153269. {0,0,&_44u3__p5_0},
  153270. {&_44u3__p6_0,&_44u3__p6_1},
  153271. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153272. }
  153273. };
  153274. static static_bookblock _resbook_44u_4={
  153275. {
  153276. {0},
  153277. {0,0,&_44u4__p1_0},
  153278. {0,0,&_44u4__p2_0},
  153279. {0,0,&_44u4__p3_0},
  153280. {0,0,&_44u4__p4_0},
  153281. {0,0,&_44u4__p5_0},
  153282. {&_44u4__p6_0,&_44u4__p6_1},
  153283. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153284. }
  153285. };
  153286. static static_bookblock _resbook_44u_5={
  153287. {
  153288. {0},
  153289. {0,0,&_44u5__p1_0},
  153290. {0,0,&_44u5__p2_0},
  153291. {0,0,&_44u5__p3_0},
  153292. {0,0,&_44u5__p4_0},
  153293. {0,0,&_44u5__p5_0},
  153294. {0,0,&_44u5__p6_0},
  153295. {&_44u5__p7_0,&_44u5__p7_1},
  153296. {&_44u5__p8_0,&_44u5__p8_1},
  153297. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153298. }
  153299. };
  153300. static static_bookblock _resbook_44u_6={
  153301. {
  153302. {0},
  153303. {0,0,&_44u6__p1_0},
  153304. {0,0,&_44u6__p2_0},
  153305. {0,0,&_44u6__p3_0},
  153306. {0,0,&_44u6__p4_0},
  153307. {0,0,&_44u6__p5_0},
  153308. {0,0,&_44u6__p6_0},
  153309. {&_44u6__p7_0,&_44u6__p7_1},
  153310. {&_44u6__p8_0,&_44u6__p8_1},
  153311. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153312. }
  153313. };
  153314. static static_bookblock _resbook_44u_7={
  153315. {
  153316. {0},
  153317. {0,0,&_44u7__p1_0},
  153318. {0,0,&_44u7__p2_0},
  153319. {0,0,&_44u7__p3_0},
  153320. {0,0,&_44u7__p4_0},
  153321. {0,0,&_44u7__p5_0},
  153322. {0,0,&_44u7__p6_0},
  153323. {&_44u7__p7_0,&_44u7__p7_1},
  153324. {&_44u7__p8_0,&_44u7__p8_1},
  153325. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153326. }
  153327. };
  153328. static static_bookblock _resbook_44u_8={
  153329. {
  153330. {0},
  153331. {0,0,&_44u8_p1_0},
  153332. {0,0,&_44u8_p2_0},
  153333. {0,0,&_44u8_p3_0},
  153334. {0,0,&_44u8_p4_0},
  153335. {&_44u8_p5_0,&_44u8_p5_1},
  153336. {&_44u8_p6_0,&_44u8_p6_1},
  153337. {&_44u8_p7_0,&_44u8_p7_1},
  153338. {&_44u8_p8_0,&_44u8_p8_1},
  153339. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153340. }
  153341. };
  153342. static static_bookblock _resbook_44u_9={
  153343. {
  153344. {0},
  153345. {0,0,&_44u9_p1_0},
  153346. {0,0,&_44u9_p2_0},
  153347. {0,0,&_44u9_p3_0},
  153348. {0,0,&_44u9_p4_0},
  153349. {&_44u9_p5_0,&_44u9_p5_1},
  153350. {&_44u9_p6_0,&_44u9_p6_1},
  153351. {&_44u9_p7_0,&_44u9_p7_1},
  153352. {&_44u9_p8_0,&_44u9_p8_1},
  153353. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153354. }
  153355. };
  153356. static vorbis_residue_template _res_44u_n1[]={
  153357. {1,0, &_residue_44_low_un,
  153358. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153359. &_resbook_44u_n1,&_resbook_44u_n1},
  153360. {1,0, &_residue_44_low_un,
  153361. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153362. &_resbook_44u_n1,&_resbook_44u_n1}
  153363. };
  153364. static vorbis_residue_template _res_44u_0[]={
  153365. {1,0, &_residue_44_low_un,
  153366. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153367. &_resbook_44u_0,&_resbook_44u_0},
  153368. {1,0, &_residue_44_low_un,
  153369. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153370. &_resbook_44u_0,&_resbook_44u_0}
  153371. };
  153372. static vorbis_residue_template _res_44u_1[]={
  153373. {1,0, &_residue_44_low_un,
  153374. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153375. &_resbook_44u_1,&_resbook_44u_1},
  153376. {1,0, &_residue_44_low_un,
  153377. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153378. &_resbook_44u_1,&_resbook_44u_1}
  153379. };
  153380. static vorbis_residue_template _res_44u_2[]={
  153381. {1,0, &_residue_44_low_un,
  153382. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153383. &_resbook_44u_2,&_resbook_44u_2},
  153384. {1,0, &_residue_44_low_un,
  153385. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153386. &_resbook_44u_2,&_resbook_44u_2}
  153387. };
  153388. static vorbis_residue_template _res_44u_3[]={
  153389. {1,0, &_residue_44_low_un,
  153390. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153391. &_resbook_44u_3,&_resbook_44u_3},
  153392. {1,0, &_residue_44_low_un,
  153393. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153394. &_resbook_44u_3,&_resbook_44u_3}
  153395. };
  153396. static vorbis_residue_template _res_44u_4[]={
  153397. {1,0, &_residue_44_low_un,
  153398. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153399. &_resbook_44u_4,&_resbook_44u_4},
  153400. {1,0, &_residue_44_low_un,
  153401. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153402. &_resbook_44u_4,&_resbook_44u_4}
  153403. };
  153404. static vorbis_residue_template _res_44u_5[]={
  153405. {1,0, &_residue_44_mid_un,
  153406. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153407. &_resbook_44u_5,&_resbook_44u_5},
  153408. {1,0, &_residue_44_mid_un,
  153409. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153410. &_resbook_44u_5,&_resbook_44u_5}
  153411. };
  153412. static vorbis_residue_template _res_44u_6[]={
  153413. {1,0, &_residue_44_mid_un,
  153414. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153415. &_resbook_44u_6,&_resbook_44u_6},
  153416. {1,0, &_residue_44_mid_un,
  153417. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153418. &_resbook_44u_6,&_resbook_44u_6}
  153419. };
  153420. static vorbis_residue_template _res_44u_7[]={
  153421. {1,0, &_residue_44_mid_un,
  153422. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153423. &_resbook_44u_7,&_resbook_44u_7},
  153424. {1,0, &_residue_44_mid_un,
  153425. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153426. &_resbook_44u_7,&_resbook_44u_7}
  153427. };
  153428. static vorbis_residue_template _res_44u_8[]={
  153429. {1,0, &_residue_44_hi_un,
  153430. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153431. &_resbook_44u_8,&_resbook_44u_8},
  153432. {1,0, &_residue_44_hi_un,
  153433. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153434. &_resbook_44u_8,&_resbook_44u_8}
  153435. };
  153436. static vorbis_residue_template _res_44u_9[]={
  153437. {1,0, &_residue_44_hi_un,
  153438. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153439. &_resbook_44u_9,&_resbook_44u_9},
  153440. {1,0, &_residue_44_hi_un,
  153441. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153442. &_resbook_44u_9,&_resbook_44u_9}
  153443. };
  153444. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153445. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153446. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153447. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153448. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153449. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153450. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153451. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153452. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153453. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153454. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153455. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153456. };
  153457. /*** End of inlined file: residue_44u.h ***/
  153458. static double rate_mapping_44_un[12]={
  153459. 32000.,48000.,60000.,70000.,80000.,86000.,
  153460. 96000.,110000.,120000.,140000.,160000.,240001.
  153461. };
  153462. ve_setup_data_template ve_setup_44_uncoupled={
  153463. 11,
  153464. rate_mapping_44_un,
  153465. quality_mapping_44,
  153466. -1,
  153467. 40000,
  153468. 50000,
  153469. blocksize_short_44,
  153470. blocksize_long_44,
  153471. _psy_tone_masteratt_44,
  153472. _psy_tone_0dB,
  153473. _psy_tone_suppress,
  153474. _vp_tonemask_adj_otherblock,
  153475. _vp_tonemask_adj_longblock,
  153476. _vp_tonemask_adj_otherblock,
  153477. _psy_noiseguards_44,
  153478. _psy_noisebias_impulse,
  153479. _psy_noisebias_padding,
  153480. _psy_noisebias_trans,
  153481. _psy_noisebias_long,
  153482. _psy_noise_suppress,
  153483. _psy_compand_44,
  153484. _psy_compand_short_mapping,
  153485. _psy_compand_long_mapping,
  153486. {_noise_start_short_44,_noise_start_long_44},
  153487. {_noise_part_short_44,_noise_part_long_44},
  153488. _noise_thresh_44,
  153489. _psy_ath_floater,
  153490. _psy_ath_abs,
  153491. _psy_lowpass_44,
  153492. _psy_global_44,
  153493. _global_mapping_44,
  153494. NULL,
  153495. _floor_books,
  153496. _floor,
  153497. _floor_short_mapping_44,
  153498. _floor_long_mapping_44,
  153499. _mapres_template_44_uncoupled
  153500. };
  153501. /*** End of inlined file: setup_44u.h ***/
  153502. /*** Start of inlined file: setup_32.h ***/
  153503. static double rate_mapping_32[12]={
  153504. 18000.,28000.,35000.,45000.,56000.,60000.,
  153505. 75000.,90000.,100000.,115000.,150000.,190000.,
  153506. };
  153507. static double rate_mapping_32_un[12]={
  153508. 30000.,42000.,52000.,64000.,72000.,78000.,
  153509. 86000.,92000.,110000.,120000.,140000.,190000.,
  153510. };
  153511. static double _psy_lowpass_32[12]={
  153512. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153513. };
  153514. ve_setup_data_template ve_setup_32_stereo={
  153515. 11,
  153516. rate_mapping_32,
  153517. quality_mapping_44,
  153518. 2,
  153519. 26000,
  153520. 40000,
  153521. blocksize_short_44,
  153522. blocksize_long_44,
  153523. _psy_tone_masteratt_44,
  153524. _psy_tone_0dB,
  153525. _psy_tone_suppress,
  153526. _vp_tonemask_adj_otherblock,
  153527. _vp_tonemask_adj_longblock,
  153528. _vp_tonemask_adj_otherblock,
  153529. _psy_noiseguards_44,
  153530. _psy_noisebias_impulse,
  153531. _psy_noisebias_padding,
  153532. _psy_noisebias_trans,
  153533. _psy_noisebias_long,
  153534. _psy_noise_suppress,
  153535. _psy_compand_44,
  153536. _psy_compand_short_mapping,
  153537. _psy_compand_long_mapping,
  153538. {_noise_start_short_44,_noise_start_long_44},
  153539. {_noise_part_short_44,_noise_part_long_44},
  153540. _noise_thresh_44,
  153541. _psy_ath_floater,
  153542. _psy_ath_abs,
  153543. _psy_lowpass_32,
  153544. _psy_global_44,
  153545. _global_mapping_44,
  153546. _psy_stereo_modes_44,
  153547. _floor_books,
  153548. _floor,
  153549. _floor_short_mapping_44,
  153550. _floor_long_mapping_44,
  153551. _mapres_template_44_stereo
  153552. };
  153553. ve_setup_data_template ve_setup_32_uncoupled={
  153554. 11,
  153555. rate_mapping_32_un,
  153556. quality_mapping_44,
  153557. -1,
  153558. 26000,
  153559. 40000,
  153560. blocksize_short_44,
  153561. blocksize_long_44,
  153562. _psy_tone_masteratt_44,
  153563. _psy_tone_0dB,
  153564. _psy_tone_suppress,
  153565. _vp_tonemask_adj_otherblock,
  153566. _vp_tonemask_adj_longblock,
  153567. _vp_tonemask_adj_otherblock,
  153568. _psy_noiseguards_44,
  153569. _psy_noisebias_impulse,
  153570. _psy_noisebias_padding,
  153571. _psy_noisebias_trans,
  153572. _psy_noisebias_long,
  153573. _psy_noise_suppress,
  153574. _psy_compand_44,
  153575. _psy_compand_short_mapping,
  153576. _psy_compand_long_mapping,
  153577. {_noise_start_short_44,_noise_start_long_44},
  153578. {_noise_part_short_44,_noise_part_long_44},
  153579. _noise_thresh_44,
  153580. _psy_ath_floater,
  153581. _psy_ath_abs,
  153582. _psy_lowpass_32,
  153583. _psy_global_44,
  153584. _global_mapping_44,
  153585. NULL,
  153586. _floor_books,
  153587. _floor,
  153588. _floor_short_mapping_44,
  153589. _floor_long_mapping_44,
  153590. _mapres_template_44_uncoupled
  153591. };
  153592. /*** End of inlined file: setup_32.h ***/
  153593. /*** Start of inlined file: setup_8.h ***/
  153594. /*** Start of inlined file: psych_8.h ***/
  153595. static att3 _psy_tone_masteratt_8[3]={
  153596. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153597. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153598. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153599. };
  153600. static vp_adjblock _vp_tonemask_adj_8[3]={
  153601. /* adjust for mode zero */
  153602. /* 63 125 250 500 1 2 4 8 16 */
  153603. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153604. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153605. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153606. };
  153607. static noise3 _psy_noisebias_8[3]={
  153608. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153609. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153610. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153611. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153612. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153613. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153614. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153615. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153616. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153617. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153618. };
  153619. /* stereo mode by base quality level */
  153620. static adj_stereo _psy_stereo_modes_8[3]={
  153621. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153622. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153623. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153624. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153625. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153626. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153627. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153628. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153629. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153630. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153631. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153632. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153633. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153634. };
  153635. static noiseguard _psy_noiseguards_8[2]={
  153636. {10,10,-1},
  153637. {10,10,-1},
  153638. };
  153639. static compandblock _psy_compand_8[2]={
  153640. {{
  153641. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153642. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153643. 12,12,13,13,14,14,15, 15, /* 23dB */
  153644. 16,16,17,17,17,18,18, 19, /* 31dB */
  153645. 19,19,20,21,22,23,24, 25, /* 39dB */
  153646. }},
  153647. {{
  153648. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153649. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153650. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153651. 9,10,11,12,13,14,15, 16, /* 31dB */
  153652. 17,18,19,20,21,22,23, 24, /* 39dB */
  153653. }},
  153654. };
  153655. static double _psy_lowpass_8[3]={3.,4.,4.};
  153656. static int _noise_start_8[2]={
  153657. 64,64,
  153658. };
  153659. static int _noise_part_8[2]={
  153660. 8,8,
  153661. };
  153662. static int _psy_ath_floater_8[3]={
  153663. -100,-100,-105,
  153664. };
  153665. static int _psy_ath_abs_8[3]={
  153666. -130,-130,-140,
  153667. };
  153668. /*** End of inlined file: psych_8.h ***/
  153669. /*** Start of inlined file: residue_8.h ***/
  153670. /***** residue backends *********************************************/
  153671. static static_bookblock _resbook_8s_0={
  153672. {
  153673. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153674. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153675. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153676. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153677. }
  153678. };
  153679. static static_bookblock _resbook_8s_1={
  153680. {
  153681. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153682. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153683. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153684. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153685. }
  153686. };
  153687. static vorbis_residue_template _res_8s_0[]={
  153688. {2,0, &_residue_44_mid,
  153689. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153690. &_resbook_8s_0,&_resbook_8s_0},
  153691. };
  153692. static vorbis_residue_template _res_8s_1[]={
  153693. {2,0, &_residue_44_mid,
  153694. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153695. &_resbook_8s_1,&_resbook_8s_1},
  153696. };
  153697. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153698. { _map_nominal, _res_8s_0 }, /* 0 */
  153699. { _map_nominal, _res_8s_1 }, /* 1 */
  153700. };
  153701. static static_bookblock _resbook_8u_0={
  153702. {
  153703. {0},
  153704. {0,0,&_8u0__p1_0},
  153705. {0,0,&_8u0__p2_0},
  153706. {0,0,&_8u0__p3_0},
  153707. {0,0,&_8u0__p4_0},
  153708. {0,0,&_8u0__p5_0},
  153709. {&_8u0__p6_0,&_8u0__p6_1},
  153710. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153711. }
  153712. };
  153713. static static_bookblock _resbook_8u_1={
  153714. {
  153715. {0},
  153716. {0,0,&_8u1__p1_0},
  153717. {0,0,&_8u1__p2_0},
  153718. {0,0,&_8u1__p3_0},
  153719. {0,0,&_8u1__p4_0},
  153720. {0,0,&_8u1__p5_0},
  153721. {0,0,&_8u1__p6_0},
  153722. {&_8u1__p7_0,&_8u1__p7_1},
  153723. {&_8u1__p8_0,&_8u1__p8_1},
  153724. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153725. }
  153726. };
  153727. static vorbis_residue_template _res_8u_0[]={
  153728. {1,0, &_residue_44_low_un,
  153729. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153730. &_resbook_8u_0,&_resbook_8u_0},
  153731. };
  153732. static vorbis_residue_template _res_8u_1[]={
  153733. {1,0, &_residue_44_mid_un,
  153734. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153735. &_resbook_8u_1,&_resbook_8u_1},
  153736. };
  153737. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153738. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153739. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153740. };
  153741. /*** End of inlined file: residue_8.h ***/
  153742. static int blocksize_8[2]={
  153743. 512,512
  153744. };
  153745. static int _floor_mapping_8[2]={
  153746. 6,6,
  153747. };
  153748. static double rate_mapping_8[3]={
  153749. 6000.,9000.,32000.,
  153750. };
  153751. static double rate_mapping_8_uncoupled[3]={
  153752. 8000.,14000.,42000.,
  153753. };
  153754. static double quality_mapping_8[3]={
  153755. -.1,.0,1.
  153756. };
  153757. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153758. static double _global_mapping_8[3]={ 1., 2., 3. };
  153759. ve_setup_data_template ve_setup_8_stereo={
  153760. 2,
  153761. rate_mapping_8,
  153762. quality_mapping_8,
  153763. 2,
  153764. 8000,
  153765. 9000,
  153766. blocksize_8,
  153767. blocksize_8,
  153768. _psy_tone_masteratt_8,
  153769. _psy_tone_0dB,
  153770. _psy_tone_suppress,
  153771. _vp_tonemask_adj_8,
  153772. NULL,
  153773. _vp_tonemask_adj_8,
  153774. _psy_noiseguards_8,
  153775. _psy_noisebias_8,
  153776. _psy_noisebias_8,
  153777. NULL,
  153778. NULL,
  153779. _psy_noise_suppress,
  153780. _psy_compand_8,
  153781. _psy_compand_8_mapping,
  153782. NULL,
  153783. {_noise_start_8,_noise_start_8},
  153784. {_noise_part_8,_noise_part_8},
  153785. _noise_thresh_5only,
  153786. _psy_ath_floater_8,
  153787. _psy_ath_abs_8,
  153788. _psy_lowpass_8,
  153789. _psy_global_44,
  153790. _global_mapping_8,
  153791. _psy_stereo_modes_8,
  153792. _floor_books,
  153793. _floor,
  153794. _floor_mapping_8,
  153795. NULL,
  153796. _mapres_template_8_stereo
  153797. };
  153798. ve_setup_data_template ve_setup_8_uncoupled={
  153799. 2,
  153800. rate_mapping_8_uncoupled,
  153801. quality_mapping_8,
  153802. -1,
  153803. 8000,
  153804. 9000,
  153805. blocksize_8,
  153806. blocksize_8,
  153807. _psy_tone_masteratt_8,
  153808. _psy_tone_0dB,
  153809. _psy_tone_suppress,
  153810. _vp_tonemask_adj_8,
  153811. NULL,
  153812. _vp_tonemask_adj_8,
  153813. _psy_noiseguards_8,
  153814. _psy_noisebias_8,
  153815. _psy_noisebias_8,
  153816. NULL,
  153817. NULL,
  153818. _psy_noise_suppress,
  153819. _psy_compand_8,
  153820. _psy_compand_8_mapping,
  153821. NULL,
  153822. {_noise_start_8,_noise_start_8},
  153823. {_noise_part_8,_noise_part_8},
  153824. _noise_thresh_5only,
  153825. _psy_ath_floater_8,
  153826. _psy_ath_abs_8,
  153827. _psy_lowpass_8,
  153828. _psy_global_44,
  153829. _global_mapping_8,
  153830. _psy_stereo_modes_8,
  153831. _floor_books,
  153832. _floor,
  153833. _floor_mapping_8,
  153834. NULL,
  153835. _mapres_template_8_uncoupled
  153836. };
  153837. /*** End of inlined file: setup_8.h ***/
  153838. /*** Start of inlined file: setup_11.h ***/
  153839. /*** Start of inlined file: psych_11.h ***/
  153840. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153841. static att3 _psy_tone_masteratt_11[3]={
  153842. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153843. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153844. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153845. };
  153846. static vp_adjblock _vp_tonemask_adj_11[3]={
  153847. /* adjust for mode zero */
  153848. /* 63 125 250 500 1 2 4 8 16 */
  153849. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153850. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153851. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153852. };
  153853. static noise3 _psy_noisebias_11[3]={
  153854. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153855. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153856. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153857. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153858. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153859. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153860. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153861. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153862. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153863. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153864. };
  153865. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153866. /*** End of inlined file: psych_11.h ***/
  153867. static int blocksize_11[2]={
  153868. 512,512
  153869. };
  153870. static int _floor_mapping_11[2]={
  153871. 6,6,
  153872. };
  153873. static double rate_mapping_11[3]={
  153874. 8000.,13000.,44000.,
  153875. };
  153876. static double rate_mapping_11_uncoupled[3]={
  153877. 12000.,20000.,50000.,
  153878. };
  153879. static double quality_mapping_11[3]={
  153880. -.1,.0,1.
  153881. };
  153882. ve_setup_data_template ve_setup_11_stereo={
  153883. 2,
  153884. rate_mapping_11,
  153885. quality_mapping_11,
  153886. 2,
  153887. 9000,
  153888. 15000,
  153889. blocksize_11,
  153890. blocksize_11,
  153891. _psy_tone_masteratt_11,
  153892. _psy_tone_0dB,
  153893. _psy_tone_suppress,
  153894. _vp_tonemask_adj_11,
  153895. NULL,
  153896. _vp_tonemask_adj_11,
  153897. _psy_noiseguards_8,
  153898. _psy_noisebias_11,
  153899. _psy_noisebias_11,
  153900. NULL,
  153901. NULL,
  153902. _psy_noise_suppress,
  153903. _psy_compand_8,
  153904. _psy_compand_8_mapping,
  153905. NULL,
  153906. {_noise_start_8,_noise_start_8},
  153907. {_noise_part_8,_noise_part_8},
  153908. _noise_thresh_11,
  153909. _psy_ath_floater_8,
  153910. _psy_ath_abs_8,
  153911. _psy_lowpass_11,
  153912. _psy_global_44,
  153913. _global_mapping_8,
  153914. _psy_stereo_modes_8,
  153915. _floor_books,
  153916. _floor,
  153917. _floor_mapping_11,
  153918. NULL,
  153919. _mapres_template_8_stereo
  153920. };
  153921. ve_setup_data_template ve_setup_11_uncoupled={
  153922. 2,
  153923. rate_mapping_11_uncoupled,
  153924. quality_mapping_11,
  153925. -1,
  153926. 9000,
  153927. 15000,
  153928. blocksize_11,
  153929. blocksize_11,
  153930. _psy_tone_masteratt_11,
  153931. _psy_tone_0dB,
  153932. _psy_tone_suppress,
  153933. _vp_tonemask_adj_11,
  153934. NULL,
  153935. _vp_tonemask_adj_11,
  153936. _psy_noiseguards_8,
  153937. _psy_noisebias_11,
  153938. _psy_noisebias_11,
  153939. NULL,
  153940. NULL,
  153941. _psy_noise_suppress,
  153942. _psy_compand_8,
  153943. _psy_compand_8_mapping,
  153944. NULL,
  153945. {_noise_start_8,_noise_start_8},
  153946. {_noise_part_8,_noise_part_8},
  153947. _noise_thresh_11,
  153948. _psy_ath_floater_8,
  153949. _psy_ath_abs_8,
  153950. _psy_lowpass_11,
  153951. _psy_global_44,
  153952. _global_mapping_8,
  153953. _psy_stereo_modes_8,
  153954. _floor_books,
  153955. _floor,
  153956. _floor_mapping_11,
  153957. NULL,
  153958. _mapres_template_8_uncoupled
  153959. };
  153960. /*** End of inlined file: setup_11.h ***/
  153961. /*** Start of inlined file: setup_16.h ***/
  153962. /*** Start of inlined file: psych_16.h ***/
  153963. /* stereo mode by base quality level */
  153964. static adj_stereo _psy_stereo_modes_16[4]={
  153965. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153966. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153967. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153968. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153969. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153970. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153971. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153972. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153973. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153974. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153975. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153976. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153977. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153978. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153979. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153980. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153981. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153982. };
  153983. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153984. static att3 _psy_tone_masteratt_16[4]={
  153985. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153986. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153987. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153988. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153989. };
  153990. static vp_adjblock _vp_tonemask_adj_16[4]={
  153991. /* adjust for mode zero */
  153992. /* 63 125 250 500 1 2 4 8 16 */
  153993. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153994. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153995. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153996. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153997. };
  153998. static noise3 _psy_noisebias_16_short[4]={
  153999. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154000. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154001. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154002. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154003. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154004. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154005. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154006. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154007. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154008. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154009. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154010. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154011. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154012. };
  154013. static noise3 _psy_noisebias_16_impulse[4]={
  154014. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154015. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154016. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154017. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154018. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154019. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154020. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154021. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154022. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154023. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154024. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154025. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154026. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154027. };
  154028. static noise3 _psy_noisebias_16[4]={
  154029. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154030. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154031. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154032. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154033. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154034. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154035. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154036. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154037. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154038. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154039. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154040. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154041. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154042. };
  154043. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154044. static int _noise_start_16[3]={ 256,256,9999 };
  154045. static int _noise_part_16[4]={ 8,8,8,8 };
  154046. static int _psy_ath_floater_16[4]={
  154047. -100,-100,-100,-105,
  154048. };
  154049. static int _psy_ath_abs_16[4]={
  154050. -130,-130,-130,-140,
  154051. };
  154052. /*** End of inlined file: psych_16.h ***/
  154053. /*** Start of inlined file: residue_16.h ***/
  154054. /***** residue backends *********************************************/
  154055. static static_bookblock _resbook_16s_0={
  154056. {
  154057. {0},
  154058. {0,0,&_16c0_s_p1_0},
  154059. {0,0,&_16c0_s_p2_0},
  154060. {0,0,&_16c0_s_p3_0},
  154061. {0,0,&_16c0_s_p4_0},
  154062. {0,0,&_16c0_s_p5_0},
  154063. {0,0,&_16c0_s_p6_0},
  154064. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154065. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154066. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154067. }
  154068. };
  154069. static static_bookblock _resbook_16s_1={
  154070. {
  154071. {0},
  154072. {0,0,&_16c1_s_p1_0},
  154073. {0,0,&_16c1_s_p2_0},
  154074. {0,0,&_16c1_s_p3_0},
  154075. {0,0,&_16c1_s_p4_0},
  154076. {0,0,&_16c1_s_p5_0},
  154077. {0,0,&_16c1_s_p6_0},
  154078. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154079. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154080. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154081. }
  154082. };
  154083. static static_bookblock _resbook_16s_2={
  154084. {
  154085. {0},
  154086. {0,0,&_16c2_s_p1_0},
  154087. {0,0,&_16c2_s_p2_0},
  154088. {0,0,&_16c2_s_p3_0},
  154089. {0,0,&_16c2_s_p4_0},
  154090. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154091. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154092. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154093. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154094. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154095. }
  154096. };
  154097. static vorbis_residue_template _res_16s_0[]={
  154098. {2,0, &_residue_44_mid,
  154099. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154100. &_resbook_16s_0,&_resbook_16s_0},
  154101. };
  154102. static vorbis_residue_template _res_16s_1[]={
  154103. {2,0, &_residue_44_mid,
  154104. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154105. &_resbook_16s_1,&_resbook_16s_1},
  154106. {2,0, &_residue_44_mid,
  154107. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154108. &_resbook_16s_1,&_resbook_16s_1}
  154109. };
  154110. static vorbis_residue_template _res_16s_2[]={
  154111. {2,0, &_residue_44_high,
  154112. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154113. &_resbook_16s_2,&_resbook_16s_2},
  154114. {2,0, &_residue_44_high,
  154115. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154116. &_resbook_16s_2,&_resbook_16s_2}
  154117. };
  154118. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154119. { _map_nominal, _res_16s_0 }, /* 0 */
  154120. { _map_nominal, _res_16s_1 }, /* 1 */
  154121. { _map_nominal, _res_16s_2 }, /* 2 */
  154122. };
  154123. static static_bookblock _resbook_16u_0={
  154124. {
  154125. {0},
  154126. {0,0,&_16u0__p1_0},
  154127. {0,0,&_16u0__p2_0},
  154128. {0,0,&_16u0__p3_0},
  154129. {0,0,&_16u0__p4_0},
  154130. {0,0,&_16u0__p5_0},
  154131. {&_16u0__p6_0,&_16u0__p6_1},
  154132. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154133. }
  154134. };
  154135. static static_bookblock _resbook_16u_1={
  154136. {
  154137. {0},
  154138. {0,0,&_16u1__p1_0},
  154139. {0,0,&_16u1__p2_0},
  154140. {0,0,&_16u1__p3_0},
  154141. {0,0,&_16u1__p4_0},
  154142. {0,0,&_16u1__p5_0},
  154143. {0,0,&_16u1__p6_0},
  154144. {&_16u1__p7_0,&_16u1__p7_1},
  154145. {&_16u1__p8_0,&_16u1__p8_1},
  154146. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154147. }
  154148. };
  154149. static static_bookblock _resbook_16u_2={
  154150. {
  154151. {0},
  154152. {0,0,&_16u2_p1_0},
  154153. {0,0,&_16u2_p2_0},
  154154. {0,0,&_16u2_p3_0},
  154155. {0,0,&_16u2_p4_0},
  154156. {&_16u2_p5_0,&_16u2_p5_1},
  154157. {&_16u2_p6_0,&_16u2_p6_1},
  154158. {&_16u2_p7_0,&_16u2_p7_1},
  154159. {&_16u2_p8_0,&_16u2_p8_1},
  154160. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154161. }
  154162. };
  154163. static vorbis_residue_template _res_16u_0[]={
  154164. {1,0, &_residue_44_low_un,
  154165. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154166. &_resbook_16u_0,&_resbook_16u_0},
  154167. };
  154168. static vorbis_residue_template _res_16u_1[]={
  154169. {1,0, &_residue_44_mid_un,
  154170. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154171. &_resbook_16u_1,&_resbook_16u_1},
  154172. {1,0, &_residue_44_mid_un,
  154173. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154174. &_resbook_16u_1,&_resbook_16u_1}
  154175. };
  154176. static vorbis_residue_template _res_16u_2[]={
  154177. {1,0, &_residue_44_hi_un,
  154178. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154179. &_resbook_16u_2,&_resbook_16u_2},
  154180. {1,0, &_residue_44_hi_un,
  154181. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154182. &_resbook_16u_2,&_resbook_16u_2}
  154183. };
  154184. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154185. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154186. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154187. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154188. };
  154189. /*** End of inlined file: residue_16.h ***/
  154190. static int blocksize_16_short[3]={
  154191. 1024,512,512
  154192. };
  154193. static int blocksize_16_long[3]={
  154194. 1024,1024,1024
  154195. };
  154196. static int _floor_mapping_16_short[3]={
  154197. 9,3,3
  154198. };
  154199. static int _floor_mapping_16[3]={
  154200. 9,9,9
  154201. };
  154202. static double rate_mapping_16[4]={
  154203. 12000.,20000.,44000.,86000.
  154204. };
  154205. static double rate_mapping_16_uncoupled[4]={
  154206. 16000.,28000.,64000.,100000.
  154207. };
  154208. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154209. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154210. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154211. ve_setup_data_template ve_setup_16_stereo={
  154212. 3,
  154213. rate_mapping_16,
  154214. quality_mapping_16,
  154215. 2,
  154216. 15000,
  154217. 19000,
  154218. blocksize_16_short,
  154219. blocksize_16_long,
  154220. _psy_tone_masteratt_16,
  154221. _psy_tone_0dB,
  154222. _psy_tone_suppress,
  154223. _vp_tonemask_adj_16,
  154224. _vp_tonemask_adj_16,
  154225. _vp_tonemask_adj_16,
  154226. _psy_noiseguards_8,
  154227. _psy_noisebias_16_impulse,
  154228. _psy_noisebias_16_short,
  154229. _psy_noisebias_16_short,
  154230. _psy_noisebias_16,
  154231. _psy_noise_suppress,
  154232. _psy_compand_8,
  154233. _psy_compand_16_mapping,
  154234. _psy_compand_16_mapping,
  154235. {_noise_start_16,_noise_start_16},
  154236. { _noise_part_16, _noise_part_16},
  154237. _noise_thresh_16,
  154238. _psy_ath_floater_16,
  154239. _psy_ath_abs_16,
  154240. _psy_lowpass_16,
  154241. _psy_global_44,
  154242. _global_mapping_16,
  154243. _psy_stereo_modes_16,
  154244. _floor_books,
  154245. _floor,
  154246. _floor_mapping_16_short,
  154247. _floor_mapping_16,
  154248. _mapres_template_16_stereo
  154249. };
  154250. ve_setup_data_template ve_setup_16_uncoupled={
  154251. 3,
  154252. rate_mapping_16_uncoupled,
  154253. quality_mapping_16,
  154254. -1,
  154255. 15000,
  154256. 19000,
  154257. blocksize_16_short,
  154258. blocksize_16_long,
  154259. _psy_tone_masteratt_16,
  154260. _psy_tone_0dB,
  154261. _psy_tone_suppress,
  154262. _vp_tonemask_adj_16,
  154263. _vp_tonemask_adj_16,
  154264. _vp_tonemask_adj_16,
  154265. _psy_noiseguards_8,
  154266. _psy_noisebias_16_impulse,
  154267. _psy_noisebias_16_short,
  154268. _psy_noisebias_16_short,
  154269. _psy_noisebias_16,
  154270. _psy_noise_suppress,
  154271. _psy_compand_8,
  154272. _psy_compand_16_mapping,
  154273. _psy_compand_16_mapping,
  154274. {_noise_start_16,_noise_start_16},
  154275. { _noise_part_16, _noise_part_16},
  154276. _noise_thresh_16,
  154277. _psy_ath_floater_16,
  154278. _psy_ath_abs_16,
  154279. _psy_lowpass_16,
  154280. _psy_global_44,
  154281. _global_mapping_16,
  154282. _psy_stereo_modes_16,
  154283. _floor_books,
  154284. _floor,
  154285. _floor_mapping_16_short,
  154286. _floor_mapping_16,
  154287. _mapres_template_16_uncoupled
  154288. };
  154289. /*** End of inlined file: setup_16.h ***/
  154290. /*** Start of inlined file: setup_22.h ***/
  154291. static double rate_mapping_22[4]={
  154292. 15000.,20000.,44000.,86000.
  154293. };
  154294. static double rate_mapping_22_uncoupled[4]={
  154295. 16000.,28000.,50000.,90000.
  154296. };
  154297. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154298. ve_setup_data_template ve_setup_22_stereo={
  154299. 3,
  154300. rate_mapping_22,
  154301. quality_mapping_16,
  154302. 2,
  154303. 19000,
  154304. 26000,
  154305. blocksize_16_short,
  154306. blocksize_16_long,
  154307. _psy_tone_masteratt_16,
  154308. _psy_tone_0dB,
  154309. _psy_tone_suppress,
  154310. _vp_tonemask_adj_16,
  154311. _vp_tonemask_adj_16,
  154312. _vp_tonemask_adj_16,
  154313. _psy_noiseguards_8,
  154314. _psy_noisebias_16_impulse,
  154315. _psy_noisebias_16_short,
  154316. _psy_noisebias_16_short,
  154317. _psy_noisebias_16,
  154318. _psy_noise_suppress,
  154319. _psy_compand_8,
  154320. _psy_compand_8_mapping,
  154321. _psy_compand_8_mapping,
  154322. {_noise_start_16,_noise_start_16},
  154323. { _noise_part_16, _noise_part_16},
  154324. _noise_thresh_16,
  154325. _psy_ath_floater_16,
  154326. _psy_ath_abs_16,
  154327. _psy_lowpass_22,
  154328. _psy_global_44,
  154329. _global_mapping_16,
  154330. _psy_stereo_modes_16,
  154331. _floor_books,
  154332. _floor,
  154333. _floor_mapping_16_short,
  154334. _floor_mapping_16,
  154335. _mapres_template_16_stereo
  154336. };
  154337. ve_setup_data_template ve_setup_22_uncoupled={
  154338. 3,
  154339. rate_mapping_22_uncoupled,
  154340. quality_mapping_16,
  154341. -1,
  154342. 19000,
  154343. 26000,
  154344. blocksize_16_short,
  154345. blocksize_16_long,
  154346. _psy_tone_masteratt_16,
  154347. _psy_tone_0dB,
  154348. _psy_tone_suppress,
  154349. _vp_tonemask_adj_16,
  154350. _vp_tonemask_adj_16,
  154351. _vp_tonemask_adj_16,
  154352. _psy_noiseguards_8,
  154353. _psy_noisebias_16_impulse,
  154354. _psy_noisebias_16_short,
  154355. _psy_noisebias_16_short,
  154356. _psy_noisebias_16,
  154357. _psy_noise_suppress,
  154358. _psy_compand_8,
  154359. _psy_compand_8_mapping,
  154360. _psy_compand_8_mapping,
  154361. {_noise_start_16,_noise_start_16},
  154362. { _noise_part_16, _noise_part_16},
  154363. _noise_thresh_16,
  154364. _psy_ath_floater_16,
  154365. _psy_ath_abs_16,
  154366. _psy_lowpass_22,
  154367. _psy_global_44,
  154368. _global_mapping_16,
  154369. _psy_stereo_modes_16,
  154370. _floor_books,
  154371. _floor,
  154372. _floor_mapping_16_short,
  154373. _floor_mapping_16,
  154374. _mapres_template_16_uncoupled
  154375. };
  154376. /*** End of inlined file: setup_22.h ***/
  154377. /*** Start of inlined file: setup_X.h ***/
  154378. static double rate_mapping_X[12]={
  154379. -1.,-1.,-1.,-1.,-1.,-1.,
  154380. -1.,-1.,-1.,-1.,-1.,-1.
  154381. };
  154382. ve_setup_data_template ve_setup_X_stereo={
  154383. 11,
  154384. rate_mapping_X,
  154385. quality_mapping_44,
  154386. 2,
  154387. 50000,
  154388. 200000,
  154389. blocksize_short_44,
  154390. blocksize_long_44,
  154391. _psy_tone_masteratt_44,
  154392. _psy_tone_0dB,
  154393. _psy_tone_suppress,
  154394. _vp_tonemask_adj_otherblock,
  154395. _vp_tonemask_adj_longblock,
  154396. _vp_tonemask_adj_otherblock,
  154397. _psy_noiseguards_44,
  154398. _psy_noisebias_impulse,
  154399. _psy_noisebias_padding,
  154400. _psy_noisebias_trans,
  154401. _psy_noisebias_long,
  154402. _psy_noise_suppress,
  154403. _psy_compand_44,
  154404. _psy_compand_short_mapping,
  154405. _psy_compand_long_mapping,
  154406. {_noise_start_short_44,_noise_start_long_44},
  154407. {_noise_part_short_44,_noise_part_long_44},
  154408. _noise_thresh_44,
  154409. _psy_ath_floater,
  154410. _psy_ath_abs,
  154411. _psy_lowpass_44,
  154412. _psy_global_44,
  154413. _global_mapping_44,
  154414. _psy_stereo_modes_44,
  154415. _floor_books,
  154416. _floor,
  154417. _floor_short_mapping_44,
  154418. _floor_long_mapping_44,
  154419. _mapres_template_44_stereo
  154420. };
  154421. ve_setup_data_template ve_setup_X_uncoupled={
  154422. 11,
  154423. rate_mapping_X,
  154424. quality_mapping_44,
  154425. -1,
  154426. 50000,
  154427. 200000,
  154428. blocksize_short_44,
  154429. blocksize_long_44,
  154430. _psy_tone_masteratt_44,
  154431. _psy_tone_0dB,
  154432. _psy_tone_suppress,
  154433. _vp_tonemask_adj_otherblock,
  154434. _vp_tonemask_adj_longblock,
  154435. _vp_tonemask_adj_otherblock,
  154436. _psy_noiseguards_44,
  154437. _psy_noisebias_impulse,
  154438. _psy_noisebias_padding,
  154439. _psy_noisebias_trans,
  154440. _psy_noisebias_long,
  154441. _psy_noise_suppress,
  154442. _psy_compand_44,
  154443. _psy_compand_short_mapping,
  154444. _psy_compand_long_mapping,
  154445. {_noise_start_short_44,_noise_start_long_44},
  154446. {_noise_part_short_44,_noise_part_long_44},
  154447. _noise_thresh_44,
  154448. _psy_ath_floater,
  154449. _psy_ath_abs,
  154450. _psy_lowpass_44,
  154451. _psy_global_44,
  154452. _global_mapping_44,
  154453. NULL,
  154454. _floor_books,
  154455. _floor,
  154456. _floor_short_mapping_44,
  154457. _floor_long_mapping_44,
  154458. _mapres_template_44_uncoupled
  154459. };
  154460. ve_setup_data_template ve_setup_XX_stereo={
  154461. 2,
  154462. rate_mapping_X,
  154463. quality_mapping_8,
  154464. 2,
  154465. 0,
  154466. 8000,
  154467. blocksize_8,
  154468. blocksize_8,
  154469. _psy_tone_masteratt_8,
  154470. _psy_tone_0dB,
  154471. _psy_tone_suppress,
  154472. _vp_tonemask_adj_8,
  154473. NULL,
  154474. _vp_tonemask_adj_8,
  154475. _psy_noiseguards_8,
  154476. _psy_noisebias_8,
  154477. _psy_noisebias_8,
  154478. NULL,
  154479. NULL,
  154480. _psy_noise_suppress,
  154481. _psy_compand_8,
  154482. _psy_compand_8_mapping,
  154483. NULL,
  154484. {_noise_start_8,_noise_start_8},
  154485. {_noise_part_8,_noise_part_8},
  154486. _noise_thresh_5only,
  154487. _psy_ath_floater_8,
  154488. _psy_ath_abs_8,
  154489. _psy_lowpass_8,
  154490. _psy_global_44,
  154491. _global_mapping_8,
  154492. _psy_stereo_modes_8,
  154493. _floor_books,
  154494. _floor,
  154495. _floor_mapping_8,
  154496. NULL,
  154497. _mapres_template_8_stereo
  154498. };
  154499. ve_setup_data_template ve_setup_XX_uncoupled={
  154500. 2,
  154501. rate_mapping_X,
  154502. quality_mapping_8,
  154503. -1,
  154504. 0,
  154505. 8000,
  154506. blocksize_8,
  154507. blocksize_8,
  154508. _psy_tone_masteratt_8,
  154509. _psy_tone_0dB,
  154510. _psy_tone_suppress,
  154511. _vp_tonemask_adj_8,
  154512. NULL,
  154513. _vp_tonemask_adj_8,
  154514. _psy_noiseguards_8,
  154515. _psy_noisebias_8,
  154516. _psy_noisebias_8,
  154517. NULL,
  154518. NULL,
  154519. _psy_noise_suppress,
  154520. _psy_compand_8,
  154521. _psy_compand_8_mapping,
  154522. NULL,
  154523. {_noise_start_8,_noise_start_8},
  154524. {_noise_part_8,_noise_part_8},
  154525. _noise_thresh_5only,
  154526. _psy_ath_floater_8,
  154527. _psy_ath_abs_8,
  154528. _psy_lowpass_8,
  154529. _psy_global_44,
  154530. _global_mapping_8,
  154531. _psy_stereo_modes_8,
  154532. _floor_books,
  154533. _floor,
  154534. _floor_mapping_8,
  154535. NULL,
  154536. _mapres_template_8_uncoupled
  154537. };
  154538. /*** End of inlined file: setup_X.h ***/
  154539. static ve_setup_data_template *setup_list[]={
  154540. &ve_setup_44_stereo,
  154541. &ve_setup_44_uncoupled,
  154542. &ve_setup_32_stereo,
  154543. &ve_setup_32_uncoupled,
  154544. &ve_setup_22_stereo,
  154545. &ve_setup_22_uncoupled,
  154546. &ve_setup_16_stereo,
  154547. &ve_setup_16_uncoupled,
  154548. &ve_setup_11_stereo,
  154549. &ve_setup_11_uncoupled,
  154550. &ve_setup_8_stereo,
  154551. &ve_setup_8_uncoupled,
  154552. &ve_setup_X_stereo,
  154553. &ve_setup_X_uncoupled,
  154554. &ve_setup_XX_stereo,
  154555. &ve_setup_XX_uncoupled,
  154556. 0
  154557. };
  154558. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154559. if(vi && vi->codec_setup){
  154560. vi->version=0;
  154561. vi->channels=ch;
  154562. vi->rate=rate;
  154563. return(0);
  154564. }
  154565. return(OV_EINVAL);
  154566. }
  154567. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154568. static_codebook ***books,
  154569. vorbis_info_floor1 *in,
  154570. int *x){
  154571. int i,k,is=s;
  154572. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154573. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154574. memcpy(f,in+x[is],sizeof(*f));
  154575. /* fill in the lowpass field, even if it's temporary */
  154576. f->n=ci->blocksizes[block]>>1;
  154577. /* books */
  154578. {
  154579. int partitions=f->partitions;
  154580. int maxclass=-1;
  154581. int maxbook=-1;
  154582. for(i=0;i<partitions;i++)
  154583. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154584. for(i=0;i<=maxclass;i++){
  154585. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154586. f->class_book[i]+=ci->books;
  154587. for(k=0;k<(1<<f->class_subs[i]);k++){
  154588. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154589. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154590. }
  154591. }
  154592. for(i=0;i<=maxbook;i++)
  154593. ci->book_param[ci->books++]=books[x[is]][i];
  154594. }
  154595. /* for now, we're only using floor 1 */
  154596. ci->floor_type[ci->floors]=1;
  154597. ci->floor_param[ci->floors]=f;
  154598. ci->floors++;
  154599. return;
  154600. }
  154601. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154602. vorbis_info_psy_global *in,
  154603. double *x){
  154604. int i,is=s;
  154605. double ds=s-is;
  154606. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154607. vorbis_info_psy_global *g=&ci->psy_g_param;
  154608. memcpy(g,in+(int)x[is],sizeof(*g));
  154609. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154610. is=(int)ds;
  154611. ds-=is;
  154612. if(ds==0 && is>0){
  154613. is--;
  154614. ds=1.;
  154615. }
  154616. /* interpolate the trigger threshholds */
  154617. for(i=0;i<4;i++){
  154618. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154619. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154620. }
  154621. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154622. return;
  154623. }
  154624. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154625. highlevel_encode_setup *hi,
  154626. adj_stereo *p){
  154627. float s=hi->stereo_point_setting;
  154628. int i,is=s;
  154629. double ds=s-is;
  154630. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154631. vorbis_info_psy_global *g=&ci->psy_g_param;
  154632. if(p){
  154633. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154634. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154635. if(hi->managed){
  154636. /* interpolate the kHz threshholds */
  154637. for(i=0;i<PACKETBLOBS;i++){
  154638. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154639. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154640. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154641. g->coupling_pkHz[i]=kHz;
  154642. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154643. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154644. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154645. }
  154646. }else{
  154647. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154648. for(i=0;i<PACKETBLOBS;i++){
  154649. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154650. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154651. g->coupling_pkHz[i]=kHz;
  154652. }
  154653. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154654. for(i=0;i<PACKETBLOBS;i++){
  154655. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154656. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154657. }
  154658. }
  154659. }else{
  154660. for(i=0;i<PACKETBLOBS;i++){
  154661. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154662. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154663. }
  154664. }
  154665. return;
  154666. }
  154667. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154668. int *nn_start,
  154669. int *nn_partition,
  154670. double *nn_thresh,
  154671. int block){
  154672. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154673. vorbis_info_psy *p=ci->psy_param[block];
  154674. highlevel_encode_setup *hi=&ci->hi;
  154675. int is=s;
  154676. if(block>=ci->psys)
  154677. ci->psys=block+1;
  154678. if(!p){
  154679. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154680. ci->psy_param[block]=p;
  154681. }
  154682. memcpy(p,&_psy_info_template,sizeof(*p));
  154683. p->blockflag=block>>1;
  154684. if(hi->noise_normalize_p){
  154685. p->normal_channel_p=1;
  154686. p->normal_point_p=1;
  154687. p->normal_start=nn_start[is];
  154688. p->normal_partition=nn_partition[is];
  154689. p->normal_thresh=nn_thresh[is];
  154690. }
  154691. return;
  154692. }
  154693. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154694. att3 *att,
  154695. int *max,
  154696. vp_adjblock *in){
  154697. int i,is=s;
  154698. double ds=s-is;
  154699. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154700. vorbis_info_psy *p=ci->psy_param[block];
  154701. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154702. filling the values in here */
  154703. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154704. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154705. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154706. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154707. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154708. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154709. for(i=0;i<P_BANDS;i++)
  154710. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154711. return;
  154712. }
  154713. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154714. compandblock *in, double *x){
  154715. int i,is=s;
  154716. double ds=s-is;
  154717. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154718. vorbis_info_psy *p=ci->psy_param[block];
  154719. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154720. is=(int)ds;
  154721. ds-=is;
  154722. if(ds==0 && is>0){
  154723. is--;
  154724. ds=1.;
  154725. }
  154726. /* interpolate the compander settings */
  154727. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154728. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154729. return;
  154730. }
  154731. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154732. int *suppress){
  154733. int is=s;
  154734. double ds=s-is;
  154735. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154736. vorbis_info_psy *p=ci->psy_param[block];
  154737. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154738. return;
  154739. }
  154740. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154741. int *suppress,
  154742. noise3 *in,
  154743. noiseguard *guard,
  154744. double userbias){
  154745. int i,is=s,j;
  154746. double ds=s-is;
  154747. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154748. vorbis_info_psy *p=ci->psy_param[block];
  154749. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154750. p->noisewindowlomin=guard[block].lo;
  154751. p->noisewindowhimin=guard[block].hi;
  154752. p->noisewindowfixed=guard[block].fixed;
  154753. for(j=0;j<P_NOISECURVES;j++)
  154754. for(i=0;i<P_BANDS;i++)
  154755. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154756. /* impulse blocks may take a user specified bias to boost the
  154757. nominal/high noise encoding depth */
  154758. for(j=0;j<P_NOISECURVES;j++){
  154759. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154760. for(i=0;i<P_BANDS;i++){
  154761. p->noiseoff[j][i]+=userbias;
  154762. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154763. }
  154764. }
  154765. return;
  154766. }
  154767. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154768. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154769. vorbis_info_psy *p=ci->psy_param[block];
  154770. p->ath_adjatt=ci->hi.ath_floating_dB;
  154771. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154772. return;
  154773. }
  154774. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154775. int i;
  154776. for(i=0;i<ci->books;i++)
  154777. if(ci->book_param[i]==book)return(i);
  154778. return(ci->books++);
  154779. }
  154780. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154781. int *shortb,int *longb){
  154782. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154783. int is=s;
  154784. int blockshort=shortb[is];
  154785. int blocklong=longb[is];
  154786. ci->blocksizes[0]=blockshort;
  154787. ci->blocksizes[1]=blocklong;
  154788. }
  154789. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154790. int number, int block,
  154791. vorbis_residue_template *res){
  154792. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154793. int i,n;
  154794. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154795. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154796. memcpy(r,res->res,sizeof(*r));
  154797. if(ci->residues<=number)ci->residues=number+1;
  154798. switch(ci->blocksizes[block]){
  154799. case 64:case 128:case 256:
  154800. r->grouping=16;
  154801. break;
  154802. default:
  154803. r->grouping=32;
  154804. break;
  154805. }
  154806. ci->residue_type[number]=res->res_type;
  154807. /* to be adjusted by lowpass/pointlimit later */
  154808. n=r->end=ci->blocksizes[block]>>1;
  154809. if(res->res_type==2)
  154810. n=r->end*=vi->channels;
  154811. /* fill in all the books */
  154812. {
  154813. int booklist=0,k;
  154814. if(ci->hi.managed){
  154815. for(i=0;i<r->partitions;i++)
  154816. for(k=0;k<3;k++)
  154817. if(res->books_base_managed->books[i][k])
  154818. r->secondstages[i]|=(1<<k);
  154819. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154820. ci->book_param[r->groupbook]=res->book_aux_managed;
  154821. for(i=0;i<r->partitions;i++){
  154822. for(k=0;k<3;k++){
  154823. if(res->books_base_managed->books[i][k]){
  154824. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154825. r->booklist[booklist++]=bookid;
  154826. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154827. }
  154828. }
  154829. }
  154830. }else{
  154831. for(i=0;i<r->partitions;i++)
  154832. for(k=0;k<3;k++)
  154833. if(res->books_base->books[i][k])
  154834. r->secondstages[i]|=(1<<k);
  154835. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154836. ci->book_param[r->groupbook]=res->book_aux;
  154837. for(i=0;i<r->partitions;i++){
  154838. for(k=0;k<3;k++){
  154839. if(res->books_base->books[i][k]){
  154840. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154841. r->booklist[booklist++]=bookid;
  154842. ci->book_param[bookid]=res->books_base->books[i][k];
  154843. }
  154844. }
  154845. }
  154846. }
  154847. }
  154848. /* lowpass setup/pointlimit */
  154849. {
  154850. double freq=ci->hi.lowpass_kHz*1000.;
  154851. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154852. double nyq=vi->rate/2.;
  154853. long blocksize=ci->blocksizes[block]>>1;
  154854. /* lowpass needs to be set in the floor and the residue. */
  154855. if(freq>nyq)freq=nyq;
  154856. /* in the floor, the granularity can be very fine; it doesn't alter
  154857. the encoding structure, only the samples used to fit the floor
  154858. approximation */
  154859. f->n=freq/nyq*blocksize;
  154860. /* this res may by limited by the maximum pointlimit of the mode,
  154861. not the lowpass. the floor is always lowpass limited. */
  154862. if(res->limit_type){
  154863. if(ci->hi.managed)
  154864. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154865. else
  154866. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154867. if(freq>nyq)freq=nyq;
  154868. }
  154869. /* in the residue, we're constrained, physically, by partition
  154870. boundaries. We still lowpass 'wherever', but we have to round up
  154871. here to next boundary, or the vorbis spec will round it *down* to
  154872. previous boundary in encode/decode */
  154873. if(ci->residue_type[block]==2)
  154874. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154875. r->grouping;
  154876. else
  154877. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154878. r->grouping;
  154879. }
  154880. }
  154881. /* we assume two maps in this encoder */
  154882. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154883. vorbis_mapping_template *maps){
  154884. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154885. int i,j,is=s,modes=2;
  154886. vorbis_info_mapping0 *map=maps[is].map;
  154887. vorbis_info_mode *mode=_mode_template;
  154888. vorbis_residue_template *res=maps[is].res;
  154889. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154890. for(i=0;i<modes;i++){
  154891. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154892. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154893. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154894. if(i>=ci->modes)ci->modes=i+1;
  154895. ci->map_type[i]=0;
  154896. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154897. if(i>=ci->maps)ci->maps=i+1;
  154898. for(j=0;j<map[i].submaps;j++)
  154899. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154900. ,res+map[i].residuesubmap[j]);
  154901. }
  154902. }
  154903. static double setting_to_approx_bitrate(vorbis_info *vi){
  154904. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154905. highlevel_encode_setup *hi=&ci->hi;
  154906. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154907. int is=hi->base_setting;
  154908. double ds=hi->base_setting-is;
  154909. int ch=vi->channels;
  154910. double *r=setup->rate_mapping;
  154911. if(r==NULL)
  154912. return(-1);
  154913. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154914. }
  154915. static void get_setup_template(vorbis_info *vi,
  154916. long ch,long srate,
  154917. double req,int q_or_bitrate){
  154918. int i=0,j;
  154919. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154920. highlevel_encode_setup *hi=&ci->hi;
  154921. if(q_or_bitrate)req/=ch;
  154922. while(setup_list[i]){
  154923. if(setup_list[i]->coupling_restriction==-1 ||
  154924. setup_list[i]->coupling_restriction==ch){
  154925. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154926. srate<=setup_list[i]->samplerate_max_restriction){
  154927. int mappings=setup_list[i]->mappings;
  154928. double *map=(q_or_bitrate?
  154929. setup_list[i]->rate_mapping:
  154930. setup_list[i]->quality_mapping);
  154931. /* the template matches. Does the requested quality mode
  154932. fall within this template's modes? */
  154933. if(req<map[0]){++i;continue;}
  154934. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154935. for(j=0;j<mappings;j++)
  154936. if(req>=map[j] && req<map[j+1])break;
  154937. /* an all-points match */
  154938. hi->setup=setup_list[i];
  154939. if(j==mappings)
  154940. hi->base_setting=j-.001;
  154941. else{
  154942. float low=map[j];
  154943. float high=map[j+1];
  154944. float del=(req-low)/(high-low);
  154945. hi->base_setting=j+del;
  154946. }
  154947. return;
  154948. }
  154949. }
  154950. i++;
  154951. }
  154952. hi->setup=NULL;
  154953. }
  154954. /* encoders will need to use vorbis_info_init beforehand and call
  154955. vorbis_info clear when all done */
  154956. /* two interfaces; this, more detailed one, and later a convenience
  154957. layer on top */
  154958. /* the final setup call */
  154959. int vorbis_encode_setup_init(vorbis_info *vi){
  154960. int i0=0,singleblock=0;
  154961. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154962. ve_setup_data_template *setup=NULL;
  154963. highlevel_encode_setup *hi=&ci->hi;
  154964. if(ci==NULL)return(OV_EINVAL);
  154965. if(!hi->impulse_block_p)i0=1;
  154966. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154967. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154968. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154969. /* again, bound this to avoid the app shooting itself int he foot
  154970. too badly */
  154971. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154972. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154973. /* get the appropriate setup template; matches the fetch in previous
  154974. stages */
  154975. setup=(ve_setup_data_template *)hi->setup;
  154976. if(setup==NULL)return(OV_EINVAL);
  154977. hi->set_in_stone=1;
  154978. /* choose block sizes from configured sizes as well as paying
  154979. attention to long_block_p and short_block_p. If the configured
  154980. short and long blocks are the same length, we set long_block_p
  154981. and unset short_block_p */
  154982. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154983. setup->blocksize_short,
  154984. setup->blocksize_long);
  154985. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154986. /* floor setup; choose proper floor params. Allocated on the floor
  154987. stack in order; if we alloc only long floor, it's 0 */
  154988. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154989. setup->floor_books,
  154990. setup->floor_params,
  154991. setup->floor_short_mapping);
  154992. if(!singleblock)
  154993. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154994. setup->floor_books,
  154995. setup->floor_params,
  154996. setup->floor_long_mapping);
  154997. /* setup of [mostly] short block detection and stereo*/
  154998. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154999. setup->global_params,
  155000. setup->global_mapping);
  155001. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155002. /* basic psych setup and noise normalization */
  155003. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155004. setup->psy_noise_normal_start[0],
  155005. setup->psy_noise_normal_partition[0],
  155006. setup->psy_noise_normal_thresh,
  155007. 0);
  155008. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155009. setup->psy_noise_normal_start[0],
  155010. setup->psy_noise_normal_partition[0],
  155011. setup->psy_noise_normal_thresh,
  155012. 1);
  155013. if(!singleblock){
  155014. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155015. setup->psy_noise_normal_start[1],
  155016. setup->psy_noise_normal_partition[1],
  155017. setup->psy_noise_normal_thresh,
  155018. 2);
  155019. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155020. setup->psy_noise_normal_start[1],
  155021. setup->psy_noise_normal_partition[1],
  155022. setup->psy_noise_normal_thresh,
  155023. 3);
  155024. }
  155025. /* tone masking setup */
  155026. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155027. setup->psy_tone_masteratt,
  155028. setup->psy_tone_0dB,
  155029. setup->psy_tone_adj_impulse);
  155030. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155031. setup->psy_tone_masteratt,
  155032. setup->psy_tone_0dB,
  155033. setup->psy_tone_adj_other);
  155034. if(!singleblock){
  155035. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155036. setup->psy_tone_masteratt,
  155037. setup->psy_tone_0dB,
  155038. setup->psy_tone_adj_other);
  155039. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155040. setup->psy_tone_masteratt,
  155041. setup->psy_tone_0dB,
  155042. setup->psy_tone_adj_long);
  155043. }
  155044. /* noise companding setup */
  155045. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155046. setup->psy_noise_compand,
  155047. setup->psy_noise_compand_short_mapping);
  155048. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155049. setup->psy_noise_compand,
  155050. setup->psy_noise_compand_short_mapping);
  155051. if(!singleblock){
  155052. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155053. setup->psy_noise_compand,
  155054. setup->psy_noise_compand_long_mapping);
  155055. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155056. setup->psy_noise_compand,
  155057. setup->psy_noise_compand_long_mapping);
  155058. }
  155059. /* peak guarding setup */
  155060. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155061. setup->psy_tone_dBsuppress);
  155062. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155063. setup->psy_tone_dBsuppress);
  155064. if(!singleblock){
  155065. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155066. setup->psy_tone_dBsuppress);
  155067. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155068. setup->psy_tone_dBsuppress);
  155069. }
  155070. /* noise bias setup */
  155071. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155072. setup->psy_noise_dBsuppress,
  155073. setup->psy_noise_bias_impulse,
  155074. setup->psy_noiseguards,
  155075. (i0==0?hi->impulse_noisetune:0.));
  155076. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155077. setup->psy_noise_dBsuppress,
  155078. setup->psy_noise_bias_padding,
  155079. setup->psy_noiseguards,0.);
  155080. if(!singleblock){
  155081. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155082. setup->psy_noise_dBsuppress,
  155083. setup->psy_noise_bias_trans,
  155084. setup->psy_noiseguards,0.);
  155085. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155086. setup->psy_noise_dBsuppress,
  155087. setup->psy_noise_bias_long,
  155088. setup->psy_noiseguards,0.);
  155089. }
  155090. vorbis_encode_ath_setup(vi,0);
  155091. vorbis_encode_ath_setup(vi,1);
  155092. if(!singleblock){
  155093. vorbis_encode_ath_setup(vi,2);
  155094. vorbis_encode_ath_setup(vi,3);
  155095. }
  155096. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155097. /* set bitrate readonlies and management */
  155098. if(hi->bitrate_av>0)
  155099. vi->bitrate_nominal=hi->bitrate_av;
  155100. else{
  155101. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155102. }
  155103. vi->bitrate_lower=hi->bitrate_min;
  155104. vi->bitrate_upper=hi->bitrate_max;
  155105. if(hi->bitrate_av)
  155106. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155107. else
  155108. vi->bitrate_window=0.;
  155109. if(hi->managed){
  155110. ci->bi.avg_rate=hi->bitrate_av;
  155111. ci->bi.min_rate=hi->bitrate_min;
  155112. ci->bi.max_rate=hi->bitrate_max;
  155113. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155114. ci->bi.reservoir_bias=
  155115. hi->bitrate_reservoir_bias;
  155116. ci->bi.slew_damp=hi->bitrate_av_damp;
  155117. }
  155118. return(0);
  155119. }
  155120. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155121. long channels,
  155122. long rate){
  155123. int ret=0,i,is;
  155124. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155125. highlevel_encode_setup *hi=&ci->hi;
  155126. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155127. double ds;
  155128. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155129. if(ret)return(ret);
  155130. is=hi->base_setting;
  155131. ds=hi->base_setting-is;
  155132. hi->short_setting=hi->base_setting;
  155133. hi->long_setting=hi->base_setting;
  155134. hi->managed=0;
  155135. hi->impulse_block_p=1;
  155136. hi->noise_normalize_p=1;
  155137. hi->stereo_point_setting=hi->base_setting;
  155138. hi->lowpass_kHz=
  155139. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155140. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155141. setup->psy_ath_float[is+1]*ds;
  155142. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155143. setup->psy_ath_abs[is+1]*ds;
  155144. hi->amplitude_track_dBpersec=-6.;
  155145. hi->trigger_setting=hi->base_setting;
  155146. for(i=0;i<4;i++){
  155147. hi->block[i].tone_mask_setting=hi->base_setting;
  155148. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155149. hi->block[i].noise_bias_setting=hi->base_setting;
  155150. hi->block[i].noise_compand_setting=hi->base_setting;
  155151. }
  155152. return(ret);
  155153. }
  155154. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155155. long channels,
  155156. long rate,
  155157. float quality){
  155158. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155159. highlevel_encode_setup *hi=&ci->hi;
  155160. quality+=.0000001;
  155161. if(quality>=1.)quality=.9999;
  155162. get_setup_template(vi,channels,rate,quality,0);
  155163. if(!hi->setup)return OV_EIMPL;
  155164. return vorbis_encode_setup_setting(vi,channels,rate);
  155165. }
  155166. int vorbis_encode_init_vbr(vorbis_info *vi,
  155167. long channels,
  155168. long rate,
  155169. float base_quality /* 0. to 1. */
  155170. ){
  155171. int ret=0;
  155172. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155173. if(ret){
  155174. vorbis_info_clear(vi);
  155175. return ret;
  155176. }
  155177. ret=vorbis_encode_setup_init(vi);
  155178. if(ret)
  155179. vorbis_info_clear(vi);
  155180. return(ret);
  155181. }
  155182. int vorbis_encode_setup_managed(vorbis_info *vi,
  155183. long channels,
  155184. long rate,
  155185. long max_bitrate,
  155186. long nominal_bitrate,
  155187. long min_bitrate){
  155188. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155189. highlevel_encode_setup *hi=&ci->hi;
  155190. double tnominal=nominal_bitrate;
  155191. int ret=0;
  155192. if(nominal_bitrate<=0.){
  155193. if(max_bitrate>0.){
  155194. if(min_bitrate>0.)
  155195. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155196. else
  155197. nominal_bitrate=max_bitrate*.875;
  155198. }else{
  155199. if(min_bitrate>0.){
  155200. nominal_bitrate=min_bitrate;
  155201. }else{
  155202. return(OV_EINVAL);
  155203. }
  155204. }
  155205. }
  155206. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155207. if(!hi->setup)return OV_EIMPL;
  155208. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155209. if(ret){
  155210. vorbis_info_clear(vi);
  155211. return ret;
  155212. }
  155213. /* initialize management with sane defaults */
  155214. hi->managed=1;
  155215. hi->bitrate_min=min_bitrate;
  155216. hi->bitrate_max=max_bitrate;
  155217. hi->bitrate_av=tnominal;
  155218. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155219. hi->bitrate_reservoir=nominal_bitrate*2;
  155220. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155221. return(ret);
  155222. }
  155223. int vorbis_encode_init(vorbis_info *vi,
  155224. long channels,
  155225. long rate,
  155226. long max_bitrate,
  155227. long nominal_bitrate,
  155228. long min_bitrate){
  155229. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155230. max_bitrate,
  155231. nominal_bitrate,
  155232. min_bitrate);
  155233. if(ret){
  155234. vorbis_info_clear(vi);
  155235. return(ret);
  155236. }
  155237. ret=vorbis_encode_setup_init(vi);
  155238. if(ret)
  155239. vorbis_info_clear(vi);
  155240. return(ret);
  155241. }
  155242. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155243. if(vi){
  155244. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155245. highlevel_encode_setup *hi=&ci->hi;
  155246. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155247. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155248. switch(number){
  155249. /* now deprecated *****************/
  155250. case OV_ECTL_RATEMANAGE_GET:
  155251. {
  155252. struct ovectl_ratemanage_arg *ai=
  155253. (struct ovectl_ratemanage_arg *)arg;
  155254. ai->management_active=hi->managed;
  155255. ai->bitrate_hard_window=ai->bitrate_av_window=
  155256. (double)hi->bitrate_reservoir/vi->rate;
  155257. ai->bitrate_av_window_center=1.;
  155258. ai->bitrate_hard_min=hi->bitrate_min;
  155259. ai->bitrate_hard_max=hi->bitrate_max;
  155260. ai->bitrate_av_lo=hi->bitrate_av;
  155261. ai->bitrate_av_hi=hi->bitrate_av;
  155262. }
  155263. return(0);
  155264. /* now deprecated *****************/
  155265. case OV_ECTL_RATEMANAGE_SET:
  155266. {
  155267. struct ovectl_ratemanage_arg *ai=
  155268. (struct ovectl_ratemanage_arg *)arg;
  155269. if(ai==NULL){
  155270. hi->managed=0;
  155271. }else{
  155272. hi->managed=ai->management_active;
  155273. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155274. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155275. }
  155276. }
  155277. return 0;
  155278. /* now deprecated *****************/
  155279. case OV_ECTL_RATEMANAGE_AVG:
  155280. {
  155281. struct ovectl_ratemanage_arg *ai=
  155282. (struct ovectl_ratemanage_arg *)arg;
  155283. if(ai==NULL){
  155284. hi->bitrate_av=0;
  155285. }else{
  155286. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155287. }
  155288. }
  155289. return(0);
  155290. /* now deprecated *****************/
  155291. case OV_ECTL_RATEMANAGE_HARD:
  155292. {
  155293. struct ovectl_ratemanage_arg *ai=
  155294. (struct ovectl_ratemanage_arg *)arg;
  155295. if(ai==NULL){
  155296. hi->bitrate_min=0;
  155297. hi->bitrate_max=0;
  155298. }else{
  155299. hi->bitrate_min=ai->bitrate_hard_min;
  155300. hi->bitrate_max=ai->bitrate_hard_max;
  155301. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155302. (hi->bitrate_max+hi->bitrate_min)*.5;
  155303. }
  155304. if(hi->bitrate_reservoir<128.)
  155305. hi->bitrate_reservoir=128.;
  155306. }
  155307. return(0);
  155308. /* replacement ratemanage interface */
  155309. case OV_ECTL_RATEMANAGE2_GET:
  155310. {
  155311. struct ovectl_ratemanage2_arg *ai=
  155312. (struct ovectl_ratemanage2_arg *)arg;
  155313. if(ai==NULL)return OV_EINVAL;
  155314. ai->management_active=hi->managed;
  155315. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155316. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155317. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155318. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155319. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155320. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155321. }
  155322. return (0);
  155323. case OV_ECTL_RATEMANAGE2_SET:
  155324. {
  155325. struct ovectl_ratemanage2_arg *ai=
  155326. (struct ovectl_ratemanage2_arg *)arg;
  155327. if(ai==NULL){
  155328. hi->managed=0;
  155329. }else{
  155330. /* sanity check; only catch invariant violations */
  155331. if(ai->bitrate_limit_min_kbps>0 &&
  155332. ai->bitrate_average_kbps>0 &&
  155333. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155334. return OV_EINVAL;
  155335. if(ai->bitrate_limit_max_kbps>0 &&
  155336. ai->bitrate_average_kbps>0 &&
  155337. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155338. return OV_EINVAL;
  155339. if(ai->bitrate_limit_min_kbps>0 &&
  155340. ai->bitrate_limit_max_kbps>0 &&
  155341. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155342. return OV_EINVAL;
  155343. if(ai->bitrate_average_damping <= 0.)
  155344. return OV_EINVAL;
  155345. if(ai->bitrate_limit_reservoir_bits < 0)
  155346. return OV_EINVAL;
  155347. if(ai->bitrate_limit_reservoir_bias < 0.)
  155348. return OV_EINVAL;
  155349. if(ai->bitrate_limit_reservoir_bias > 1.)
  155350. return OV_EINVAL;
  155351. hi->managed=ai->management_active;
  155352. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155353. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155354. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155355. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155356. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155357. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155358. }
  155359. }
  155360. return 0;
  155361. case OV_ECTL_LOWPASS_GET:
  155362. {
  155363. double *farg=(double *)arg;
  155364. *farg=hi->lowpass_kHz;
  155365. }
  155366. return(0);
  155367. case OV_ECTL_LOWPASS_SET:
  155368. {
  155369. double *farg=(double *)arg;
  155370. hi->lowpass_kHz=*farg;
  155371. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155372. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155373. }
  155374. return(0);
  155375. case OV_ECTL_IBLOCK_GET:
  155376. {
  155377. double *farg=(double *)arg;
  155378. *farg=hi->impulse_noisetune;
  155379. }
  155380. return(0);
  155381. case OV_ECTL_IBLOCK_SET:
  155382. {
  155383. double *farg=(double *)arg;
  155384. hi->impulse_noisetune=*farg;
  155385. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155386. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155387. }
  155388. return(0);
  155389. }
  155390. return(OV_EIMPL);
  155391. }
  155392. return(OV_EINVAL);
  155393. }
  155394. #endif
  155395. /*** End of inlined file: vorbisenc.c ***/
  155396. /*** Start of inlined file: vorbisfile.c ***/
  155397. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155398. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155399. // tasks..
  155400. #if JUCE_MSVC
  155401. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155402. #endif
  155403. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155404. #if JUCE_USE_OGGVORBIS
  155405. #include <stdlib.h>
  155406. #include <stdio.h>
  155407. #include <errno.h>
  155408. #include <string.h>
  155409. #include <math.h>
  155410. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155411. one logical bitstream arranged end to end (the only form of Ogg
  155412. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155413. multiplexing] is not allowed in Vorbis) */
  155414. /* A Vorbis file can be played beginning to end (streamed) without
  155415. worrying ahead of time about chaining (see decoder_example.c). If
  155416. we have the whole file, however, and want random access
  155417. (seeking/scrubbing) or desire to know the total length/time of a
  155418. file, we need to account for the possibility of chaining. */
  155419. /* We can handle things a number of ways; we can determine the entire
  155420. bitstream structure right off the bat, or find pieces on demand.
  155421. This example determines and caches structure for the entire
  155422. bitstream, but builds a virtual decoder on the fly when moving
  155423. between links in the chain. */
  155424. /* There are also different ways to implement seeking. Enough
  155425. information exists in an Ogg bitstream to seek to
  155426. sample-granularity positions in the output. Or, one can seek by
  155427. picking some portion of the stream roughly in the desired area if
  155428. we only want coarse navigation through the stream. */
  155429. /*************************************************************************
  155430. * Many, many internal helpers. The intention is not to be confusing;
  155431. * rampant duplication and monolithic function implementation would be
  155432. * harder to understand anyway. The high level functions are last. Begin
  155433. * grokking near the end of the file */
  155434. /* read a little more data from the file/pipe into the ogg_sync framer
  155435. */
  155436. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155437. over 8k gets what they deserve */
  155438. static long _get_data(OggVorbis_File *vf){
  155439. errno=0;
  155440. if(vf->datasource){
  155441. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155442. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155443. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155444. if(bytes==0 && errno)return(-1);
  155445. return(bytes);
  155446. }else
  155447. return(0);
  155448. }
  155449. /* save a tiny smidge of verbosity to make the code more readable */
  155450. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155451. if(vf->datasource){
  155452. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155453. vf->offset=offset;
  155454. ogg_sync_reset(&vf->oy);
  155455. }else{
  155456. /* shouldn't happen unless someone writes a broken callback */
  155457. return;
  155458. }
  155459. }
  155460. /* The read/seek functions track absolute position within the stream */
  155461. /* from the head of the stream, get the next page. boundary specifies
  155462. if the function is allowed to fetch more data from the stream (and
  155463. how much) or only use internally buffered data.
  155464. boundary: -1) unbounded search
  155465. 0) read no additional data; use cached only
  155466. n) search for a new page beginning for n bytes
  155467. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155468. n) found a page at absolute offset n */
  155469. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155470. ogg_int64_t boundary){
  155471. if(boundary>0)boundary+=vf->offset;
  155472. while(1){
  155473. long more;
  155474. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155475. more=ogg_sync_pageseek(&vf->oy,og);
  155476. if(more<0){
  155477. /* skipped n bytes */
  155478. vf->offset-=more;
  155479. }else{
  155480. if(more==0){
  155481. /* send more paramedics */
  155482. if(!boundary)return(OV_FALSE);
  155483. {
  155484. long ret=_get_data(vf);
  155485. if(ret==0)return(OV_EOF);
  155486. if(ret<0)return(OV_EREAD);
  155487. }
  155488. }else{
  155489. /* got a page. Return the offset at the page beginning,
  155490. advance the internal offset past the page end */
  155491. ogg_int64_t ret=vf->offset;
  155492. vf->offset+=more;
  155493. return(ret);
  155494. }
  155495. }
  155496. }
  155497. }
  155498. /* find the latest page beginning before the current stream cursor
  155499. position. Much dirtier than the above as Ogg doesn't have any
  155500. backward search linkage. no 'readp' as it will certainly have to
  155501. read. */
  155502. /* returns offset or OV_EREAD, OV_FAULT */
  155503. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155504. ogg_int64_t begin=vf->offset;
  155505. ogg_int64_t end=begin;
  155506. ogg_int64_t ret;
  155507. ogg_int64_t offset=-1;
  155508. while(offset==-1){
  155509. begin-=CHUNKSIZE;
  155510. if(begin<0)
  155511. begin=0;
  155512. _seek_helper(vf,begin);
  155513. while(vf->offset<end){
  155514. ret=_get_next_page(vf,og,end-vf->offset);
  155515. if(ret==OV_EREAD)return(OV_EREAD);
  155516. if(ret<0){
  155517. break;
  155518. }else{
  155519. offset=ret;
  155520. }
  155521. }
  155522. }
  155523. /* we have the offset. Actually snork and hold the page now */
  155524. _seek_helper(vf,offset);
  155525. ret=_get_next_page(vf,og,CHUNKSIZE);
  155526. if(ret<0)
  155527. /* this shouldn't be possible */
  155528. return(OV_EFAULT);
  155529. return(offset);
  155530. }
  155531. /* finds each bitstream link one at a time using a bisection search
  155532. (has to begin by knowing the offset of the lb's initial page).
  155533. Recurses for each link so it can alloc the link storage after
  155534. finding them all, then unroll and fill the cache at the same time */
  155535. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155536. ogg_int64_t begin,
  155537. ogg_int64_t searched,
  155538. ogg_int64_t end,
  155539. long currentno,
  155540. long m){
  155541. ogg_int64_t endsearched=end;
  155542. ogg_int64_t next=end;
  155543. ogg_page og;
  155544. ogg_int64_t ret;
  155545. /* the below guards against garbage seperating the last and
  155546. first pages of two links. */
  155547. while(searched<endsearched){
  155548. ogg_int64_t bisect;
  155549. if(endsearched-searched<CHUNKSIZE){
  155550. bisect=searched;
  155551. }else{
  155552. bisect=(searched+endsearched)/2;
  155553. }
  155554. _seek_helper(vf,bisect);
  155555. ret=_get_next_page(vf,&og,-1);
  155556. if(ret==OV_EREAD)return(OV_EREAD);
  155557. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155558. endsearched=bisect;
  155559. if(ret>=0)next=ret;
  155560. }else{
  155561. searched=ret+og.header_len+og.body_len;
  155562. }
  155563. }
  155564. _seek_helper(vf,next);
  155565. ret=_get_next_page(vf,&og,-1);
  155566. if(ret==OV_EREAD)return(OV_EREAD);
  155567. if(searched>=end || ret<0){
  155568. vf->links=m+1;
  155569. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155570. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155571. vf->offsets[m+1]=searched;
  155572. }else{
  155573. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155574. end,ogg_page_serialno(&og),m+1);
  155575. if(ret==OV_EREAD)return(OV_EREAD);
  155576. }
  155577. vf->offsets[m]=begin;
  155578. vf->serialnos[m]=currentno;
  155579. return(0);
  155580. }
  155581. /* uses the local ogg_stream storage in vf; this is important for
  155582. non-streaming input sources */
  155583. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155584. long *serialno,ogg_page *og_ptr){
  155585. ogg_page og;
  155586. ogg_packet op;
  155587. int i,ret;
  155588. if(!og_ptr){
  155589. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155590. if(llret==OV_EREAD)return(OV_EREAD);
  155591. if(llret<0)return OV_ENOTVORBIS;
  155592. og_ptr=&og;
  155593. }
  155594. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155595. if(serialno)*serialno=vf->os.serialno;
  155596. vf->ready_state=STREAMSET;
  155597. /* extract the initial header from the first page and verify that the
  155598. Ogg bitstream is in fact Vorbis data */
  155599. vorbis_info_init(vi);
  155600. vorbis_comment_init(vc);
  155601. i=0;
  155602. while(i<3){
  155603. ogg_stream_pagein(&vf->os,og_ptr);
  155604. while(i<3){
  155605. int result=ogg_stream_packetout(&vf->os,&op);
  155606. if(result==0)break;
  155607. if(result==-1){
  155608. ret=OV_EBADHEADER;
  155609. goto bail_header;
  155610. }
  155611. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155612. goto bail_header;
  155613. }
  155614. i++;
  155615. }
  155616. if(i<3)
  155617. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155618. ret=OV_EBADHEADER;
  155619. goto bail_header;
  155620. }
  155621. }
  155622. return 0;
  155623. bail_header:
  155624. vorbis_info_clear(vi);
  155625. vorbis_comment_clear(vc);
  155626. vf->ready_state=OPENED;
  155627. return ret;
  155628. }
  155629. /* last step of the OggVorbis_File initialization; get all the
  155630. vorbis_info structs and PCM positions. Only called by the seekable
  155631. initialization (local stream storage is hacked slightly; pay
  155632. attention to how that's done) */
  155633. /* this is void and does not propogate errors up because we want to be
  155634. able to open and use damaged bitstreams as well as we can. Just
  155635. watch out for missing information for links in the OggVorbis_File
  155636. struct */
  155637. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155638. ogg_page og;
  155639. int i;
  155640. ogg_int64_t ret;
  155641. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155642. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155643. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155644. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155645. for(i=0;i<vf->links;i++){
  155646. if(i==0){
  155647. /* we already grabbed the initial header earlier. Just set the offset */
  155648. vf->dataoffsets[i]=dataoffset;
  155649. _seek_helper(vf,dataoffset);
  155650. }else{
  155651. /* seek to the location of the initial header */
  155652. _seek_helper(vf,vf->offsets[i]);
  155653. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155654. vf->dataoffsets[i]=-1;
  155655. }else{
  155656. vf->dataoffsets[i]=vf->offset;
  155657. }
  155658. }
  155659. /* fetch beginning PCM offset */
  155660. if(vf->dataoffsets[i]!=-1){
  155661. ogg_int64_t accumulated=0;
  155662. long lastblock=-1;
  155663. int result;
  155664. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155665. while(1){
  155666. ogg_packet op;
  155667. ret=_get_next_page(vf,&og,-1);
  155668. if(ret<0)
  155669. /* this should not be possible unless the file is
  155670. truncated/mangled */
  155671. break;
  155672. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155673. break;
  155674. /* count blocksizes of all frames in the page */
  155675. ogg_stream_pagein(&vf->os,&og);
  155676. while((result=ogg_stream_packetout(&vf->os,&op))){
  155677. if(result>0){ /* ignore holes */
  155678. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155679. if(lastblock!=-1)
  155680. accumulated+=(lastblock+thisblock)>>2;
  155681. lastblock=thisblock;
  155682. }
  155683. }
  155684. if(ogg_page_granulepos(&og)!=-1){
  155685. /* pcm offset of last packet on the first audio page */
  155686. accumulated= ogg_page_granulepos(&og)-accumulated;
  155687. break;
  155688. }
  155689. }
  155690. /* less than zero? This is a stream with samples trimmed off
  155691. the beginning, a normal occurrence; set the offset to zero */
  155692. if(accumulated<0)accumulated=0;
  155693. vf->pcmlengths[i*2]=accumulated;
  155694. }
  155695. /* get the PCM length of this link. To do this,
  155696. get the last page of the stream */
  155697. {
  155698. ogg_int64_t end=vf->offsets[i+1];
  155699. _seek_helper(vf,end);
  155700. while(1){
  155701. ret=_get_prev_page(vf,&og);
  155702. if(ret<0){
  155703. /* this should not be possible */
  155704. vorbis_info_clear(vf->vi+i);
  155705. vorbis_comment_clear(vf->vc+i);
  155706. break;
  155707. }
  155708. if(ogg_page_granulepos(&og)!=-1){
  155709. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155710. break;
  155711. }
  155712. vf->offset=ret;
  155713. }
  155714. }
  155715. }
  155716. }
  155717. static int _make_decode_ready(OggVorbis_File *vf){
  155718. if(vf->ready_state>STREAMSET)return 0;
  155719. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155720. if(vf->seekable){
  155721. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155722. return OV_EBADLINK;
  155723. }else{
  155724. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155725. return OV_EBADLINK;
  155726. }
  155727. vorbis_block_init(&vf->vd,&vf->vb);
  155728. vf->ready_state=INITSET;
  155729. vf->bittrack=0.f;
  155730. vf->samptrack=0.f;
  155731. return 0;
  155732. }
  155733. static int _open_seekable2(OggVorbis_File *vf){
  155734. long serialno=vf->current_serialno;
  155735. ogg_int64_t dataoffset=vf->offset, end;
  155736. ogg_page og;
  155737. /* we're partially open and have a first link header state in
  155738. storage in vf */
  155739. /* we can seek, so set out learning all about this file */
  155740. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155741. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155742. /* We get the offset for the last page of the physical bitstream.
  155743. Most OggVorbis files will contain a single logical bitstream */
  155744. end=_get_prev_page(vf,&og);
  155745. if(end<0)return(end);
  155746. /* more than one logical bitstream? */
  155747. if(ogg_page_serialno(&og)!=serialno){
  155748. /* Chained bitstream. Bisect-search each logical bitstream
  155749. section. Do so based on serial number only */
  155750. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155751. }else{
  155752. /* Only one logical bitstream */
  155753. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155754. }
  155755. /* the initial header memory is referenced by vf after; don't free it */
  155756. _prefetch_all_headers(vf,dataoffset);
  155757. return(ov_raw_seek(vf,0));
  155758. }
  155759. /* clear out the current logical bitstream decoder */
  155760. static void _decode_clear(OggVorbis_File *vf){
  155761. vorbis_dsp_clear(&vf->vd);
  155762. vorbis_block_clear(&vf->vb);
  155763. vf->ready_state=OPENED;
  155764. }
  155765. /* fetch and process a packet. Handles the case where we're at a
  155766. bitstream boundary and dumps the decoding machine. If the decoding
  155767. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155768. date (seek and read both use this. seek uses a special hack with
  155769. readp).
  155770. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155771. 0) need more data (only if readp==0)
  155772. 1) got a packet
  155773. */
  155774. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155775. ogg_packet *op_in,
  155776. int readp,
  155777. int spanp){
  155778. ogg_page og;
  155779. /* handle one packet. Try to fetch it from current stream state */
  155780. /* extract packets from page */
  155781. while(1){
  155782. /* process a packet if we can. If the machine isn't loaded,
  155783. neither is a page */
  155784. if(vf->ready_state==INITSET){
  155785. while(1) {
  155786. ogg_packet op;
  155787. ogg_packet *op_ptr=(op_in?op_in:&op);
  155788. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155789. ogg_int64_t granulepos;
  155790. op_in=NULL;
  155791. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155792. if(result>0){
  155793. /* got a packet. process it */
  155794. granulepos=op_ptr->granulepos;
  155795. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155796. header handling. The
  155797. header packets aren't
  155798. audio, so if/when we
  155799. submit them,
  155800. vorbis_synthesis will
  155801. reject them */
  155802. /* suck in the synthesis data and track bitrate */
  155803. {
  155804. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155805. /* for proper use of libvorbis within libvorbisfile,
  155806. oldsamples will always be zero. */
  155807. if(oldsamples)return(OV_EFAULT);
  155808. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155809. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155810. vf->bittrack+=op_ptr->bytes*8;
  155811. }
  155812. /* update the pcm offset. */
  155813. if(granulepos!=-1 && !op_ptr->e_o_s){
  155814. int link=(vf->seekable?vf->current_link:0);
  155815. int i,samples;
  155816. /* this packet has a pcm_offset on it (the last packet
  155817. completed on a page carries the offset) After processing
  155818. (above), we know the pcm position of the *last* sample
  155819. ready to be returned. Find the offset of the *first*
  155820. As an aside, this trick is inaccurate if we begin
  155821. reading anew right at the last page; the end-of-stream
  155822. granulepos declares the last frame in the stream, and the
  155823. last packet of the last page may be a partial frame.
  155824. So, we need a previous granulepos from an in-sequence page
  155825. to have a reference point. Thus the !op_ptr->e_o_s clause
  155826. above */
  155827. if(vf->seekable && link>0)
  155828. granulepos-=vf->pcmlengths[link*2];
  155829. if(granulepos<0)granulepos=0; /* actually, this
  155830. shouldn't be possible
  155831. here unless the stream
  155832. is very broken */
  155833. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155834. granulepos-=samples;
  155835. for(i=0;i<link;i++)
  155836. granulepos+=vf->pcmlengths[i*2+1];
  155837. vf->pcm_offset=granulepos;
  155838. }
  155839. return(1);
  155840. }
  155841. }
  155842. else
  155843. break;
  155844. }
  155845. }
  155846. if(vf->ready_state>=OPENED){
  155847. ogg_int64_t ret;
  155848. if(!readp)return(0);
  155849. if((ret=_get_next_page(vf,&og,-1))<0){
  155850. return(OV_EOF); /* eof.
  155851. leave unitialized */
  155852. }
  155853. /* bitrate tracking; add the header's bytes here, the body bytes
  155854. are done by packet above */
  155855. vf->bittrack+=og.header_len*8;
  155856. /* has our decoding just traversed a bitstream boundary? */
  155857. if(vf->ready_state==INITSET){
  155858. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155859. if(!spanp)
  155860. return(OV_EOF);
  155861. _decode_clear(vf);
  155862. if(!vf->seekable){
  155863. vorbis_info_clear(vf->vi);
  155864. vorbis_comment_clear(vf->vc);
  155865. }
  155866. }
  155867. }
  155868. }
  155869. /* Do we need to load a new machine before submitting the page? */
  155870. /* This is different in the seekable and non-seekable cases.
  155871. In the seekable case, we already have all the header
  155872. information loaded and cached; we just initialize the machine
  155873. with it and continue on our merry way.
  155874. In the non-seekable (streaming) case, we'll only be at a
  155875. boundary if we just left the previous logical bitstream and
  155876. we're now nominally at the header of the next bitstream
  155877. */
  155878. if(vf->ready_state!=INITSET){
  155879. int link;
  155880. if(vf->ready_state<STREAMSET){
  155881. if(vf->seekable){
  155882. vf->current_serialno=ogg_page_serialno(&og);
  155883. /* match the serialno to bitstream section. We use this rather than
  155884. offset positions to avoid problems near logical bitstream
  155885. boundaries */
  155886. for(link=0;link<vf->links;link++)
  155887. if(vf->serialnos[link]==vf->current_serialno)break;
  155888. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155889. stream. error out,
  155890. leave machine
  155891. uninitialized */
  155892. vf->current_link=link;
  155893. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155894. vf->ready_state=STREAMSET;
  155895. }else{
  155896. /* we're streaming */
  155897. /* fetch the three header packets, build the info struct */
  155898. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155899. if(ret)return(ret);
  155900. vf->current_link++;
  155901. link=0;
  155902. }
  155903. }
  155904. {
  155905. int ret=_make_decode_ready(vf);
  155906. if(ret<0)return ret;
  155907. }
  155908. }
  155909. ogg_stream_pagein(&vf->os,&og);
  155910. }
  155911. }
  155912. /* if, eg, 64 bit stdio is configured by default, this will build with
  155913. fseek64 */
  155914. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155915. if(f==NULL)return(-1);
  155916. return fseek(f,off,whence);
  155917. }
  155918. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155919. long ibytes, ov_callbacks callbacks){
  155920. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155921. int ret;
  155922. memset(vf,0,sizeof(*vf));
  155923. vf->datasource=f;
  155924. vf->callbacks = callbacks;
  155925. /* init the framing state */
  155926. ogg_sync_init(&vf->oy);
  155927. /* perhaps some data was previously read into a buffer for testing
  155928. against other stream types. Allow initialization from this
  155929. previously read data (as we may be reading from a non-seekable
  155930. stream) */
  155931. if(initial){
  155932. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155933. memcpy(buffer,initial,ibytes);
  155934. ogg_sync_wrote(&vf->oy,ibytes);
  155935. }
  155936. /* can we seek? Stevens suggests the seek test was portable */
  155937. if(offsettest!=-1)vf->seekable=1;
  155938. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155939. entry for partial open */
  155940. vf->links=1;
  155941. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155942. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155943. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155944. /* Try to fetch the headers, maintaining all the storage */
  155945. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155946. vf->datasource=NULL;
  155947. ov_clear(vf);
  155948. }else
  155949. vf->ready_state=PARTOPEN;
  155950. return(ret);
  155951. }
  155952. static int _ov_open2(OggVorbis_File *vf){
  155953. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155954. vf->ready_state=OPENED;
  155955. if(vf->seekable){
  155956. int ret=_open_seekable2(vf);
  155957. if(ret){
  155958. vf->datasource=NULL;
  155959. ov_clear(vf);
  155960. }
  155961. return(ret);
  155962. }else
  155963. vf->ready_state=STREAMSET;
  155964. return 0;
  155965. }
  155966. /* clear out the OggVorbis_File struct */
  155967. int ov_clear(OggVorbis_File *vf){
  155968. if(vf){
  155969. vorbis_block_clear(&vf->vb);
  155970. vorbis_dsp_clear(&vf->vd);
  155971. ogg_stream_clear(&vf->os);
  155972. if(vf->vi && vf->links){
  155973. int i;
  155974. for(i=0;i<vf->links;i++){
  155975. vorbis_info_clear(vf->vi+i);
  155976. vorbis_comment_clear(vf->vc+i);
  155977. }
  155978. _ogg_free(vf->vi);
  155979. _ogg_free(vf->vc);
  155980. }
  155981. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155982. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155983. if(vf->serialnos)_ogg_free(vf->serialnos);
  155984. if(vf->offsets)_ogg_free(vf->offsets);
  155985. ogg_sync_clear(&vf->oy);
  155986. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155987. memset(vf,0,sizeof(*vf));
  155988. }
  155989. #ifdef DEBUG_LEAKS
  155990. _VDBG_dump();
  155991. #endif
  155992. return(0);
  155993. }
  155994. /* inspects the OggVorbis file and finds/documents all the logical
  155995. bitstreams contained in it. Tries to be tolerant of logical
  155996. bitstream sections that are truncated/woogie.
  155997. return: -1) error
  155998. 0) OK
  155999. */
  156000. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156001. ov_callbacks callbacks){
  156002. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156003. if(ret)return ret;
  156004. return _ov_open2(vf);
  156005. }
  156006. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156007. ov_callbacks callbacks = {
  156008. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156009. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156010. (int (*)(void *)) fclose,
  156011. (long (*)(void *)) ftell
  156012. };
  156013. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156014. }
  156015. /* cheap hack for game usage where downsampling is desirable; there's
  156016. no need for SRC as we can just do it cheaply in libvorbis. */
  156017. int ov_halfrate(OggVorbis_File *vf,int flag){
  156018. int i;
  156019. if(vf->vi==NULL)return OV_EINVAL;
  156020. if(!vf->seekable)return OV_EINVAL;
  156021. if(vf->ready_state>=STREAMSET)
  156022. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156023. will be able to swap this on the fly, but
  156024. for now dumping the decode machine is needed
  156025. to reinit the MDCT lookups. 1.1 libvorbis
  156026. is planned to be able to switch on the fly */
  156027. for(i=0;i<vf->links;i++){
  156028. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156029. ov_halfrate(vf,0);
  156030. return OV_EINVAL;
  156031. }
  156032. }
  156033. return 0;
  156034. }
  156035. int ov_halfrate_p(OggVorbis_File *vf){
  156036. if(vf->vi==NULL)return OV_EINVAL;
  156037. return vorbis_synthesis_halfrate_p(vf->vi);
  156038. }
  156039. /* Only partially open the vorbis file; test for Vorbisness, and load
  156040. the headers for the first chain. Do not seek (although test for
  156041. seekability). Use ov_test_open to finish opening the file, else
  156042. ov_clear to close/free it. Same return codes as open. */
  156043. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156044. ov_callbacks callbacks)
  156045. {
  156046. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156047. }
  156048. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156049. ov_callbacks callbacks = {
  156050. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156051. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156052. (int (*)(void *)) fclose,
  156053. (long (*)(void *)) ftell
  156054. };
  156055. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156056. }
  156057. int ov_test_open(OggVorbis_File *vf){
  156058. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156059. return _ov_open2(vf);
  156060. }
  156061. /* How many logical bitstreams in this physical bitstream? */
  156062. long ov_streams(OggVorbis_File *vf){
  156063. return vf->links;
  156064. }
  156065. /* Is the FILE * associated with vf seekable? */
  156066. long ov_seekable(OggVorbis_File *vf){
  156067. return vf->seekable;
  156068. }
  156069. /* returns the bitrate for a given logical bitstream or the entire
  156070. physical bitstream. If the file is open for random access, it will
  156071. find the *actual* average bitrate. If the file is streaming, it
  156072. returns the nominal bitrate (if set) else the average of the
  156073. upper/lower bounds (if set) else -1 (unset).
  156074. If you want the actual bitrate field settings, get them from the
  156075. vorbis_info structs */
  156076. long ov_bitrate(OggVorbis_File *vf,int i){
  156077. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156078. if(i>=vf->links)return(OV_EINVAL);
  156079. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156080. if(i<0){
  156081. ogg_int64_t bits=0;
  156082. int i;
  156083. float br;
  156084. for(i=0;i<vf->links;i++)
  156085. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156086. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156087. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156088. * so this is slightly transformed to make it work.
  156089. */
  156090. br = bits/ov_time_total(vf,-1);
  156091. return(rint(br));
  156092. }else{
  156093. if(vf->seekable){
  156094. /* return the actual bitrate */
  156095. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156096. }else{
  156097. /* return nominal if set */
  156098. if(vf->vi[i].bitrate_nominal>0){
  156099. return vf->vi[i].bitrate_nominal;
  156100. }else{
  156101. if(vf->vi[i].bitrate_upper>0){
  156102. if(vf->vi[i].bitrate_lower>0){
  156103. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156104. }else{
  156105. return vf->vi[i].bitrate_upper;
  156106. }
  156107. }
  156108. return(OV_FALSE);
  156109. }
  156110. }
  156111. }
  156112. }
  156113. /* returns the actual bitrate since last call. returns -1 if no
  156114. additional data to offer since last call (or at beginning of stream),
  156115. EINVAL if stream is only partially open
  156116. */
  156117. long ov_bitrate_instant(OggVorbis_File *vf){
  156118. int link=(vf->seekable?vf->current_link:0);
  156119. long ret;
  156120. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156121. if(vf->samptrack==0)return(OV_FALSE);
  156122. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156123. vf->bittrack=0.f;
  156124. vf->samptrack=0.f;
  156125. return(ret);
  156126. }
  156127. /* Guess */
  156128. long ov_serialnumber(OggVorbis_File *vf,int i){
  156129. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156130. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156131. if(i<0){
  156132. return(vf->current_serialno);
  156133. }else{
  156134. return(vf->serialnos[i]);
  156135. }
  156136. }
  156137. /* returns: total raw (compressed) length of content if i==-1
  156138. raw (compressed) length of that logical bitstream for i==0 to n
  156139. OV_EINVAL if the stream is not seekable (we can't know the length)
  156140. or if stream is only partially open
  156141. */
  156142. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156143. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156144. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156145. if(i<0){
  156146. ogg_int64_t acc=0;
  156147. int i;
  156148. for(i=0;i<vf->links;i++)
  156149. acc+=ov_raw_total(vf,i);
  156150. return(acc);
  156151. }else{
  156152. return(vf->offsets[i+1]-vf->offsets[i]);
  156153. }
  156154. }
  156155. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156156. (samples) of that logical bitstream for i==0 to n
  156157. OV_EINVAL if the stream is not seekable (we can't know the
  156158. length) or only partially open
  156159. */
  156160. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156161. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156162. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156163. if(i<0){
  156164. ogg_int64_t acc=0;
  156165. int i;
  156166. for(i=0;i<vf->links;i++)
  156167. acc+=ov_pcm_total(vf,i);
  156168. return(acc);
  156169. }else{
  156170. return(vf->pcmlengths[i*2+1]);
  156171. }
  156172. }
  156173. /* returns: total seconds of content if i==-1
  156174. seconds in that logical bitstream for i==0 to n
  156175. OV_EINVAL if the stream is not seekable (we can't know the
  156176. length) or only partially open
  156177. */
  156178. double ov_time_total(OggVorbis_File *vf,int i){
  156179. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156180. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156181. if(i<0){
  156182. double acc=0;
  156183. int i;
  156184. for(i=0;i<vf->links;i++)
  156185. acc+=ov_time_total(vf,i);
  156186. return(acc);
  156187. }else{
  156188. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156189. }
  156190. }
  156191. /* seek to an offset relative to the *compressed* data. This also
  156192. scans packets to update the PCM cursor. It will cross a logical
  156193. bitstream boundary, but only if it can't get any packets out of the
  156194. tail of the bitstream we seek to (so no surprises).
  156195. returns zero on success, nonzero on failure */
  156196. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156197. ogg_stream_state work_os;
  156198. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156199. if(!vf->seekable)
  156200. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156201. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156202. /* don't yet clear out decoding machine (if it's initialized), in
  156203. the case we're in the same link. Restart the decode lapping, and
  156204. let _fetch_and_process_packet deal with a potential bitstream
  156205. boundary */
  156206. vf->pcm_offset=-1;
  156207. ogg_stream_reset_serialno(&vf->os,
  156208. vf->current_serialno); /* must set serialno */
  156209. vorbis_synthesis_restart(&vf->vd);
  156210. _seek_helper(vf,pos);
  156211. /* we need to make sure the pcm_offset is set, but we don't want to
  156212. advance the raw cursor past good packets just to get to the first
  156213. with a granulepos. That's not equivalent behavior to beginning
  156214. decoding as immediately after the seek position as possible.
  156215. So, a hack. We use two stream states; a local scratch state and
  156216. the shared vf->os stream state. We use the local state to
  156217. scan, and the shared state as a buffer for later decode.
  156218. Unfortuantely, on the last page we still advance to last packet
  156219. because the granulepos on the last page is not necessarily on a
  156220. packet boundary, and we need to make sure the granpos is
  156221. correct.
  156222. */
  156223. {
  156224. ogg_page og;
  156225. ogg_packet op;
  156226. int lastblock=0;
  156227. int accblock=0;
  156228. int thisblock;
  156229. int eosflag;
  156230. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156231. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156232. return from not necessarily
  156233. starting from the beginning */
  156234. while(1){
  156235. if(vf->ready_state>=STREAMSET){
  156236. /* snarf/scan a packet if we can */
  156237. int result=ogg_stream_packetout(&work_os,&op);
  156238. if(result>0){
  156239. if(vf->vi[vf->current_link].codec_setup){
  156240. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156241. if(thisblock<0){
  156242. ogg_stream_packetout(&vf->os,NULL);
  156243. thisblock=0;
  156244. }else{
  156245. if(eosflag)
  156246. ogg_stream_packetout(&vf->os,NULL);
  156247. else
  156248. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156249. }
  156250. if(op.granulepos!=-1){
  156251. int i,link=vf->current_link;
  156252. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156253. if(granulepos<0)granulepos=0;
  156254. for(i=0;i<link;i++)
  156255. granulepos+=vf->pcmlengths[i*2+1];
  156256. vf->pcm_offset=granulepos-accblock;
  156257. break;
  156258. }
  156259. lastblock=thisblock;
  156260. continue;
  156261. }else
  156262. ogg_stream_packetout(&vf->os,NULL);
  156263. }
  156264. }
  156265. if(!lastblock){
  156266. if(_get_next_page(vf,&og,-1)<0){
  156267. vf->pcm_offset=ov_pcm_total(vf,-1);
  156268. break;
  156269. }
  156270. }else{
  156271. /* huh? Bogus stream with packets but no granulepos */
  156272. vf->pcm_offset=-1;
  156273. break;
  156274. }
  156275. /* has our decoding just traversed a bitstream boundary? */
  156276. if(vf->ready_state>=STREAMSET)
  156277. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156278. _decode_clear(vf); /* clear out stream state */
  156279. ogg_stream_clear(&work_os);
  156280. }
  156281. if(vf->ready_state<STREAMSET){
  156282. int link;
  156283. vf->current_serialno=ogg_page_serialno(&og);
  156284. for(link=0;link<vf->links;link++)
  156285. if(vf->serialnos[link]==vf->current_serialno)break;
  156286. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156287. error out, leave
  156288. machine uninitialized */
  156289. vf->current_link=link;
  156290. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156291. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156292. vf->ready_state=STREAMSET;
  156293. }
  156294. ogg_stream_pagein(&vf->os,&og);
  156295. ogg_stream_pagein(&work_os,&og);
  156296. eosflag=ogg_page_eos(&og);
  156297. }
  156298. }
  156299. ogg_stream_clear(&work_os);
  156300. vf->bittrack=0.f;
  156301. vf->samptrack=0.f;
  156302. return(0);
  156303. seek_error:
  156304. /* dump the machine so we're in a known state */
  156305. vf->pcm_offset=-1;
  156306. ogg_stream_clear(&work_os);
  156307. _decode_clear(vf);
  156308. return OV_EBADLINK;
  156309. }
  156310. /* Page granularity seek (faster than sample granularity because we
  156311. don't do the last bit of decode to find a specific sample).
  156312. Seek to the last [granule marked] page preceeding the specified pos
  156313. location, such that decoding past the returned point will quickly
  156314. arrive at the requested position. */
  156315. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156316. int link=-1;
  156317. ogg_int64_t result=0;
  156318. ogg_int64_t total=ov_pcm_total(vf,-1);
  156319. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156320. if(!vf->seekable)return(OV_ENOSEEK);
  156321. if(pos<0 || pos>total)return(OV_EINVAL);
  156322. /* which bitstream section does this pcm offset occur in? */
  156323. for(link=vf->links-1;link>=0;link--){
  156324. total-=vf->pcmlengths[link*2+1];
  156325. if(pos>=total)break;
  156326. }
  156327. /* search within the logical bitstream for the page with the highest
  156328. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156329. missing pages or incorrect frame number information in the
  156330. bitstream could make our task impossible. Account for that (it
  156331. would be an error condition) */
  156332. /* new search algorithm by HB (Nicholas Vinen) */
  156333. {
  156334. ogg_int64_t end=vf->offsets[link+1];
  156335. ogg_int64_t begin=vf->offsets[link];
  156336. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156337. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156338. ogg_int64_t target=pos-total+begintime;
  156339. ogg_int64_t best=begin;
  156340. ogg_page og;
  156341. while(begin<end){
  156342. ogg_int64_t bisect;
  156343. if(end-begin<CHUNKSIZE){
  156344. bisect=begin;
  156345. }else{
  156346. /* take a (pretty decent) guess. */
  156347. bisect=begin +
  156348. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156349. if(bisect<=begin)
  156350. bisect=begin+1;
  156351. }
  156352. _seek_helper(vf,bisect);
  156353. while(begin<end){
  156354. result=_get_next_page(vf,&og,end-vf->offset);
  156355. if(result==OV_EREAD) goto seek_error;
  156356. if(result<0){
  156357. if(bisect<=begin+1)
  156358. end=begin; /* found it */
  156359. else{
  156360. if(bisect==0) goto seek_error;
  156361. bisect-=CHUNKSIZE;
  156362. if(bisect<=begin)bisect=begin+1;
  156363. _seek_helper(vf,bisect);
  156364. }
  156365. }else{
  156366. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156367. if(granulepos==-1)continue;
  156368. if(granulepos<target){
  156369. best=result; /* raw offset of packet with granulepos */
  156370. begin=vf->offset; /* raw offset of next page */
  156371. begintime=granulepos;
  156372. if(target-begintime>44100)break;
  156373. bisect=begin; /* *not* begin + 1 */
  156374. }else{
  156375. if(bisect<=begin+1)
  156376. end=begin; /* found it */
  156377. else{
  156378. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156379. end=result;
  156380. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156381. if(bisect<=begin)bisect=begin+1;
  156382. _seek_helper(vf,bisect);
  156383. }else{
  156384. end=result;
  156385. endtime=granulepos;
  156386. break;
  156387. }
  156388. }
  156389. }
  156390. }
  156391. }
  156392. }
  156393. /* found our page. seek to it, update pcm offset. Easier case than
  156394. raw_seek, don't keep packets preceeding granulepos. */
  156395. {
  156396. ogg_page og;
  156397. ogg_packet op;
  156398. /* seek */
  156399. _seek_helper(vf,best);
  156400. vf->pcm_offset=-1;
  156401. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156402. if(link!=vf->current_link){
  156403. /* Different link; dump entire decode machine */
  156404. _decode_clear(vf);
  156405. vf->current_link=link;
  156406. vf->current_serialno=ogg_page_serialno(&og);
  156407. vf->ready_state=STREAMSET;
  156408. }else{
  156409. vorbis_synthesis_restart(&vf->vd);
  156410. }
  156411. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156412. ogg_stream_pagein(&vf->os,&og);
  156413. /* pull out all but last packet; the one with granulepos */
  156414. while(1){
  156415. result=ogg_stream_packetpeek(&vf->os,&op);
  156416. if(result==0){
  156417. /* !!! the packet finishing this page originated on a
  156418. preceeding page. Keep fetching previous pages until we
  156419. get one with a granulepos or without the 'continued' flag
  156420. set. Then just use raw_seek for simplicity. */
  156421. _seek_helper(vf,best);
  156422. while(1){
  156423. result=_get_prev_page(vf,&og);
  156424. if(result<0) goto seek_error;
  156425. if(ogg_page_granulepos(&og)>-1 ||
  156426. !ogg_page_continued(&og)){
  156427. return ov_raw_seek(vf,result);
  156428. }
  156429. vf->offset=result;
  156430. }
  156431. }
  156432. if(result<0){
  156433. result = OV_EBADPACKET;
  156434. goto seek_error;
  156435. }
  156436. if(op.granulepos!=-1){
  156437. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156438. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156439. vf->pcm_offset+=total;
  156440. break;
  156441. }else
  156442. result=ogg_stream_packetout(&vf->os,NULL);
  156443. }
  156444. }
  156445. }
  156446. /* verify result */
  156447. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156448. result=OV_EFAULT;
  156449. goto seek_error;
  156450. }
  156451. vf->bittrack=0.f;
  156452. vf->samptrack=0.f;
  156453. return(0);
  156454. seek_error:
  156455. /* dump machine so we're in a known state */
  156456. vf->pcm_offset=-1;
  156457. _decode_clear(vf);
  156458. return (int)result;
  156459. }
  156460. /* seek to a sample offset relative to the decompressed pcm stream
  156461. returns zero on success, nonzero on failure */
  156462. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156463. int thisblock,lastblock=0;
  156464. int ret=ov_pcm_seek_page(vf,pos);
  156465. if(ret<0)return(ret);
  156466. if((ret=_make_decode_ready(vf)))return ret;
  156467. /* discard leading packets we don't need for the lapping of the
  156468. position we want; don't decode them */
  156469. while(1){
  156470. ogg_packet op;
  156471. ogg_page og;
  156472. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156473. if(ret>0){
  156474. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156475. if(thisblock<0){
  156476. ogg_stream_packetout(&vf->os,NULL);
  156477. continue; /* non audio packet */
  156478. }
  156479. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156480. if(vf->pcm_offset+((thisblock+
  156481. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156482. /* remove the packet from packet queue and track its granulepos */
  156483. ogg_stream_packetout(&vf->os,NULL);
  156484. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156485. only tracking, no
  156486. pcm_decode */
  156487. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156488. /* end of logical stream case is hard, especially with exact
  156489. length positioning. */
  156490. if(op.granulepos>-1){
  156491. int i;
  156492. /* always believe the stream markers */
  156493. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156494. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156495. for(i=0;i<vf->current_link;i++)
  156496. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156497. }
  156498. lastblock=thisblock;
  156499. }else{
  156500. if(ret<0 && ret!=OV_HOLE)break;
  156501. /* suck in a new page */
  156502. if(_get_next_page(vf,&og,-1)<0)break;
  156503. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156504. if(vf->ready_state<STREAMSET){
  156505. int link;
  156506. vf->current_serialno=ogg_page_serialno(&og);
  156507. for(link=0;link<vf->links;link++)
  156508. if(vf->serialnos[link]==vf->current_serialno)break;
  156509. if(link==vf->links)return(OV_EBADLINK);
  156510. vf->current_link=link;
  156511. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156512. vf->ready_state=STREAMSET;
  156513. ret=_make_decode_ready(vf);
  156514. if(ret)return ret;
  156515. lastblock=0;
  156516. }
  156517. ogg_stream_pagein(&vf->os,&og);
  156518. }
  156519. }
  156520. vf->bittrack=0.f;
  156521. vf->samptrack=0.f;
  156522. /* discard samples until we reach the desired position. Crossing a
  156523. logical bitstream boundary with abandon is OK. */
  156524. while(vf->pcm_offset<pos){
  156525. ogg_int64_t target=pos-vf->pcm_offset;
  156526. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156527. if(samples>target)samples=target;
  156528. vorbis_synthesis_read(&vf->vd,samples);
  156529. vf->pcm_offset+=samples;
  156530. if(samples<target)
  156531. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156532. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156533. }
  156534. return 0;
  156535. }
  156536. /* seek to a playback time relative to the decompressed pcm stream
  156537. returns zero on success, nonzero on failure */
  156538. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156539. /* translate time to PCM position and call ov_pcm_seek */
  156540. int link=-1;
  156541. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156542. double time_total=ov_time_total(vf,-1);
  156543. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156544. if(!vf->seekable)return(OV_ENOSEEK);
  156545. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156546. /* which bitstream section does this time offset occur in? */
  156547. for(link=vf->links-1;link>=0;link--){
  156548. pcm_total-=vf->pcmlengths[link*2+1];
  156549. time_total-=ov_time_total(vf,link);
  156550. if(seconds>=time_total)break;
  156551. }
  156552. /* enough information to convert time offset to pcm offset */
  156553. {
  156554. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156555. return(ov_pcm_seek(vf,target));
  156556. }
  156557. }
  156558. /* page-granularity version of ov_time_seek
  156559. returns zero on success, nonzero on failure */
  156560. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156561. /* translate time to PCM position and call ov_pcm_seek */
  156562. int link=-1;
  156563. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156564. double time_total=ov_time_total(vf,-1);
  156565. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156566. if(!vf->seekable)return(OV_ENOSEEK);
  156567. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156568. /* which bitstream section does this time offset occur in? */
  156569. for(link=vf->links-1;link>=0;link--){
  156570. pcm_total-=vf->pcmlengths[link*2+1];
  156571. time_total-=ov_time_total(vf,link);
  156572. if(seconds>=time_total)break;
  156573. }
  156574. /* enough information to convert time offset to pcm offset */
  156575. {
  156576. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156577. return(ov_pcm_seek_page(vf,target));
  156578. }
  156579. }
  156580. /* tell the current stream offset cursor. Note that seek followed by
  156581. tell will likely not give the set offset due to caching */
  156582. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156583. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156584. return(vf->offset);
  156585. }
  156586. /* return PCM offset (sample) of next PCM sample to be read */
  156587. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156588. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156589. return(vf->pcm_offset);
  156590. }
  156591. /* return time offset (seconds) of next PCM sample to be read */
  156592. double ov_time_tell(OggVorbis_File *vf){
  156593. int link=0;
  156594. ogg_int64_t pcm_total=0;
  156595. double time_total=0.f;
  156596. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156597. if(vf->seekable){
  156598. pcm_total=ov_pcm_total(vf,-1);
  156599. time_total=ov_time_total(vf,-1);
  156600. /* which bitstream section does this time offset occur in? */
  156601. for(link=vf->links-1;link>=0;link--){
  156602. pcm_total-=vf->pcmlengths[link*2+1];
  156603. time_total-=ov_time_total(vf,link);
  156604. if(vf->pcm_offset>=pcm_total)break;
  156605. }
  156606. }
  156607. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156608. }
  156609. /* link: -1) return the vorbis_info struct for the bitstream section
  156610. currently being decoded
  156611. 0-n) to request information for a specific bitstream section
  156612. In the case of a non-seekable bitstream, any call returns the
  156613. current bitstream. NULL in the case that the machine is not
  156614. initialized */
  156615. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156616. if(vf->seekable){
  156617. if(link<0)
  156618. if(vf->ready_state>=STREAMSET)
  156619. return vf->vi+vf->current_link;
  156620. else
  156621. return vf->vi;
  156622. else
  156623. if(link>=vf->links)
  156624. return NULL;
  156625. else
  156626. return vf->vi+link;
  156627. }else{
  156628. return vf->vi;
  156629. }
  156630. }
  156631. /* grr, strong typing, grr, no templates/inheritence, grr */
  156632. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156633. if(vf->seekable){
  156634. if(link<0)
  156635. if(vf->ready_state>=STREAMSET)
  156636. return vf->vc+vf->current_link;
  156637. else
  156638. return vf->vc;
  156639. else
  156640. if(link>=vf->links)
  156641. return NULL;
  156642. else
  156643. return vf->vc+link;
  156644. }else{
  156645. return vf->vc;
  156646. }
  156647. }
  156648. static int host_is_big_endian() {
  156649. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156650. unsigned char *bytewise = (unsigned char *)&pattern;
  156651. if (bytewise[0] == 0xfe) return 1;
  156652. return 0;
  156653. }
  156654. /* up to this point, everything could more or less hide the multiple
  156655. logical bitstream nature of chaining from the toplevel application
  156656. if the toplevel application didn't particularly care. However, at
  156657. the point that we actually read audio back, the multiple-section
  156658. nature must surface: Multiple bitstream sections do not necessarily
  156659. have to have the same number of channels or sampling rate.
  156660. ov_read returns the sequential logical bitstream number currently
  156661. being decoded along with the PCM data in order that the toplevel
  156662. application can take action on channel/sample rate changes. This
  156663. number will be incremented even for streamed (non-seekable) streams
  156664. (for seekable streams, it represents the actual logical bitstream
  156665. index within the physical bitstream. Note that the accessor
  156666. functions above are aware of this dichotomy).
  156667. input values: buffer) a buffer to hold packed PCM data for return
  156668. length) the byte length requested to be placed into buffer
  156669. bigendianp) should the data be packed LSB first (0) or
  156670. MSB first (1)
  156671. word) word size for output. currently 1 (byte) or
  156672. 2 (16 bit short)
  156673. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156674. 0) EOF
  156675. n) number of bytes of PCM actually returned. The
  156676. below works on a packet-by-packet basis, so the
  156677. return length is not related to the 'length' passed
  156678. in, just guaranteed to fit.
  156679. *section) set to the logical bitstream number */
  156680. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156681. int bigendianp,int word,int sgned,int *bitstream){
  156682. int i,j;
  156683. int host_endian = host_is_big_endian();
  156684. float **pcm;
  156685. long samples;
  156686. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156687. while(1){
  156688. if(vf->ready_state==INITSET){
  156689. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156690. if(samples)break;
  156691. }
  156692. /* suck in another packet */
  156693. {
  156694. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156695. if(ret==OV_EOF)
  156696. return(0);
  156697. if(ret<=0)
  156698. return(ret);
  156699. }
  156700. }
  156701. if(samples>0){
  156702. /* yay! proceed to pack data into the byte buffer */
  156703. long channels=ov_info(vf,-1)->channels;
  156704. long bytespersample=word * channels;
  156705. vorbis_fpu_control fpu;
  156706. (void) fpu; // (to avoid a warning about it being unused)
  156707. if(samples>length/bytespersample)samples=length/bytespersample;
  156708. if(samples <= 0)
  156709. return OV_EINVAL;
  156710. /* a tight loop to pack each size */
  156711. {
  156712. int val;
  156713. if(word==1){
  156714. int off=(sgned?0:128);
  156715. vorbis_fpu_setround(&fpu);
  156716. for(j=0;j<samples;j++)
  156717. for(i=0;i<channels;i++){
  156718. val=vorbis_ftoi(pcm[i][j]*128.f);
  156719. if(val>127)val=127;
  156720. else if(val<-128)val=-128;
  156721. *buffer++=val+off;
  156722. }
  156723. vorbis_fpu_restore(fpu);
  156724. }else{
  156725. int off=(sgned?0:32768);
  156726. if(host_endian==bigendianp){
  156727. if(sgned){
  156728. vorbis_fpu_setround(&fpu);
  156729. for(i=0;i<channels;i++) { /* It's faster in this order */
  156730. float *src=pcm[i];
  156731. short *dest=((short *)buffer)+i;
  156732. for(j=0;j<samples;j++) {
  156733. val=vorbis_ftoi(src[j]*32768.f);
  156734. if(val>32767)val=32767;
  156735. else if(val<-32768)val=-32768;
  156736. *dest=val;
  156737. dest+=channels;
  156738. }
  156739. }
  156740. vorbis_fpu_restore(fpu);
  156741. }else{
  156742. vorbis_fpu_setround(&fpu);
  156743. for(i=0;i<channels;i++) {
  156744. float *src=pcm[i];
  156745. short *dest=((short *)buffer)+i;
  156746. for(j=0;j<samples;j++) {
  156747. val=vorbis_ftoi(src[j]*32768.f);
  156748. if(val>32767)val=32767;
  156749. else if(val<-32768)val=-32768;
  156750. *dest=val+off;
  156751. dest+=channels;
  156752. }
  156753. }
  156754. vorbis_fpu_restore(fpu);
  156755. }
  156756. }else if(bigendianp){
  156757. vorbis_fpu_setround(&fpu);
  156758. for(j=0;j<samples;j++)
  156759. for(i=0;i<channels;i++){
  156760. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156761. if(val>32767)val=32767;
  156762. else if(val<-32768)val=-32768;
  156763. val+=off;
  156764. *buffer++=(val>>8);
  156765. *buffer++=(val&0xff);
  156766. }
  156767. vorbis_fpu_restore(fpu);
  156768. }else{
  156769. int val;
  156770. vorbis_fpu_setround(&fpu);
  156771. for(j=0;j<samples;j++)
  156772. for(i=0;i<channels;i++){
  156773. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156774. if(val>32767)val=32767;
  156775. else if(val<-32768)val=-32768;
  156776. val+=off;
  156777. *buffer++=(val&0xff);
  156778. *buffer++=(val>>8);
  156779. }
  156780. vorbis_fpu_restore(fpu);
  156781. }
  156782. }
  156783. }
  156784. vorbis_synthesis_read(&vf->vd,samples);
  156785. vf->pcm_offset+=samples;
  156786. if(bitstream)*bitstream=vf->current_link;
  156787. return(samples*bytespersample);
  156788. }else{
  156789. return(samples);
  156790. }
  156791. }
  156792. /* input values: pcm_channels) a float vector per channel of output
  156793. length) the sample length being read by the app
  156794. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156795. 0) EOF
  156796. n) number of samples of PCM actually returned. The
  156797. below works on a packet-by-packet basis, so the
  156798. return length is not related to the 'length' passed
  156799. in, just guaranteed to fit.
  156800. *section) set to the logical bitstream number */
  156801. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156802. int *bitstream){
  156803. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156804. while(1){
  156805. if(vf->ready_state==INITSET){
  156806. float **pcm;
  156807. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156808. if(samples){
  156809. if(pcm_channels)*pcm_channels=pcm;
  156810. if(samples>length)samples=length;
  156811. vorbis_synthesis_read(&vf->vd,samples);
  156812. vf->pcm_offset+=samples;
  156813. if(bitstream)*bitstream=vf->current_link;
  156814. return samples;
  156815. }
  156816. }
  156817. /* suck in another packet */
  156818. {
  156819. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156820. if(ret==OV_EOF)return(0);
  156821. if(ret<=0)return(ret);
  156822. }
  156823. }
  156824. }
  156825. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156826. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156827. ogg_int64_t off);
  156828. static void _ov_splice(float **pcm,float **lappcm,
  156829. int n1, int n2,
  156830. int ch1, int ch2,
  156831. float *w1, float *w2){
  156832. int i,j;
  156833. float *w=w1;
  156834. int n=n1;
  156835. if(n1>n2){
  156836. n=n2;
  156837. w=w2;
  156838. }
  156839. /* splice */
  156840. for(j=0;j<ch1 && j<ch2;j++){
  156841. float *s=lappcm[j];
  156842. float *d=pcm[j];
  156843. for(i=0;i<n;i++){
  156844. float wd=w[i]*w[i];
  156845. float ws=1.-wd;
  156846. d[i]=d[i]*wd + s[i]*ws;
  156847. }
  156848. }
  156849. /* window from zero */
  156850. for(;j<ch2;j++){
  156851. float *d=pcm[j];
  156852. for(i=0;i<n;i++){
  156853. float wd=w[i]*w[i];
  156854. d[i]=d[i]*wd;
  156855. }
  156856. }
  156857. }
  156858. /* make sure vf is INITSET */
  156859. static int _ov_initset(OggVorbis_File *vf){
  156860. while(1){
  156861. if(vf->ready_state==INITSET)break;
  156862. /* suck in another packet */
  156863. {
  156864. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156865. if(ret<0 && ret!=OV_HOLE)return(ret);
  156866. }
  156867. }
  156868. return 0;
  156869. }
  156870. /* make sure vf is INITSET and that we have a primed buffer; if
  156871. we're crosslapping at a stream section boundary, this also makes
  156872. sure we're sanity checking against the right stream information */
  156873. static int _ov_initprime(OggVorbis_File *vf){
  156874. vorbis_dsp_state *vd=&vf->vd;
  156875. while(1){
  156876. if(vf->ready_state==INITSET)
  156877. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156878. /* suck in another packet */
  156879. {
  156880. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156881. if(ret<0 && ret!=OV_HOLE)return(ret);
  156882. }
  156883. }
  156884. return 0;
  156885. }
  156886. /* grab enough data for lapping from vf; this may be in the form of
  156887. unreturned, already-decoded pcm, remaining PCM we will need to
  156888. decode, or synthetic postextrapolation from last packets. */
  156889. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156890. float **lappcm,int lapsize){
  156891. int lapcount=0,i;
  156892. float **pcm;
  156893. /* try first to decode the lapping data */
  156894. while(lapcount<lapsize){
  156895. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156896. if(samples){
  156897. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156898. for(i=0;i<vi->channels;i++)
  156899. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156900. lapcount+=samples;
  156901. vorbis_synthesis_read(vd,samples);
  156902. }else{
  156903. /* suck in another packet */
  156904. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156905. if(ret==OV_EOF)break;
  156906. }
  156907. }
  156908. if(lapcount<lapsize){
  156909. /* failed to get lapping data from normal decode; pry it from the
  156910. postextrapolation buffering, or the second half of the MDCT
  156911. from the last packet */
  156912. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156913. if(samples==0){
  156914. for(i=0;i<vi->channels;i++)
  156915. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156916. lapcount=lapsize;
  156917. }else{
  156918. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156919. for(i=0;i<vi->channels;i++)
  156920. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156921. lapcount+=samples;
  156922. }
  156923. }
  156924. }
  156925. /* this sets up crosslapping of a sample by using trailing data from
  156926. sample 1 and lapping it into the windowing buffer of sample 2 */
  156927. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156928. vorbis_info *vi1,*vi2;
  156929. float **lappcm;
  156930. float **pcm;
  156931. float *w1,*w2;
  156932. int n1,n2,i,ret,hs1,hs2;
  156933. if(vf1==vf2)return(0); /* degenerate case */
  156934. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156935. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156936. /* the relevant overlap buffers must be pre-checked and pre-primed
  156937. before looking at settings in the event that priming would cross
  156938. a bitstream boundary. So, do it now */
  156939. ret=_ov_initset(vf1);
  156940. if(ret)return(ret);
  156941. ret=_ov_initprime(vf2);
  156942. if(ret)return(ret);
  156943. vi1=ov_info(vf1,-1);
  156944. vi2=ov_info(vf2,-1);
  156945. hs1=ov_halfrate_p(vf1);
  156946. hs2=ov_halfrate_p(vf2);
  156947. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156948. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156949. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156950. w1=vorbis_window(&vf1->vd,0);
  156951. w2=vorbis_window(&vf2->vd,0);
  156952. for(i=0;i<vi1->channels;i++)
  156953. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156954. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156955. /* have a lapping buffer from vf1; now to splice it into the lapping
  156956. buffer of vf2 */
  156957. /* consolidate and expose the buffer. */
  156958. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156959. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156960. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156961. /* splice */
  156962. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156963. /* done */
  156964. return(0);
  156965. }
  156966. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156967. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156968. vorbis_info *vi;
  156969. float **lappcm;
  156970. float **pcm;
  156971. float *w1,*w2;
  156972. int n1,n2,ch1,ch2,hs;
  156973. int i,ret;
  156974. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156975. ret=_ov_initset(vf);
  156976. if(ret)return(ret);
  156977. vi=ov_info(vf,-1);
  156978. hs=ov_halfrate_p(vf);
  156979. ch1=vi->channels;
  156980. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156981. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156982. persistent; even if the decode state
  156983. from this link gets dumped, this
  156984. window array continues to exist */
  156985. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156986. for(i=0;i<ch1;i++)
  156987. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156988. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156989. /* have lapping data; seek and prime the buffer */
  156990. ret=localseek(vf,pos);
  156991. if(ret)return ret;
  156992. ret=_ov_initprime(vf);
  156993. if(ret)return(ret);
  156994. /* Guard against cross-link changes; they're perfectly legal */
  156995. vi=ov_info(vf,-1);
  156996. ch2=vi->channels;
  156997. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156998. w2=vorbis_window(&vf->vd,0);
  156999. /* consolidate and expose the buffer. */
  157000. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157001. /* splice */
  157002. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157003. /* done */
  157004. return(0);
  157005. }
  157006. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157007. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157008. }
  157009. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157010. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157011. }
  157012. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157013. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157014. }
  157015. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157016. int (*localseek)(OggVorbis_File *,double)){
  157017. vorbis_info *vi;
  157018. float **lappcm;
  157019. float **pcm;
  157020. float *w1,*w2;
  157021. int n1,n2,ch1,ch2,hs;
  157022. int i,ret;
  157023. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157024. ret=_ov_initset(vf);
  157025. if(ret)return(ret);
  157026. vi=ov_info(vf,-1);
  157027. hs=ov_halfrate_p(vf);
  157028. ch1=vi->channels;
  157029. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157030. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157031. persistent; even if the decode state
  157032. from this link gets dumped, this
  157033. window array continues to exist */
  157034. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157035. for(i=0;i<ch1;i++)
  157036. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157037. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157038. /* have lapping data; seek and prime the buffer */
  157039. ret=localseek(vf,pos);
  157040. if(ret)return ret;
  157041. ret=_ov_initprime(vf);
  157042. if(ret)return(ret);
  157043. /* Guard against cross-link changes; they're perfectly legal */
  157044. vi=ov_info(vf,-1);
  157045. ch2=vi->channels;
  157046. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157047. w2=vorbis_window(&vf->vd,0);
  157048. /* consolidate and expose the buffer. */
  157049. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157050. /* splice */
  157051. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157052. /* done */
  157053. return(0);
  157054. }
  157055. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157056. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157057. }
  157058. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157059. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157060. }
  157061. #endif
  157062. /*** End of inlined file: vorbisfile.c ***/
  157063. /*** Start of inlined file: window.c ***/
  157064. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157065. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157066. // tasks..
  157067. #if JUCE_MSVC
  157068. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157069. #endif
  157070. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157071. #if JUCE_USE_OGGVORBIS
  157072. #include <stdlib.h>
  157073. #include <math.h>
  157074. static float vwin64[32] = {
  157075. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157076. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157077. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157078. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157079. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157080. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157081. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157082. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157083. };
  157084. static float vwin128[64] = {
  157085. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157086. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157087. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157088. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157089. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157090. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157091. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157092. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157093. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157094. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157095. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157096. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157097. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157098. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157099. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157100. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157101. };
  157102. static float vwin256[128] = {
  157103. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157104. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157105. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157106. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157107. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157108. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157109. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157110. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157111. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157112. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157113. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157114. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157115. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157116. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157117. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157118. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157119. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157120. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157121. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157122. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157123. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157124. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157125. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157126. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157127. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157128. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157129. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157130. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157131. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157132. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157133. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157134. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157135. };
  157136. static float vwin512[256] = {
  157137. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157138. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157139. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157140. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157141. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157142. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157143. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157144. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157145. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157146. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157147. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157148. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157149. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157150. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157151. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157152. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157153. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157154. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157155. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157156. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157157. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157158. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157159. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157160. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157161. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157162. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157163. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157164. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157165. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157166. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157167. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157168. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157169. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157170. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157171. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157172. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157173. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157174. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157175. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157176. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157177. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157178. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157179. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157180. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157181. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157182. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157183. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157184. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157185. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157186. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157187. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157188. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157189. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157190. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157191. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157192. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157193. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157194. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157195. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157196. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157197. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157198. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157199. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157200. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157201. };
  157202. static float vwin1024[512] = {
  157203. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157204. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157205. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157206. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157207. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157208. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157209. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157210. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157211. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157212. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157213. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157214. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157215. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157216. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157217. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157218. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157219. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157220. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157221. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157222. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157223. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157224. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157225. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157226. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157227. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157228. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157229. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157230. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157231. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157232. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157233. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157234. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157235. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157236. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157237. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157238. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157239. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157240. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157241. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157242. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157243. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157244. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157245. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157246. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157247. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157248. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157249. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157250. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157251. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157252. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157253. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157254. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157255. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157256. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157257. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157258. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157259. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157260. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157261. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157262. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157263. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157264. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157265. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157266. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157267. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157268. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157269. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157270. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157271. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157272. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157273. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157274. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157275. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157276. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157277. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157278. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157279. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157280. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157281. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157282. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157283. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157284. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157285. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157286. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157287. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157288. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157289. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157290. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157291. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157292. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157293. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157294. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157295. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157296. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157297. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157298. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157299. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157300. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157301. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157302. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157303. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157304. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157305. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157306. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157307. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157308. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157309. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157310. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157311. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157312. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157313. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157314. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157315. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157316. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157317. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157318. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157319. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157320. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157321. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157322. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157323. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157324. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157325. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157326. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157327. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157328. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157329. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157330. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157331. };
  157332. static float vwin2048[1024] = {
  157333. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157334. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157335. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157336. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157337. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157338. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157339. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157340. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157341. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157342. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157343. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157344. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157345. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157346. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157347. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157348. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157349. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157350. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157351. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157352. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157353. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157354. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157355. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157356. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157357. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157358. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157359. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157360. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157361. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157362. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157363. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157364. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157365. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157366. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157367. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157368. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157369. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157370. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157371. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157372. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157373. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157374. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157375. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157376. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157377. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157378. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157379. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157380. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157381. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157382. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157383. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157384. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157385. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157386. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157387. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157388. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157389. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157390. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157391. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157392. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157393. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157394. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157395. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157396. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157397. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157398. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157399. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157400. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157401. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157402. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157403. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157404. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157405. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157406. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157407. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157408. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157409. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157410. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157411. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157412. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157413. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157414. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157415. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157416. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157417. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157418. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157419. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157420. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157421. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157422. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157423. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157424. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157425. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157426. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157427. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157428. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157429. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157430. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157431. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157432. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157433. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157434. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157435. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157436. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157437. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157438. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157439. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157440. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157441. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157442. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157443. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157444. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157445. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157446. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157447. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157448. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157449. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157450. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157451. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157452. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157453. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157454. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157455. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157456. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157457. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157458. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157459. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157460. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157461. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157462. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157463. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157464. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157465. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157466. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157467. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157468. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157469. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157470. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157471. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157472. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157473. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157474. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157475. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157476. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157477. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157478. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157479. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157480. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157481. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157482. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157483. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157484. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157485. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157486. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157487. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157488. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157489. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157490. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157491. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157492. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157493. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157494. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157495. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157496. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157497. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157498. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157499. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157500. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157501. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157502. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157503. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157504. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157505. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157506. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157507. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157508. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157509. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157510. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157511. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157512. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157513. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157514. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157515. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157516. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157517. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157518. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157519. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157520. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157521. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157522. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157523. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157524. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157525. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157526. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157527. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157528. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157529. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157530. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157531. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157532. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157533. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157534. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157535. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157536. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157537. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157538. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157539. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157540. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157541. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157542. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157543. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157544. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157545. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157546. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157547. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157548. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157549. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157550. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157551. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157552. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157553. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157554. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157555. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157556. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157557. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157558. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157559. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157560. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157561. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157562. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157563. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157564. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157565. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157566. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157567. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157568. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157569. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157570. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157571. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157572. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157573. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157574. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157575. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157576. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157577. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157578. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157579. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157580. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157581. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157582. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157583. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157584. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157585. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157586. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157587. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157588. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157589. };
  157590. static float vwin4096[2048] = {
  157591. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157592. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157593. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157594. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157595. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157596. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157597. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157598. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157599. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157600. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157601. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157602. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157603. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157604. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157605. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157606. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157607. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157608. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157609. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157610. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157611. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157612. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157613. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157614. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157615. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157616. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157617. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157618. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157619. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157620. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157621. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157622. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157623. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157624. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157625. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157626. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157627. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157628. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157629. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157630. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157631. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157632. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157633. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157634. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157635. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157636. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157637. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157638. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157639. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157640. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157641. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157642. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157643. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157644. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157645. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157646. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157647. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157648. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157649. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157650. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157651. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157652. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157653. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157654. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157655. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157656. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157657. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157658. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157659. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157660. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157661. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157662. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157663. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157664. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157665. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157666. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157667. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157668. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157669. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157670. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157671. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157672. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157673. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157674. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157675. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157676. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157677. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157678. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157679. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157680. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157681. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157682. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157683. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157684. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157685. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157686. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157687. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157688. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157689. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157690. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157691. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157692. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157693. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157694. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157695. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157696. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157697. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157698. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157699. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157700. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157701. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157702. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157703. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157704. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157705. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157706. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157707. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157708. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157709. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157710. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157711. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157712. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157713. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157714. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157715. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157716. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157717. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157718. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157719. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157720. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157721. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157722. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157723. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157724. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157725. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157726. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157727. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157728. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157729. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157730. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157731. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157732. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157733. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157734. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157735. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157736. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157737. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157738. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157739. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157740. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157741. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157742. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157743. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157744. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157745. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157746. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157747. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157748. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157749. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157750. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157751. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157752. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157753. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157754. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157755. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157756. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157757. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157758. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157759. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157760. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157761. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157762. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157763. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157764. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157765. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157766. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157767. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157768. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157769. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157770. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157771. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157772. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157773. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157774. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157775. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157776. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157777. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157778. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157779. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157780. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157781. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157782. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157783. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157784. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157785. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157786. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157787. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157788. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157789. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157790. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157791. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157792. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157793. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157794. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157795. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157796. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157797. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157798. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157799. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157800. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157801. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157802. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157803. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157804. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157805. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157806. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157807. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157808. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157809. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157810. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157811. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157812. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157813. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157814. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157815. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157816. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157817. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157818. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157819. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157820. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157821. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157822. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157823. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157824. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157825. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157826. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157827. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157828. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157829. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157830. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157831. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157832. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157833. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157834. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157835. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157836. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157837. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157838. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157839. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157840. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157841. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157842. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157843. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157844. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157845. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157846. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157847. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157848. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157849. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157850. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157851. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157852. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157853. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157854. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157855. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157856. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157857. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157858. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157859. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157860. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157861. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157862. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157863. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157864. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157865. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157866. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157867. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157868. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157869. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157870. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157871. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157872. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157873. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157874. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157875. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157876. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157877. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157878. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157879. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157880. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157881. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157882. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157883. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157884. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157885. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157886. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157887. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157888. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157889. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157890. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157891. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157892. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157893. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157894. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157895. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157896. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157897. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157898. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157899. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157900. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157901. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157902. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157903. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157904. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157905. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157906. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157907. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157908. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157909. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157910. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157911. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157912. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157913. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157914. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157915. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157916. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157917. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157918. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157919. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157920. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157921. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157922. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157923. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157924. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157925. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157926. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157927. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157928. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157929. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157930. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157931. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157932. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157933. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157934. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157935. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157936. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157937. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157938. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157939. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157940. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157941. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157942. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157943. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157944. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157945. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157946. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157947. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157948. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157949. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157950. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157951. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157952. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157953. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157954. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157955. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157956. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157957. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157958. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157959. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157960. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157961. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157962. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157963. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157964. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157965. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157966. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157967. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157968. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157969. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157970. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157971. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157972. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157973. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157974. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157975. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157976. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157977. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157978. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157979. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157980. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157981. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157982. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157983. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157984. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157985. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157986. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157987. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157988. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157989. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157990. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157991. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157992. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157993. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157994. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157995. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157996. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157997. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157998. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157999. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158000. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158001. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158002. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158003. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158004. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158005. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158006. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158007. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158008. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158009. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158010. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158011. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158012. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158013. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158014. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158015. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158016. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158017. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158018. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158019. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158020. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158021. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158022. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158023. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158024. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158025. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158026. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158027. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158028. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158029. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158030. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158031. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158032. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158033. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158034. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158035. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158036. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158037. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158038. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158039. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158040. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158041. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158042. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158043. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158044. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158045. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158046. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158047. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158048. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158049. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158050. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158051. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158052. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158053. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158054. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158055. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158056. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158057. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158058. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158059. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158060. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158061. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158062. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158063. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158064. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158065. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158066. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158067. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158068. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158069. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158070. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158071. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158072. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158073. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158074. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158075. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158076. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158077. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158078. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158079. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158080. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158081. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158082. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158083. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158084. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158085. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158086. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158087. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158088. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158089. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158090. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158091. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158092. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158093. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158094. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158095. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158096. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158097. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158098. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158099. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158100. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158101. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158102. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158103. };
  158104. static float vwin8192[4096] = {
  158105. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158106. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158107. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158108. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158109. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158110. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158111. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158112. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158113. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158114. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158115. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158116. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158117. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158118. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158119. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158120. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158121. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158122. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158123. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158124. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158125. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158126. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158127. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158128. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158129. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158130. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158131. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158132. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158133. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158134. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158135. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158136. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158137. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158138. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158139. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158140. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158141. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158142. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158143. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158144. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158145. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158146. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158147. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158148. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158149. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158150. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158151. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158152. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158153. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158154. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158155. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158156. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158157. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158158. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158159. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158160. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158161. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158162. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158163. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158164. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158165. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158166. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158167. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158168. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158169. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158170. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158171. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158172. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158173. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158174. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158175. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158176. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158177. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158178. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158179. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158180. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158181. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158182. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158183. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158184. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158185. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158186. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158187. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158188. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158189. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158190. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158191. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158192. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158193. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158194. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158195. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158196. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158197. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158198. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158199. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158200. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158201. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158202. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158203. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158204. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158205. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158206. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158207. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158208. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158209. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158210. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158211. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158212. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158213. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158214. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158215. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158216. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158217. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158218. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158219. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158220. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158221. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158222. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158223. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158224. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158225. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158226. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158227. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158228. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158229. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158230. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158231. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158232. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158233. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158234. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158235. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158236. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158237. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158238. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158239. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158240. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158241. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158242. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158243. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158244. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158245. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158246. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158247. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158248. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158249. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158250. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158251. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158252. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158253. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158254. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158255. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158256. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158257. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158258. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158259. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158260. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158261. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158262. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158263. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158264. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158265. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158266. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158267. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158268. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158269. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158270. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158271. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158272. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158273. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158274. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158275. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158276. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158277. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158278. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158279. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158280. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158281. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158282. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158283. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158284. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158285. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158286. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158287. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158288. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158289. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158290. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158291. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158292. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158293. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158294. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158295. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158296. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158297. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158298. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158299. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158300. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158301. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158302. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158303. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158304. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158305. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158306. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158307. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158308. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158309. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158310. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158311. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158312. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158313. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158314. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158315. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158316. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158317. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158318. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158319. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158320. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158321. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158322. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158323. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158324. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158325. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158326. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158327. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158328. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158329. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158330. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158331. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158332. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158333. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158334. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158335. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158336. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158337. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158338. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158339. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158340. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158341. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158342. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158343. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158344. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158345. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158346. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158347. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158348. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158349. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158350. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158351. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158352. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158353. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158354. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158355. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158356. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158357. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158358. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158359. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158360. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158361. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158362. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158363. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158364. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158365. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158366. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158367. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158368. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158369. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158370. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158371. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158372. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158373. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158374. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158375. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158376. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158377. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158378. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158379. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158380. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158381. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158382. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158383. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158384. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158385. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158386. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158387. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158388. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158389. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158390. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158391. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158392. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158393. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158394. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158395. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158396. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158397. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158398. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158399. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158400. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158401. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158402. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158403. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158404. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158405. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158406. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158407. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158408. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158409. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158410. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158411. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158412. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158413. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158414. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158415. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158416. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158417. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158418. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158419. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158420. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158421. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158422. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158423. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158424. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158425. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158426. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158427. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158428. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158429. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158430. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158431. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158432. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158433. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158434. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158435. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158436. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158437. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158438. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158439. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158440. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158441. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158442. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158443. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158444. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158445. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158446. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158447. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158448. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158449. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158450. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158451. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158452. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158453. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158454. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158455. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158456. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158457. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158458. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158459. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158460. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158461. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158462. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158463. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158464. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158465. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158466. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158467. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158468. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158469. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158470. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158471. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158472. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158473. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158474. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158475. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158476. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158477. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158478. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158479. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158480. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158481. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158482. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158483. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158484. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158485. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158486. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158487. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158488. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158489. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158490. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158491. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158492. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158493. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158494. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158495. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158496. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158497. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158498. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158499. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158500. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158501. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158502. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158503. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158504. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158505. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158506. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158507. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158508. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158509. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158510. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158511. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158512. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158513. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158514. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158515. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158516. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158517. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158518. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158519. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158520. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158521. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158522. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158523. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158524. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158525. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158526. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158527. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158528. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158529. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158530. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158531. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158532. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158533. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158534. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158535. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158536. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158537. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158538. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158539. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158540. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158541. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158542. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158543. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158544. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158545. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158546. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158547. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158548. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158549. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158550. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158551. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158552. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158553. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158554. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158555. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158556. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158557. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158558. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158559. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158560. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158561. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158562. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158563. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158564. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158565. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158566. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158567. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158568. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158569. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158570. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158571. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158572. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158573. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158574. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158575. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158576. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158577. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158578. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158579. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158580. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158581. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158582. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158583. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158584. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158585. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158586. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158587. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158588. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158589. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158590. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158591. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158592. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158593. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158594. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158595. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158596. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158597. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158598. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158599. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158600. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158601. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158602. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158603. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158604. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158605. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158606. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158607. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158608. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158609. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158610. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158611. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158612. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158613. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158614. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158615. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158616. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158617. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158618. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158619. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158620. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158621. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158622. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158623. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158624. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158625. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158626. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158627. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158628. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158629. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158630. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158631. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158632. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158633. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158634. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158635. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158636. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158637. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158638. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158639. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158640. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158641. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158642. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158643. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158644. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158645. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158646. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158647. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158648. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158649. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158650. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158651. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158652. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158653. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158654. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158655. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158656. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158657. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158658. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158659. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158660. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158661. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158662. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158663. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158664. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158665. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158666. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158667. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158668. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158669. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158670. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158671. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158672. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158673. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158674. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158675. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158676. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158677. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158678. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158679. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158680. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158681. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158682. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158683. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158684. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158685. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158686. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158687. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158688. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158689. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158690. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158691. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158692. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158693. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158694. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158695. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158696. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158697. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158698. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158699. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158700. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158701. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158702. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158703. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158704. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158705. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158706. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158707. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158708. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158709. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158710. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158711. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158712. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158713. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158714. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158715. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158716. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158717. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158718. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158719. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158720. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158721. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158722. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158723. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158724. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158725. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158726. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158727. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158728. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158729. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158730. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158731. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158732. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158733. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158734. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158735. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158736. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158737. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158738. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158739. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158740. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158741. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158742. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158743. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158744. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158745. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158746. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158747. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158748. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158749. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158750. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158751. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158752. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158753. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158754. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158755. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158756. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158757. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158758. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158759. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158760. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158761. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158762. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158763. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158764. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158765. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158766. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158767. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158768. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158769. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158770. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158771. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158772. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158773. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158774. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158775. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158776. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158777. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158778. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158779. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158780. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158781. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158782. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158783. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158784. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158785. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158786. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158787. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158788. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158789. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158790. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158791. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158792. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158793. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158794. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158795. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158796. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158797. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158798. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158799. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158800. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158801. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158802. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158803. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158804. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158805. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158806. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158807. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158808. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158809. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158810. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158811. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158812. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158813. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158814. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158815. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158816. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158817. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158818. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158819. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158820. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158821. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158822. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158823. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158824. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158825. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158826. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158827. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158828. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158829. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158830. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158831. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158832. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158833. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158834. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158835. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158836. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158837. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158838. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158839. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158840. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158841. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158842. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158843. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158844. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158845. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158846. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158847. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158848. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158849. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158850. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158851. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158852. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158853. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158854. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158855. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158856. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158857. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158858. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158859. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158860. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158861. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158862. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158863. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158864. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158865. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158866. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158867. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158868. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158869. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158870. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158871. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158872. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158873. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158874. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158875. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158876. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158877. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158878. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158879. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158880. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158881. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158882. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158883. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158884. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158885. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158886. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158887. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158888. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158889. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158890. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158891. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158892. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158893. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158894. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158895. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158896. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158897. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158898. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158899. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158900. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158901. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158902. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158903. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158904. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158905. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158906. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158907. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158908. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158909. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158910. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158911. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158912. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158913. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158914. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158915. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158916. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158917. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158918. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158919. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158920. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158921. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158922. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158923. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158924. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158925. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158926. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158927. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158928. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158929. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158930. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158931. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158932. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158933. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158934. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158935. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158936. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158937. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158938. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158939. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158940. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158941. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158942. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158943. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158944. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158945. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158946. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158947. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158948. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158949. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158950. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158951. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158952. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158953. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158954. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158955. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158956. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158957. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158958. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158959. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158960. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158961. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158962. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158963. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158964. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158965. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158966. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158967. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158968. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158969. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158970. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158971. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158972. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158973. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158974. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158975. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158976. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158977. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158978. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158979. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158980. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158981. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158982. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158983. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158984. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158985. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158986. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158987. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158988. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158989. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158990. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158991. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158992. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158993. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158994. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158995. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158996. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158997. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158998. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158999. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159000. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159001. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159002. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159003. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159004. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159005. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159006. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159007. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159008. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159009. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159010. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159011. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159012. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159013. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159014. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159015. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159016. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159017. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159018. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159019. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159020. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159021. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159022. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159023. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159024. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159025. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159026. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159027. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159028. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159029. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159030. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159031. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159032. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159033. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159034. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159035. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159036. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159037. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159038. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159039. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159040. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159041. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159042. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159043. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159044. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159045. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159046. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159047. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159048. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159049. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159050. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159051. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159052. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159053. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159054. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159055. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159056. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159057. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159058. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159059. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159060. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159061. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159062. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159063. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159064. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159065. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159066. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159067. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159068. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159069. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159070. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159071. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159072. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159073. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159074. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159075. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159076. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159077. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159078. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159079. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159080. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159081. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159082. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159083. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159084. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159085. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159086. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159087. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159088. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159089. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159090. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159091. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159092. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159093. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159094. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159095. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159096. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159097. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159098. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159099. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159100. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159101. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159102. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159103. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159104. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159105. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159106. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159107. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159108. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159109. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159110. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159111. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159112. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159113. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159114. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159115. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159116. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159117. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159118. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159119. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159120. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159121. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159122. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159123. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159124. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159125. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159126. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159127. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159128. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159129. };
  159130. static float *vwin[8] = {
  159131. vwin64,
  159132. vwin128,
  159133. vwin256,
  159134. vwin512,
  159135. vwin1024,
  159136. vwin2048,
  159137. vwin4096,
  159138. vwin8192,
  159139. };
  159140. float *_vorbis_window_get(int n){
  159141. return vwin[n];
  159142. }
  159143. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159144. int lW,int W,int nW){
  159145. lW=(W?lW:0);
  159146. nW=(W?nW:0);
  159147. {
  159148. float *windowLW=vwin[winno[lW]];
  159149. float *windowNW=vwin[winno[nW]];
  159150. long n=blocksizes[W];
  159151. long ln=blocksizes[lW];
  159152. long rn=blocksizes[nW];
  159153. long leftbegin=n/4-ln/4;
  159154. long leftend=leftbegin+ln/2;
  159155. long rightbegin=n/2+n/4-rn/4;
  159156. long rightend=rightbegin+rn/2;
  159157. int i,p;
  159158. for(i=0;i<leftbegin;i++)
  159159. d[i]=0.f;
  159160. for(p=0;i<leftend;i++,p++)
  159161. d[i]*=windowLW[p];
  159162. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159163. d[i]*=windowNW[p];
  159164. for(;i<n;i++)
  159165. d[i]=0.f;
  159166. }
  159167. }
  159168. #endif
  159169. /*** End of inlined file: window.c ***/
  159170. #else
  159171. #include <vorbis/vorbisenc.h>
  159172. #include <vorbis/codec.h>
  159173. #include <vorbis/vorbisfile.h>
  159174. #endif
  159175. }
  159176. #undef max
  159177. #undef min
  159178. BEGIN_JUCE_NAMESPACE
  159179. static const char* const oggFormatName = "Ogg-Vorbis file";
  159180. static const char* const oggExtensions[] = { ".ogg", 0 };
  159181. class OggReader : public AudioFormatReader
  159182. {
  159183. OggVorbisNamespace::OggVorbis_File ovFile;
  159184. OggVorbisNamespace::ov_callbacks callbacks;
  159185. AudioSampleBuffer reservoir;
  159186. int reservoirStart, samplesInReservoir;
  159187. public:
  159188. OggReader (InputStream* const inp)
  159189. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159190. reservoir (2, 4096),
  159191. reservoirStart (0),
  159192. samplesInReservoir (0)
  159193. {
  159194. using namespace OggVorbisNamespace;
  159195. sampleRate = 0;
  159196. usesFloatingPointData = true;
  159197. callbacks.read_func = &oggReadCallback;
  159198. callbacks.seek_func = &oggSeekCallback;
  159199. callbacks.close_func = &oggCloseCallback;
  159200. callbacks.tell_func = &oggTellCallback;
  159201. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159202. if (err == 0)
  159203. {
  159204. vorbis_info* info = ov_info (&ovFile, -1);
  159205. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159206. numChannels = info->channels;
  159207. bitsPerSample = 16;
  159208. sampleRate = info->rate;
  159209. reservoir.setSize (numChannels,
  159210. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159211. }
  159212. }
  159213. ~OggReader()
  159214. {
  159215. OggVorbisNamespace::ov_clear (&ovFile);
  159216. }
  159217. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159218. int64 startSampleInFile, int numSamples)
  159219. {
  159220. while (numSamples > 0)
  159221. {
  159222. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159223. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159224. {
  159225. // got a few samples overlapping, so use them before seeking..
  159226. const int numToUse = jmin (numSamples, numAvailable);
  159227. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159228. if (destSamples[i] != 0)
  159229. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159230. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159231. sizeof (float) * numToUse);
  159232. startSampleInFile += numToUse;
  159233. numSamples -= numToUse;
  159234. startOffsetInDestBuffer += numToUse;
  159235. if (numSamples == 0)
  159236. break;
  159237. }
  159238. if (startSampleInFile < reservoirStart
  159239. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159240. {
  159241. // buffer miss, so refill the reservoir
  159242. int bitStream = 0;
  159243. reservoirStart = jmax (0, (int) startSampleInFile);
  159244. samplesInReservoir = reservoir.getNumSamples();
  159245. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159246. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159247. int offset = 0;
  159248. int numToRead = samplesInReservoir;
  159249. while (numToRead > 0)
  159250. {
  159251. float** dataIn = 0;
  159252. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159253. if (samps <= 0)
  159254. break;
  159255. jassert (samps <= numToRead);
  159256. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159257. {
  159258. memcpy (reservoir.getSampleData (i, offset),
  159259. dataIn[i],
  159260. sizeof (float) * samps);
  159261. }
  159262. numToRead -= samps;
  159263. offset += samps;
  159264. }
  159265. if (numToRead > 0)
  159266. reservoir.clear (offset, numToRead);
  159267. }
  159268. }
  159269. if (numSamples > 0)
  159270. {
  159271. for (int i = numDestChannels; --i >= 0;)
  159272. if (destSamples[i] != 0)
  159273. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159274. sizeof (int) * numSamples);
  159275. }
  159276. return true;
  159277. }
  159278. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159279. {
  159280. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159281. }
  159282. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159283. {
  159284. InputStream* const in = static_cast <InputStream*> (datasource);
  159285. if (whence == SEEK_CUR)
  159286. offset += in->getPosition();
  159287. else if (whence == SEEK_END)
  159288. offset += in->getTotalLength();
  159289. in->setPosition (offset);
  159290. return 0;
  159291. }
  159292. static int oggCloseCallback (void*)
  159293. {
  159294. return 0;
  159295. }
  159296. static long oggTellCallback (void* datasource)
  159297. {
  159298. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159299. }
  159300. private:
  159301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159302. };
  159303. class OggWriter : public AudioFormatWriter
  159304. {
  159305. OggVorbisNamespace::ogg_stream_state os;
  159306. OggVorbisNamespace::ogg_page og;
  159307. OggVorbisNamespace::ogg_packet op;
  159308. OggVorbisNamespace::vorbis_info vi;
  159309. OggVorbisNamespace::vorbis_comment vc;
  159310. OggVorbisNamespace::vorbis_dsp_state vd;
  159311. OggVorbisNamespace::vorbis_block vb;
  159312. public:
  159313. bool ok;
  159314. OggWriter (OutputStream* const out,
  159315. const double sampleRate,
  159316. const int numChannels,
  159317. const int bitsPerSample,
  159318. const int qualityIndex)
  159319. : AudioFormatWriter (out, TRANS (oggFormatName),
  159320. sampleRate,
  159321. numChannels,
  159322. bitsPerSample)
  159323. {
  159324. using namespace OggVorbisNamespace;
  159325. ok = false;
  159326. vorbis_info_init (&vi);
  159327. if (vorbis_encode_init_vbr (&vi,
  159328. numChannels,
  159329. (int) sampleRate,
  159330. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159331. {
  159332. vorbis_comment_init (&vc);
  159333. if (JUCEApplication::getInstance() != 0)
  159334. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159335. vorbis_analysis_init (&vd, &vi);
  159336. vorbis_block_init (&vd, &vb);
  159337. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159338. ogg_packet header;
  159339. ogg_packet header_comm;
  159340. ogg_packet header_code;
  159341. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159342. ogg_stream_packetin (&os, &header);
  159343. ogg_stream_packetin (&os, &header_comm);
  159344. ogg_stream_packetin (&os, &header_code);
  159345. for (;;)
  159346. {
  159347. if (ogg_stream_flush (&os, &og) == 0)
  159348. break;
  159349. output->write (og.header, og.header_len);
  159350. output->write (og.body, og.body_len);
  159351. }
  159352. ok = true;
  159353. }
  159354. }
  159355. ~OggWriter()
  159356. {
  159357. using namespace OggVorbisNamespace;
  159358. if (ok)
  159359. {
  159360. // write a zero-length packet to show ogg that we're finished..
  159361. write (0, 0);
  159362. ogg_stream_clear (&os);
  159363. vorbis_block_clear (&vb);
  159364. vorbis_dsp_clear (&vd);
  159365. vorbis_comment_clear (&vc);
  159366. vorbis_info_clear (&vi);
  159367. output->flush();
  159368. }
  159369. else
  159370. {
  159371. vorbis_info_clear (&vi);
  159372. output = 0; // to stop the base class deleting this, as it needs to be returned
  159373. // to the caller of createWriter()
  159374. }
  159375. }
  159376. bool write (const int** samplesToWrite, int numSamples)
  159377. {
  159378. using namespace OggVorbisNamespace;
  159379. if (! ok)
  159380. return false;
  159381. if (numSamples > 0)
  159382. {
  159383. const double gain = 1.0 / 0x80000000u;
  159384. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159385. for (int i = numChannels; --i >= 0;)
  159386. {
  159387. float* const dst = vorbisBuffer[i];
  159388. const int* const src = samplesToWrite [i];
  159389. if (src != 0 && dst != 0)
  159390. {
  159391. for (int j = 0; j < numSamples; ++j)
  159392. dst[j] = (float) (src[j] * gain);
  159393. }
  159394. }
  159395. }
  159396. vorbis_analysis_wrote (&vd, numSamples);
  159397. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159398. {
  159399. vorbis_analysis (&vb, 0);
  159400. vorbis_bitrate_addblock (&vb);
  159401. while (vorbis_bitrate_flushpacket (&vd, &op))
  159402. {
  159403. ogg_stream_packetin (&os, &op);
  159404. for (;;)
  159405. {
  159406. if (ogg_stream_pageout (&os, &og) == 0)
  159407. break;
  159408. output->write (og.header, og.header_len);
  159409. output->write (og.body, og.body_len);
  159410. if (ogg_page_eos (&og))
  159411. break;
  159412. }
  159413. }
  159414. }
  159415. return true;
  159416. }
  159417. private:
  159418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159419. };
  159420. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159421. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159422. {
  159423. }
  159424. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159425. {
  159426. }
  159427. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159428. {
  159429. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159430. return Array <int> (rates);
  159431. }
  159432. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159433. {
  159434. const int depths[] = { 32, 0 };
  159435. return Array <int> (depths);
  159436. }
  159437. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159438. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159439. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159440. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159441. const bool deleteStreamIfOpeningFails)
  159442. {
  159443. ScopedPointer <OggReader> r (new OggReader (in));
  159444. if (r->sampleRate != 0)
  159445. return r.release();
  159446. if (! deleteStreamIfOpeningFails)
  159447. r->input = 0;
  159448. return 0;
  159449. }
  159450. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159451. double sampleRate,
  159452. unsigned int numChannels,
  159453. int bitsPerSample,
  159454. const StringPairArray& /*metadataValues*/,
  159455. int qualityOptionIndex)
  159456. {
  159457. ScopedPointer <OggWriter> w (new OggWriter (out,
  159458. sampleRate,
  159459. numChannels,
  159460. bitsPerSample,
  159461. qualityOptionIndex));
  159462. return w->ok ? w.release() : 0;
  159463. }
  159464. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159465. {
  159466. StringArray s;
  159467. s.add ("Low Quality");
  159468. s.add ("Medium Quality");
  159469. s.add ("High Quality");
  159470. return s;
  159471. }
  159472. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159473. {
  159474. FileInputStream* const in = source.createInputStream();
  159475. if (in != 0)
  159476. {
  159477. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159478. if (r != 0)
  159479. {
  159480. const int64 numSamps = r->lengthInSamples;
  159481. r = 0;
  159482. const int64 fileNumSamps = source.getSize() / 4;
  159483. const double ratio = numSamps / (double) fileNumSamps;
  159484. if (ratio > 12.0)
  159485. return 0;
  159486. else if (ratio > 6.0)
  159487. return 1;
  159488. else
  159489. return 2;
  159490. }
  159491. }
  159492. return 1;
  159493. }
  159494. END_JUCE_NAMESPACE
  159495. #endif
  159496. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159497. #endif
  159498. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159499. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159500. #if JUCE_MSVC
  159501. #pragma warning (push)
  159502. #endif
  159503. namespace jpeglibNamespace
  159504. {
  159505. #if JUCE_INCLUDE_JPEGLIB_CODE
  159506. #if JUCE_MINGW
  159507. typedef unsigned char boolean;
  159508. #endif
  159509. #define JPEG_INTERNALS
  159510. #undef FAR
  159511. /*** Start of inlined file: jpeglib.h ***/
  159512. #ifndef JPEGLIB_H
  159513. #define JPEGLIB_H
  159514. /*
  159515. * First we include the configuration files that record how this
  159516. * installation of the JPEG library is set up. jconfig.h can be
  159517. * generated automatically for many systems. jmorecfg.h contains
  159518. * manual configuration options that most people need not worry about.
  159519. */
  159520. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159521. /*** Start of inlined file: jconfig.h ***/
  159522. /* see jconfig.doc for explanations */
  159523. // disable all the warnings under MSVC
  159524. #ifdef _MSC_VER
  159525. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159526. #endif
  159527. #ifdef __BORLANDC__
  159528. #pragma warn -8057
  159529. #pragma warn -8019
  159530. #pragma warn -8004
  159531. #pragma warn -8008
  159532. #endif
  159533. #define HAVE_PROTOTYPES
  159534. #define HAVE_UNSIGNED_CHAR
  159535. #define HAVE_UNSIGNED_SHORT
  159536. /* #define void char */
  159537. /* #define const */
  159538. #undef CHAR_IS_UNSIGNED
  159539. #define HAVE_STDDEF_H
  159540. #define HAVE_STDLIB_H
  159541. #undef NEED_BSD_STRINGS
  159542. #undef NEED_SYS_TYPES_H
  159543. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159544. #undef NEED_SHORT_EXTERNAL_NAMES
  159545. #undef INCOMPLETE_TYPES_BROKEN
  159546. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159547. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159548. typedef unsigned char boolean;
  159549. #endif
  159550. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159551. #ifdef JPEG_INTERNALS
  159552. #undef RIGHT_SHIFT_IS_UNSIGNED
  159553. #endif /* JPEG_INTERNALS */
  159554. #ifdef JPEG_CJPEG_DJPEG
  159555. #define BMP_SUPPORTED /* BMP image file format */
  159556. #define GIF_SUPPORTED /* GIF image file format */
  159557. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159558. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159559. #define TARGA_SUPPORTED /* Targa image file format */
  159560. #define TWO_FILE_COMMANDLINE /* optional */
  159561. #define USE_SETMODE /* Microsoft has setmode() */
  159562. #undef NEED_SIGNAL_CATCHER
  159563. #undef DONT_USE_B_MODE
  159564. #undef PROGRESS_REPORT /* optional */
  159565. #endif /* JPEG_CJPEG_DJPEG */
  159566. /*** End of inlined file: jconfig.h ***/
  159567. /* widely used configuration options */
  159568. #endif
  159569. /*** Start of inlined file: jmorecfg.h ***/
  159570. /*
  159571. * Define BITS_IN_JSAMPLE as either
  159572. * 8 for 8-bit sample values (the usual setting)
  159573. * 12 for 12-bit sample values
  159574. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159575. * JPEG standard, and the IJG code does not support anything else!
  159576. * We do not support run-time selection of data precision, sorry.
  159577. */
  159578. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159579. /*
  159580. * Maximum number of components (color channels) allowed in JPEG image.
  159581. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159582. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159583. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159584. * really short on memory. (Each allowed component costs a hundred or so
  159585. * bytes of storage, whether actually used in an image or not.)
  159586. */
  159587. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159588. /*
  159589. * Basic data types.
  159590. * You may need to change these if you have a machine with unusual data
  159591. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159592. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159593. * but it had better be at least 16.
  159594. */
  159595. /* Representation of a single sample (pixel element value).
  159596. * We frequently allocate large arrays of these, so it's important to keep
  159597. * them small. But if you have memory to burn and access to char or short
  159598. * arrays is very slow on your hardware, you might want to change these.
  159599. */
  159600. #if BITS_IN_JSAMPLE == 8
  159601. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159602. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159603. */
  159604. #ifdef HAVE_UNSIGNED_CHAR
  159605. typedef unsigned char JSAMPLE;
  159606. #define GETJSAMPLE(value) ((int) (value))
  159607. #else /* not HAVE_UNSIGNED_CHAR */
  159608. typedef char JSAMPLE;
  159609. #ifdef CHAR_IS_UNSIGNED
  159610. #define GETJSAMPLE(value) ((int) (value))
  159611. #else
  159612. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159613. #endif /* CHAR_IS_UNSIGNED */
  159614. #endif /* HAVE_UNSIGNED_CHAR */
  159615. #define MAXJSAMPLE 255
  159616. #define CENTERJSAMPLE 128
  159617. #endif /* BITS_IN_JSAMPLE == 8 */
  159618. #if BITS_IN_JSAMPLE == 12
  159619. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159620. * On nearly all machines "short" will do nicely.
  159621. */
  159622. typedef short JSAMPLE;
  159623. #define GETJSAMPLE(value) ((int) (value))
  159624. #define MAXJSAMPLE 4095
  159625. #define CENTERJSAMPLE 2048
  159626. #endif /* BITS_IN_JSAMPLE == 12 */
  159627. /* Representation of a DCT frequency coefficient.
  159628. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159629. * Again, we allocate large arrays of these, but you can change to int
  159630. * if you have memory to burn and "short" is really slow.
  159631. */
  159632. typedef short JCOEF;
  159633. /* Compressed datastreams are represented as arrays of JOCTET.
  159634. * These must be EXACTLY 8 bits wide, at least once they are written to
  159635. * external storage. Note that when using the stdio data source/destination
  159636. * managers, this is also the data type passed to fread/fwrite.
  159637. */
  159638. #ifdef HAVE_UNSIGNED_CHAR
  159639. typedef unsigned char JOCTET;
  159640. #define GETJOCTET(value) (value)
  159641. #else /* not HAVE_UNSIGNED_CHAR */
  159642. typedef char JOCTET;
  159643. #ifdef CHAR_IS_UNSIGNED
  159644. #define GETJOCTET(value) (value)
  159645. #else
  159646. #define GETJOCTET(value) ((value) & 0xFF)
  159647. #endif /* CHAR_IS_UNSIGNED */
  159648. #endif /* HAVE_UNSIGNED_CHAR */
  159649. /* These typedefs are used for various table entries and so forth.
  159650. * They must be at least as wide as specified; but making them too big
  159651. * won't cost a huge amount of memory, so we don't provide special
  159652. * extraction code like we did for JSAMPLE. (In other words, these
  159653. * typedefs live at a different point on the speed/space tradeoff curve.)
  159654. */
  159655. /* UINT8 must hold at least the values 0..255. */
  159656. #ifdef HAVE_UNSIGNED_CHAR
  159657. typedef unsigned char UINT8;
  159658. #else /* not HAVE_UNSIGNED_CHAR */
  159659. #ifdef CHAR_IS_UNSIGNED
  159660. typedef char UINT8;
  159661. #else /* not CHAR_IS_UNSIGNED */
  159662. typedef short UINT8;
  159663. #endif /* CHAR_IS_UNSIGNED */
  159664. #endif /* HAVE_UNSIGNED_CHAR */
  159665. /* UINT16 must hold at least the values 0..65535. */
  159666. #ifdef HAVE_UNSIGNED_SHORT
  159667. typedef unsigned short UINT16;
  159668. #else /* not HAVE_UNSIGNED_SHORT */
  159669. typedef unsigned int UINT16;
  159670. #endif /* HAVE_UNSIGNED_SHORT */
  159671. /* INT16 must hold at least the values -32768..32767. */
  159672. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159673. typedef short INT16;
  159674. #endif
  159675. /* INT32 must hold at least signed 32-bit values. */
  159676. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159677. typedef long INT32;
  159678. #endif
  159679. /* Datatype used for image dimensions. The JPEG standard only supports
  159680. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159681. * "unsigned int" is sufficient on all machines. However, if you need to
  159682. * handle larger images and you don't mind deviating from the spec, you
  159683. * can change this datatype.
  159684. */
  159685. typedef unsigned int JDIMENSION;
  159686. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159687. /* These macros are used in all function definitions and extern declarations.
  159688. * You could modify them if you need to change function linkage conventions;
  159689. * in particular, you'll need to do that to make the library a Windows DLL.
  159690. * Another application is to make all functions global for use with debuggers
  159691. * or code profilers that require it.
  159692. */
  159693. /* a function called through method pointers: */
  159694. #define METHODDEF(type) static type
  159695. /* a function used only in its module: */
  159696. #define LOCAL(type) static type
  159697. /* a function referenced thru EXTERNs: */
  159698. #define GLOBAL(type) type
  159699. /* a reference to a GLOBAL function: */
  159700. #define EXTERN(type) extern type
  159701. /* This macro is used to declare a "method", that is, a function pointer.
  159702. * We want to supply prototype parameters if the compiler can cope.
  159703. * Note that the arglist parameter must be parenthesized!
  159704. * Again, you can customize this if you need special linkage keywords.
  159705. */
  159706. #ifdef HAVE_PROTOTYPES
  159707. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159708. #else
  159709. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159710. #endif
  159711. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159712. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159713. * by just saying "FAR *" where such a pointer is needed. In a few places
  159714. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159715. */
  159716. #ifdef NEED_FAR_POINTERS
  159717. #define FAR far
  159718. #else
  159719. #define FAR
  159720. #endif
  159721. /*
  159722. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159723. * in standard header files. Or you may have conflicts with application-
  159724. * specific header files that you want to include together with these files.
  159725. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159726. */
  159727. #ifndef HAVE_BOOLEAN
  159728. typedef int boolean;
  159729. #endif
  159730. #ifndef FALSE /* in case these macros already exist */
  159731. #define FALSE 0 /* values of boolean */
  159732. #endif
  159733. #ifndef TRUE
  159734. #define TRUE 1
  159735. #endif
  159736. /*
  159737. * The remaining options affect code selection within the JPEG library,
  159738. * but they don't need to be visible to most applications using the library.
  159739. * To minimize application namespace pollution, the symbols won't be
  159740. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159741. */
  159742. #ifdef JPEG_INTERNALS
  159743. #define JPEG_INTERNAL_OPTIONS
  159744. #endif
  159745. #ifdef JPEG_INTERNAL_OPTIONS
  159746. /*
  159747. * These defines indicate whether to include various optional functions.
  159748. * Undefining some of these symbols will produce a smaller but less capable
  159749. * library. Note that you can leave certain source files out of the
  159750. * compilation/linking process if you've #undef'd the corresponding symbols.
  159751. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159752. */
  159753. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159754. /* Capability options common to encoder and decoder: */
  159755. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159756. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159757. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159758. /* Encoder capability options: */
  159759. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159760. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159761. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159762. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159763. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159764. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159765. * precision, so jchuff.c normally uses entropy optimization to compute
  159766. * usable tables for higher precision. If you don't want to do optimization,
  159767. * you'll have to supply different default Huffman tables.
  159768. * The exact same statements apply for progressive JPEG: the default tables
  159769. * don't work for progressive mode. (This may get fixed, however.)
  159770. */
  159771. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159772. /* Decoder capability options: */
  159773. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159774. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159775. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159776. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159777. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159778. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159779. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159780. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159781. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159782. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159783. /* more capability options later, no doubt */
  159784. /*
  159785. * Ordering of RGB data in scanlines passed to or from the application.
  159786. * If your application wants to deal with data in the order B,G,R, just
  159787. * change these macros. You can also deal with formats such as R,G,B,X
  159788. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159789. * the offsets will also change the order in which colormap data is organized.
  159790. * RESTRICTIONS:
  159791. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159792. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159793. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159794. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159795. * is not 3 (they don't understand about dummy color components!). So you
  159796. * can't use color quantization if you change that value.
  159797. */
  159798. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159799. #define RGB_GREEN 1 /* Offset of Green */
  159800. #define RGB_BLUE 2 /* Offset of Blue */
  159801. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159802. /* Definitions for speed-related optimizations. */
  159803. /* If your compiler supports inline functions, define INLINE
  159804. * as the inline keyword; otherwise define it as empty.
  159805. */
  159806. #ifndef INLINE
  159807. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159808. #define INLINE __inline__
  159809. #endif
  159810. #ifndef INLINE
  159811. #define INLINE /* default is to define it as empty */
  159812. #endif
  159813. #endif
  159814. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159815. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159816. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159817. */
  159818. #ifndef MULTIPLIER
  159819. #define MULTIPLIER int /* type for fastest integer multiply */
  159820. #endif
  159821. /* FAST_FLOAT should be either float or double, whichever is done faster
  159822. * by your compiler. (Note that this type is only used in the floating point
  159823. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159824. * Typically, float is faster in ANSI C compilers, while double is faster in
  159825. * pre-ANSI compilers (because they insist on converting to double anyway).
  159826. * The code below therefore chooses float if we have ANSI-style prototypes.
  159827. */
  159828. #ifndef FAST_FLOAT
  159829. #ifdef HAVE_PROTOTYPES
  159830. #define FAST_FLOAT float
  159831. #else
  159832. #define FAST_FLOAT double
  159833. #endif
  159834. #endif
  159835. #endif /* JPEG_INTERNAL_OPTIONS */
  159836. /*** End of inlined file: jmorecfg.h ***/
  159837. /* seldom changed options */
  159838. /* Version ID for the JPEG library.
  159839. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159840. */
  159841. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159842. /* Various constants determining the sizes of things.
  159843. * All of these are specified by the JPEG standard, so don't change them
  159844. * if you want to be compatible.
  159845. */
  159846. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159847. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159848. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159849. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159850. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159851. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159852. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159853. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159854. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159855. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159856. * to handle it. We even let you do this from the jconfig.h file. However,
  159857. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159858. * sometimes emits noncompliant files doesn't mean you should too.
  159859. */
  159860. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159861. #ifndef D_MAX_BLOCKS_IN_MCU
  159862. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159863. #endif
  159864. /* Data structures for images (arrays of samples and of DCT coefficients).
  159865. * On 80x86 machines, the image arrays are too big for near pointers,
  159866. * but the pointer arrays can fit in near memory.
  159867. */
  159868. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159869. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159870. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159871. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159872. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159873. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159874. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159875. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159876. /* Types for JPEG compression parameters and working tables. */
  159877. /* DCT coefficient quantization tables. */
  159878. typedef struct {
  159879. /* This array gives the coefficient quantizers in natural array order
  159880. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159881. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159882. */
  159883. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159884. /* This field is used only during compression. It's initialized FALSE when
  159885. * the table is created, and set TRUE when it's been output to the file.
  159886. * You could suppress output of a table by setting this to TRUE.
  159887. * (See jpeg_suppress_tables for an example.)
  159888. */
  159889. boolean sent_table; /* TRUE when table has been output */
  159890. } JQUANT_TBL;
  159891. /* Huffman coding tables. */
  159892. typedef struct {
  159893. /* These two fields directly represent the contents of a JPEG DHT marker */
  159894. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159895. /* length k bits; bits[0] is unused */
  159896. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159897. /* This field is used only during compression. It's initialized FALSE when
  159898. * the table is created, and set TRUE when it's been output to the file.
  159899. * You could suppress output of a table by setting this to TRUE.
  159900. * (See jpeg_suppress_tables for an example.)
  159901. */
  159902. boolean sent_table; /* TRUE when table has been output */
  159903. } JHUFF_TBL;
  159904. /* Basic info about one component (color channel). */
  159905. typedef struct {
  159906. /* These values are fixed over the whole image. */
  159907. /* For compression, they must be supplied by parameter setup; */
  159908. /* for decompression, they are read from the SOF marker. */
  159909. int component_id; /* identifier for this component (0..255) */
  159910. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159911. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159912. int v_samp_factor; /* vertical sampling factor (1..4) */
  159913. int quant_tbl_no; /* quantization table selector (0..3) */
  159914. /* These values may vary between scans. */
  159915. /* For compression, they must be supplied by parameter setup; */
  159916. /* for decompression, they are read from the SOS marker. */
  159917. /* The decompressor output side may not use these variables. */
  159918. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159919. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159920. /* Remaining fields should be treated as private by applications. */
  159921. /* These values are computed during compression or decompression startup: */
  159922. /* Component's size in DCT blocks.
  159923. * Any dummy blocks added to complete an MCU are not counted; therefore
  159924. * these values do not depend on whether a scan is interleaved or not.
  159925. */
  159926. JDIMENSION width_in_blocks;
  159927. JDIMENSION height_in_blocks;
  159928. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159929. * For decompression this is the size of the output from one DCT block,
  159930. * reflecting any scaling we choose to apply during the IDCT step.
  159931. * Values of 1,2,4,8 are likely to be supported. Note that different
  159932. * components may receive different IDCT scalings.
  159933. */
  159934. int DCT_scaled_size;
  159935. /* The downsampled dimensions are the component's actual, unpadded number
  159936. * of samples at the main buffer (preprocessing/compression interface), thus
  159937. * downsampled_width = ceil(image_width * Hi/Hmax)
  159938. * and similarly for height. For decompression, IDCT scaling is included, so
  159939. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159940. */
  159941. JDIMENSION downsampled_width; /* actual width in samples */
  159942. JDIMENSION downsampled_height; /* actual height in samples */
  159943. /* This flag is used only for decompression. In cases where some of the
  159944. * components will be ignored (eg grayscale output from YCbCr image),
  159945. * we can skip most computations for the unused components.
  159946. */
  159947. boolean component_needed; /* do we need the value of this component? */
  159948. /* These values are computed before starting a scan of the component. */
  159949. /* The decompressor output side may not use these variables. */
  159950. int MCU_width; /* number of blocks per MCU, horizontally */
  159951. int MCU_height; /* number of blocks per MCU, vertically */
  159952. int MCU_blocks; /* MCU_width * MCU_height */
  159953. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159954. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159955. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159956. /* Saved quantization table for component; NULL if none yet saved.
  159957. * See jdinput.c comments about the need for this information.
  159958. * This field is currently used only for decompression.
  159959. */
  159960. JQUANT_TBL * quant_table;
  159961. /* Private per-component storage for DCT or IDCT subsystem. */
  159962. void * dct_table;
  159963. } jpeg_component_info;
  159964. /* The script for encoding a multiple-scan file is an array of these: */
  159965. typedef struct {
  159966. int comps_in_scan; /* number of components encoded in this scan */
  159967. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159968. int Ss, Se; /* progressive JPEG spectral selection parms */
  159969. int Ah, Al; /* progressive JPEG successive approx. parms */
  159970. } jpeg_scan_info;
  159971. /* The decompressor can save APPn and COM markers in a list of these: */
  159972. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159973. struct jpeg_marker_struct {
  159974. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159975. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159976. unsigned int original_length; /* # bytes of data in the file */
  159977. unsigned int data_length; /* # bytes of data saved at data[] */
  159978. JOCTET FAR * data; /* the data contained in the marker */
  159979. /* the marker length word is not counted in data_length or original_length */
  159980. };
  159981. /* Known color spaces. */
  159982. typedef enum {
  159983. JCS_UNKNOWN, /* error/unspecified */
  159984. JCS_GRAYSCALE, /* monochrome */
  159985. JCS_RGB, /* red/green/blue */
  159986. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159987. JCS_CMYK, /* C/M/Y/K */
  159988. JCS_YCCK /* Y/Cb/Cr/K */
  159989. } J_COLOR_SPACE;
  159990. /* DCT/IDCT algorithm options. */
  159991. typedef enum {
  159992. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159993. JDCT_IFAST, /* faster, less accurate integer method */
  159994. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159995. } J_DCT_METHOD;
  159996. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159997. #define JDCT_DEFAULT JDCT_ISLOW
  159998. #endif
  159999. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160000. #define JDCT_FASTEST JDCT_IFAST
  160001. #endif
  160002. /* Dithering options for decompression. */
  160003. typedef enum {
  160004. JDITHER_NONE, /* no dithering */
  160005. JDITHER_ORDERED, /* simple ordered dither */
  160006. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160007. } J_DITHER_MODE;
  160008. /* Common fields between JPEG compression and decompression master structs. */
  160009. #define jpeg_common_fields \
  160010. struct jpeg_error_mgr * err; /* Error handler module */\
  160011. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160012. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160013. void * client_data; /* Available for use by application */\
  160014. boolean is_decompressor; /* So common code can tell which is which */\
  160015. int global_state /* For checking call sequence validity */
  160016. /* Routines that are to be used by both halves of the library are declared
  160017. * to receive a pointer to this structure. There are no actual instances of
  160018. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160019. */
  160020. struct jpeg_common_struct {
  160021. jpeg_common_fields; /* Fields common to both master struct types */
  160022. /* Additional fields follow in an actual jpeg_compress_struct or
  160023. * jpeg_decompress_struct. All three structs must agree on these
  160024. * initial fields! (This would be a lot cleaner in C++.)
  160025. */
  160026. };
  160027. typedef struct jpeg_common_struct * j_common_ptr;
  160028. typedef struct jpeg_compress_struct * j_compress_ptr;
  160029. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160030. /* Master record for a compression instance */
  160031. struct jpeg_compress_struct {
  160032. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160033. /* Destination for compressed data */
  160034. struct jpeg_destination_mgr * dest;
  160035. /* Description of source image --- these fields must be filled in by
  160036. * outer application before starting compression. in_color_space must
  160037. * be correct before you can even call jpeg_set_defaults().
  160038. */
  160039. JDIMENSION image_width; /* input image width */
  160040. JDIMENSION image_height; /* input image height */
  160041. int input_components; /* # of color components in input image */
  160042. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160043. double input_gamma; /* image gamma of input image */
  160044. /* Compression parameters --- these fields must be set before calling
  160045. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160046. * initialize everything to reasonable defaults, then changing anything
  160047. * the application specifically wants to change. That way you won't get
  160048. * burnt when new parameters are added. Also note that there are several
  160049. * helper routines to simplify changing parameters.
  160050. */
  160051. int data_precision; /* bits of precision in image data */
  160052. int num_components; /* # of color components in JPEG image */
  160053. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160054. jpeg_component_info * comp_info;
  160055. /* comp_info[i] describes component that appears i'th in SOF */
  160056. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160057. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160058. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160059. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160060. /* ptrs to Huffman coding tables, or NULL if not defined */
  160061. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160062. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160063. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160064. int num_scans; /* # of entries in scan_info array */
  160065. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160066. /* The default value of scan_info is NULL, which causes a single-scan
  160067. * sequential JPEG file to be emitted. To create a multi-scan file,
  160068. * set num_scans and scan_info to point to an array of scan definitions.
  160069. */
  160070. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160071. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160072. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160073. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160074. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160075. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160076. /* The restart interval can be specified in absolute MCUs by setting
  160077. * restart_interval, or in MCU rows by setting restart_in_rows
  160078. * (in which case the correct restart_interval will be figured
  160079. * for each scan).
  160080. */
  160081. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160082. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160083. /* Parameters controlling emission of special markers. */
  160084. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160085. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160086. UINT8 JFIF_minor_version;
  160087. /* These three values are not used by the JPEG code, merely copied */
  160088. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160089. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160090. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160091. UINT8 density_unit; /* JFIF code for pixel size units */
  160092. UINT16 X_density; /* Horizontal pixel density */
  160093. UINT16 Y_density; /* Vertical pixel density */
  160094. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160095. /* State variable: index of next scanline to be written to
  160096. * jpeg_write_scanlines(). Application may use this to control its
  160097. * processing loop, e.g., "while (next_scanline < image_height)".
  160098. */
  160099. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160100. /* Remaining fields are known throughout compressor, but generally
  160101. * should not be touched by a surrounding application.
  160102. */
  160103. /*
  160104. * These fields are computed during compression startup
  160105. */
  160106. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160107. int max_h_samp_factor; /* largest h_samp_factor */
  160108. int max_v_samp_factor; /* largest v_samp_factor */
  160109. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160110. /* The coefficient controller receives data in units of MCU rows as defined
  160111. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160112. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160113. * "iMCU" (interleaved MCU) row.
  160114. */
  160115. /*
  160116. * These fields are valid during any one scan.
  160117. * They describe the components and MCUs actually appearing in the scan.
  160118. */
  160119. int comps_in_scan; /* # of JPEG components in this scan */
  160120. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160121. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160122. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160123. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160124. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160125. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160126. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160127. /* i'th block in an MCU */
  160128. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160129. /*
  160130. * Links to compression subobjects (methods and private variables of modules)
  160131. */
  160132. struct jpeg_comp_master * master;
  160133. struct jpeg_c_main_controller * main;
  160134. struct jpeg_c_prep_controller * prep;
  160135. struct jpeg_c_coef_controller * coef;
  160136. struct jpeg_marker_writer * marker;
  160137. struct jpeg_color_converter * cconvert;
  160138. struct jpeg_downsampler * downsample;
  160139. struct jpeg_forward_dct * fdct;
  160140. struct jpeg_entropy_encoder * entropy;
  160141. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160142. int script_space_size;
  160143. };
  160144. /* Master record for a decompression instance */
  160145. struct jpeg_decompress_struct {
  160146. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160147. /* Source of compressed data */
  160148. struct jpeg_source_mgr * src;
  160149. /* Basic description of image --- filled in by jpeg_read_header(). */
  160150. /* Application may inspect these values to decide how to process image. */
  160151. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160152. JDIMENSION image_height; /* nominal image height */
  160153. int num_components; /* # of color components in JPEG image */
  160154. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160155. /* Decompression processing parameters --- these fields must be set before
  160156. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160157. * them to default values.
  160158. */
  160159. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160160. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160161. double output_gamma; /* image gamma wanted in output */
  160162. boolean buffered_image; /* TRUE=multiple output passes */
  160163. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160164. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160165. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160166. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160167. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160168. /* the following are ignored if not quantize_colors: */
  160169. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160170. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160171. int desired_number_of_colors; /* max # colors to use in created colormap */
  160172. /* these are significant only in buffered-image mode: */
  160173. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160174. boolean enable_external_quant;/* enable future use of external colormap */
  160175. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160176. /* Description of actual output image that will be returned to application.
  160177. * These fields are computed by jpeg_start_decompress().
  160178. * You can also use jpeg_calc_output_dimensions() to determine these values
  160179. * in advance of calling jpeg_start_decompress().
  160180. */
  160181. JDIMENSION output_width; /* scaled image width */
  160182. JDIMENSION output_height; /* scaled image height */
  160183. int out_color_components; /* # of color components in out_color_space */
  160184. int output_components; /* # of color components returned */
  160185. /* output_components is 1 (a colormap index) when quantizing colors;
  160186. * otherwise it equals out_color_components.
  160187. */
  160188. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160189. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160190. * high, space and time will be wasted due to unnecessary data copying.
  160191. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160192. */
  160193. /* When quantizing colors, the output colormap is described by these fields.
  160194. * The application can supply a colormap by setting colormap non-NULL before
  160195. * calling jpeg_start_decompress; otherwise a colormap is created during
  160196. * jpeg_start_decompress or jpeg_start_output.
  160197. * The map has out_color_components rows and actual_number_of_colors columns.
  160198. */
  160199. int actual_number_of_colors; /* number of entries in use */
  160200. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160201. /* State variables: these variables indicate the progress of decompression.
  160202. * The application may examine these but must not modify them.
  160203. */
  160204. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160205. * Application may use this to control its processing loop, e.g.,
  160206. * "while (output_scanline < output_height)".
  160207. */
  160208. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160209. /* Current input scan number and number of iMCU rows completed in scan.
  160210. * These indicate the progress of the decompressor input side.
  160211. */
  160212. int input_scan_number; /* Number of SOS markers seen so far */
  160213. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160214. /* The "output scan number" is the notional scan being displayed by the
  160215. * output side. The decompressor will not allow output scan/row number
  160216. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160217. */
  160218. int output_scan_number; /* Nominal scan number being displayed */
  160219. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160220. /* Current progression status. coef_bits[c][i] indicates the precision
  160221. * with which component c's DCT coefficient i (in zigzag order) is known.
  160222. * It is -1 when no data has yet been received, otherwise it is the point
  160223. * transform (shift) value for the most recent scan of the coefficient
  160224. * (thus, 0 at completion of the progression).
  160225. * This pointer is NULL when reading a non-progressive file.
  160226. */
  160227. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160228. /* Internal JPEG parameters --- the application usually need not look at
  160229. * these fields. Note that the decompressor output side may not use
  160230. * any parameters that can change between scans.
  160231. */
  160232. /* Quantization and Huffman tables are carried forward across input
  160233. * datastreams when processing abbreviated JPEG datastreams.
  160234. */
  160235. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160236. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160237. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160238. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160239. /* ptrs to Huffman coding tables, or NULL if not defined */
  160240. /* These parameters are never carried across datastreams, since they
  160241. * are given in SOF/SOS markers or defined to be reset by SOI.
  160242. */
  160243. int data_precision; /* bits of precision in image data */
  160244. jpeg_component_info * comp_info;
  160245. /* comp_info[i] describes component that appears i'th in SOF */
  160246. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160247. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160248. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160249. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160250. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160251. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160252. /* These fields record data obtained from optional markers recognized by
  160253. * the JPEG library.
  160254. */
  160255. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160256. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160257. UINT8 JFIF_major_version; /* JFIF version number */
  160258. UINT8 JFIF_minor_version;
  160259. UINT8 density_unit; /* JFIF code for pixel size units */
  160260. UINT16 X_density; /* Horizontal pixel density */
  160261. UINT16 Y_density; /* Vertical pixel density */
  160262. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160263. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160264. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160265. /* Aside from the specific data retained from APPn markers known to the
  160266. * library, the uninterpreted contents of any or all APPn and COM markers
  160267. * can be saved in a list for examination by the application.
  160268. */
  160269. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160270. /* Remaining fields are known throughout decompressor, but generally
  160271. * should not be touched by a surrounding application.
  160272. */
  160273. /*
  160274. * These fields are computed during decompression startup
  160275. */
  160276. int max_h_samp_factor; /* largest h_samp_factor */
  160277. int max_v_samp_factor; /* largest v_samp_factor */
  160278. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160279. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160280. /* The coefficient controller's input and output progress is measured in
  160281. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160282. * in fully interleaved JPEG scans, but are used whether the scan is
  160283. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160284. * rows of each component. Therefore, the IDCT output contains
  160285. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160286. */
  160287. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160288. /*
  160289. * These fields are valid during any one scan.
  160290. * They describe the components and MCUs actually appearing in the scan.
  160291. * Note that the decompressor output side must not use these fields.
  160292. */
  160293. int comps_in_scan; /* # of JPEG components in this scan */
  160294. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160295. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160296. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160297. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160298. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160299. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160300. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160301. /* i'th block in an MCU */
  160302. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160303. /* This field is shared between entropy decoder and marker parser.
  160304. * It is either zero or the code of a JPEG marker that has been
  160305. * read from the data source, but has not yet been processed.
  160306. */
  160307. int unread_marker;
  160308. /*
  160309. * Links to decompression subobjects (methods, private variables of modules)
  160310. */
  160311. struct jpeg_decomp_master * master;
  160312. struct jpeg_d_main_controller * main;
  160313. struct jpeg_d_coef_controller * coef;
  160314. struct jpeg_d_post_controller * post;
  160315. struct jpeg_input_controller * inputctl;
  160316. struct jpeg_marker_reader * marker;
  160317. struct jpeg_entropy_decoder * entropy;
  160318. struct jpeg_inverse_dct * idct;
  160319. struct jpeg_upsampler * upsample;
  160320. struct jpeg_color_deconverter * cconvert;
  160321. struct jpeg_color_quantizer * cquantize;
  160322. };
  160323. /* "Object" declarations for JPEG modules that may be supplied or called
  160324. * directly by the surrounding application.
  160325. * As with all objects in the JPEG library, these structs only define the
  160326. * publicly visible methods and state variables of a module. Additional
  160327. * private fields may exist after the public ones.
  160328. */
  160329. /* Error handler object */
  160330. struct jpeg_error_mgr {
  160331. /* Error exit handler: does not return to caller */
  160332. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160333. /* Conditionally emit a trace or warning message */
  160334. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160335. /* Routine that actually outputs a trace or error message */
  160336. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160337. /* Format a message string for the most recent JPEG error or message */
  160338. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160339. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160340. /* Reset error state variables at start of a new image */
  160341. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160342. /* The message ID code and any parameters are saved here.
  160343. * A message can have one string parameter or up to 8 int parameters.
  160344. */
  160345. int msg_code;
  160346. #define JMSG_STR_PARM_MAX 80
  160347. union {
  160348. int i[8];
  160349. char s[JMSG_STR_PARM_MAX];
  160350. } msg_parm;
  160351. /* Standard state variables for error facility */
  160352. int trace_level; /* max msg_level that will be displayed */
  160353. /* For recoverable corrupt-data errors, we emit a warning message,
  160354. * but keep going unless emit_message chooses to abort. emit_message
  160355. * should count warnings in num_warnings. The surrounding application
  160356. * can check for bad data by seeing if num_warnings is nonzero at the
  160357. * end of processing.
  160358. */
  160359. long num_warnings; /* number of corrupt-data warnings */
  160360. /* These fields point to the table(s) of error message strings.
  160361. * An application can change the table pointer to switch to a different
  160362. * message list (typically, to change the language in which errors are
  160363. * reported). Some applications may wish to add additional error codes
  160364. * that will be handled by the JPEG library error mechanism; the second
  160365. * table pointer is used for this purpose.
  160366. *
  160367. * First table includes all errors generated by JPEG library itself.
  160368. * Error code 0 is reserved for a "no such error string" message.
  160369. */
  160370. const char * const * jpeg_message_table; /* Library errors */
  160371. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160372. /* Second table can be added by application (see cjpeg/djpeg for example).
  160373. * It contains strings numbered first_addon_message..last_addon_message.
  160374. */
  160375. const char * const * addon_message_table; /* Non-library errors */
  160376. int first_addon_message; /* code for first string in addon table */
  160377. int last_addon_message; /* code for last string in addon table */
  160378. };
  160379. /* Progress monitor object */
  160380. struct jpeg_progress_mgr {
  160381. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160382. long pass_counter; /* work units completed in this pass */
  160383. long pass_limit; /* total number of work units in this pass */
  160384. int completed_passes; /* passes completed so far */
  160385. int total_passes; /* total number of passes expected */
  160386. };
  160387. /* Data destination object for compression */
  160388. struct jpeg_destination_mgr {
  160389. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160390. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160391. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160392. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160393. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160394. };
  160395. /* Data source object for decompression */
  160396. struct jpeg_source_mgr {
  160397. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160398. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160399. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160400. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160401. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160402. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160403. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160404. };
  160405. /* Memory manager object.
  160406. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160407. * and "really big" objects (virtual arrays with backing store if needed).
  160408. * The memory manager does not allow individual objects to be freed; rather,
  160409. * each created object is assigned to a pool, and whole pools can be freed
  160410. * at once. This is faster and more convenient than remembering exactly what
  160411. * to free, especially where malloc()/free() are not too speedy.
  160412. * NB: alloc routines never return NULL. They exit to error_exit if not
  160413. * successful.
  160414. */
  160415. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160416. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160417. #define JPOOL_NUMPOOLS 2
  160418. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160419. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160420. struct jpeg_memory_mgr {
  160421. /* Method pointers */
  160422. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160423. size_t sizeofobject));
  160424. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160425. size_t sizeofobject));
  160426. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160427. JDIMENSION samplesperrow,
  160428. JDIMENSION numrows));
  160429. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160430. JDIMENSION blocksperrow,
  160431. JDIMENSION numrows));
  160432. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160433. int pool_id,
  160434. boolean pre_zero,
  160435. JDIMENSION samplesperrow,
  160436. JDIMENSION numrows,
  160437. JDIMENSION maxaccess));
  160438. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160439. int pool_id,
  160440. boolean pre_zero,
  160441. JDIMENSION blocksperrow,
  160442. JDIMENSION numrows,
  160443. JDIMENSION maxaccess));
  160444. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160445. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160446. jvirt_sarray_ptr ptr,
  160447. JDIMENSION start_row,
  160448. JDIMENSION num_rows,
  160449. boolean writable));
  160450. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160451. jvirt_barray_ptr ptr,
  160452. JDIMENSION start_row,
  160453. JDIMENSION num_rows,
  160454. boolean writable));
  160455. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160456. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160457. /* Limit on memory allocation for this JPEG object. (Note that this is
  160458. * merely advisory, not a guaranteed maximum; it only affects the space
  160459. * used for virtual-array buffers.) May be changed by outer application
  160460. * after creating the JPEG object.
  160461. */
  160462. long max_memory_to_use;
  160463. /* Maximum allocation request accepted by alloc_large. */
  160464. long max_alloc_chunk;
  160465. };
  160466. /* Routine signature for application-supplied marker processing methods.
  160467. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160468. */
  160469. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160470. /* Declarations for routines called by application.
  160471. * The JPP macro hides prototype parameters from compilers that can't cope.
  160472. * Note JPP requires double parentheses.
  160473. */
  160474. #ifdef HAVE_PROTOTYPES
  160475. #define JPP(arglist) arglist
  160476. #else
  160477. #define JPP(arglist) ()
  160478. #endif
  160479. /* Short forms of external names for systems with brain-damaged linkers.
  160480. * We shorten external names to be unique in the first six letters, which
  160481. * is good enough for all known systems.
  160482. * (If your compiler itself needs names to be unique in less than 15
  160483. * characters, you are out of luck. Get a better compiler.)
  160484. */
  160485. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160486. #define jpeg_std_error jStdError
  160487. #define jpeg_CreateCompress jCreaCompress
  160488. #define jpeg_CreateDecompress jCreaDecompress
  160489. #define jpeg_destroy_compress jDestCompress
  160490. #define jpeg_destroy_decompress jDestDecompress
  160491. #define jpeg_stdio_dest jStdDest
  160492. #define jpeg_stdio_src jStdSrc
  160493. #define jpeg_set_defaults jSetDefaults
  160494. #define jpeg_set_colorspace jSetColorspace
  160495. #define jpeg_default_colorspace jDefColorspace
  160496. #define jpeg_set_quality jSetQuality
  160497. #define jpeg_set_linear_quality jSetLQuality
  160498. #define jpeg_add_quant_table jAddQuantTable
  160499. #define jpeg_quality_scaling jQualityScaling
  160500. #define jpeg_simple_progression jSimProgress
  160501. #define jpeg_suppress_tables jSuppressTables
  160502. #define jpeg_alloc_quant_table jAlcQTable
  160503. #define jpeg_alloc_huff_table jAlcHTable
  160504. #define jpeg_start_compress jStrtCompress
  160505. #define jpeg_write_scanlines jWrtScanlines
  160506. #define jpeg_finish_compress jFinCompress
  160507. #define jpeg_write_raw_data jWrtRawData
  160508. #define jpeg_write_marker jWrtMarker
  160509. #define jpeg_write_m_header jWrtMHeader
  160510. #define jpeg_write_m_byte jWrtMByte
  160511. #define jpeg_write_tables jWrtTables
  160512. #define jpeg_read_header jReadHeader
  160513. #define jpeg_start_decompress jStrtDecompress
  160514. #define jpeg_read_scanlines jReadScanlines
  160515. #define jpeg_finish_decompress jFinDecompress
  160516. #define jpeg_read_raw_data jReadRawData
  160517. #define jpeg_has_multiple_scans jHasMultScn
  160518. #define jpeg_start_output jStrtOutput
  160519. #define jpeg_finish_output jFinOutput
  160520. #define jpeg_input_complete jInComplete
  160521. #define jpeg_new_colormap jNewCMap
  160522. #define jpeg_consume_input jConsumeInput
  160523. #define jpeg_calc_output_dimensions jCalcDimensions
  160524. #define jpeg_save_markers jSaveMarkers
  160525. #define jpeg_set_marker_processor jSetMarker
  160526. #define jpeg_read_coefficients jReadCoefs
  160527. #define jpeg_write_coefficients jWrtCoefs
  160528. #define jpeg_copy_critical_parameters jCopyCrit
  160529. #define jpeg_abort_compress jAbrtCompress
  160530. #define jpeg_abort_decompress jAbrtDecompress
  160531. #define jpeg_abort jAbort
  160532. #define jpeg_destroy jDestroy
  160533. #define jpeg_resync_to_restart jResyncRestart
  160534. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160535. /* Default error-management setup */
  160536. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160537. JPP((struct jpeg_error_mgr * err));
  160538. /* Initialization of JPEG compression objects.
  160539. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160540. * names that applications should call. These expand to calls on
  160541. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160542. * passed for version mismatch checking.
  160543. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160544. */
  160545. #define jpeg_create_compress(cinfo) \
  160546. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160547. (size_t) sizeof(struct jpeg_compress_struct))
  160548. #define jpeg_create_decompress(cinfo) \
  160549. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160550. (size_t) sizeof(struct jpeg_decompress_struct))
  160551. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160552. int version, size_t structsize));
  160553. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160554. int version, size_t structsize));
  160555. /* Destruction of JPEG compression objects */
  160556. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160557. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160558. /* Standard data source and destination managers: stdio streams. */
  160559. /* Caller is responsible for opening the file before and closing after. */
  160560. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160561. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160562. /* Default parameter setup for compression */
  160563. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160564. /* Compression parameter setup aids */
  160565. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160566. J_COLOR_SPACE colorspace));
  160567. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160568. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160569. boolean force_baseline));
  160570. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160571. int scale_factor,
  160572. boolean force_baseline));
  160573. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160574. const unsigned int *basic_table,
  160575. int scale_factor,
  160576. boolean force_baseline));
  160577. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160578. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160579. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160580. boolean suppress));
  160581. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160582. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160583. /* Main entry points for compression */
  160584. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160585. boolean write_all_tables));
  160586. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160587. JSAMPARRAY scanlines,
  160588. JDIMENSION num_lines));
  160589. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160590. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160591. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160592. JSAMPIMAGE data,
  160593. JDIMENSION num_lines));
  160594. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160595. EXTERN(void) jpeg_write_marker
  160596. JPP((j_compress_ptr cinfo, int marker,
  160597. const JOCTET * dataptr, unsigned int datalen));
  160598. /* Same, but piecemeal. */
  160599. EXTERN(void) jpeg_write_m_header
  160600. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160601. EXTERN(void) jpeg_write_m_byte
  160602. JPP((j_compress_ptr cinfo, int val));
  160603. /* Alternate compression function: just write an abbreviated table file */
  160604. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160605. /* Decompression startup: read start of JPEG datastream to see what's there */
  160606. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160607. boolean require_image));
  160608. /* Return value is one of: */
  160609. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160610. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160611. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160612. /* If you pass require_image = TRUE (normal case), you need not check for
  160613. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160614. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160615. * give a suspension return (the stdio source module doesn't).
  160616. */
  160617. /* Main entry points for decompression */
  160618. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160619. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160620. JSAMPARRAY scanlines,
  160621. JDIMENSION max_lines));
  160622. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160623. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160624. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160625. JSAMPIMAGE data,
  160626. JDIMENSION max_lines));
  160627. /* Additional entry points for buffered-image mode. */
  160628. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160629. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160630. int scan_number));
  160631. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160632. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160633. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160634. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160635. /* Return value is one of: */
  160636. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160637. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160638. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160639. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160640. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160641. /* Precalculate output dimensions for current decompression parameters. */
  160642. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160643. /* Control saving of COM and APPn markers into marker_list. */
  160644. EXTERN(void) jpeg_save_markers
  160645. JPP((j_decompress_ptr cinfo, int marker_code,
  160646. unsigned int length_limit));
  160647. /* Install a special processing method for COM or APPn markers. */
  160648. EXTERN(void) jpeg_set_marker_processor
  160649. JPP((j_decompress_ptr cinfo, int marker_code,
  160650. jpeg_marker_parser_method routine));
  160651. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160652. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160653. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160654. jvirt_barray_ptr * coef_arrays));
  160655. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160656. j_compress_ptr dstinfo));
  160657. /* If you choose to abort compression or decompression before completing
  160658. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160659. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160660. * if you're done with the JPEG object, but if you want to clean it up and
  160661. * reuse it, call this:
  160662. */
  160663. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160664. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160665. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160666. * flavor of JPEG object. These may be more convenient in some places.
  160667. */
  160668. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160669. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160670. /* Default restart-marker-resync procedure for use by data source modules */
  160671. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160672. int desired));
  160673. /* These marker codes are exported since applications and data source modules
  160674. * are likely to want to use them.
  160675. */
  160676. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160677. #define JPEG_EOI 0xD9 /* EOI marker code */
  160678. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160679. #define JPEG_COM 0xFE /* COM marker code */
  160680. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160681. * for structure definitions that are never filled in, keep it quiet by
  160682. * supplying dummy definitions for the various substructures.
  160683. */
  160684. #ifdef INCOMPLETE_TYPES_BROKEN
  160685. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160686. struct jvirt_sarray_control { long dummy; };
  160687. struct jvirt_barray_control { long dummy; };
  160688. struct jpeg_comp_master { long dummy; };
  160689. struct jpeg_c_main_controller { long dummy; };
  160690. struct jpeg_c_prep_controller { long dummy; };
  160691. struct jpeg_c_coef_controller { long dummy; };
  160692. struct jpeg_marker_writer { long dummy; };
  160693. struct jpeg_color_converter { long dummy; };
  160694. struct jpeg_downsampler { long dummy; };
  160695. struct jpeg_forward_dct { long dummy; };
  160696. struct jpeg_entropy_encoder { long dummy; };
  160697. struct jpeg_decomp_master { long dummy; };
  160698. struct jpeg_d_main_controller { long dummy; };
  160699. struct jpeg_d_coef_controller { long dummy; };
  160700. struct jpeg_d_post_controller { long dummy; };
  160701. struct jpeg_input_controller { long dummy; };
  160702. struct jpeg_marker_reader { long dummy; };
  160703. struct jpeg_entropy_decoder { long dummy; };
  160704. struct jpeg_inverse_dct { long dummy; };
  160705. struct jpeg_upsampler { long dummy; };
  160706. struct jpeg_color_deconverter { long dummy; };
  160707. struct jpeg_color_quantizer { long dummy; };
  160708. #endif /* JPEG_INTERNALS */
  160709. #endif /* INCOMPLETE_TYPES_BROKEN */
  160710. /*
  160711. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160712. * The internal structure declarations are read only when that is true.
  160713. * Applications using the library should not include jpegint.h, but may wish
  160714. * to include jerror.h.
  160715. */
  160716. #ifdef JPEG_INTERNALS
  160717. /*** Start of inlined file: jpegint.h ***/
  160718. /* Declarations for both compression & decompression */
  160719. typedef enum { /* Operating modes for buffer controllers */
  160720. JBUF_PASS_THRU, /* Plain stripwise operation */
  160721. /* Remaining modes require a full-image buffer to have been created */
  160722. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160723. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160724. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160725. } J_BUF_MODE;
  160726. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160727. #define CSTATE_START 100 /* after create_compress */
  160728. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160729. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160730. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160731. #define DSTATE_START 200 /* after create_decompress */
  160732. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160733. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160734. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160735. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160736. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160737. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160738. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160739. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160740. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160741. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160742. /* Declarations for compression modules */
  160743. /* Master control module */
  160744. struct jpeg_comp_master {
  160745. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160746. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160747. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160748. /* State variables made visible to other modules */
  160749. boolean call_pass_startup; /* True if pass_startup must be called */
  160750. boolean is_last_pass; /* True during last pass */
  160751. };
  160752. /* Main buffer control (downsampled-data buffer) */
  160753. struct jpeg_c_main_controller {
  160754. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160755. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160756. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160757. JDIMENSION in_rows_avail));
  160758. };
  160759. /* Compression preprocessing (downsampling input buffer control) */
  160760. struct jpeg_c_prep_controller {
  160761. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160762. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160763. JSAMPARRAY input_buf,
  160764. JDIMENSION *in_row_ctr,
  160765. JDIMENSION in_rows_avail,
  160766. JSAMPIMAGE output_buf,
  160767. JDIMENSION *out_row_group_ctr,
  160768. JDIMENSION out_row_groups_avail));
  160769. };
  160770. /* Coefficient buffer control */
  160771. struct jpeg_c_coef_controller {
  160772. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160773. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160774. JSAMPIMAGE input_buf));
  160775. };
  160776. /* Colorspace conversion */
  160777. struct jpeg_color_converter {
  160778. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160779. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160780. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160781. JDIMENSION output_row, int num_rows));
  160782. };
  160783. /* Downsampling */
  160784. struct jpeg_downsampler {
  160785. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160786. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160787. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160788. JSAMPIMAGE output_buf,
  160789. JDIMENSION out_row_group_index));
  160790. boolean need_context_rows; /* TRUE if need rows above & below */
  160791. };
  160792. /* Forward DCT (also controls coefficient quantization) */
  160793. struct jpeg_forward_dct {
  160794. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160795. /* perhaps this should be an array??? */
  160796. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160797. jpeg_component_info * compptr,
  160798. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160799. JDIMENSION start_row, JDIMENSION start_col,
  160800. JDIMENSION num_blocks));
  160801. };
  160802. /* Entropy encoding */
  160803. struct jpeg_entropy_encoder {
  160804. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160805. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160806. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160807. };
  160808. /* Marker writing */
  160809. struct jpeg_marker_writer {
  160810. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160811. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160812. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160813. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160814. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160815. /* These routines are exported to allow insertion of extra markers */
  160816. /* Probably only COM and APPn markers should be written this way */
  160817. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160818. unsigned int datalen));
  160819. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160820. };
  160821. /* Declarations for decompression modules */
  160822. /* Master control module */
  160823. struct jpeg_decomp_master {
  160824. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160825. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160826. /* State variables made visible to other modules */
  160827. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160828. };
  160829. /* Input control module */
  160830. struct jpeg_input_controller {
  160831. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160832. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160833. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160834. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160835. /* State variables made visible to other modules */
  160836. boolean has_multiple_scans; /* True if file has multiple scans */
  160837. boolean eoi_reached; /* True when EOI has been consumed */
  160838. };
  160839. /* Main buffer control (downsampled-data buffer) */
  160840. struct jpeg_d_main_controller {
  160841. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160842. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160843. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160844. JDIMENSION out_rows_avail));
  160845. };
  160846. /* Coefficient buffer control */
  160847. struct jpeg_d_coef_controller {
  160848. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160849. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160850. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160851. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160852. JSAMPIMAGE output_buf));
  160853. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160854. jvirt_barray_ptr *coef_arrays;
  160855. };
  160856. /* Decompression postprocessing (color quantization buffer control) */
  160857. struct jpeg_d_post_controller {
  160858. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160859. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160860. JSAMPIMAGE input_buf,
  160861. JDIMENSION *in_row_group_ctr,
  160862. JDIMENSION in_row_groups_avail,
  160863. JSAMPARRAY output_buf,
  160864. JDIMENSION *out_row_ctr,
  160865. JDIMENSION out_rows_avail));
  160866. };
  160867. /* Marker reading & parsing */
  160868. struct jpeg_marker_reader {
  160869. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160870. /* Read markers until SOS or EOI.
  160871. * Returns same codes as are defined for jpeg_consume_input:
  160872. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160873. */
  160874. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160875. /* Read a restart marker --- exported for use by entropy decoder only */
  160876. jpeg_marker_parser_method read_restart_marker;
  160877. /* State of marker reader --- nominally internal, but applications
  160878. * supplying COM or APPn handlers might like to know the state.
  160879. */
  160880. boolean saw_SOI; /* found SOI? */
  160881. boolean saw_SOF; /* found SOF? */
  160882. int next_restart_num; /* next restart number expected (0-7) */
  160883. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160884. };
  160885. /* Entropy decoding */
  160886. struct jpeg_entropy_decoder {
  160887. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160888. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160889. JBLOCKROW *MCU_data));
  160890. /* This is here to share code between baseline and progressive decoders; */
  160891. /* other modules probably should not use it */
  160892. boolean insufficient_data; /* set TRUE after emitting warning */
  160893. };
  160894. /* Inverse DCT (also performs dequantization) */
  160895. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160896. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160897. JCOEFPTR coef_block,
  160898. JSAMPARRAY output_buf, JDIMENSION output_col));
  160899. struct jpeg_inverse_dct {
  160900. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160901. /* It is useful to allow each component to have a separate IDCT method. */
  160902. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160903. };
  160904. /* Upsampling (note that upsampler must also call color converter) */
  160905. struct jpeg_upsampler {
  160906. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160907. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160908. JSAMPIMAGE input_buf,
  160909. JDIMENSION *in_row_group_ctr,
  160910. JDIMENSION in_row_groups_avail,
  160911. JSAMPARRAY output_buf,
  160912. JDIMENSION *out_row_ctr,
  160913. JDIMENSION out_rows_avail));
  160914. boolean need_context_rows; /* TRUE if need rows above & below */
  160915. };
  160916. /* Colorspace conversion */
  160917. struct jpeg_color_deconverter {
  160918. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160919. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160920. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160921. JSAMPARRAY output_buf, int num_rows));
  160922. };
  160923. /* Color quantization or color precision reduction */
  160924. struct jpeg_color_quantizer {
  160925. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160926. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160927. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160928. int num_rows));
  160929. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160930. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160931. };
  160932. /* Miscellaneous useful macros */
  160933. #undef MAX
  160934. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160935. #undef MIN
  160936. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160937. /* We assume that right shift corresponds to signed division by 2 with
  160938. * rounding towards minus infinity. This is correct for typical "arithmetic
  160939. * shift" instructions that shift in copies of the sign bit. But some
  160940. * C compilers implement >> with an unsigned shift. For these machines you
  160941. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160942. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160943. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160944. * included in the variables of any routine using RIGHT_SHIFT.
  160945. */
  160946. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160947. #define SHIFT_TEMPS INT32 shift_temp;
  160948. #define RIGHT_SHIFT(x,shft) \
  160949. ((shift_temp = (x)) < 0 ? \
  160950. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160951. (shift_temp >> (shft)))
  160952. #else
  160953. #define SHIFT_TEMPS
  160954. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160955. #endif
  160956. /* Short forms of external names for systems with brain-damaged linkers. */
  160957. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160958. #define jinit_compress_master jICompress
  160959. #define jinit_c_master_control jICMaster
  160960. #define jinit_c_main_controller jICMainC
  160961. #define jinit_c_prep_controller jICPrepC
  160962. #define jinit_c_coef_controller jICCoefC
  160963. #define jinit_color_converter jICColor
  160964. #define jinit_downsampler jIDownsampler
  160965. #define jinit_forward_dct jIFDCT
  160966. #define jinit_huff_encoder jIHEncoder
  160967. #define jinit_phuff_encoder jIPHEncoder
  160968. #define jinit_marker_writer jIMWriter
  160969. #define jinit_master_decompress jIDMaster
  160970. #define jinit_d_main_controller jIDMainC
  160971. #define jinit_d_coef_controller jIDCoefC
  160972. #define jinit_d_post_controller jIDPostC
  160973. #define jinit_input_controller jIInCtlr
  160974. #define jinit_marker_reader jIMReader
  160975. #define jinit_huff_decoder jIHDecoder
  160976. #define jinit_phuff_decoder jIPHDecoder
  160977. #define jinit_inverse_dct jIIDCT
  160978. #define jinit_upsampler jIUpsampler
  160979. #define jinit_color_deconverter jIDColor
  160980. #define jinit_1pass_quantizer jI1Quant
  160981. #define jinit_2pass_quantizer jI2Quant
  160982. #define jinit_merged_upsampler jIMUpsampler
  160983. #define jinit_memory_mgr jIMemMgr
  160984. #define jdiv_round_up jDivRound
  160985. #define jround_up jRound
  160986. #define jcopy_sample_rows jCopySamples
  160987. #define jcopy_block_row jCopyBlocks
  160988. #define jzero_far jZeroFar
  160989. #define jpeg_zigzag_order jZIGTable
  160990. #define jpeg_natural_order jZAGTable
  160991. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160992. /* Compression module initialization routines */
  160993. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160994. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160995. boolean transcode_only));
  160996. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160997. boolean need_full_buffer));
  160998. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160999. boolean need_full_buffer));
  161000. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161001. boolean need_full_buffer));
  161002. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161003. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161004. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161005. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161006. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161007. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161008. /* Decompression module initialization routines */
  161009. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161010. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161011. boolean need_full_buffer));
  161012. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161013. boolean need_full_buffer));
  161014. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161015. boolean need_full_buffer));
  161016. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161017. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161018. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161019. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161020. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161021. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161022. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161023. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161024. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161025. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161026. /* Memory manager initialization */
  161027. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161028. /* Utility routines in jutils.c */
  161029. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161030. EXTERN(long) jround_up JPP((long a, long b));
  161031. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161032. JSAMPARRAY output_array, int dest_row,
  161033. int num_rows, JDIMENSION num_cols));
  161034. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161035. JDIMENSION num_blocks));
  161036. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161037. /* Constant tables in jutils.c */
  161038. #if 0 /* This table is not actually needed in v6a */
  161039. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161040. #endif
  161041. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161042. /* Suppress undefined-structure complaints if necessary. */
  161043. #ifdef INCOMPLETE_TYPES_BROKEN
  161044. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161045. struct jvirt_sarray_control { long dummy; };
  161046. struct jvirt_barray_control { long dummy; };
  161047. #endif
  161048. #endif /* INCOMPLETE_TYPES_BROKEN */
  161049. /*** End of inlined file: jpegint.h ***/
  161050. /* fetch private declarations */
  161051. /*** Start of inlined file: jerror.h ***/
  161052. /*
  161053. * To define the enum list of message codes, include this file without
  161054. * defining macro JMESSAGE. To create a message string table, include it
  161055. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161056. */
  161057. #ifndef JMESSAGE
  161058. #ifndef JERROR_H
  161059. /* First time through, define the enum list */
  161060. #define JMAKE_ENUM_LIST
  161061. #else
  161062. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161063. #define JMESSAGE(code,string)
  161064. #endif /* JERROR_H */
  161065. #endif /* JMESSAGE */
  161066. #ifdef JMAKE_ENUM_LIST
  161067. typedef enum {
  161068. #define JMESSAGE(code,string) code ,
  161069. #endif /* JMAKE_ENUM_LIST */
  161070. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161071. /* For maintenance convenience, list is alphabetical by message code name */
  161072. JMESSAGE(JERR_ARITH_NOTIMPL,
  161073. "Sorry, there are legal restrictions on arithmetic coding")
  161074. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161075. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161076. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161077. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161078. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161079. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161080. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161081. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161082. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161083. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161084. JMESSAGE(JERR_BAD_LIB_VERSION,
  161085. "Wrong JPEG library version: library is %d, caller expects %d")
  161086. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161087. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161088. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161089. JMESSAGE(JERR_BAD_PROGRESSION,
  161090. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161091. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161092. "Invalid progressive parameters at scan script entry %d")
  161093. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161094. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161095. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161096. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161097. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161098. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161099. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161100. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161101. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161102. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161103. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161104. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161105. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161106. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161107. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161108. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161109. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161110. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161111. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161112. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161113. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161114. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161115. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161116. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161117. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161118. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161119. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161120. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161121. "Cannot transcode due to multiple use of quantization table %d")
  161122. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161123. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161124. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161125. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161126. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161127. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161128. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161129. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161130. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161131. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161132. JMESSAGE(JERR_QUANT_COMPONENTS,
  161133. "Cannot quantize more than %d color components")
  161134. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161135. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161136. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161137. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161138. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161139. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161140. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161141. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161142. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161143. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161144. JMESSAGE(JERR_TFILE_WRITE,
  161145. "Write failed on temporary file --- out of disk space?")
  161146. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161147. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161148. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161149. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161150. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161151. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161152. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161153. JMESSAGE(JMSG_VERSION, JVERSION)
  161154. JMESSAGE(JTRC_16BIT_TABLES,
  161155. "Caution: quantization tables are too coarse for baseline JPEG")
  161156. JMESSAGE(JTRC_ADOBE,
  161157. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161158. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161159. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161160. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161161. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161162. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161163. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161164. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161165. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161166. JMESSAGE(JTRC_EOI, "End Of Image")
  161167. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161168. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161169. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161170. "Warning: thumbnail image size does not match data length %u")
  161171. JMESSAGE(JTRC_JFIF_EXTENSION,
  161172. "JFIF extension marker: type 0x%02x, length %u")
  161173. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161174. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161175. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161176. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161177. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161178. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161179. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161180. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161181. JMESSAGE(JTRC_RST, "RST%d")
  161182. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161183. "Smoothing not supported with nonstandard sampling ratios")
  161184. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161185. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161186. JMESSAGE(JTRC_SOI, "Start of Image")
  161187. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161188. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161189. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161190. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161191. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161192. JMESSAGE(JTRC_THUMB_JPEG,
  161193. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161194. JMESSAGE(JTRC_THUMB_PALETTE,
  161195. "JFIF extension marker: palette thumbnail image, length %u")
  161196. JMESSAGE(JTRC_THUMB_RGB,
  161197. "JFIF extension marker: RGB thumbnail image, length %u")
  161198. JMESSAGE(JTRC_UNKNOWN_IDS,
  161199. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161200. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161201. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161202. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161203. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161204. "Inconsistent progression sequence for component %d coefficient %d")
  161205. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161206. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161207. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161208. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161209. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161210. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161211. JMESSAGE(JWRN_MUST_RESYNC,
  161212. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161213. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161214. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161215. #ifdef JMAKE_ENUM_LIST
  161216. JMSG_LASTMSGCODE
  161217. } J_MESSAGE_CODE;
  161218. #undef JMAKE_ENUM_LIST
  161219. #endif /* JMAKE_ENUM_LIST */
  161220. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161221. #undef JMESSAGE
  161222. #ifndef JERROR_H
  161223. #define JERROR_H
  161224. /* Macros to simplify using the error and trace message stuff */
  161225. /* The first parameter is either type of cinfo pointer */
  161226. /* Fatal errors (print message and exit) */
  161227. #define ERREXIT(cinfo,code) \
  161228. ((cinfo)->err->msg_code = (code), \
  161229. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161230. #define ERREXIT1(cinfo,code,p1) \
  161231. ((cinfo)->err->msg_code = (code), \
  161232. (cinfo)->err->msg_parm.i[0] = (p1), \
  161233. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161234. #define ERREXIT2(cinfo,code,p1,p2) \
  161235. ((cinfo)->err->msg_code = (code), \
  161236. (cinfo)->err->msg_parm.i[0] = (p1), \
  161237. (cinfo)->err->msg_parm.i[1] = (p2), \
  161238. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161239. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161240. ((cinfo)->err->msg_code = (code), \
  161241. (cinfo)->err->msg_parm.i[0] = (p1), \
  161242. (cinfo)->err->msg_parm.i[1] = (p2), \
  161243. (cinfo)->err->msg_parm.i[2] = (p3), \
  161244. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161245. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161246. ((cinfo)->err->msg_code = (code), \
  161247. (cinfo)->err->msg_parm.i[0] = (p1), \
  161248. (cinfo)->err->msg_parm.i[1] = (p2), \
  161249. (cinfo)->err->msg_parm.i[2] = (p3), \
  161250. (cinfo)->err->msg_parm.i[3] = (p4), \
  161251. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161252. #define ERREXITS(cinfo,code,str) \
  161253. ((cinfo)->err->msg_code = (code), \
  161254. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161255. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161256. #define MAKESTMT(stuff) do { stuff } while (0)
  161257. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161258. #define WARNMS(cinfo,code) \
  161259. ((cinfo)->err->msg_code = (code), \
  161260. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161261. #define WARNMS1(cinfo,code,p1) \
  161262. ((cinfo)->err->msg_code = (code), \
  161263. (cinfo)->err->msg_parm.i[0] = (p1), \
  161264. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161265. #define WARNMS2(cinfo,code,p1,p2) \
  161266. ((cinfo)->err->msg_code = (code), \
  161267. (cinfo)->err->msg_parm.i[0] = (p1), \
  161268. (cinfo)->err->msg_parm.i[1] = (p2), \
  161269. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161270. /* Informational/debugging messages */
  161271. #define TRACEMS(cinfo,lvl,code) \
  161272. ((cinfo)->err->msg_code = (code), \
  161273. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161274. #define TRACEMS1(cinfo,lvl,code,p1) \
  161275. ((cinfo)->err->msg_code = (code), \
  161276. (cinfo)->err->msg_parm.i[0] = (p1), \
  161277. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161278. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161279. ((cinfo)->err->msg_code = (code), \
  161280. (cinfo)->err->msg_parm.i[0] = (p1), \
  161281. (cinfo)->err->msg_parm.i[1] = (p2), \
  161282. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161283. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161284. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161285. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161286. (cinfo)->err->msg_code = (code); \
  161287. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161288. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161289. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161290. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161291. (cinfo)->err->msg_code = (code); \
  161292. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161293. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161294. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161295. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161296. _mp[4] = (p5); \
  161297. (cinfo)->err->msg_code = (code); \
  161298. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161299. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161300. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161301. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161302. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161303. (cinfo)->err->msg_code = (code); \
  161304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161305. #define TRACEMSS(cinfo,lvl,code,str) \
  161306. ((cinfo)->err->msg_code = (code), \
  161307. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161308. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161309. #endif /* JERROR_H */
  161310. /*** End of inlined file: jerror.h ***/
  161311. /* fetch error codes too */
  161312. #endif
  161313. #endif /* JPEGLIB_H */
  161314. /*** End of inlined file: jpeglib.h ***/
  161315. /*** Start of inlined file: jcapimin.c ***/
  161316. #define JPEG_INTERNALS
  161317. /*** Start of inlined file: jinclude.h ***/
  161318. /* Include auto-config file to find out which system include files we need. */
  161319. #ifndef __jinclude_h__
  161320. #define __jinclude_h__
  161321. /*** Start of inlined file: jconfig.h ***/
  161322. /* see jconfig.doc for explanations */
  161323. // disable all the warnings under MSVC
  161324. #ifdef _MSC_VER
  161325. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161326. #endif
  161327. #ifdef __BORLANDC__
  161328. #pragma warn -8057
  161329. #pragma warn -8019
  161330. #pragma warn -8004
  161331. #pragma warn -8008
  161332. #endif
  161333. #define HAVE_PROTOTYPES
  161334. #define HAVE_UNSIGNED_CHAR
  161335. #define HAVE_UNSIGNED_SHORT
  161336. /* #define void char */
  161337. /* #define const */
  161338. #undef CHAR_IS_UNSIGNED
  161339. #define HAVE_STDDEF_H
  161340. #define HAVE_STDLIB_H
  161341. #undef NEED_BSD_STRINGS
  161342. #undef NEED_SYS_TYPES_H
  161343. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161344. #undef NEED_SHORT_EXTERNAL_NAMES
  161345. #undef INCOMPLETE_TYPES_BROKEN
  161346. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161347. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161348. typedef unsigned char boolean;
  161349. #endif
  161350. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161351. #ifdef JPEG_INTERNALS
  161352. #undef RIGHT_SHIFT_IS_UNSIGNED
  161353. #endif /* JPEG_INTERNALS */
  161354. #ifdef JPEG_CJPEG_DJPEG
  161355. #define BMP_SUPPORTED /* BMP image file format */
  161356. #define GIF_SUPPORTED /* GIF image file format */
  161357. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161358. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161359. #define TARGA_SUPPORTED /* Targa image file format */
  161360. #define TWO_FILE_COMMANDLINE /* optional */
  161361. #define USE_SETMODE /* Microsoft has setmode() */
  161362. #undef NEED_SIGNAL_CATCHER
  161363. #undef DONT_USE_B_MODE
  161364. #undef PROGRESS_REPORT /* optional */
  161365. #endif /* JPEG_CJPEG_DJPEG */
  161366. /*** End of inlined file: jconfig.h ***/
  161367. /* auto configuration options */
  161368. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161369. /*
  161370. * We need the NULL macro and size_t typedef.
  161371. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161372. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161373. * pull in <sys/types.h> as well.
  161374. * Note that the core JPEG library does not require <stdio.h>;
  161375. * only the default error handler and data source/destination modules do.
  161376. * But we must pull it in because of the references to FILE in jpeglib.h.
  161377. * You can remove those references if you want to compile without <stdio.h>.
  161378. */
  161379. #ifdef HAVE_STDDEF_H
  161380. #include <stddef.h>
  161381. #endif
  161382. #ifdef HAVE_STDLIB_H
  161383. #include <stdlib.h>
  161384. #endif
  161385. #ifdef NEED_SYS_TYPES_H
  161386. #include <sys/types.h>
  161387. #endif
  161388. #include <stdio.h>
  161389. /*
  161390. * We need memory copying and zeroing functions, plus strncpy().
  161391. * ANSI and System V implementations declare these in <string.h>.
  161392. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161393. * Some systems may declare memset and memcpy in <memory.h>.
  161394. *
  161395. * NOTE: we assume the size parameters to these functions are of type size_t.
  161396. * Change the casts in these macros if not!
  161397. */
  161398. #ifdef NEED_BSD_STRINGS
  161399. #include <strings.h>
  161400. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161401. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161402. #else /* not BSD, assume ANSI/SysV string lib */
  161403. #include <string.h>
  161404. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161405. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161406. #endif
  161407. /*
  161408. * In ANSI C, and indeed any rational implementation, size_t is also the
  161409. * type returned by sizeof(). However, it seems there are some irrational
  161410. * implementations out there, in which sizeof() returns an int even though
  161411. * size_t is defined as long or unsigned long. To ensure consistent results
  161412. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161413. */
  161414. #define SIZEOF(object) ((size_t) sizeof(object))
  161415. /*
  161416. * The modules that use fread() and fwrite() always invoke them through
  161417. * these macros. On some systems you may need to twiddle the argument casts.
  161418. * CAUTION: argument order is different from underlying functions!
  161419. */
  161420. #define JFREAD(file,buf,sizeofbuf) \
  161421. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161422. #define JFWRITE(file,buf,sizeofbuf) \
  161423. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161424. typedef enum { /* JPEG marker codes */
  161425. M_SOF0 = 0xc0,
  161426. M_SOF1 = 0xc1,
  161427. M_SOF2 = 0xc2,
  161428. M_SOF3 = 0xc3,
  161429. M_SOF5 = 0xc5,
  161430. M_SOF6 = 0xc6,
  161431. M_SOF7 = 0xc7,
  161432. M_JPG = 0xc8,
  161433. M_SOF9 = 0xc9,
  161434. M_SOF10 = 0xca,
  161435. M_SOF11 = 0xcb,
  161436. M_SOF13 = 0xcd,
  161437. M_SOF14 = 0xce,
  161438. M_SOF15 = 0xcf,
  161439. M_DHT = 0xc4,
  161440. M_DAC = 0xcc,
  161441. M_RST0 = 0xd0,
  161442. M_RST1 = 0xd1,
  161443. M_RST2 = 0xd2,
  161444. M_RST3 = 0xd3,
  161445. M_RST4 = 0xd4,
  161446. M_RST5 = 0xd5,
  161447. M_RST6 = 0xd6,
  161448. M_RST7 = 0xd7,
  161449. M_SOI = 0xd8,
  161450. M_EOI = 0xd9,
  161451. M_SOS = 0xda,
  161452. M_DQT = 0xdb,
  161453. M_DNL = 0xdc,
  161454. M_DRI = 0xdd,
  161455. M_DHP = 0xde,
  161456. M_EXP = 0xdf,
  161457. M_APP0 = 0xe0,
  161458. M_APP1 = 0xe1,
  161459. M_APP2 = 0xe2,
  161460. M_APP3 = 0xe3,
  161461. M_APP4 = 0xe4,
  161462. M_APP5 = 0xe5,
  161463. M_APP6 = 0xe6,
  161464. M_APP7 = 0xe7,
  161465. M_APP8 = 0xe8,
  161466. M_APP9 = 0xe9,
  161467. M_APP10 = 0xea,
  161468. M_APP11 = 0xeb,
  161469. M_APP12 = 0xec,
  161470. M_APP13 = 0xed,
  161471. M_APP14 = 0xee,
  161472. M_APP15 = 0xef,
  161473. M_JPG0 = 0xf0,
  161474. M_JPG13 = 0xfd,
  161475. M_COM = 0xfe,
  161476. M_TEM = 0x01,
  161477. M_ERROR = 0x100
  161478. } JPEG_MARKER;
  161479. /*
  161480. * Figure F.12: extend sign bit.
  161481. * On some machines, a shift and add will be faster than a table lookup.
  161482. */
  161483. #ifdef AVOID_TABLES
  161484. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161485. #else
  161486. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161487. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161488. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161489. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161490. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161491. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161492. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161493. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161494. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161495. #endif /* AVOID_TABLES */
  161496. #endif
  161497. /*** End of inlined file: jinclude.h ***/
  161498. /*
  161499. * Initialization of a JPEG compression object.
  161500. * The error manager must already be set up (in case memory manager fails).
  161501. */
  161502. GLOBAL(void)
  161503. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161504. {
  161505. int i;
  161506. /* Guard against version mismatches between library and caller. */
  161507. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161508. if (version != JPEG_LIB_VERSION)
  161509. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161510. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161511. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161512. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161513. /* For debugging purposes, we zero the whole master structure.
  161514. * But the application has already set the err pointer, and may have set
  161515. * client_data, so we have to save and restore those fields.
  161516. * Note: if application hasn't set client_data, tools like Purify may
  161517. * complain here.
  161518. */
  161519. {
  161520. struct jpeg_error_mgr * err = cinfo->err;
  161521. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161522. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161523. cinfo->err = err;
  161524. cinfo->client_data = client_data;
  161525. }
  161526. cinfo->is_decompressor = FALSE;
  161527. /* Initialize a memory manager instance for this object */
  161528. jinit_memory_mgr((j_common_ptr) cinfo);
  161529. /* Zero out pointers to permanent structures. */
  161530. cinfo->progress = NULL;
  161531. cinfo->dest = NULL;
  161532. cinfo->comp_info = NULL;
  161533. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161534. cinfo->quant_tbl_ptrs[i] = NULL;
  161535. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161536. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161537. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161538. }
  161539. cinfo->script_space = NULL;
  161540. cinfo->input_gamma = 1.0; /* in case application forgets */
  161541. /* OK, I'm ready */
  161542. cinfo->global_state = CSTATE_START;
  161543. }
  161544. /*
  161545. * Destruction of a JPEG compression object
  161546. */
  161547. GLOBAL(void)
  161548. jpeg_destroy_compress (j_compress_ptr cinfo)
  161549. {
  161550. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161551. }
  161552. /*
  161553. * Abort processing of a JPEG compression operation,
  161554. * but don't destroy the object itself.
  161555. */
  161556. GLOBAL(void)
  161557. jpeg_abort_compress (j_compress_ptr cinfo)
  161558. {
  161559. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161560. }
  161561. /*
  161562. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161563. * Marks all currently defined tables as already written (if suppress)
  161564. * or not written (if !suppress). This will control whether they get emitted
  161565. * by a subsequent jpeg_start_compress call.
  161566. *
  161567. * This routine is exported for use by applications that want to produce
  161568. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161569. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161570. * jcparam.o would be linked whether the application used it or not.
  161571. */
  161572. GLOBAL(void)
  161573. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161574. {
  161575. int i;
  161576. JQUANT_TBL * qtbl;
  161577. JHUFF_TBL * htbl;
  161578. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161579. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161580. qtbl->sent_table = suppress;
  161581. }
  161582. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161583. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161584. htbl->sent_table = suppress;
  161585. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161586. htbl->sent_table = suppress;
  161587. }
  161588. }
  161589. /*
  161590. * Finish JPEG compression.
  161591. *
  161592. * If a multipass operating mode was selected, this may do a great deal of
  161593. * work including most of the actual output.
  161594. */
  161595. GLOBAL(void)
  161596. jpeg_finish_compress (j_compress_ptr cinfo)
  161597. {
  161598. JDIMENSION iMCU_row;
  161599. if (cinfo->global_state == CSTATE_SCANNING ||
  161600. cinfo->global_state == CSTATE_RAW_OK) {
  161601. /* Terminate first pass */
  161602. if (cinfo->next_scanline < cinfo->image_height)
  161603. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161604. (*cinfo->master->finish_pass) (cinfo);
  161605. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161606. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161607. /* Perform any remaining passes */
  161608. while (! cinfo->master->is_last_pass) {
  161609. (*cinfo->master->prepare_for_pass) (cinfo);
  161610. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161611. if (cinfo->progress != NULL) {
  161612. cinfo->progress->pass_counter = (long) iMCU_row;
  161613. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161614. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161615. }
  161616. /* We bypass the main controller and invoke coef controller directly;
  161617. * all work is being done from the coefficient buffer.
  161618. */
  161619. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161620. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161621. }
  161622. (*cinfo->master->finish_pass) (cinfo);
  161623. }
  161624. /* Write EOI, do final cleanup */
  161625. (*cinfo->marker->write_file_trailer) (cinfo);
  161626. (*cinfo->dest->term_destination) (cinfo);
  161627. /* We can use jpeg_abort to release memory and reset global_state */
  161628. jpeg_abort((j_common_ptr) cinfo);
  161629. }
  161630. /*
  161631. * Write a special marker.
  161632. * This is only recommended for writing COM or APPn markers.
  161633. * Must be called after jpeg_start_compress() and before
  161634. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161635. */
  161636. GLOBAL(void)
  161637. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161638. const JOCTET *dataptr, unsigned int datalen)
  161639. {
  161640. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161641. if (cinfo->next_scanline != 0 ||
  161642. (cinfo->global_state != CSTATE_SCANNING &&
  161643. cinfo->global_state != CSTATE_RAW_OK &&
  161644. cinfo->global_state != CSTATE_WRCOEFS))
  161645. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161646. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161647. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161648. while (datalen--) {
  161649. (*write_marker_byte) (cinfo, *dataptr);
  161650. dataptr++;
  161651. }
  161652. }
  161653. /* Same, but piecemeal. */
  161654. GLOBAL(void)
  161655. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161656. {
  161657. if (cinfo->next_scanline != 0 ||
  161658. (cinfo->global_state != CSTATE_SCANNING &&
  161659. cinfo->global_state != CSTATE_RAW_OK &&
  161660. cinfo->global_state != CSTATE_WRCOEFS))
  161661. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161662. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161663. }
  161664. GLOBAL(void)
  161665. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161666. {
  161667. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161668. }
  161669. /*
  161670. * Alternate compression function: just write an abbreviated table file.
  161671. * Before calling this, all parameters and a data destination must be set up.
  161672. *
  161673. * To produce a pair of files containing abbreviated tables and abbreviated
  161674. * image data, one would proceed as follows:
  161675. *
  161676. * initialize JPEG object
  161677. * set JPEG parameters
  161678. * set destination to table file
  161679. * jpeg_write_tables(cinfo);
  161680. * set destination to image file
  161681. * jpeg_start_compress(cinfo, FALSE);
  161682. * write data...
  161683. * jpeg_finish_compress(cinfo);
  161684. *
  161685. * jpeg_write_tables has the side effect of marking all tables written
  161686. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161687. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161688. */
  161689. GLOBAL(void)
  161690. jpeg_write_tables (j_compress_ptr cinfo)
  161691. {
  161692. if (cinfo->global_state != CSTATE_START)
  161693. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161694. /* (Re)initialize error mgr and destination modules */
  161695. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161696. (*cinfo->dest->init_destination) (cinfo);
  161697. /* Initialize the marker writer ... bit of a crock to do it here. */
  161698. jinit_marker_writer(cinfo);
  161699. /* Write them tables! */
  161700. (*cinfo->marker->write_tables_only) (cinfo);
  161701. /* And clean up. */
  161702. (*cinfo->dest->term_destination) (cinfo);
  161703. /*
  161704. * In library releases up through v6a, we called jpeg_abort() here to free
  161705. * any working memory allocated by the destination manager and marker
  161706. * writer. Some applications had a problem with that: they allocated space
  161707. * of their own from the library memory manager, and didn't want it to go
  161708. * away during write_tables. So now we do nothing. This will cause a
  161709. * memory leak if an app calls write_tables repeatedly without doing a full
  161710. * compression cycle or otherwise resetting the JPEG object. However, that
  161711. * seems less bad than unexpectedly freeing memory in the normal case.
  161712. * An app that prefers the old behavior can call jpeg_abort for itself after
  161713. * each call to jpeg_write_tables().
  161714. */
  161715. }
  161716. /*** End of inlined file: jcapimin.c ***/
  161717. /*** Start of inlined file: jcapistd.c ***/
  161718. #define JPEG_INTERNALS
  161719. /*
  161720. * Compression initialization.
  161721. * Before calling this, all parameters and a data destination must be set up.
  161722. *
  161723. * We require a write_all_tables parameter as a failsafe check when writing
  161724. * multiple datastreams from the same compression object. Since prior runs
  161725. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161726. * would emit an abbreviated stream (no tables) by default. This may be what
  161727. * is wanted, but for safety's sake it should not be the default behavior:
  161728. * programmers should have to make a deliberate choice to emit abbreviated
  161729. * images. Therefore the documentation and examples should encourage people
  161730. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161731. * wrong thing.
  161732. */
  161733. GLOBAL(void)
  161734. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161735. {
  161736. if (cinfo->global_state != CSTATE_START)
  161737. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161738. if (write_all_tables)
  161739. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161740. /* (Re)initialize error mgr and destination modules */
  161741. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161742. (*cinfo->dest->init_destination) (cinfo);
  161743. /* Perform master selection of active modules */
  161744. jinit_compress_master(cinfo);
  161745. /* Set up for the first pass */
  161746. (*cinfo->master->prepare_for_pass) (cinfo);
  161747. /* Ready for application to drive first pass through jpeg_write_scanlines
  161748. * or jpeg_write_raw_data.
  161749. */
  161750. cinfo->next_scanline = 0;
  161751. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161752. }
  161753. /*
  161754. * Write some scanlines of data to the JPEG compressor.
  161755. *
  161756. * The return value will be the number of lines actually written.
  161757. * This should be less than the supplied num_lines only in case that
  161758. * the data destination module has requested suspension of the compressor,
  161759. * or if more than image_height scanlines are passed in.
  161760. *
  161761. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161762. * this likely signals an application programmer error. However,
  161763. * excess scanlines passed in the last valid call are *silently* ignored,
  161764. * so that the application need not adjust num_lines for end-of-image
  161765. * when using a multiple-scanline buffer.
  161766. */
  161767. GLOBAL(JDIMENSION)
  161768. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161769. JDIMENSION num_lines)
  161770. {
  161771. JDIMENSION row_ctr, rows_left;
  161772. if (cinfo->global_state != CSTATE_SCANNING)
  161773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161774. if (cinfo->next_scanline >= cinfo->image_height)
  161775. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161776. /* Call progress monitor hook if present */
  161777. if (cinfo->progress != NULL) {
  161778. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161779. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161780. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161781. }
  161782. /* Give master control module another chance if this is first call to
  161783. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161784. * delayed so that application can write COM, etc, markers between
  161785. * jpeg_start_compress and jpeg_write_scanlines.
  161786. */
  161787. if (cinfo->master->call_pass_startup)
  161788. (*cinfo->master->pass_startup) (cinfo);
  161789. /* Ignore any extra scanlines at bottom of image. */
  161790. rows_left = cinfo->image_height - cinfo->next_scanline;
  161791. if (num_lines > rows_left)
  161792. num_lines = rows_left;
  161793. row_ctr = 0;
  161794. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161795. cinfo->next_scanline += row_ctr;
  161796. return row_ctr;
  161797. }
  161798. /*
  161799. * Alternate entry point to write raw data.
  161800. * Processes exactly one iMCU row per call, unless suspended.
  161801. */
  161802. GLOBAL(JDIMENSION)
  161803. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161804. JDIMENSION num_lines)
  161805. {
  161806. JDIMENSION lines_per_iMCU_row;
  161807. if (cinfo->global_state != CSTATE_RAW_OK)
  161808. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161809. if (cinfo->next_scanline >= cinfo->image_height) {
  161810. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161811. return 0;
  161812. }
  161813. /* Call progress monitor hook if present */
  161814. if (cinfo->progress != NULL) {
  161815. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161816. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161817. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161818. }
  161819. /* Give master control module another chance if this is first call to
  161820. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161821. * delayed so that application can write COM, etc, markers between
  161822. * jpeg_start_compress and jpeg_write_raw_data.
  161823. */
  161824. if (cinfo->master->call_pass_startup)
  161825. (*cinfo->master->pass_startup) (cinfo);
  161826. /* Verify that at least one iMCU row has been passed. */
  161827. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161828. if (num_lines < lines_per_iMCU_row)
  161829. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161830. /* Directly compress the row. */
  161831. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161832. /* If compressor did not consume the whole row, suspend processing. */
  161833. return 0;
  161834. }
  161835. /* OK, we processed one iMCU row. */
  161836. cinfo->next_scanline += lines_per_iMCU_row;
  161837. return lines_per_iMCU_row;
  161838. }
  161839. /*** End of inlined file: jcapistd.c ***/
  161840. /*** Start of inlined file: jccoefct.c ***/
  161841. #define JPEG_INTERNALS
  161842. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161843. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161844. * step is run during the first pass, and subsequent passes need only read
  161845. * the buffered coefficients.
  161846. */
  161847. #ifdef ENTROPY_OPT_SUPPORTED
  161848. #define FULL_COEF_BUFFER_SUPPORTED
  161849. #else
  161850. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161851. #define FULL_COEF_BUFFER_SUPPORTED
  161852. #endif
  161853. #endif
  161854. /* Private buffer controller object */
  161855. typedef struct {
  161856. struct jpeg_c_coef_controller pub; /* public fields */
  161857. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161858. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161859. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161860. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161861. /* For single-pass compression, it's sufficient to buffer just one MCU
  161862. * (although this may prove a bit slow in practice). We allocate a
  161863. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161864. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161865. * it's not really very big; this is to keep the module interfaces unchanged
  161866. * when a large coefficient buffer is necessary.)
  161867. * In multi-pass modes, this array points to the current MCU's blocks
  161868. * within the virtual arrays.
  161869. */
  161870. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161871. /* In multi-pass modes, we need a virtual block array for each component. */
  161872. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161873. } my_coef_controller;
  161874. typedef my_coef_controller * my_coef_ptr;
  161875. /* Forward declarations */
  161876. METHODDEF(boolean) compress_data
  161877. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161878. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161879. METHODDEF(boolean) compress_first_pass
  161880. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161881. METHODDEF(boolean) compress_output
  161882. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161883. #endif
  161884. LOCAL(void)
  161885. start_iMCU_row (j_compress_ptr cinfo)
  161886. /* Reset within-iMCU-row counters for a new row */
  161887. {
  161888. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161889. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161890. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161891. * But at the bottom of the image, process only what's left.
  161892. */
  161893. if (cinfo->comps_in_scan > 1) {
  161894. coef->MCU_rows_per_iMCU_row = 1;
  161895. } else {
  161896. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161897. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161898. else
  161899. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161900. }
  161901. coef->mcu_ctr = 0;
  161902. coef->MCU_vert_offset = 0;
  161903. }
  161904. /*
  161905. * Initialize for a processing pass.
  161906. */
  161907. METHODDEF(void)
  161908. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161909. {
  161910. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161911. coef->iMCU_row_num = 0;
  161912. start_iMCU_row(cinfo);
  161913. switch (pass_mode) {
  161914. case JBUF_PASS_THRU:
  161915. if (coef->whole_image[0] != NULL)
  161916. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161917. coef->pub.compress_data = compress_data;
  161918. break;
  161919. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161920. case JBUF_SAVE_AND_PASS:
  161921. if (coef->whole_image[0] == NULL)
  161922. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161923. coef->pub.compress_data = compress_first_pass;
  161924. break;
  161925. case JBUF_CRANK_DEST:
  161926. if (coef->whole_image[0] == NULL)
  161927. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161928. coef->pub.compress_data = compress_output;
  161929. break;
  161930. #endif
  161931. default:
  161932. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161933. break;
  161934. }
  161935. }
  161936. /*
  161937. * Process some data in the single-pass case.
  161938. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161939. * per call, ie, v_samp_factor block rows for each component in the image.
  161940. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161941. *
  161942. * NB: input_buf contains a plane for each component in image,
  161943. * which we index according to the component's SOF position.
  161944. */
  161945. METHODDEF(boolean)
  161946. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161947. {
  161948. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161949. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161950. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161951. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161952. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161953. JDIMENSION ypos, xpos;
  161954. jpeg_component_info *compptr;
  161955. /* Loop to write as much as one whole iMCU row */
  161956. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161957. yoffset++) {
  161958. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161959. MCU_col_num++) {
  161960. /* Determine where data comes from in input_buf and do the DCT thing.
  161961. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161962. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161963. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161964. * specially. The data in them does not matter for image reconstruction,
  161965. * so we fill them with values that will encode to the smallest amount of
  161966. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161967. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161968. */
  161969. blkn = 0;
  161970. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161971. compptr = cinfo->cur_comp_info[ci];
  161972. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161973. : compptr->last_col_width;
  161974. xpos = MCU_col_num * compptr->MCU_sample_width;
  161975. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161976. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161977. if (coef->iMCU_row_num < last_iMCU_row ||
  161978. yoffset+yindex < compptr->last_row_height) {
  161979. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161980. input_buf[compptr->component_index],
  161981. coef->MCU_buffer[blkn],
  161982. ypos, xpos, (JDIMENSION) blockcnt);
  161983. if (blockcnt < compptr->MCU_width) {
  161984. /* Create some dummy blocks at the right edge of the image. */
  161985. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161986. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161987. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161988. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161989. }
  161990. }
  161991. } else {
  161992. /* Create a row of dummy blocks at the bottom of the image. */
  161993. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161994. compptr->MCU_width * SIZEOF(JBLOCK));
  161995. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161996. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161997. }
  161998. }
  161999. blkn += compptr->MCU_width;
  162000. ypos += DCTSIZE;
  162001. }
  162002. }
  162003. /* Try to write the MCU. In event of a suspension failure, we will
  162004. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162005. */
  162006. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162007. /* Suspension forced; update state counters and exit */
  162008. coef->MCU_vert_offset = yoffset;
  162009. coef->mcu_ctr = MCU_col_num;
  162010. return FALSE;
  162011. }
  162012. }
  162013. /* Completed an MCU row, but perhaps not an iMCU row */
  162014. coef->mcu_ctr = 0;
  162015. }
  162016. /* Completed the iMCU row, advance counters for next one */
  162017. coef->iMCU_row_num++;
  162018. start_iMCU_row(cinfo);
  162019. return TRUE;
  162020. }
  162021. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162022. /*
  162023. * Process some data in the first pass of a multi-pass case.
  162024. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162025. * per call, ie, v_samp_factor block rows for each component in the image.
  162026. * This amount of data is read from the source buffer, DCT'd and quantized,
  162027. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162028. * as needed at the right and lower edges. (The dummy blocks are constructed
  162029. * in the virtual arrays, which have been padded appropriately.) This makes
  162030. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162031. *
  162032. * We must also emit the data to the entropy encoder. This is conveniently
  162033. * done by calling compress_output() after we've loaded the current strip
  162034. * of the virtual arrays.
  162035. *
  162036. * NB: input_buf contains a plane for each component in image. All
  162037. * components are DCT'd and loaded into the virtual arrays in this pass.
  162038. * However, it may be that only a subset of the components are emitted to
  162039. * the entropy encoder during this first pass; be careful about looking
  162040. * at the scan-dependent variables (MCU dimensions, etc).
  162041. */
  162042. METHODDEF(boolean)
  162043. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162044. {
  162045. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162046. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162047. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162048. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162049. JCOEF lastDC;
  162050. jpeg_component_info *compptr;
  162051. JBLOCKARRAY buffer;
  162052. JBLOCKROW thisblockrow, lastblockrow;
  162053. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162054. ci++, compptr++) {
  162055. /* Align the virtual buffer for this component. */
  162056. buffer = (*cinfo->mem->access_virt_barray)
  162057. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162058. coef->iMCU_row_num * compptr->v_samp_factor,
  162059. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162060. /* Count non-dummy DCT block rows in this iMCU row. */
  162061. if (coef->iMCU_row_num < last_iMCU_row)
  162062. block_rows = compptr->v_samp_factor;
  162063. else {
  162064. /* NB: can't use last_row_height here, since may not be set! */
  162065. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162066. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162067. }
  162068. blocks_across = compptr->width_in_blocks;
  162069. h_samp_factor = compptr->h_samp_factor;
  162070. /* Count number of dummy blocks to be added at the right margin. */
  162071. ndummy = (int) (blocks_across % h_samp_factor);
  162072. if (ndummy > 0)
  162073. ndummy = h_samp_factor - ndummy;
  162074. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162075. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162076. */
  162077. for (block_row = 0; block_row < block_rows; block_row++) {
  162078. thisblockrow = buffer[block_row];
  162079. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162080. input_buf[ci], thisblockrow,
  162081. (JDIMENSION) (block_row * DCTSIZE),
  162082. (JDIMENSION) 0, blocks_across);
  162083. if (ndummy > 0) {
  162084. /* Create dummy blocks at the right edge of the image. */
  162085. thisblockrow += blocks_across; /* => first dummy block */
  162086. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162087. lastDC = thisblockrow[-1][0];
  162088. for (bi = 0; bi < ndummy; bi++) {
  162089. thisblockrow[bi][0] = lastDC;
  162090. }
  162091. }
  162092. }
  162093. /* If at end of image, create dummy block rows as needed.
  162094. * The tricky part here is that within each MCU, we want the DC values
  162095. * of the dummy blocks to match the last real block's DC value.
  162096. * This squeezes a few more bytes out of the resulting file...
  162097. */
  162098. if (coef->iMCU_row_num == last_iMCU_row) {
  162099. blocks_across += ndummy; /* include lower right corner */
  162100. MCUs_across = blocks_across / h_samp_factor;
  162101. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162102. block_row++) {
  162103. thisblockrow = buffer[block_row];
  162104. lastblockrow = buffer[block_row-1];
  162105. jzero_far((void FAR *) thisblockrow,
  162106. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162107. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162108. lastDC = lastblockrow[h_samp_factor-1][0];
  162109. for (bi = 0; bi < h_samp_factor; bi++) {
  162110. thisblockrow[bi][0] = lastDC;
  162111. }
  162112. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162113. lastblockrow += h_samp_factor;
  162114. }
  162115. }
  162116. }
  162117. }
  162118. /* NB: compress_output will increment iMCU_row_num if successful.
  162119. * A suspension return will result in redoing all the work above next time.
  162120. */
  162121. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162122. return compress_output(cinfo, input_buf);
  162123. }
  162124. /*
  162125. * Process some data in subsequent passes of a multi-pass case.
  162126. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162127. * per call, ie, v_samp_factor block rows for each component in the scan.
  162128. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162129. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162130. *
  162131. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162132. */
  162133. METHODDEF(boolean)
  162134. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162135. {
  162136. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162137. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162138. int blkn, ci, xindex, yindex, yoffset;
  162139. JDIMENSION start_col;
  162140. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162141. JBLOCKROW buffer_ptr;
  162142. jpeg_component_info *compptr;
  162143. /* Align the virtual buffers for the components used in this scan.
  162144. * NB: during first pass, this is safe only because the buffers will
  162145. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162146. */
  162147. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162148. compptr = cinfo->cur_comp_info[ci];
  162149. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162150. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162151. coef->iMCU_row_num * compptr->v_samp_factor,
  162152. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162153. }
  162154. /* Loop to process one whole iMCU row */
  162155. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162156. yoffset++) {
  162157. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162158. MCU_col_num++) {
  162159. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162160. blkn = 0; /* index of current DCT block within MCU */
  162161. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162162. compptr = cinfo->cur_comp_info[ci];
  162163. start_col = MCU_col_num * compptr->MCU_width;
  162164. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162165. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162166. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162167. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162168. }
  162169. }
  162170. }
  162171. /* Try to write the MCU. */
  162172. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162173. /* Suspension forced; update state counters and exit */
  162174. coef->MCU_vert_offset = yoffset;
  162175. coef->mcu_ctr = MCU_col_num;
  162176. return FALSE;
  162177. }
  162178. }
  162179. /* Completed an MCU row, but perhaps not an iMCU row */
  162180. coef->mcu_ctr = 0;
  162181. }
  162182. /* Completed the iMCU row, advance counters for next one */
  162183. coef->iMCU_row_num++;
  162184. start_iMCU_row(cinfo);
  162185. return TRUE;
  162186. }
  162187. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162188. /*
  162189. * Initialize coefficient buffer controller.
  162190. */
  162191. GLOBAL(void)
  162192. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162193. {
  162194. my_coef_ptr coef;
  162195. coef = (my_coef_ptr)
  162196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162197. SIZEOF(my_coef_controller));
  162198. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162199. coef->pub.start_pass = start_pass_coef;
  162200. /* Create the coefficient buffer. */
  162201. if (need_full_buffer) {
  162202. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162203. /* Allocate a full-image virtual array for each component, */
  162204. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162205. int ci;
  162206. jpeg_component_info *compptr;
  162207. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162208. ci++, compptr++) {
  162209. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162210. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162211. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162212. (long) compptr->h_samp_factor),
  162213. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162214. (long) compptr->v_samp_factor),
  162215. (JDIMENSION) compptr->v_samp_factor);
  162216. }
  162217. #else
  162218. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162219. #endif
  162220. } else {
  162221. /* We only need a single-MCU buffer. */
  162222. JBLOCKROW buffer;
  162223. int i;
  162224. buffer = (JBLOCKROW)
  162225. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162226. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162227. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162228. coef->MCU_buffer[i] = buffer + i;
  162229. }
  162230. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162231. }
  162232. }
  162233. /*** End of inlined file: jccoefct.c ***/
  162234. /*** Start of inlined file: jccolor.c ***/
  162235. #define JPEG_INTERNALS
  162236. /* Private subobject */
  162237. typedef struct {
  162238. struct jpeg_color_converter pub; /* public fields */
  162239. /* Private state for RGB->YCC conversion */
  162240. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162241. } my_color_converter;
  162242. typedef my_color_converter * my_cconvert_ptr;
  162243. /**************** RGB -> YCbCr conversion: most common case **************/
  162244. /*
  162245. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162246. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162247. * The conversion equations to be implemented are therefore
  162248. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162249. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162250. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162251. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162252. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162253. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162254. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162255. * were not represented exactly. Now we sacrifice exact representation of
  162256. * maximum red and maximum blue in order to get exact grayscales.
  162257. *
  162258. * To avoid floating-point arithmetic, we represent the fractional constants
  162259. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162260. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162261. *
  162262. * For even more speed, we avoid doing any multiplications in the inner loop
  162263. * by precalculating the constants times R,G,B for all possible values.
  162264. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162265. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162266. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162267. * colorspace anyway.
  162268. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162269. * in the tables to save adding them separately in the inner loop.
  162270. */
  162271. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162272. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162273. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162274. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162275. /* We allocate one big table and divide it up into eight parts, instead of
  162276. * doing eight alloc_small requests. This lets us use a single table base
  162277. * address, which can be held in a register in the inner loops on many
  162278. * machines (more than can hold all eight addresses, anyway).
  162279. */
  162280. #define R_Y_OFF 0 /* offset to R => Y section */
  162281. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162282. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162283. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162284. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162285. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162286. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162287. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162288. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162289. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162290. /*
  162291. * Initialize for RGB->YCC colorspace conversion.
  162292. */
  162293. METHODDEF(void)
  162294. rgb_ycc_start (j_compress_ptr cinfo)
  162295. {
  162296. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162297. INT32 * rgb_ycc_tab;
  162298. INT32 i;
  162299. /* Allocate and fill in the conversion tables. */
  162300. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162301. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162302. (TABLE_SIZE * SIZEOF(INT32)));
  162303. for (i = 0; i <= MAXJSAMPLE; i++) {
  162304. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162305. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162306. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162307. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162308. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162309. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162310. * This ensures that the maximum output will round to MAXJSAMPLE
  162311. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162312. */
  162313. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162314. /* B=>Cb and R=>Cr tables are the same
  162315. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162316. */
  162317. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162318. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162319. }
  162320. }
  162321. /*
  162322. * Convert some rows of samples to the JPEG colorspace.
  162323. *
  162324. * Note that we change from the application's interleaved-pixel format
  162325. * to our internal noninterleaved, one-plane-per-component format.
  162326. * The input buffer is therefore three times as wide as the output buffer.
  162327. *
  162328. * A starting row offset is provided only for the output buffer. The caller
  162329. * can easily adjust the passed input_buf value to accommodate any row
  162330. * offset required on that side.
  162331. */
  162332. METHODDEF(void)
  162333. rgb_ycc_convert (j_compress_ptr cinfo,
  162334. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162335. JDIMENSION output_row, int num_rows)
  162336. {
  162337. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162338. register int r, g, b;
  162339. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162340. register JSAMPROW inptr;
  162341. register JSAMPROW outptr0, outptr1, outptr2;
  162342. register JDIMENSION col;
  162343. JDIMENSION num_cols = cinfo->image_width;
  162344. while (--num_rows >= 0) {
  162345. inptr = *input_buf++;
  162346. outptr0 = output_buf[0][output_row];
  162347. outptr1 = output_buf[1][output_row];
  162348. outptr2 = output_buf[2][output_row];
  162349. output_row++;
  162350. for (col = 0; col < num_cols; col++) {
  162351. r = GETJSAMPLE(inptr[RGB_RED]);
  162352. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162353. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162354. inptr += RGB_PIXELSIZE;
  162355. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162356. * must be too; we do not need an explicit range-limiting operation.
  162357. * Hence the value being shifted is never negative, and we don't
  162358. * need the general RIGHT_SHIFT macro.
  162359. */
  162360. /* Y */
  162361. outptr0[col] = (JSAMPLE)
  162362. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162363. >> SCALEBITS);
  162364. /* Cb */
  162365. outptr1[col] = (JSAMPLE)
  162366. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162367. >> SCALEBITS);
  162368. /* Cr */
  162369. outptr2[col] = (JSAMPLE)
  162370. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162371. >> SCALEBITS);
  162372. }
  162373. }
  162374. }
  162375. /**************** Cases other than RGB -> YCbCr **************/
  162376. /*
  162377. * Convert some rows of samples to the JPEG colorspace.
  162378. * This version handles RGB->grayscale conversion, which is the same
  162379. * as the RGB->Y portion of RGB->YCbCr.
  162380. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162381. */
  162382. METHODDEF(void)
  162383. rgb_gray_convert (j_compress_ptr cinfo,
  162384. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162385. JDIMENSION output_row, int num_rows)
  162386. {
  162387. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162388. register int r, g, b;
  162389. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162390. register JSAMPROW inptr;
  162391. register JSAMPROW outptr;
  162392. register JDIMENSION col;
  162393. JDIMENSION num_cols = cinfo->image_width;
  162394. while (--num_rows >= 0) {
  162395. inptr = *input_buf++;
  162396. outptr = output_buf[0][output_row];
  162397. output_row++;
  162398. for (col = 0; col < num_cols; col++) {
  162399. r = GETJSAMPLE(inptr[RGB_RED]);
  162400. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162401. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162402. inptr += RGB_PIXELSIZE;
  162403. /* Y */
  162404. outptr[col] = (JSAMPLE)
  162405. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162406. >> SCALEBITS);
  162407. }
  162408. }
  162409. }
  162410. /*
  162411. * Convert some rows of samples to the JPEG colorspace.
  162412. * This version handles Adobe-style CMYK->YCCK conversion,
  162413. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162414. * conversion as above, while passing K (black) unchanged.
  162415. * We assume rgb_ycc_start has been called.
  162416. */
  162417. METHODDEF(void)
  162418. cmyk_ycck_convert (j_compress_ptr cinfo,
  162419. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162420. JDIMENSION output_row, int num_rows)
  162421. {
  162422. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162423. register int r, g, b;
  162424. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162425. register JSAMPROW inptr;
  162426. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162427. register JDIMENSION col;
  162428. JDIMENSION num_cols = cinfo->image_width;
  162429. while (--num_rows >= 0) {
  162430. inptr = *input_buf++;
  162431. outptr0 = output_buf[0][output_row];
  162432. outptr1 = output_buf[1][output_row];
  162433. outptr2 = output_buf[2][output_row];
  162434. outptr3 = output_buf[3][output_row];
  162435. output_row++;
  162436. for (col = 0; col < num_cols; col++) {
  162437. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162438. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162439. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162440. /* K passes through as-is */
  162441. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162442. inptr += 4;
  162443. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162444. * must be too; we do not need an explicit range-limiting operation.
  162445. * Hence the value being shifted is never negative, and we don't
  162446. * need the general RIGHT_SHIFT macro.
  162447. */
  162448. /* Y */
  162449. outptr0[col] = (JSAMPLE)
  162450. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162451. >> SCALEBITS);
  162452. /* Cb */
  162453. outptr1[col] = (JSAMPLE)
  162454. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162455. >> SCALEBITS);
  162456. /* Cr */
  162457. outptr2[col] = (JSAMPLE)
  162458. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162459. >> SCALEBITS);
  162460. }
  162461. }
  162462. }
  162463. /*
  162464. * Convert some rows of samples to the JPEG colorspace.
  162465. * This version handles grayscale output with no conversion.
  162466. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162467. */
  162468. METHODDEF(void)
  162469. grayscale_convert (j_compress_ptr cinfo,
  162470. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162471. JDIMENSION output_row, int num_rows)
  162472. {
  162473. register JSAMPROW inptr;
  162474. register JSAMPROW outptr;
  162475. register JDIMENSION col;
  162476. JDIMENSION num_cols = cinfo->image_width;
  162477. int instride = cinfo->input_components;
  162478. while (--num_rows >= 0) {
  162479. inptr = *input_buf++;
  162480. outptr = output_buf[0][output_row];
  162481. output_row++;
  162482. for (col = 0; col < num_cols; col++) {
  162483. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162484. inptr += instride;
  162485. }
  162486. }
  162487. }
  162488. /*
  162489. * Convert some rows of samples to the JPEG colorspace.
  162490. * This version handles multi-component colorspaces without conversion.
  162491. * We assume input_components == num_components.
  162492. */
  162493. METHODDEF(void)
  162494. null_convert (j_compress_ptr cinfo,
  162495. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162496. JDIMENSION output_row, int num_rows)
  162497. {
  162498. register JSAMPROW inptr;
  162499. register JSAMPROW outptr;
  162500. register JDIMENSION col;
  162501. register int ci;
  162502. int nc = cinfo->num_components;
  162503. JDIMENSION num_cols = cinfo->image_width;
  162504. while (--num_rows >= 0) {
  162505. /* It seems fastest to make a separate pass for each component. */
  162506. for (ci = 0; ci < nc; ci++) {
  162507. inptr = *input_buf;
  162508. outptr = output_buf[ci][output_row];
  162509. for (col = 0; col < num_cols; col++) {
  162510. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162511. inptr += nc;
  162512. }
  162513. }
  162514. input_buf++;
  162515. output_row++;
  162516. }
  162517. }
  162518. /*
  162519. * Empty method for start_pass.
  162520. */
  162521. METHODDEF(void)
  162522. null_method (j_compress_ptr)
  162523. {
  162524. /* no work needed */
  162525. }
  162526. /*
  162527. * Module initialization routine for input colorspace conversion.
  162528. */
  162529. GLOBAL(void)
  162530. jinit_color_converter (j_compress_ptr cinfo)
  162531. {
  162532. my_cconvert_ptr cconvert;
  162533. cconvert = (my_cconvert_ptr)
  162534. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162535. SIZEOF(my_color_converter));
  162536. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162537. /* set start_pass to null method until we find out differently */
  162538. cconvert->pub.start_pass = null_method;
  162539. /* Make sure input_components agrees with in_color_space */
  162540. switch (cinfo->in_color_space) {
  162541. case JCS_GRAYSCALE:
  162542. if (cinfo->input_components != 1)
  162543. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162544. break;
  162545. case JCS_RGB:
  162546. #if RGB_PIXELSIZE != 3
  162547. if (cinfo->input_components != RGB_PIXELSIZE)
  162548. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162549. break;
  162550. #endif /* else share code with YCbCr */
  162551. case JCS_YCbCr:
  162552. if (cinfo->input_components != 3)
  162553. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162554. break;
  162555. case JCS_CMYK:
  162556. case JCS_YCCK:
  162557. if (cinfo->input_components != 4)
  162558. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162559. break;
  162560. default: /* JCS_UNKNOWN can be anything */
  162561. if (cinfo->input_components < 1)
  162562. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162563. break;
  162564. }
  162565. /* Check num_components, set conversion method based on requested space */
  162566. switch (cinfo->jpeg_color_space) {
  162567. case JCS_GRAYSCALE:
  162568. if (cinfo->num_components != 1)
  162569. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162570. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162571. cconvert->pub.color_convert = grayscale_convert;
  162572. else if (cinfo->in_color_space == JCS_RGB) {
  162573. cconvert->pub.start_pass = rgb_ycc_start;
  162574. cconvert->pub.color_convert = rgb_gray_convert;
  162575. } else if (cinfo->in_color_space == JCS_YCbCr)
  162576. cconvert->pub.color_convert = grayscale_convert;
  162577. else
  162578. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162579. break;
  162580. case JCS_RGB:
  162581. if (cinfo->num_components != 3)
  162582. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162583. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162584. cconvert->pub.color_convert = null_convert;
  162585. else
  162586. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162587. break;
  162588. case JCS_YCbCr:
  162589. if (cinfo->num_components != 3)
  162590. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162591. if (cinfo->in_color_space == JCS_RGB) {
  162592. cconvert->pub.start_pass = rgb_ycc_start;
  162593. cconvert->pub.color_convert = rgb_ycc_convert;
  162594. } else if (cinfo->in_color_space == JCS_YCbCr)
  162595. cconvert->pub.color_convert = null_convert;
  162596. else
  162597. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162598. break;
  162599. case JCS_CMYK:
  162600. if (cinfo->num_components != 4)
  162601. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162602. if (cinfo->in_color_space == JCS_CMYK)
  162603. cconvert->pub.color_convert = null_convert;
  162604. else
  162605. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162606. break;
  162607. case JCS_YCCK:
  162608. if (cinfo->num_components != 4)
  162609. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162610. if (cinfo->in_color_space == JCS_CMYK) {
  162611. cconvert->pub.start_pass = rgb_ycc_start;
  162612. cconvert->pub.color_convert = cmyk_ycck_convert;
  162613. } else if (cinfo->in_color_space == JCS_YCCK)
  162614. cconvert->pub.color_convert = null_convert;
  162615. else
  162616. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162617. break;
  162618. default: /* allow null conversion of JCS_UNKNOWN */
  162619. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162620. cinfo->num_components != cinfo->input_components)
  162621. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162622. cconvert->pub.color_convert = null_convert;
  162623. break;
  162624. }
  162625. }
  162626. /*** End of inlined file: jccolor.c ***/
  162627. #undef FIX
  162628. /*** Start of inlined file: jcdctmgr.c ***/
  162629. #define JPEG_INTERNALS
  162630. /*** Start of inlined file: jdct.h ***/
  162631. /*
  162632. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162633. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162634. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162635. * implementations use an array of type FAST_FLOAT, instead.)
  162636. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162637. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162638. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162639. * convention improves accuracy in integer implementations and saves some
  162640. * work in floating-point ones.
  162641. * Quantization of the output coefficients is done by jcdctmgr.c.
  162642. */
  162643. #ifndef __jdct_h__
  162644. #define __jdct_h__
  162645. #if BITS_IN_JSAMPLE == 8
  162646. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162647. #else
  162648. typedef INT32 DCTELEM; /* must have 32 bits */
  162649. #endif
  162650. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162651. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162652. /*
  162653. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162654. * to an output sample array. The routine must dequantize the input data as
  162655. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162656. * pointed to by compptr->dct_table. The output data is to be placed into the
  162657. * sample array starting at a specified column. (Any row offset needed will
  162658. * be applied to the array pointer before it is passed to the IDCT code.)
  162659. * Note that the number of samples emitted by the IDCT routine is
  162660. * DCT_scaled_size * DCT_scaled_size.
  162661. */
  162662. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162663. /*
  162664. * Each IDCT routine has its own ideas about the best dct_table element type.
  162665. */
  162666. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162667. #if BITS_IN_JSAMPLE == 8
  162668. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162669. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162670. #else
  162671. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162672. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162673. #endif
  162674. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162675. /*
  162676. * Each IDCT routine is responsible for range-limiting its results and
  162677. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162678. * be quite far out of range if the input data is corrupt, so a bulletproof
  162679. * range-limiting step is required. We use a mask-and-table-lookup method
  162680. * to do the combined operations quickly. See the comments with
  162681. * prepare_range_limit_table (in jdmaster.c) for more info.
  162682. */
  162683. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162684. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162685. /* Short forms of external names for systems with brain-damaged linkers. */
  162686. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162687. #define jpeg_fdct_islow jFDislow
  162688. #define jpeg_fdct_ifast jFDifast
  162689. #define jpeg_fdct_float jFDfloat
  162690. #define jpeg_idct_islow jRDislow
  162691. #define jpeg_idct_ifast jRDifast
  162692. #define jpeg_idct_float jRDfloat
  162693. #define jpeg_idct_4x4 jRD4x4
  162694. #define jpeg_idct_2x2 jRD2x2
  162695. #define jpeg_idct_1x1 jRD1x1
  162696. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162697. /* Extern declarations for the forward and inverse DCT routines. */
  162698. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162699. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162700. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162701. EXTERN(void) jpeg_idct_islow
  162702. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162703. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162704. EXTERN(void) jpeg_idct_ifast
  162705. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162706. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162707. EXTERN(void) jpeg_idct_float
  162708. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162709. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162710. EXTERN(void) jpeg_idct_4x4
  162711. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162712. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162713. EXTERN(void) jpeg_idct_2x2
  162714. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162715. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162716. EXTERN(void) jpeg_idct_1x1
  162717. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162718. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162719. /*
  162720. * Macros for handling fixed-point arithmetic; these are used by many
  162721. * but not all of the DCT/IDCT modules.
  162722. *
  162723. * All values are expected to be of type INT32.
  162724. * Fractional constants are scaled left by CONST_BITS bits.
  162725. * CONST_BITS is defined within each module using these macros,
  162726. * and may differ from one module to the next.
  162727. */
  162728. #define ONE ((INT32) 1)
  162729. #define CONST_SCALE (ONE << CONST_BITS)
  162730. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162731. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162732. * thus causing a lot of useless floating-point operations at run time.
  162733. */
  162734. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162735. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162736. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162737. * the fudge factor is correct for either sign of X.
  162738. */
  162739. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162740. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162741. * This macro is used only when the two inputs will actually be no more than
  162742. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162743. * full 32x32 multiply. This provides a useful speedup on many machines.
  162744. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162745. * in C, but some C compilers will do the right thing if you provide the
  162746. * correct combination of casts.
  162747. */
  162748. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162749. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162750. #endif
  162751. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162752. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162753. #endif
  162754. #ifndef MULTIPLY16C16 /* default definition */
  162755. #define MULTIPLY16C16(var,const) ((var) * (const))
  162756. #endif
  162757. /* Same except both inputs are variables. */
  162758. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162759. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162760. #endif
  162761. #ifndef MULTIPLY16V16 /* default definition */
  162762. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162763. #endif
  162764. #endif
  162765. /*** End of inlined file: jdct.h ***/
  162766. /* Private declarations for DCT subsystem */
  162767. /* Private subobject for this module */
  162768. typedef struct {
  162769. struct jpeg_forward_dct pub; /* public fields */
  162770. /* Pointer to the DCT routine actually in use */
  162771. forward_DCT_method_ptr do_dct;
  162772. /* The actual post-DCT divisors --- not identical to the quant table
  162773. * entries, because of scaling (especially for an unnormalized DCT).
  162774. * Each table is given in normal array order.
  162775. */
  162776. DCTELEM * divisors[NUM_QUANT_TBLS];
  162777. #ifdef DCT_FLOAT_SUPPORTED
  162778. /* Same as above for the floating-point case. */
  162779. float_DCT_method_ptr do_float_dct;
  162780. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162781. #endif
  162782. } my_fdct_controller;
  162783. typedef my_fdct_controller * my_fdct_ptr;
  162784. /*
  162785. * Initialize for a processing pass.
  162786. * Verify that all referenced Q-tables are present, and set up
  162787. * the divisor table for each one.
  162788. * In the current implementation, DCT of all components is done during
  162789. * the first pass, even if only some components will be output in the
  162790. * first scan. Hence all components should be examined here.
  162791. */
  162792. METHODDEF(void)
  162793. start_pass_fdctmgr (j_compress_ptr cinfo)
  162794. {
  162795. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162796. int ci, qtblno, i;
  162797. jpeg_component_info *compptr;
  162798. JQUANT_TBL * qtbl;
  162799. DCTELEM * dtbl;
  162800. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162801. ci++, compptr++) {
  162802. qtblno = compptr->quant_tbl_no;
  162803. /* Make sure specified quantization table is present */
  162804. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162805. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162806. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162807. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162808. /* Compute divisors for this quant table */
  162809. /* We may do this more than once for same table, but it's not a big deal */
  162810. switch (cinfo->dct_method) {
  162811. #ifdef DCT_ISLOW_SUPPORTED
  162812. case JDCT_ISLOW:
  162813. /* For LL&M IDCT method, divisors are equal to raw quantization
  162814. * coefficients multiplied by 8 (to counteract scaling).
  162815. */
  162816. if (fdct->divisors[qtblno] == NULL) {
  162817. fdct->divisors[qtblno] = (DCTELEM *)
  162818. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162819. DCTSIZE2 * SIZEOF(DCTELEM));
  162820. }
  162821. dtbl = fdct->divisors[qtblno];
  162822. for (i = 0; i < DCTSIZE2; i++) {
  162823. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162824. }
  162825. break;
  162826. #endif
  162827. #ifdef DCT_IFAST_SUPPORTED
  162828. case JDCT_IFAST:
  162829. {
  162830. /* For AA&N IDCT method, divisors are equal to quantization
  162831. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162832. * scalefactor[0] = 1
  162833. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162834. * We apply a further scale factor of 8.
  162835. */
  162836. #define CONST_BITS 14
  162837. static const INT16 aanscales[DCTSIZE2] = {
  162838. /* precomputed values scaled up by 14 bits */
  162839. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162840. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162841. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162842. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162843. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162844. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162845. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162846. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162847. };
  162848. SHIFT_TEMPS
  162849. if (fdct->divisors[qtblno] == NULL) {
  162850. fdct->divisors[qtblno] = (DCTELEM *)
  162851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162852. DCTSIZE2 * SIZEOF(DCTELEM));
  162853. }
  162854. dtbl = fdct->divisors[qtblno];
  162855. for (i = 0; i < DCTSIZE2; i++) {
  162856. dtbl[i] = (DCTELEM)
  162857. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162858. (INT32) aanscales[i]),
  162859. CONST_BITS-3);
  162860. }
  162861. }
  162862. break;
  162863. #endif
  162864. #ifdef DCT_FLOAT_SUPPORTED
  162865. case JDCT_FLOAT:
  162866. {
  162867. /* For float AA&N IDCT method, divisors are equal to quantization
  162868. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162869. * scalefactor[0] = 1
  162870. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162871. * We apply a further scale factor of 8.
  162872. * What's actually stored is 1/divisor so that the inner loop can
  162873. * use a multiplication rather than a division.
  162874. */
  162875. FAST_FLOAT * fdtbl;
  162876. int row, col;
  162877. static const double aanscalefactor[DCTSIZE] = {
  162878. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162879. 1.0, 0.785694958, 0.541196100, 0.275899379
  162880. };
  162881. if (fdct->float_divisors[qtblno] == NULL) {
  162882. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162884. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162885. }
  162886. fdtbl = fdct->float_divisors[qtblno];
  162887. i = 0;
  162888. for (row = 0; row < DCTSIZE; row++) {
  162889. for (col = 0; col < DCTSIZE; col++) {
  162890. fdtbl[i] = (FAST_FLOAT)
  162891. (1.0 / (((double) qtbl->quantval[i] *
  162892. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162893. i++;
  162894. }
  162895. }
  162896. }
  162897. break;
  162898. #endif
  162899. default:
  162900. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162901. break;
  162902. }
  162903. }
  162904. }
  162905. /*
  162906. * Perform forward DCT on one or more blocks of a component.
  162907. *
  162908. * The input samples are taken from the sample_data[] array starting at
  162909. * position start_row/start_col, and moving to the right for any additional
  162910. * blocks. The quantized coefficients are returned in coef_blocks[].
  162911. */
  162912. METHODDEF(void)
  162913. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162914. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162915. JDIMENSION start_row, JDIMENSION start_col,
  162916. JDIMENSION num_blocks)
  162917. /* This version is used for integer DCT implementations. */
  162918. {
  162919. /* This routine is heavily used, so it's worth coding it tightly. */
  162920. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162921. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162922. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162923. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162924. JDIMENSION bi;
  162925. sample_data += start_row; /* fold in the vertical offset once */
  162926. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162927. /* Load data into workspace, applying unsigned->signed conversion */
  162928. { register DCTELEM *workspaceptr;
  162929. register JSAMPROW elemptr;
  162930. register int elemr;
  162931. workspaceptr = workspace;
  162932. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162933. elemptr = sample_data[elemr] + start_col;
  162934. #if DCTSIZE == 8 /* unroll the inner loop */
  162935. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162936. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162937. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162938. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162939. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162940. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162941. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162942. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162943. #else
  162944. { register int elemc;
  162945. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162946. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162947. }
  162948. }
  162949. #endif
  162950. }
  162951. }
  162952. /* Perform the DCT */
  162953. (*do_dct) (workspace);
  162954. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162955. { register DCTELEM temp, qval;
  162956. register int i;
  162957. register JCOEFPTR output_ptr = coef_blocks[bi];
  162958. for (i = 0; i < DCTSIZE2; i++) {
  162959. qval = divisors[i];
  162960. temp = workspace[i];
  162961. /* Divide the coefficient value by qval, ensuring proper rounding.
  162962. * Since C does not specify the direction of rounding for negative
  162963. * quotients, we have to force the dividend positive for portability.
  162964. *
  162965. * In most files, at least half of the output values will be zero
  162966. * (at default quantization settings, more like three-quarters...)
  162967. * so we should ensure that this case is fast. On many machines,
  162968. * a comparison is enough cheaper than a divide to make a special test
  162969. * a win. Since both inputs will be nonnegative, we need only test
  162970. * for a < b to discover whether a/b is 0.
  162971. * If your machine's division is fast enough, define FAST_DIVIDE.
  162972. */
  162973. #ifdef FAST_DIVIDE
  162974. #define DIVIDE_BY(a,b) a /= b
  162975. #else
  162976. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162977. #endif
  162978. if (temp < 0) {
  162979. temp = -temp;
  162980. temp += qval>>1; /* for rounding */
  162981. DIVIDE_BY(temp, qval);
  162982. temp = -temp;
  162983. } else {
  162984. temp += qval>>1; /* for rounding */
  162985. DIVIDE_BY(temp, qval);
  162986. }
  162987. output_ptr[i] = (JCOEF) temp;
  162988. }
  162989. }
  162990. }
  162991. }
  162992. #ifdef DCT_FLOAT_SUPPORTED
  162993. METHODDEF(void)
  162994. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162995. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162996. JDIMENSION start_row, JDIMENSION start_col,
  162997. JDIMENSION num_blocks)
  162998. /* This version is used for floating-point DCT implementations. */
  162999. {
  163000. /* This routine is heavily used, so it's worth coding it tightly. */
  163001. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163002. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163003. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163004. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163005. JDIMENSION bi;
  163006. sample_data += start_row; /* fold in the vertical offset once */
  163007. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163008. /* Load data into workspace, applying unsigned->signed conversion */
  163009. { register FAST_FLOAT *workspaceptr;
  163010. register JSAMPROW elemptr;
  163011. register int elemr;
  163012. workspaceptr = workspace;
  163013. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163014. elemptr = sample_data[elemr] + start_col;
  163015. #if DCTSIZE == 8 /* unroll the inner loop */
  163016. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163017. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163018. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163019. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163020. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163021. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163022. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163023. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163024. #else
  163025. { register int elemc;
  163026. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163027. *workspaceptr++ = (FAST_FLOAT)
  163028. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163029. }
  163030. }
  163031. #endif
  163032. }
  163033. }
  163034. /* Perform the DCT */
  163035. (*do_dct) (workspace);
  163036. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163037. { register FAST_FLOAT temp;
  163038. register int i;
  163039. register JCOEFPTR output_ptr = coef_blocks[bi];
  163040. for (i = 0; i < DCTSIZE2; i++) {
  163041. /* Apply the quantization and scaling factor */
  163042. temp = workspace[i] * divisors[i];
  163043. /* Round to nearest integer.
  163044. * Since C does not specify the direction of rounding for negative
  163045. * quotients, we have to force the dividend positive for portability.
  163046. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163047. * code should work for either 16-bit or 32-bit ints.
  163048. */
  163049. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163050. }
  163051. }
  163052. }
  163053. }
  163054. #endif /* DCT_FLOAT_SUPPORTED */
  163055. /*
  163056. * Initialize FDCT manager.
  163057. */
  163058. GLOBAL(void)
  163059. jinit_forward_dct (j_compress_ptr cinfo)
  163060. {
  163061. my_fdct_ptr fdct;
  163062. int i;
  163063. fdct = (my_fdct_ptr)
  163064. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163065. SIZEOF(my_fdct_controller));
  163066. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163067. fdct->pub.start_pass = start_pass_fdctmgr;
  163068. switch (cinfo->dct_method) {
  163069. #ifdef DCT_ISLOW_SUPPORTED
  163070. case JDCT_ISLOW:
  163071. fdct->pub.forward_DCT = forward_DCT;
  163072. fdct->do_dct = jpeg_fdct_islow;
  163073. break;
  163074. #endif
  163075. #ifdef DCT_IFAST_SUPPORTED
  163076. case JDCT_IFAST:
  163077. fdct->pub.forward_DCT = forward_DCT;
  163078. fdct->do_dct = jpeg_fdct_ifast;
  163079. break;
  163080. #endif
  163081. #ifdef DCT_FLOAT_SUPPORTED
  163082. case JDCT_FLOAT:
  163083. fdct->pub.forward_DCT = forward_DCT_float;
  163084. fdct->do_float_dct = jpeg_fdct_float;
  163085. break;
  163086. #endif
  163087. default:
  163088. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163089. break;
  163090. }
  163091. /* Mark divisor tables unallocated */
  163092. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163093. fdct->divisors[i] = NULL;
  163094. #ifdef DCT_FLOAT_SUPPORTED
  163095. fdct->float_divisors[i] = NULL;
  163096. #endif
  163097. }
  163098. }
  163099. /*** End of inlined file: jcdctmgr.c ***/
  163100. #undef CONST_BITS
  163101. /*** Start of inlined file: jchuff.c ***/
  163102. #define JPEG_INTERNALS
  163103. /*** Start of inlined file: jchuff.h ***/
  163104. /* The legal range of a DCT coefficient is
  163105. * -1024 .. +1023 for 8-bit data;
  163106. * -16384 .. +16383 for 12-bit data.
  163107. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163108. */
  163109. #ifndef _jchuff_h_
  163110. #define _jchuff_h_
  163111. #if BITS_IN_JSAMPLE == 8
  163112. #define MAX_COEF_BITS 10
  163113. #else
  163114. #define MAX_COEF_BITS 14
  163115. #endif
  163116. /* Derived data constructed for each Huffman table */
  163117. typedef struct {
  163118. unsigned int ehufco[256]; /* code for each symbol */
  163119. char ehufsi[256]; /* length of code for each symbol */
  163120. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163121. } c_derived_tbl;
  163122. /* Short forms of external names for systems with brain-damaged linkers. */
  163123. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163124. #define jpeg_make_c_derived_tbl jMkCDerived
  163125. #define jpeg_gen_optimal_table jGenOptTbl
  163126. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163127. /* Expand a Huffman table definition into the derived format */
  163128. EXTERN(void) jpeg_make_c_derived_tbl
  163129. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163130. c_derived_tbl ** pdtbl));
  163131. /* Generate an optimal table definition given the specified counts */
  163132. EXTERN(void) jpeg_gen_optimal_table
  163133. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163134. #endif
  163135. /*** End of inlined file: jchuff.h ***/
  163136. /* Declarations shared with jcphuff.c */
  163137. /* Expanded entropy encoder object for Huffman encoding.
  163138. *
  163139. * The savable_state subrecord contains fields that change within an MCU,
  163140. * but must not be updated permanently until we complete the MCU.
  163141. */
  163142. typedef struct {
  163143. INT32 put_buffer; /* current bit-accumulation buffer */
  163144. int put_bits; /* # of bits now in it */
  163145. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163146. } savable_state;
  163147. /* This macro is to work around compilers with missing or broken
  163148. * structure assignment. You'll need to fix this code if you have
  163149. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163150. */
  163151. #ifndef NO_STRUCT_ASSIGN
  163152. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163153. #else
  163154. #if MAX_COMPS_IN_SCAN == 4
  163155. #define ASSIGN_STATE(dest,src) \
  163156. ((dest).put_buffer = (src).put_buffer, \
  163157. (dest).put_bits = (src).put_bits, \
  163158. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163159. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163160. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163161. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163162. #endif
  163163. #endif
  163164. typedef struct {
  163165. struct jpeg_entropy_encoder pub; /* public fields */
  163166. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163167. /* These fields are NOT loaded into local working state. */
  163168. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163169. int next_restart_num; /* next restart number to write (0-7) */
  163170. /* Pointers to derived tables (these workspaces have image lifespan) */
  163171. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163172. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163173. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163174. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163175. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163176. #endif
  163177. } huff_entropy_encoder;
  163178. typedef huff_entropy_encoder * huff_entropy_ptr;
  163179. /* Working state while writing an MCU.
  163180. * This struct contains all the fields that are needed by subroutines.
  163181. */
  163182. typedef struct {
  163183. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163184. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163185. savable_state cur; /* Current bit buffer & DC state */
  163186. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163187. } working_state;
  163188. /* Forward declarations */
  163189. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163190. JBLOCKROW *MCU_data));
  163191. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163192. #ifdef ENTROPY_OPT_SUPPORTED
  163193. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163194. JBLOCKROW *MCU_data));
  163195. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163196. #endif
  163197. /*
  163198. * Initialize for a Huffman-compressed scan.
  163199. * If gather_statistics is TRUE, we do not output anything during the scan,
  163200. * just count the Huffman symbols used and generate Huffman code tables.
  163201. */
  163202. METHODDEF(void)
  163203. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163204. {
  163205. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163206. int ci, dctbl, actbl;
  163207. jpeg_component_info * compptr;
  163208. if (gather_statistics) {
  163209. #ifdef ENTROPY_OPT_SUPPORTED
  163210. entropy->pub.encode_mcu = encode_mcu_gather;
  163211. entropy->pub.finish_pass = finish_pass_gather;
  163212. #else
  163213. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163214. #endif
  163215. } else {
  163216. entropy->pub.encode_mcu = encode_mcu_huff;
  163217. entropy->pub.finish_pass = finish_pass_huff;
  163218. }
  163219. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163220. compptr = cinfo->cur_comp_info[ci];
  163221. dctbl = compptr->dc_tbl_no;
  163222. actbl = compptr->ac_tbl_no;
  163223. if (gather_statistics) {
  163224. #ifdef ENTROPY_OPT_SUPPORTED
  163225. /* Check for invalid table indexes */
  163226. /* (make_c_derived_tbl does this in the other path) */
  163227. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163228. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163229. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163230. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163231. /* Allocate and zero the statistics tables */
  163232. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163233. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163234. entropy->dc_count_ptrs[dctbl] = (long *)
  163235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163236. 257 * SIZEOF(long));
  163237. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163238. if (entropy->ac_count_ptrs[actbl] == NULL)
  163239. entropy->ac_count_ptrs[actbl] = (long *)
  163240. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163241. 257 * SIZEOF(long));
  163242. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163243. #endif
  163244. } else {
  163245. /* Compute derived values for Huffman tables */
  163246. /* We may do this more than once for a table, but it's not expensive */
  163247. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163248. & entropy->dc_derived_tbls[dctbl]);
  163249. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163250. & entropy->ac_derived_tbls[actbl]);
  163251. }
  163252. /* Initialize DC predictions to 0 */
  163253. entropy->saved.last_dc_val[ci] = 0;
  163254. }
  163255. /* Initialize bit buffer to empty */
  163256. entropy->saved.put_buffer = 0;
  163257. entropy->saved.put_bits = 0;
  163258. /* Initialize restart stuff */
  163259. entropy->restarts_to_go = cinfo->restart_interval;
  163260. entropy->next_restart_num = 0;
  163261. }
  163262. /*
  163263. * Compute the derived values for a Huffman table.
  163264. * This routine also performs some validation checks on the table.
  163265. *
  163266. * Note this is also used by jcphuff.c.
  163267. */
  163268. GLOBAL(void)
  163269. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163270. c_derived_tbl ** pdtbl)
  163271. {
  163272. JHUFF_TBL *htbl;
  163273. c_derived_tbl *dtbl;
  163274. int p, i, l, lastp, si, maxsymbol;
  163275. char huffsize[257];
  163276. unsigned int huffcode[257];
  163277. unsigned int code;
  163278. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163279. * paralleling the order of the symbols themselves in htbl->huffval[].
  163280. */
  163281. /* Find the input Huffman table */
  163282. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163283. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163284. htbl =
  163285. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163286. if (htbl == NULL)
  163287. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163288. /* Allocate a workspace if we haven't already done so. */
  163289. if (*pdtbl == NULL)
  163290. *pdtbl = (c_derived_tbl *)
  163291. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163292. SIZEOF(c_derived_tbl));
  163293. dtbl = *pdtbl;
  163294. /* Figure C.1: make table of Huffman code length for each symbol */
  163295. p = 0;
  163296. for (l = 1; l <= 16; l++) {
  163297. i = (int) htbl->bits[l];
  163298. if (i < 0 || p + i > 256) /* protect against table overrun */
  163299. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163300. while (i--)
  163301. huffsize[p++] = (char) l;
  163302. }
  163303. huffsize[p] = 0;
  163304. lastp = p;
  163305. /* Figure C.2: generate the codes themselves */
  163306. /* We also validate that the counts represent a legal Huffman code tree. */
  163307. code = 0;
  163308. si = huffsize[0];
  163309. p = 0;
  163310. while (huffsize[p]) {
  163311. while (((int) huffsize[p]) == si) {
  163312. huffcode[p++] = code;
  163313. code++;
  163314. }
  163315. /* code is now 1 more than the last code used for codelength si; but
  163316. * it must still fit in si bits, since no code is allowed to be all ones.
  163317. */
  163318. if (((INT32) code) >= (((INT32) 1) << si))
  163319. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163320. code <<= 1;
  163321. si++;
  163322. }
  163323. /* Figure C.3: generate encoding tables */
  163324. /* These are code and size indexed by symbol value */
  163325. /* Set all codeless symbols to have code length 0;
  163326. * this lets us detect duplicate VAL entries here, and later
  163327. * allows emit_bits to detect any attempt to emit such symbols.
  163328. */
  163329. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163330. /* This is also a convenient place to check for out-of-range
  163331. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163332. * but only 0..15 for DC. (We could constrain them further
  163333. * based on data depth and mode, but this seems enough.)
  163334. */
  163335. maxsymbol = isDC ? 15 : 255;
  163336. for (p = 0; p < lastp; p++) {
  163337. i = htbl->huffval[p];
  163338. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163339. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163340. dtbl->ehufco[i] = huffcode[p];
  163341. dtbl->ehufsi[i] = huffsize[p];
  163342. }
  163343. }
  163344. /* Outputting bytes to the file */
  163345. /* Emit a byte, taking 'action' if must suspend. */
  163346. #define emit_byte(state,val,action) \
  163347. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163348. if (--(state)->free_in_buffer == 0) \
  163349. if (! dump_buffer(state)) \
  163350. { action; } }
  163351. LOCAL(boolean)
  163352. dump_buffer (working_state * state)
  163353. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163354. {
  163355. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163356. if (! (*dest->empty_output_buffer) (state->cinfo))
  163357. return FALSE;
  163358. /* After a successful buffer dump, must reset buffer pointers */
  163359. state->next_output_byte = dest->next_output_byte;
  163360. state->free_in_buffer = dest->free_in_buffer;
  163361. return TRUE;
  163362. }
  163363. /* Outputting bits to the file */
  163364. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163365. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163366. * in one call, and we never retain more than 7 bits in put_buffer
  163367. * between calls, so 24 bits are sufficient.
  163368. */
  163369. INLINE
  163370. LOCAL(boolean)
  163371. emit_bits (working_state * state, unsigned int code, int size)
  163372. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163373. {
  163374. /* This routine is heavily used, so it's worth coding tightly. */
  163375. register INT32 put_buffer = (INT32) code;
  163376. register int put_bits = state->cur.put_bits;
  163377. /* if size is 0, caller used an invalid Huffman table entry */
  163378. if (size == 0)
  163379. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163380. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163381. put_bits += size; /* new number of bits in buffer */
  163382. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163383. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163384. while (put_bits >= 8) {
  163385. int c = (int) ((put_buffer >> 16) & 0xFF);
  163386. emit_byte(state, c, return FALSE);
  163387. if (c == 0xFF) { /* need to stuff a zero byte? */
  163388. emit_byte(state, 0, return FALSE);
  163389. }
  163390. put_buffer <<= 8;
  163391. put_bits -= 8;
  163392. }
  163393. state->cur.put_buffer = put_buffer; /* update state variables */
  163394. state->cur.put_bits = put_bits;
  163395. return TRUE;
  163396. }
  163397. LOCAL(boolean)
  163398. flush_bits (working_state * state)
  163399. {
  163400. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163401. return FALSE;
  163402. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163403. state->cur.put_bits = 0;
  163404. return TRUE;
  163405. }
  163406. /* Encode a single block's worth of coefficients */
  163407. LOCAL(boolean)
  163408. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163409. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163410. {
  163411. register int temp, temp2;
  163412. register int nbits;
  163413. register int k, r, i;
  163414. /* Encode the DC coefficient difference per section F.1.2.1 */
  163415. temp = temp2 = block[0] - last_dc_val;
  163416. if (temp < 0) {
  163417. temp = -temp; /* temp is abs value of input */
  163418. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163419. /* This code assumes we are on a two's complement machine */
  163420. temp2--;
  163421. }
  163422. /* Find the number of bits needed for the magnitude of the coefficient */
  163423. nbits = 0;
  163424. while (temp) {
  163425. nbits++;
  163426. temp >>= 1;
  163427. }
  163428. /* Check for out-of-range coefficient values.
  163429. * Since we're encoding a difference, the range limit is twice as much.
  163430. */
  163431. if (nbits > MAX_COEF_BITS+1)
  163432. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163433. /* Emit the Huffman-coded symbol for the number of bits */
  163434. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163435. return FALSE;
  163436. /* Emit that number of bits of the value, if positive, */
  163437. /* or the complement of its magnitude, if negative. */
  163438. if (nbits) /* emit_bits rejects calls with size 0 */
  163439. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163440. return FALSE;
  163441. /* Encode the AC coefficients per section F.1.2.2 */
  163442. r = 0; /* r = run length of zeros */
  163443. for (k = 1; k < DCTSIZE2; k++) {
  163444. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163445. r++;
  163446. } else {
  163447. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163448. while (r > 15) {
  163449. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163450. return FALSE;
  163451. r -= 16;
  163452. }
  163453. temp2 = temp;
  163454. if (temp < 0) {
  163455. temp = -temp; /* temp is abs value of input */
  163456. /* This code assumes we are on a two's complement machine */
  163457. temp2--;
  163458. }
  163459. /* Find the number of bits needed for the magnitude of the coefficient */
  163460. nbits = 1; /* there must be at least one 1 bit */
  163461. while ((temp >>= 1))
  163462. nbits++;
  163463. /* Check for out-of-range coefficient values */
  163464. if (nbits > MAX_COEF_BITS)
  163465. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163466. /* Emit Huffman symbol for run length / number of bits */
  163467. i = (r << 4) + nbits;
  163468. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163469. return FALSE;
  163470. /* Emit that number of bits of the value, if positive, */
  163471. /* or the complement of its magnitude, if negative. */
  163472. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163473. return FALSE;
  163474. r = 0;
  163475. }
  163476. }
  163477. /* If the last coef(s) were zero, emit an end-of-block code */
  163478. if (r > 0)
  163479. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163480. return FALSE;
  163481. return TRUE;
  163482. }
  163483. /*
  163484. * Emit a restart marker & resynchronize predictions.
  163485. */
  163486. LOCAL(boolean)
  163487. emit_restart (working_state * state, int restart_num)
  163488. {
  163489. int ci;
  163490. if (! flush_bits(state))
  163491. return FALSE;
  163492. emit_byte(state, 0xFF, return FALSE);
  163493. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163494. /* Re-initialize DC predictions to 0 */
  163495. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163496. state->cur.last_dc_val[ci] = 0;
  163497. /* The restart counter is not updated until we successfully write the MCU. */
  163498. return TRUE;
  163499. }
  163500. /*
  163501. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163502. */
  163503. METHODDEF(boolean)
  163504. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163505. {
  163506. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163507. working_state state;
  163508. int blkn, ci;
  163509. jpeg_component_info * compptr;
  163510. /* Load up working state */
  163511. state.next_output_byte = cinfo->dest->next_output_byte;
  163512. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163513. ASSIGN_STATE(state.cur, entropy->saved);
  163514. state.cinfo = cinfo;
  163515. /* Emit restart marker if needed */
  163516. if (cinfo->restart_interval) {
  163517. if (entropy->restarts_to_go == 0)
  163518. if (! emit_restart(&state, entropy->next_restart_num))
  163519. return FALSE;
  163520. }
  163521. /* Encode the MCU data blocks */
  163522. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163523. ci = cinfo->MCU_membership[blkn];
  163524. compptr = cinfo->cur_comp_info[ci];
  163525. if (! encode_one_block(&state,
  163526. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163527. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163528. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163529. return FALSE;
  163530. /* Update last_dc_val */
  163531. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163532. }
  163533. /* Completed MCU, so update state */
  163534. cinfo->dest->next_output_byte = state.next_output_byte;
  163535. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163536. ASSIGN_STATE(entropy->saved, state.cur);
  163537. /* Update restart-interval state too */
  163538. if (cinfo->restart_interval) {
  163539. if (entropy->restarts_to_go == 0) {
  163540. entropy->restarts_to_go = cinfo->restart_interval;
  163541. entropy->next_restart_num++;
  163542. entropy->next_restart_num &= 7;
  163543. }
  163544. entropy->restarts_to_go--;
  163545. }
  163546. return TRUE;
  163547. }
  163548. /*
  163549. * Finish up at the end of a Huffman-compressed scan.
  163550. */
  163551. METHODDEF(void)
  163552. finish_pass_huff (j_compress_ptr cinfo)
  163553. {
  163554. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163555. working_state state;
  163556. /* Load up working state ... flush_bits needs it */
  163557. state.next_output_byte = cinfo->dest->next_output_byte;
  163558. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163559. ASSIGN_STATE(state.cur, entropy->saved);
  163560. state.cinfo = cinfo;
  163561. /* Flush out the last data */
  163562. if (! flush_bits(&state))
  163563. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163564. /* Update state */
  163565. cinfo->dest->next_output_byte = state.next_output_byte;
  163566. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163567. ASSIGN_STATE(entropy->saved, state.cur);
  163568. }
  163569. /*
  163570. * Huffman coding optimization.
  163571. *
  163572. * We first scan the supplied data and count the number of uses of each symbol
  163573. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163574. * Then we build a Huffman coding tree for the observed counts.
  163575. * Symbols which are not needed at all for the particular image are not
  163576. * assigned any code, which saves space in the DHT marker as well as in
  163577. * the compressed data.
  163578. */
  163579. #ifdef ENTROPY_OPT_SUPPORTED
  163580. /* Process a single block's worth of coefficients */
  163581. LOCAL(void)
  163582. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163583. long dc_counts[], long ac_counts[])
  163584. {
  163585. register int temp;
  163586. register int nbits;
  163587. register int k, r;
  163588. /* Encode the DC coefficient difference per section F.1.2.1 */
  163589. temp = block[0] - last_dc_val;
  163590. if (temp < 0)
  163591. temp = -temp;
  163592. /* Find the number of bits needed for the magnitude of the coefficient */
  163593. nbits = 0;
  163594. while (temp) {
  163595. nbits++;
  163596. temp >>= 1;
  163597. }
  163598. /* Check for out-of-range coefficient values.
  163599. * Since we're encoding a difference, the range limit is twice as much.
  163600. */
  163601. if (nbits > MAX_COEF_BITS+1)
  163602. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163603. /* Count the Huffman symbol for the number of bits */
  163604. dc_counts[nbits]++;
  163605. /* Encode the AC coefficients per section F.1.2.2 */
  163606. r = 0; /* r = run length of zeros */
  163607. for (k = 1; k < DCTSIZE2; k++) {
  163608. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163609. r++;
  163610. } else {
  163611. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163612. while (r > 15) {
  163613. ac_counts[0xF0]++;
  163614. r -= 16;
  163615. }
  163616. /* Find the number of bits needed for the magnitude of the coefficient */
  163617. if (temp < 0)
  163618. temp = -temp;
  163619. /* Find the number of bits needed for the magnitude of the coefficient */
  163620. nbits = 1; /* there must be at least one 1 bit */
  163621. while ((temp >>= 1))
  163622. nbits++;
  163623. /* Check for out-of-range coefficient values */
  163624. if (nbits > MAX_COEF_BITS)
  163625. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163626. /* Count Huffman symbol for run length / number of bits */
  163627. ac_counts[(r << 4) + nbits]++;
  163628. r = 0;
  163629. }
  163630. }
  163631. /* If the last coef(s) were zero, emit an end-of-block code */
  163632. if (r > 0)
  163633. ac_counts[0]++;
  163634. }
  163635. /*
  163636. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163637. * No data is actually output, so no suspension return is possible.
  163638. */
  163639. METHODDEF(boolean)
  163640. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163641. {
  163642. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163643. int blkn, ci;
  163644. jpeg_component_info * compptr;
  163645. /* Take care of restart intervals if needed */
  163646. if (cinfo->restart_interval) {
  163647. if (entropy->restarts_to_go == 0) {
  163648. /* Re-initialize DC predictions to 0 */
  163649. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163650. entropy->saved.last_dc_val[ci] = 0;
  163651. /* Update restart state */
  163652. entropy->restarts_to_go = cinfo->restart_interval;
  163653. }
  163654. entropy->restarts_to_go--;
  163655. }
  163656. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163657. ci = cinfo->MCU_membership[blkn];
  163658. compptr = cinfo->cur_comp_info[ci];
  163659. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163660. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163661. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163662. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163663. }
  163664. return TRUE;
  163665. }
  163666. /*
  163667. * Generate the best Huffman code table for the given counts, fill htbl.
  163668. * Note this is also used by jcphuff.c.
  163669. *
  163670. * The JPEG standard requires that no symbol be assigned a codeword of all
  163671. * one bits (so that padding bits added at the end of a compressed segment
  163672. * can't look like a valid code). Because of the canonical ordering of
  163673. * codewords, this just means that there must be an unused slot in the
  163674. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163675. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163676. * with count 1. In theory that's not optimal; giving it count zero but
  163677. * including it in the symbol set anyway should give a better Huffman code.
  163678. * But the theoretically better code actually seems to come out worse in
  163679. * practice, because it produces more all-ones bytes (which incur stuffed
  163680. * zero bytes in the final file). In any case the difference is tiny.
  163681. *
  163682. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163683. * If some symbols have a very small but nonzero probability, the Huffman tree
  163684. * must be adjusted to meet the code length restriction. We currently use
  163685. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163686. * optimal; it may not choose the best possible limited-length code. But
  163687. * typically only very-low-frequency symbols will be given less-than-optimal
  163688. * lengths, so the code is almost optimal. Experimental comparisons against
  163689. * an optimal limited-length-code algorithm indicate that the difference is
  163690. * microscopic --- usually less than a hundredth of a percent of total size.
  163691. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163692. */
  163693. GLOBAL(void)
  163694. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163695. {
  163696. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163697. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163698. int codesize[257]; /* codesize[k] = code length of symbol k */
  163699. int others[257]; /* next symbol in current branch of tree */
  163700. int c1, c2;
  163701. int p, i, j;
  163702. long v;
  163703. /* This algorithm is explained in section K.2 of the JPEG standard */
  163704. MEMZERO(bits, SIZEOF(bits));
  163705. MEMZERO(codesize, SIZEOF(codesize));
  163706. for (i = 0; i < 257; i++)
  163707. others[i] = -1; /* init links to empty */
  163708. freq[256] = 1; /* make sure 256 has a nonzero count */
  163709. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163710. * that no real symbol is given code-value of all ones, because 256
  163711. * will be placed last in the largest codeword category.
  163712. */
  163713. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163714. for (;;) {
  163715. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163716. /* In case of ties, take the larger symbol number */
  163717. c1 = -1;
  163718. v = 1000000000L;
  163719. for (i = 0; i <= 256; i++) {
  163720. if (freq[i] && freq[i] <= v) {
  163721. v = freq[i];
  163722. c1 = i;
  163723. }
  163724. }
  163725. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163726. /* In case of ties, take the larger symbol number */
  163727. c2 = -1;
  163728. v = 1000000000L;
  163729. for (i = 0; i <= 256; i++) {
  163730. if (freq[i] && freq[i] <= v && i != c1) {
  163731. v = freq[i];
  163732. c2 = i;
  163733. }
  163734. }
  163735. /* Done if we've merged everything into one frequency */
  163736. if (c2 < 0)
  163737. break;
  163738. /* Else merge the two counts/trees */
  163739. freq[c1] += freq[c2];
  163740. freq[c2] = 0;
  163741. /* Increment the codesize of everything in c1's tree branch */
  163742. codesize[c1]++;
  163743. while (others[c1] >= 0) {
  163744. c1 = others[c1];
  163745. codesize[c1]++;
  163746. }
  163747. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163748. /* Increment the codesize of everything in c2's tree branch */
  163749. codesize[c2]++;
  163750. while (others[c2] >= 0) {
  163751. c2 = others[c2];
  163752. codesize[c2]++;
  163753. }
  163754. }
  163755. /* Now count the number of symbols of each code length */
  163756. for (i = 0; i <= 256; i++) {
  163757. if (codesize[i]) {
  163758. /* The JPEG standard seems to think that this can't happen, */
  163759. /* but I'm paranoid... */
  163760. if (codesize[i] > MAX_CLEN)
  163761. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163762. bits[codesize[i]]++;
  163763. }
  163764. }
  163765. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163766. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163767. * Here is what the JPEG spec says about how this next bit works:
  163768. * Since symbols are paired for the longest Huffman code, the symbols are
  163769. * removed from this length category two at a time. The prefix for the pair
  163770. * (which is one bit shorter) is allocated to one of the pair; then,
  163771. * skipping the BITS entry for that prefix length, a code word from the next
  163772. * shortest nonzero BITS entry is converted into a prefix for two code words
  163773. * one bit longer.
  163774. */
  163775. for (i = MAX_CLEN; i > 16; i--) {
  163776. while (bits[i] > 0) {
  163777. j = i - 2; /* find length of new prefix to be used */
  163778. while (bits[j] == 0)
  163779. j--;
  163780. bits[i] -= 2; /* remove two symbols */
  163781. bits[i-1]++; /* one goes in this length */
  163782. bits[j+1] += 2; /* two new symbols in this length */
  163783. bits[j]--; /* symbol of this length is now a prefix */
  163784. }
  163785. }
  163786. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163787. while (bits[i] == 0) /* find largest codelength still in use */
  163788. i--;
  163789. bits[i]--;
  163790. /* Return final symbol counts (only for lengths 0..16) */
  163791. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163792. /* Return a list of the symbols sorted by code length */
  163793. /* It's not real clear to me why we don't need to consider the codelength
  163794. * changes made above, but the JPEG spec seems to think this works.
  163795. */
  163796. p = 0;
  163797. for (i = 1; i <= MAX_CLEN; i++) {
  163798. for (j = 0; j <= 255; j++) {
  163799. if (codesize[j] == i) {
  163800. htbl->huffval[p] = (UINT8) j;
  163801. p++;
  163802. }
  163803. }
  163804. }
  163805. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163806. htbl->sent_table = FALSE;
  163807. }
  163808. /*
  163809. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163810. */
  163811. METHODDEF(void)
  163812. finish_pass_gather (j_compress_ptr cinfo)
  163813. {
  163814. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163815. int ci, dctbl, actbl;
  163816. jpeg_component_info * compptr;
  163817. JHUFF_TBL **htblptr;
  163818. boolean did_dc[NUM_HUFF_TBLS];
  163819. boolean did_ac[NUM_HUFF_TBLS];
  163820. /* It's important not to apply jpeg_gen_optimal_table more than once
  163821. * per table, because it clobbers the input frequency counts!
  163822. */
  163823. MEMZERO(did_dc, SIZEOF(did_dc));
  163824. MEMZERO(did_ac, SIZEOF(did_ac));
  163825. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163826. compptr = cinfo->cur_comp_info[ci];
  163827. dctbl = compptr->dc_tbl_no;
  163828. actbl = compptr->ac_tbl_no;
  163829. if (! did_dc[dctbl]) {
  163830. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163831. if (*htblptr == NULL)
  163832. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163833. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163834. did_dc[dctbl] = TRUE;
  163835. }
  163836. if (! did_ac[actbl]) {
  163837. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163838. if (*htblptr == NULL)
  163839. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163840. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163841. did_ac[actbl] = TRUE;
  163842. }
  163843. }
  163844. }
  163845. #endif /* ENTROPY_OPT_SUPPORTED */
  163846. /*
  163847. * Module initialization routine for Huffman entropy encoding.
  163848. */
  163849. GLOBAL(void)
  163850. jinit_huff_encoder (j_compress_ptr cinfo)
  163851. {
  163852. huff_entropy_ptr entropy;
  163853. int i;
  163854. entropy = (huff_entropy_ptr)
  163855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163856. SIZEOF(huff_entropy_encoder));
  163857. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163858. entropy->pub.start_pass = start_pass_huff;
  163859. /* Mark tables unallocated */
  163860. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163861. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163862. #ifdef ENTROPY_OPT_SUPPORTED
  163863. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163864. #endif
  163865. }
  163866. }
  163867. /*** End of inlined file: jchuff.c ***/
  163868. #undef emit_byte
  163869. /*** Start of inlined file: jcinit.c ***/
  163870. #define JPEG_INTERNALS
  163871. /*
  163872. * Master selection of compression modules.
  163873. * This is done once at the start of processing an image. We determine
  163874. * which modules will be used and give them appropriate initialization calls.
  163875. */
  163876. GLOBAL(void)
  163877. jinit_compress_master (j_compress_ptr cinfo)
  163878. {
  163879. /* Initialize master control (includes parameter checking/processing) */
  163880. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163881. /* Preprocessing */
  163882. if (! cinfo->raw_data_in) {
  163883. jinit_color_converter(cinfo);
  163884. jinit_downsampler(cinfo);
  163885. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163886. }
  163887. /* Forward DCT */
  163888. jinit_forward_dct(cinfo);
  163889. /* Entropy encoding: either Huffman or arithmetic coding. */
  163890. if (cinfo->arith_code) {
  163891. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163892. } else {
  163893. if (cinfo->progressive_mode) {
  163894. #ifdef C_PROGRESSIVE_SUPPORTED
  163895. jinit_phuff_encoder(cinfo);
  163896. #else
  163897. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163898. #endif
  163899. } else
  163900. jinit_huff_encoder(cinfo);
  163901. }
  163902. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163903. jinit_c_coef_controller(cinfo,
  163904. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163905. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163906. jinit_marker_writer(cinfo);
  163907. /* We can now tell the memory manager to allocate virtual arrays. */
  163908. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163909. /* Write the datastream header (SOI) immediately.
  163910. * Frame and scan headers are postponed till later.
  163911. * This lets application insert special markers after the SOI.
  163912. */
  163913. (*cinfo->marker->write_file_header) (cinfo);
  163914. }
  163915. /*** End of inlined file: jcinit.c ***/
  163916. /*** Start of inlined file: jcmainct.c ***/
  163917. #define JPEG_INTERNALS
  163918. /* Note: currently, there is no operating mode in which a full-image buffer
  163919. * is needed at this step. If there were, that mode could not be used with
  163920. * "raw data" input, since this module is bypassed in that case. However,
  163921. * we've left the code here for possible use in special applications.
  163922. */
  163923. #undef FULL_MAIN_BUFFER_SUPPORTED
  163924. /* Private buffer controller object */
  163925. typedef struct {
  163926. struct jpeg_c_main_controller pub; /* public fields */
  163927. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163928. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163929. boolean suspended; /* remember if we suspended output */
  163930. J_BUF_MODE pass_mode; /* current operating mode */
  163931. /* If using just a strip buffer, this points to the entire set of buffers
  163932. * (we allocate one for each component). In the full-image case, this
  163933. * points to the currently accessible strips of the virtual arrays.
  163934. */
  163935. JSAMPARRAY buffer[MAX_COMPONENTS];
  163936. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163937. /* If using full-image storage, this array holds pointers to virtual-array
  163938. * control blocks for each component. Unused if not full-image storage.
  163939. */
  163940. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163941. #endif
  163942. } my_main_controller;
  163943. typedef my_main_controller * my_main_ptr;
  163944. /* Forward declarations */
  163945. METHODDEF(void) process_data_simple_main
  163946. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163947. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163948. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163949. METHODDEF(void) process_data_buffer_main
  163950. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163951. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163952. #endif
  163953. /*
  163954. * Initialize for a processing pass.
  163955. */
  163956. METHODDEF(void)
  163957. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163958. {
  163959. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163960. /* Do nothing in raw-data mode. */
  163961. if (cinfo->raw_data_in)
  163962. return;
  163963. main_->cur_iMCU_row = 0; /* initialize counters */
  163964. main_->rowgroup_ctr = 0;
  163965. main_->suspended = FALSE;
  163966. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163967. switch (pass_mode) {
  163968. case JBUF_PASS_THRU:
  163969. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163970. if (main_->whole_image[0] != NULL)
  163971. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163972. #endif
  163973. main_->pub.process_data = process_data_simple_main;
  163974. break;
  163975. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163976. case JBUF_SAVE_SOURCE:
  163977. case JBUF_CRANK_DEST:
  163978. case JBUF_SAVE_AND_PASS:
  163979. if (main_->whole_image[0] == NULL)
  163980. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163981. main_->pub.process_data = process_data_buffer_main;
  163982. break;
  163983. #endif
  163984. default:
  163985. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163986. break;
  163987. }
  163988. }
  163989. /*
  163990. * Process some data.
  163991. * This routine handles the simple pass-through mode,
  163992. * where we have only a strip buffer.
  163993. */
  163994. METHODDEF(void)
  163995. process_data_simple_main (j_compress_ptr cinfo,
  163996. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163997. JDIMENSION in_rows_avail)
  163998. {
  163999. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164000. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164001. /* Read input data if we haven't filled the main buffer yet */
  164002. if (main_->rowgroup_ctr < DCTSIZE)
  164003. (*cinfo->prep->pre_process_data) (cinfo,
  164004. input_buf, in_row_ctr, in_rows_avail,
  164005. main_->buffer, &main_->rowgroup_ctr,
  164006. (JDIMENSION) DCTSIZE);
  164007. /* If we don't have a full iMCU row buffered, return to application for
  164008. * more data. Note that preprocessor will always pad to fill the iMCU row
  164009. * at the bottom of the image.
  164010. */
  164011. if (main_->rowgroup_ctr != DCTSIZE)
  164012. return;
  164013. /* Send the completed row to the compressor */
  164014. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164015. /* If compressor did not consume the whole row, then we must need to
  164016. * suspend processing and return to the application. In this situation
  164017. * we pretend we didn't yet consume the last input row; otherwise, if
  164018. * it happened to be the last row of the image, the application would
  164019. * think we were done.
  164020. */
  164021. if (! main_->suspended) {
  164022. (*in_row_ctr)--;
  164023. main_->suspended = TRUE;
  164024. }
  164025. return;
  164026. }
  164027. /* We did finish the row. Undo our little suspension hack if a previous
  164028. * call suspended; then mark the main buffer empty.
  164029. */
  164030. if (main_->suspended) {
  164031. (*in_row_ctr)++;
  164032. main_->suspended = FALSE;
  164033. }
  164034. main_->rowgroup_ctr = 0;
  164035. main_->cur_iMCU_row++;
  164036. }
  164037. }
  164038. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164039. /*
  164040. * Process some data.
  164041. * This routine handles all of the modes that use a full-size buffer.
  164042. */
  164043. METHODDEF(void)
  164044. process_data_buffer_main (j_compress_ptr cinfo,
  164045. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164046. JDIMENSION in_rows_avail)
  164047. {
  164048. my_main_ptr main = (my_main_ptr) cinfo->main;
  164049. int ci;
  164050. jpeg_component_info *compptr;
  164051. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164052. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164053. /* Realign the virtual buffers if at the start of an iMCU row. */
  164054. if (main->rowgroup_ctr == 0) {
  164055. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164056. ci++, compptr++) {
  164057. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164058. ((j_common_ptr) cinfo, main->whole_image[ci],
  164059. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164060. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164061. }
  164062. /* In a read pass, pretend we just read some source data. */
  164063. if (! writing) {
  164064. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164065. main->rowgroup_ctr = DCTSIZE;
  164066. }
  164067. }
  164068. /* If a write pass, read input data until the current iMCU row is full. */
  164069. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164070. if (writing) {
  164071. (*cinfo->prep->pre_process_data) (cinfo,
  164072. input_buf, in_row_ctr, in_rows_avail,
  164073. main->buffer, &main->rowgroup_ctr,
  164074. (JDIMENSION) DCTSIZE);
  164075. /* Return to application if we need more data to fill the iMCU row. */
  164076. if (main->rowgroup_ctr < DCTSIZE)
  164077. return;
  164078. }
  164079. /* Emit data, unless this is a sink-only pass. */
  164080. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164081. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164082. /* If compressor did not consume the whole row, then we must need to
  164083. * suspend processing and return to the application. In this situation
  164084. * we pretend we didn't yet consume the last input row; otherwise, if
  164085. * it happened to be the last row of the image, the application would
  164086. * think we were done.
  164087. */
  164088. if (! main->suspended) {
  164089. (*in_row_ctr)--;
  164090. main->suspended = TRUE;
  164091. }
  164092. return;
  164093. }
  164094. /* We did finish the row. Undo our little suspension hack if a previous
  164095. * call suspended; then mark the main buffer empty.
  164096. */
  164097. if (main->suspended) {
  164098. (*in_row_ctr)++;
  164099. main->suspended = FALSE;
  164100. }
  164101. }
  164102. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164103. main->rowgroup_ctr = 0;
  164104. main->cur_iMCU_row++;
  164105. }
  164106. }
  164107. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164108. /*
  164109. * Initialize main buffer controller.
  164110. */
  164111. GLOBAL(void)
  164112. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164113. {
  164114. my_main_ptr main_;
  164115. int ci;
  164116. jpeg_component_info *compptr;
  164117. main_ = (my_main_ptr)
  164118. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164119. SIZEOF(my_main_controller));
  164120. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164121. main_->pub.start_pass = start_pass_main;
  164122. /* We don't need to create a buffer in raw-data mode. */
  164123. if (cinfo->raw_data_in)
  164124. return;
  164125. /* Create the buffer. It holds downsampled data, so each component
  164126. * may be of a different size.
  164127. */
  164128. if (need_full_buffer) {
  164129. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164130. /* Allocate a full-image virtual array for each component */
  164131. /* Note we pad the bottom to a multiple of the iMCU height */
  164132. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164133. ci++, compptr++) {
  164134. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164135. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164136. compptr->width_in_blocks * DCTSIZE,
  164137. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164138. (long) compptr->v_samp_factor) * DCTSIZE,
  164139. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164140. }
  164141. #else
  164142. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164143. #endif
  164144. } else {
  164145. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164146. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164147. #endif
  164148. /* Allocate a strip buffer for each component */
  164149. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164150. ci++, compptr++) {
  164151. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164152. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164153. compptr->width_in_blocks * DCTSIZE,
  164154. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164155. }
  164156. }
  164157. }
  164158. /*** End of inlined file: jcmainct.c ***/
  164159. /*** Start of inlined file: jcmarker.c ***/
  164160. #define JPEG_INTERNALS
  164161. /* Private state */
  164162. typedef struct {
  164163. struct jpeg_marker_writer pub; /* public fields */
  164164. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164165. } my_marker_writer;
  164166. typedef my_marker_writer * my_marker_ptr;
  164167. /*
  164168. * Basic output routines.
  164169. *
  164170. * Note that we do not support suspension while writing a marker.
  164171. * Therefore, an application using suspension must ensure that there is
  164172. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164173. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164174. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164175. * modes are not supported at all with suspension, so those two are the only
  164176. * points where markers will be written.
  164177. */
  164178. LOCAL(void)
  164179. emit_byte (j_compress_ptr cinfo, int val)
  164180. /* Emit a byte */
  164181. {
  164182. struct jpeg_destination_mgr * dest = cinfo->dest;
  164183. *(dest->next_output_byte)++ = (JOCTET) val;
  164184. if (--dest->free_in_buffer == 0) {
  164185. if (! (*dest->empty_output_buffer) (cinfo))
  164186. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164187. }
  164188. }
  164189. LOCAL(void)
  164190. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164191. /* Emit a marker code */
  164192. {
  164193. emit_byte(cinfo, 0xFF);
  164194. emit_byte(cinfo, (int) mark);
  164195. }
  164196. LOCAL(void)
  164197. emit_2bytes (j_compress_ptr cinfo, int value)
  164198. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164199. {
  164200. emit_byte(cinfo, (value >> 8) & 0xFF);
  164201. emit_byte(cinfo, value & 0xFF);
  164202. }
  164203. /*
  164204. * Routines to write specific marker types.
  164205. */
  164206. LOCAL(int)
  164207. emit_dqt (j_compress_ptr cinfo, int index)
  164208. /* Emit a DQT marker */
  164209. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164210. {
  164211. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164212. int prec;
  164213. int i;
  164214. if (qtbl == NULL)
  164215. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164216. prec = 0;
  164217. for (i = 0; i < DCTSIZE2; i++) {
  164218. if (qtbl->quantval[i] > 255)
  164219. prec = 1;
  164220. }
  164221. if (! qtbl->sent_table) {
  164222. emit_marker(cinfo, M_DQT);
  164223. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164224. emit_byte(cinfo, index + (prec<<4));
  164225. for (i = 0; i < DCTSIZE2; i++) {
  164226. /* The table entries must be emitted in zigzag order. */
  164227. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164228. if (prec)
  164229. emit_byte(cinfo, (int) (qval >> 8));
  164230. emit_byte(cinfo, (int) (qval & 0xFF));
  164231. }
  164232. qtbl->sent_table = TRUE;
  164233. }
  164234. return prec;
  164235. }
  164236. LOCAL(void)
  164237. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164238. /* Emit a DHT marker */
  164239. {
  164240. JHUFF_TBL * htbl;
  164241. int length, i;
  164242. if (is_ac) {
  164243. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164244. index += 0x10; /* output index has AC bit set */
  164245. } else {
  164246. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164247. }
  164248. if (htbl == NULL)
  164249. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164250. if (! htbl->sent_table) {
  164251. emit_marker(cinfo, M_DHT);
  164252. length = 0;
  164253. for (i = 1; i <= 16; i++)
  164254. length += htbl->bits[i];
  164255. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164256. emit_byte(cinfo, index);
  164257. for (i = 1; i <= 16; i++)
  164258. emit_byte(cinfo, htbl->bits[i]);
  164259. for (i = 0; i < length; i++)
  164260. emit_byte(cinfo, htbl->huffval[i]);
  164261. htbl->sent_table = TRUE;
  164262. }
  164263. }
  164264. LOCAL(void)
  164265. emit_dac (j_compress_ptr)
  164266. /* Emit a DAC marker */
  164267. /* Since the useful info is so small, we want to emit all the tables in */
  164268. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164269. {
  164270. #ifdef C_ARITH_CODING_SUPPORTED
  164271. char dc_in_use[NUM_ARITH_TBLS];
  164272. char ac_in_use[NUM_ARITH_TBLS];
  164273. int length, i;
  164274. jpeg_component_info *compptr;
  164275. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164276. dc_in_use[i] = ac_in_use[i] = 0;
  164277. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164278. compptr = cinfo->cur_comp_info[i];
  164279. dc_in_use[compptr->dc_tbl_no] = 1;
  164280. ac_in_use[compptr->ac_tbl_no] = 1;
  164281. }
  164282. length = 0;
  164283. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164284. length += dc_in_use[i] + ac_in_use[i];
  164285. emit_marker(cinfo, M_DAC);
  164286. emit_2bytes(cinfo, length*2 + 2);
  164287. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164288. if (dc_in_use[i]) {
  164289. emit_byte(cinfo, i);
  164290. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164291. }
  164292. if (ac_in_use[i]) {
  164293. emit_byte(cinfo, i + 0x10);
  164294. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164295. }
  164296. }
  164297. #endif /* C_ARITH_CODING_SUPPORTED */
  164298. }
  164299. LOCAL(void)
  164300. emit_dri (j_compress_ptr cinfo)
  164301. /* Emit a DRI marker */
  164302. {
  164303. emit_marker(cinfo, M_DRI);
  164304. emit_2bytes(cinfo, 4); /* fixed length */
  164305. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164306. }
  164307. LOCAL(void)
  164308. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164309. /* Emit a SOF marker */
  164310. {
  164311. int ci;
  164312. jpeg_component_info *compptr;
  164313. emit_marker(cinfo, code);
  164314. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164315. /* Make sure image isn't bigger than SOF field can handle */
  164316. if ((long) cinfo->image_height > 65535L ||
  164317. (long) cinfo->image_width > 65535L)
  164318. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164319. emit_byte(cinfo, cinfo->data_precision);
  164320. emit_2bytes(cinfo, (int) cinfo->image_height);
  164321. emit_2bytes(cinfo, (int) cinfo->image_width);
  164322. emit_byte(cinfo, cinfo->num_components);
  164323. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164324. ci++, compptr++) {
  164325. emit_byte(cinfo, compptr->component_id);
  164326. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164327. emit_byte(cinfo, compptr->quant_tbl_no);
  164328. }
  164329. }
  164330. LOCAL(void)
  164331. emit_sos (j_compress_ptr cinfo)
  164332. /* Emit a SOS marker */
  164333. {
  164334. int i, td, ta;
  164335. jpeg_component_info *compptr;
  164336. emit_marker(cinfo, M_SOS);
  164337. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164338. emit_byte(cinfo, cinfo->comps_in_scan);
  164339. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164340. compptr = cinfo->cur_comp_info[i];
  164341. emit_byte(cinfo, compptr->component_id);
  164342. td = compptr->dc_tbl_no;
  164343. ta = compptr->ac_tbl_no;
  164344. if (cinfo->progressive_mode) {
  164345. /* Progressive mode: only DC or only AC tables are used in one scan;
  164346. * furthermore, Huffman coding of DC refinement uses no table at all.
  164347. * We emit 0 for unused field(s); this is recommended by the P&M text
  164348. * but does not seem to be specified in the standard.
  164349. */
  164350. if (cinfo->Ss == 0) {
  164351. ta = 0; /* DC scan */
  164352. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164353. td = 0; /* no DC table either */
  164354. } else {
  164355. td = 0; /* AC scan */
  164356. }
  164357. }
  164358. emit_byte(cinfo, (td << 4) + ta);
  164359. }
  164360. emit_byte(cinfo, cinfo->Ss);
  164361. emit_byte(cinfo, cinfo->Se);
  164362. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164363. }
  164364. LOCAL(void)
  164365. emit_jfif_app0 (j_compress_ptr cinfo)
  164366. /* Emit a JFIF-compliant APP0 marker */
  164367. {
  164368. /*
  164369. * Length of APP0 block (2 bytes)
  164370. * Block ID (4 bytes - ASCII "JFIF")
  164371. * Zero byte (1 byte to terminate the ID string)
  164372. * Version Major, Minor (2 bytes - major first)
  164373. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164374. * Xdpu (2 bytes - dots per unit horizontal)
  164375. * Ydpu (2 bytes - dots per unit vertical)
  164376. * Thumbnail X size (1 byte)
  164377. * Thumbnail Y size (1 byte)
  164378. */
  164379. emit_marker(cinfo, M_APP0);
  164380. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164381. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164382. emit_byte(cinfo, 0x46);
  164383. emit_byte(cinfo, 0x49);
  164384. emit_byte(cinfo, 0x46);
  164385. emit_byte(cinfo, 0);
  164386. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164387. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164388. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164389. emit_2bytes(cinfo, (int) cinfo->X_density);
  164390. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164391. emit_byte(cinfo, 0); /* No thumbnail image */
  164392. emit_byte(cinfo, 0);
  164393. }
  164394. LOCAL(void)
  164395. emit_adobe_app14 (j_compress_ptr cinfo)
  164396. /* Emit an Adobe APP14 marker */
  164397. {
  164398. /*
  164399. * Length of APP14 block (2 bytes)
  164400. * Block ID (5 bytes - ASCII "Adobe")
  164401. * Version Number (2 bytes - currently 100)
  164402. * Flags0 (2 bytes - currently 0)
  164403. * Flags1 (2 bytes - currently 0)
  164404. * Color transform (1 byte)
  164405. *
  164406. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164407. * now in circulation seem to use Version = 100, so that's what we write.
  164408. *
  164409. * We write the color transform byte as 1 if the JPEG color space is
  164410. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164411. * whether the encoder performed a transformation, which is pretty useless.
  164412. */
  164413. emit_marker(cinfo, M_APP14);
  164414. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164415. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164416. emit_byte(cinfo, 0x64);
  164417. emit_byte(cinfo, 0x6F);
  164418. emit_byte(cinfo, 0x62);
  164419. emit_byte(cinfo, 0x65);
  164420. emit_2bytes(cinfo, 100); /* Version */
  164421. emit_2bytes(cinfo, 0); /* Flags0 */
  164422. emit_2bytes(cinfo, 0); /* Flags1 */
  164423. switch (cinfo->jpeg_color_space) {
  164424. case JCS_YCbCr:
  164425. emit_byte(cinfo, 1); /* Color transform = 1 */
  164426. break;
  164427. case JCS_YCCK:
  164428. emit_byte(cinfo, 2); /* Color transform = 2 */
  164429. break;
  164430. default:
  164431. emit_byte(cinfo, 0); /* Color transform = 0 */
  164432. break;
  164433. }
  164434. }
  164435. /*
  164436. * These routines allow writing an arbitrary marker with parameters.
  164437. * The only intended use is to emit COM or APPn markers after calling
  164438. * write_file_header and before calling write_frame_header.
  164439. * Other uses are not guaranteed to produce desirable results.
  164440. * Counting the parameter bytes properly is the caller's responsibility.
  164441. */
  164442. METHODDEF(void)
  164443. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164444. /* Emit an arbitrary marker header */
  164445. {
  164446. if (datalen > (unsigned int) 65533) /* safety check */
  164447. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164448. emit_marker(cinfo, (JPEG_MARKER) marker);
  164449. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164450. }
  164451. METHODDEF(void)
  164452. write_marker_byte (j_compress_ptr cinfo, int val)
  164453. /* Emit one byte of marker parameters following write_marker_header */
  164454. {
  164455. emit_byte(cinfo, val);
  164456. }
  164457. /*
  164458. * Write datastream header.
  164459. * This consists of an SOI and optional APPn markers.
  164460. * We recommend use of the JFIF marker, but not the Adobe marker,
  164461. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164462. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164463. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164464. * Note that an application can write additional header markers after
  164465. * jpeg_start_compress returns.
  164466. */
  164467. METHODDEF(void)
  164468. write_file_header (j_compress_ptr cinfo)
  164469. {
  164470. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164471. emit_marker(cinfo, M_SOI); /* first the SOI */
  164472. /* SOI is defined to reset restart interval to 0 */
  164473. marker->last_restart_interval = 0;
  164474. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164475. emit_jfif_app0(cinfo);
  164476. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164477. emit_adobe_app14(cinfo);
  164478. }
  164479. /*
  164480. * Write frame header.
  164481. * This consists of DQT and SOFn markers.
  164482. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164483. * This avoids compatibility problems with incorrect implementations that
  164484. * try to error-check the quant table numbers as soon as they see the SOF.
  164485. */
  164486. METHODDEF(void)
  164487. write_frame_header (j_compress_ptr cinfo)
  164488. {
  164489. int ci, prec;
  164490. boolean is_baseline;
  164491. jpeg_component_info *compptr;
  164492. /* Emit DQT for each quantization table.
  164493. * Note that emit_dqt() suppresses any duplicate tables.
  164494. */
  164495. prec = 0;
  164496. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164497. ci++, compptr++) {
  164498. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164499. }
  164500. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164501. /* Check for a non-baseline specification.
  164502. * Note we assume that Huffman table numbers won't be changed later.
  164503. */
  164504. if (cinfo->arith_code || cinfo->progressive_mode ||
  164505. cinfo->data_precision != 8) {
  164506. is_baseline = FALSE;
  164507. } else {
  164508. is_baseline = TRUE;
  164509. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164510. ci++, compptr++) {
  164511. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164512. is_baseline = FALSE;
  164513. }
  164514. if (prec && is_baseline) {
  164515. is_baseline = FALSE;
  164516. /* If it's baseline except for quantizer size, warn the user */
  164517. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164518. }
  164519. }
  164520. /* Emit the proper SOF marker */
  164521. if (cinfo->arith_code) {
  164522. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164523. } else {
  164524. if (cinfo->progressive_mode)
  164525. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164526. else if (is_baseline)
  164527. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164528. else
  164529. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164530. }
  164531. }
  164532. /*
  164533. * Write scan header.
  164534. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164535. * Compressed data will be written following the SOS.
  164536. */
  164537. METHODDEF(void)
  164538. write_scan_header (j_compress_ptr cinfo)
  164539. {
  164540. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164541. int i;
  164542. jpeg_component_info *compptr;
  164543. if (cinfo->arith_code) {
  164544. /* Emit arith conditioning info. We may have some duplication
  164545. * if the file has multiple scans, but it's so small it's hardly
  164546. * worth worrying about.
  164547. */
  164548. emit_dac(cinfo);
  164549. } else {
  164550. /* Emit Huffman tables.
  164551. * Note that emit_dht() suppresses any duplicate tables.
  164552. */
  164553. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164554. compptr = cinfo->cur_comp_info[i];
  164555. if (cinfo->progressive_mode) {
  164556. /* Progressive mode: only DC or only AC tables are used in one scan */
  164557. if (cinfo->Ss == 0) {
  164558. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164559. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164560. } else {
  164561. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164562. }
  164563. } else {
  164564. /* Sequential mode: need both DC and AC tables */
  164565. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164566. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164567. }
  164568. }
  164569. }
  164570. /* Emit DRI if required --- note that DRI value could change for each scan.
  164571. * We avoid wasting space with unnecessary DRIs, however.
  164572. */
  164573. if (cinfo->restart_interval != marker->last_restart_interval) {
  164574. emit_dri(cinfo);
  164575. marker->last_restart_interval = cinfo->restart_interval;
  164576. }
  164577. emit_sos(cinfo);
  164578. }
  164579. /*
  164580. * Write datastream trailer.
  164581. */
  164582. METHODDEF(void)
  164583. write_file_trailer (j_compress_ptr cinfo)
  164584. {
  164585. emit_marker(cinfo, M_EOI);
  164586. }
  164587. /*
  164588. * Write an abbreviated table-specification datastream.
  164589. * This consists of SOI, DQT and DHT tables, and EOI.
  164590. * Any table that is defined and not marked sent_table = TRUE will be
  164591. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164592. */
  164593. METHODDEF(void)
  164594. write_tables_only (j_compress_ptr cinfo)
  164595. {
  164596. int i;
  164597. emit_marker(cinfo, M_SOI);
  164598. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164599. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164600. (void) emit_dqt(cinfo, i);
  164601. }
  164602. if (! cinfo->arith_code) {
  164603. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164604. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164605. emit_dht(cinfo, i, FALSE);
  164606. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164607. emit_dht(cinfo, i, TRUE);
  164608. }
  164609. }
  164610. emit_marker(cinfo, M_EOI);
  164611. }
  164612. /*
  164613. * Initialize the marker writer module.
  164614. */
  164615. GLOBAL(void)
  164616. jinit_marker_writer (j_compress_ptr cinfo)
  164617. {
  164618. my_marker_ptr marker;
  164619. /* Create the subobject */
  164620. marker = (my_marker_ptr)
  164621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164622. SIZEOF(my_marker_writer));
  164623. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164624. /* Initialize method pointers */
  164625. marker->pub.write_file_header = write_file_header;
  164626. marker->pub.write_frame_header = write_frame_header;
  164627. marker->pub.write_scan_header = write_scan_header;
  164628. marker->pub.write_file_trailer = write_file_trailer;
  164629. marker->pub.write_tables_only = write_tables_only;
  164630. marker->pub.write_marker_header = write_marker_header;
  164631. marker->pub.write_marker_byte = write_marker_byte;
  164632. /* Initialize private state */
  164633. marker->last_restart_interval = 0;
  164634. }
  164635. /*** End of inlined file: jcmarker.c ***/
  164636. /*** Start of inlined file: jcmaster.c ***/
  164637. #define JPEG_INTERNALS
  164638. /* Private state */
  164639. typedef enum {
  164640. main_pass, /* input data, also do first output step */
  164641. huff_opt_pass, /* Huffman code optimization pass */
  164642. output_pass /* data output pass */
  164643. } c_pass_type;
  164644. typedef struct {
  164645. struct jpeg_comp_master pub; /* public fields */
  164646. c_pass_type pass_type; /* the type of the current pass */
  164647. int pass_number; /* # of passes completed */
  164648. int total_passes; /* total # of passes needed */
  164649. int scan_number; /* current index in scan_info[] */
  164650. } my_comp_master;
  164651. typedef my_comp_master * my_master_ptr;
  164652. /*
  164653. * Support routines that do various essential calculations.
  164654. */
  164655. LOCAL(void)
  164656. initial_setup (j_compress_ptr cinfo)
  164657. /* Do computations that are needed before master selection phase */
  164658. {
  164659. int ci;
  164660. jpeg_component_info *compptr;
  164661. long samplesperrow;
  164662. JDIMENSION jd_samplesperrow;
  164663. /* Sanity check on image dimensions */
  164664. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164665. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164666. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164667. /* Make sure image isn't bigger than I can handle */
  164668. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164669. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164670. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164671. /* Width of an input scanline must be representable as JDIMENSION. */
  164672. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164673. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164674. if ((long) jd_samplesperrow != samplesperrow)
  164675. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164676. /* For now, precision must match compiled-in value... */
  164677. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164678. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164679. /* Check that number of components won't exceed internal array sizes */
  164680. if (cinfo->num_components > MAX_COMPONENTS)
  164681. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164682. MAX_COMPONENTS);
  164683. /* Compute maximum sampling factors; check factor validity */
  164684. cinfo->max_h_samp_factor = 1;
  164685. cinfo->max_v_samp_factor = 1;
  164686. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164687. ci++, compptr++) {
  164688. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164689. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164690. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164691. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164692. compptr->h_samp_factor);
  164693. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164694. compptr->v_samp_factor);
  164695. }
  164696. /* Compute dimensions of components */
  164697. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164698. ci++, compptr++) {
  164699. /* Fill in the correct component_index value; don't rely on application */
  164700. compptr->component_index = ci;
  164701. /* For compression, we never do DCT scaling. */
  164702. compptr->DCT_scaled_size = DCTSIZE;
  164703. /* Size in DCT blocks */
  164704. compptr->width_in_blocks = (JDIMENSION)
  164705. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164706. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164707. compptr->height_in_blocks = (JDIMENSION)
  164708. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164709. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164710. /* Size in samples */
  164711. compptr->downsampled_width = (JDIMENSION)
  164712. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164713. (long) cinfo->max_h_samp_factor);
  164714. compptr->downsampled_height = (JDIMENSION)
  164715. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164716. (long) cinfo->max_v_samp_factor);
  164717. /* Mark component needed (this flag isn't actually used for compression) */
  164718. compptr->component_needed = TRUE;
  164719. }
  164720. /* Compute number of fully interleaved MCU rows (number of times that
  164721. * main controller will call coefficient controller).
  164722. */
  164723. cinfo->total_iMCU_rows = (JDIMENSION)
  164724. jdiv_round_up((long) cinfo->image_height,
  164725. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164726. }
  164727. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164728. LOCAL(void)
  164729. validate_script (j_compress_ptr cinfo)
  164730. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164731. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164732. */
  164733. {
  164734. const jpeg_scan_info * scanptr;
  164735. int scanno, ncomps, ci, coefi, thisi;
  164736. int Ss, Se, Ah, Al;
  164737. boolean component_sent[MAX_COMPONENTS];
  164738. #ifdef C_PROGRESSIVE_SUPPORTED
  164739. int * last_bitpos_ptr;
  164740. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164741. /* -1 until that coefficient has been seen; then last Al for it */
  164742. #endif
  164743. if (cinfo->num_scans <= 0)
  164744. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164745. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164746. * for progressive JPEG, no scan can have this.
  164747. */
  164748. scanptr = cinfo->scan_info;
  164749. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164750. #ifdef C_PROGRESSIVE_SUPPORTED
  164751. cinfo->progressive_mode = TRUE;
  164752. last_bitpos_ptr = & last_bitpos[0][0];
  164753. for (ci = 0; ci < cinfo->num_components; ci++)
  164754. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164755. *last_bitpos_ptr++ = -1;
  164756. #else
  164757. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164758. #endif
  164759. } else {
  164760. cinfo->progressive_mode = FALSE;
  164761. for (ci = 0; ci < cinfo->num_components; ci++)
  164762. component_sent[ci] = FALSE;
  164763. }
  164764. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164765. /* Validate component indexes */
  164766. ncomps = scanptr->comps_in_scan;
  164767. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164768. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164769. for (ci = 0; ci < ncomps; ci++) {
  164770. thisi = scanptr->component_index[ci];
  164771. if (thisi < 0 || thisi >= cinfo->num_components)
  164772. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164773. /* Components must appear in SOF order within each scan */
  164774. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164775. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164776. }
  164777. /* Validate progression parameters */
  164778. Ss = scanptr->Ss;
  164779. Se = scanptr->Se;
  164780. Ah = scanptr->Ah;
  164781. Al = scanptr->Al;
  164782. if (cinfo->progressive_mode) {
  164783. #ifdef C_PROGRESSIVE_SUPPORTED
  164784. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164785. * seems wrong: the upper bound ought to depend on data precision.
  164786. * Perhaps they really meant 0..N+1 for N-bit precision.
  164787. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164788. * out-of-range reconstructed DC values during the first DC scan,
  164789. * which might cause problems for some decoders.
  164790. */
  164791. #if BITS_IN_JSAMPLE == 8
  164792. #define MAX_AH_AL 10
  164793. #else
  164794. #define MAX_AH_AL 13
  164795. #endif
  164796. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164797. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164798. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164799. if (Ss == 0) {
  164800. if (Se != 0) /* DC and AC together not OK */
  164801. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164802. } else {
  164803. if (ncomps != 1) /* AC scans must be for only one component */
  164804. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164805. }
  164806. for (ci = 0; ci < ncomps; ci++) {
  164807. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164808. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164809. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164810. for (coefi = Ss; coefi <= Se; coefi++) {
  164811. if (last_bitpos_ptr[coefi] < 0) {
  164812. /* first scan of this coefficient */
  164813. if (Ah != 0)
  164814. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164815. } else {
  164816. /* not first scan */
  164817. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164818. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164819. }
  164820. last_bitpos_ptr[coefi] = Al;
  164821. }
  164822. }
  164823. #endif
  164824. } else {
  164825. /* For sequential JPEG, all progression parameters must be these: */
  164826. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164827. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164828. /* Make sure components are not sent twice */
  164829. for (ci = 0; ci < ncomps; ci++) {
  164830. thisi = scanptr->component_index[ci];
  164831. if (component_sent[thisi])
  164832. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164833. component_sent[thisi] = TRUE;
  164834. }
  164835. }
  164836. }
  164837. /* Now verify that everything got sent. */
  164838. if (cinfo->progressive_mode) {
  164839. #ifdef C_PROGRESSIVE_SUPPORTED
  164840. /* For progressive mode, we only check that at least some DC data
  164841. * got sent for each component; the spec does not require that all bits
  164842. * of all coefficients be transmitted. Would it be wiser to enforce
  164843. * transmission of all coefficient bits??
  164844. */
  164845. for (ci = 0; ci < cinfo->num_components; ci++) {
  164846. if (last_bitpos[ci][0] < 0)
  164847. ERREXIT(cinfo, JERR_MISSING_DATA);
  164848. }
  164849. #endif
  164850. } else {
  164851. for (ci = 0; ci < cinfo->num_components; ci++) {
  164852. if (! component_sent[ci])
  164853. ERREXIT(cinfo, JERR_MISSING_DATA);
  164854. }
  164855. }
  164856. }
  164857. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164858. LOCAL(void)
  164859. select_scan_parameters (j_compress_ptr cinfo)
  164860. /* Set up the scan parameters for the current scan */
  164861. {
  164862. int ci;
  164863. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164864. if (cinfo->scan_info != NULL) {
  164865. /* Prepare for current scan --- the script is already validated */
  164866. my_master_ptr master = (my_master_ptr) cinfo->master;
  164867. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164868. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164869. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164870. cinfo->cur_comp_info[ci] =
  164871. &cinfo->comp_info[scanptr->component_index[ci]];
  164872. }
  164873. cinfo->Ss = scanptr->Ss;
  164874. cinfo->Se = scanptr->Se;
  164875. cinfo->Ah = scanptr->Ah;
  164876. cinfo->Al = scanptr->Al;
  164877. }
  164878. else
  164879. #endif
  164880. {
  164881. /* Prepare for single sequential-JPEG scan containing all components */
  164882. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164883. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164884. MAX_COMPS_IN_SCAN);
  164885. cinfo->comps_in_scan = cinfo->num_components;
  164886. for (ci = 0; ci < cinfo->num_components; ci++) {
  164887. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164888. }
  164889. cinfo->Ss = 0;
  164890. cinfo->Se = DCTSIZE2-1;
  164891. cinfo->Ah = 0;
  164892. cinfo->Al = 0;
  164893. }
  164894. }
  164895. LOCAL(void)
  164896. per_scan_setup (j_compress_ptr cinfo)
  164897. /* Do computations that are needed before processing a JPEG scan */
  164898. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164899. {
  164900. int ci, mcublks, tmp;
  164901. jpeg_component_info *compptr;
  164902. if (cinfo->comps_in_scan == 1) {
  164903. /* Noninterleaved (single-component) scan */
  164904. compptr = cinfo->cur_comp_info[0];
  164905. /* Overall image size in MCUs */
  164906. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164907. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164908. /* For noninterleaved scan, always one block per MCU */
  164909. compptr->MCU_width = 1;
  164910. compptr->MCU_height = 1;
  164911. compptr->MCU_blocks = 1;
  164912. compptr->MCU_sample_width = DCTSIZE;
  164913. compptr->last_col_width = 1;
  164914. /* For noninterleaved scans, it is convenient to define last_row_height
  164915. * as the number of block rows present in the last iMCU row.
  164916. */
  164917. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164918. if (tmp == 0) tmp = compptr->v_samp_factor;
  164919. compptr->last_row_height = tmp;
  164920. /* Prepare array describing MCU composition */
  164921. cinfo->blocks_in_MCU = 1;
  164922. cinfo->MCU_membership[0] = 0;
  164923. } else {
  164924. /* Interleaved (multi-component) scan */
  164925. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164926. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164927. MAX_COMPS_IN_SCAN);
  164928. /* Overall image size in MCUs */
  164929. cinfo->MCUs_per_row = (JDIMENSION)
  164930. jdiv_round_up((long) cinfo->image_width,
  164931. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164932. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164933. jdiv_round_up((long) cinfo->image_height,
  164934. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164935. cinfo->blocks_in_MCU = 0;
  164936. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164937. compptr = cinfo->cur_comp_info[ci];
  164938. /* Sampling factors give # of blocks of component in each MCU */
  164939. compptr->MCU_width = compptr->h_samp_factor;
  164940. compptr->MCU_height = compptr->v_samp_factor;
  164941. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164942. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164943. /* Figure number of non-dummy blocks in last MCU column & row */
  164944. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164945. if (tmp == 0) tmp = compptr->MCU_width;
  164946. compptr->last_col_width = tmp;
  164947. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164948. if (tmp == 0) tmp = compptr->MCU_height;
  164949. compptr->last_row_height = tmp;
  164950. /* Prepare array describing MCU composition */
  164951. mcublks = compptr->MCU_blocks;
  164952. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164953. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164954. while (mcublks-- > 0) {
  164955. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164956. }
  164957. }
  164958. }
  164959. /* Convert restart specified in rows to actual MCU count. */
  164960. /* Note that count must fit in 16 bits, so we provide limiting. */
  164961. if (cinfo->restart_in_rows > 0) {
  164962. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164963. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164964. }
  164965. }
  164966. /*
  164967. * Per-pass setup.
  164968. * This is called at the beginning of each pass. We determine which modules
  164969. * will be active during this pass and give them appropriate start_pass calls.
  164970. * We also set is_last_pass to indicate whether any more passes will be
  164971. * required.
  164972. */
  164973. METHODDEF(void)
  164974. prepare_for_pass (j_compress_ptr cinfo)
  164975. {
  164976. my_master_ptr master = (my_master_ptr) cinfo->master;
  164977. switch (master->pass_type) {
  164978. case main_pass:
  164979. /* Initial pass: will collect input data, and do either Huffman
  164980. * optimization or data output for the first scan.
  164981. */
  164982. select_scan_parameters(cinfo);
  164983. per_scan_setup(cinfo);
  164984. if (! cinfo->raw_data_in) {
  164985. (*cinfo->cconvert->start_pass) (cinfo);
  164986. (*cinfo->downsample->start_pass) (cinfo);
  164987. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164988. }
  164989. (*cinfo->fdct->start_pass) (cinfo);
  164990. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164991. (*cinfo->coef->start_pass) (cinfo,
  164992. (master->total_passes > 1 ?
  164993. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164994. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164995. if (cinfo->optimize_coding) {
  164996. /* No immediate data output; postpone writing frame/scan headers */
  164997. master->pub.call_pass_startup = FALSE;
  164998. } else {
  164999. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165000. master->pub.call_pass_startup = TRUE;
  165001. }
  165002. break;
  165003. #ifdef ENTROPY_OPT_SUPPORTED
  165004. case huff_opt_pass:
  165005. /* Do Huffman optimization for a scan after the first one. */
  165006. select_scan_parameters(cinfo);
  165007. per_scan_setup(cinfo);
  165008. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165009. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165010. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165011. master->pub.call_pass_startup = FALSE;
  165012. break;
  165013. }
  165014. /* Special case: Huffman DC refinement scans need no Huffman table
  165015. * and therefore we can skip the optimization pass for them.
  165016. */
  165017. master->pass_type = output_pass;
  165018. master->pass_number++;
  165019. /*FALLTHROUGH*/
  165020. #endif
  165021. case output_pass:
  165022. /* Do a data-output pass. */
  165023. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165024. if (! cinfo->optimize_coding) {
  165025. select_scan_parameters(cinfo);
  165026. per_scan_setup(cinfo);
  165027. }
  165028. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165029. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165030. /* We emit frame/scan headers now */
  165031. if (master->scan_number == 0)
  165032. (*cinfo->marker->write_frame_header) (cinfo);
  165033. (*cinfo->marker->write_scan_header) (cinfo);
  165034. master->pub.call_pass_startup = FALSE;
  165035. break;
  165036. default:
  165037. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165038. }
  165039. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165040. /* Set up progress monitor's pass info if present */
  165041. if (cinfo->progress != NULL) {
  165042. cinfo->progress->completed_passes = master->pass_number;
  165043. cinfo->progress->total_passes = master->total_passes;
  165044. }
  165045. }
  165046. /*
  165047. * Special start-of-pass hook.
  165048. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165049. * In single-pass processing, we need this hook because we don't want to
  165050. * write frame/scan headers during jpeg_start_compress; we want to let the
  165051. * application write COM markers etc. between jpeg_start_compress and the
  165052. * jpeg_write_scanlines loop.
  165053. * In multi-pass processing, this routine is not used.
  165054. */
  165055. METHODDEF(void)
  165056. pass_startup (j_compress_ptr cinfo)
  165057. {
  165058. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165059. (*cinfo->marker->write_frame_header) (cinfo);
  165060. (*cinfo->marker->write_scan_header) (cinfo);
  165061. }
  165062. /*
  165063. * Finish up at end of pass.
  165064. */
  165065. METHODDEF(void)
  165066. finish_pass_master (j_compress_ptr cinfo)
  165067. {
  165068. my_master_ptr master = (my_master_ptr) cinfo->master;
  165069. /* The entropy coder always needs an end-of-pass call,
  165070. * either to analyze statistics or to flush its output buffer.
  165071. */
  165072. (*cinfo->entropy->finish_pass) (cinfo);
  165073. /* Update state for next pass */
  165074. switch (master->pass_type) {
  165075. case main_pass:
  165076. /* next pass is either output of scan 0 (after optimization)
  165077. * or output of scan 1 (if no optimization).
  165078. */
  165079. master->pass_type = output_pass;
  165080. if (! cinfo->optimize_coding)
  165081. master->scan_number++;
  165082. break;
  165083. case huff_opt_pass:
  165084. /* next pass is always output of current scan */
  165085. master->pass_type = output_pass;
  165086. break;
  165087. case output_pass:
  165088. /* next pass is either optimization or output of next scan */
  165089. if (cinfo->optimize_coding)
  165090. master->pass_type = huff_opt_pass;
  165091. master->scan_number++;
  165092. break;
  165093. }
  165094. master->pass_number++;
  165095. }
  165096. /*
  165097. * Initialize master compression control.
  165098. */
  165099. GLOBAL(void)
  165100. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165101. {
  165102. my_master_ptr master;
  165103. master = (my_master_ptr)
  165104. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165105. SIZEOF(my_comp_master));
  165106. cinfo->master = (struct jpeg_comp_master *) master;
  165107. master->pub.prepare_for_pass = prepare_for_pass;
  165108. master->pub.pass_startup = pass_startup;
  165109. master->pub.finish_pass = finish_pass_master;
  165110. master->pub.is_last_pass = FALSE;
  165111. /* Validate parameters, determine derived values */
  165112. initial_setup(cinfo);
  165113. if (cinfo->scan_info != NULL) {
  165114. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165115. validate_script(cinfo);
  165116. #else
  165117. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165118. #endif
  165119. } else {
  165120. cinfo->progressive_mode = FALSE;
  165121. cinfo->num_scans = 1;
  165122. }
  165123. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165124. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165125. /* Initialize my private state */
  165126. if (transcode_only) {
  165127. /* no main pass in transcoding */
  165128. if (cinfo->optimize_coding)
  165129. master->pass_type = huff_opt_pass;
  165130. else
  165131. master->pass_type = output_pass;
  165132. } else {
  165133. /* for normal compression, first pass is always this type: */
  165134. master->pass_type = main_pass;
  165135. }
  165136. master->scan_number = 0;
  165137. master->pass_number = 0;
  165138. if (cinfo->optimize_coding)
  165139. master->total_passes = cinfo->num_scans * 2;
  165140. else
  165141. master->total_passes = cinfo->num_scans;
  165142. }
  165143. /*** End of inlined file: jcmaster.c ***/
  165144. /*** Start of inlined file: jcomapi.c ***/
  165145. #define JPEG_INTERNALS
  165146. /*
  165147. * Abort processing of a JPEG compression or decompression operation,
  165148. * but don't destroy the object itself.
  165149. *
  165150. * For this, we merely clean up all the nonpermanent memory pools.
  165151. * Note that temp files (virtual arrays) are not allowed to belong to
  165152. * the permanent pool, so we will be able to close all temp files here.
  165153. * Closing a data source or destination, if necessary, is the application's
  165154. * responsibility.
  165155. */
  165156. GLOBAL(void)
  165157. jpeg_abort (j_common_ptr cinfo)
  165158. {
  165159. int pool;
  165160. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165161. if (cinfo->mem == NULL)
  165162. return;
  165163. /* Releasing pools in reverse order might help avoid fragmentation
  165164. * with some (brain-damaged) malloc libraries.
  165165. */
  165166. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165167. (*cinfo->mem->free_pool) (cinfo, pool);
  165168. }
  165169. /* Reset overall state for possible reuse of object */
  165170. if (cinfo->is_decompressor) {
  165171. cinfo->global_state = DSTATE_START;
  165172. /* Try to keep application from accessing now-deleted marker list.
  165173. * A bit kludgy to do it here, but this is the most central place.
  165174. */
  165175. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165176. } else {
  165177. cinfo->global_state = CSTATE_START;
  165178. }
  165179. }
  165180. /*
  165181. * Destruction of a JPEG object.
  165182. *
  165183. * Everything gets deallocated except the master jpeg_compress_struct itself
  165184. * and the error manager struct. Both of these are supplied by the application
  165185. * and must be freed, if necessary, by the application. (Often they are on
  165186. * the stack and so don't need to be freed anyway.)
  165187. * Closing a data source or destination, if necessary, is the application's
  165188. * responsibility.
  165189. */
  165190. GLOBAL(void)
  165191. jpeg_destroy (j_common_ptr cinfo)
  165192. {
  165193. /* We need only tell the memory manager to release everything. */
  165194. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165195. if (cinfo->mem != NULL)
  165196. (*cinfo->mem->self_destruct) (cinfo);
  165197. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165198. cinfo->global_state = 0; /* mark it destroyed */
  165199. }
  165200. /*
  165201. * Convenience routines for allocating quantization and Huffman tables.
  165202. * (Would jutils.c be a more reasonable place to put these?)
  165203. */
  165204. GLOBAL(JQUANT_TBL *)
  165205. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165206. {
  165207. JQUANT_TBL *tbl;
  165208. tbl = (JQUANT_TBL *)
  165209. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165210. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165211. return tbl;
  165212. }
  165213. GLOBAL(JHUFF_TBL *)
  165214. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165215. {
  165216. JHUFF_TBL *tbl;
  165217. tbl = (JHUFF_TBL *)
  165218. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165219. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165220. return tbl;
  165221. }
  165222. /*** End of inlined file: jcomapi.c ***/
  165223. /*** Start of inlined file: jcparam.c ***/
  165224. #define JPEG_INTERNALS
  165225. /*
  165226. * Quantization table setup routines
  165227. */
  165228. GLOBAL(void)
  165229. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165230. const unsigned int *basic_table,
  165231. int scale_factor, boolean force_baseline)
  165232. /* Define a quantization table equal to the basic_table times
  165233. * a scale factor (given as a percentage).
  165234. * If force_baseline is TRUE, the computed quantization table entries
  165235. * are limited to 1..255 for JPEG baseline compatibility.
  165236. */
  165237. {
  165238. JQUANT_TBL ** qtblptr;
  165239. int i;
  165240. long temp;
  165241. /* Safety check to ensure start_compress not called yet. */
  165242. if (cinfo->global_state != CSTATE_START)
  165243. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165244. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165245. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165246. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165247. if (*qtblptr == NULL)
  165248. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165249. for (i = 0; i < DCTSIZE2; i++) {
  165250. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165251. /* limit the values to the valid range */
  165252. if (temp <= 0L) temp = 1L;
  165253. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165254. if (force_baseline && temp > 255L)
  165255. temp = 255L; /* limit to baseline range if requested */
  165256. (*qtblptr)->quantval[i] = (UINT16) temp;
  165257. }
  165258. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165259. (*qtblptr)->sent_table = FALSE;
  165260. }
  165261. GLOBAL(void)
  165262. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165263. boolean force_baseline)
  165264. /* Set or change the 'quality' (quantization) setting, using default tables
  165265. * and a straight percentage-scaling quality scale. In most cases it's better
  165266. * to use jpeg_set_quality (below); this entry point is provided for
  165267. * applications that insist on a linear percentage scaling.
  165268. */
  165269. {
  165270. /* These are the sample quantization tables given in JPEG spec section K.1.
  165271. * The spec says that the values given produce "good" quality, and
  165272. * when divided by 2, "very good" quality.
  165273. */
  165274. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165275. 16, 11, 10, 16, 24, 40, 51, 61,
  165276. 12, 12, 14, 19, 26, 58, 60, 55,
  165277. 14, 13, 16, 24, 40, 57, 69, 56,
  165278. 14, 17, 22, 29, 51, 87, 80, 62,
  165279. 18, 22, 37, 56, 68, 109, 103, 77,
  165280. 24, 35, 55, 64, 81, 104, 113, 92,
  165281. 49, 64, 78, 87, 103, 121, 120, 101,
  165282. 72, 92, 95, 98, 112, 100, 103, 99
  165283. };
  165284. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165285. 17, 18, 24, 47, 99, 99, 99, 99,
  165286. 18, 21, 26, 66, 99, 99, 99, 99,
  165287. 24, 26, 56, 99, 99, 99, 99, 99,
  165288. 47, 66, 99, 99, 99, 99, 99, 99,
  165289. 99, 99, 99, 99, 99, 99, 99, 99,
  165290. 99, 99, 99, 99, 99, 99, 99, 99,
  165291. 99, 99, 99, 99, 99, 99, 99, 99,
  165292. 99, 99, 99, 99, 99, 99, 99, 99
  165293. };
  165294. /* Set up two quantization tables using the specified scaling */
  165295. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165296. scale_factor, force_baseline);
  165297. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165298. scale_factor, force_baseline);
  165299. }
  165300. GLOBAL(int)
  165301. jpeg_quality_scaling (int quality)
  165302. /* Convert a user-specified quality rating to a percentage scaling factor
  165303. * for an underlying quantization table, using our recommended scaling curve.
  165304. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165305. */
  165306. {
  165307. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165308. if (quality <= 0) quality = 1;
  165309. if (quality > 100) quality = 100;
  165310. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165311. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165312. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165313. * to make all the table entries 1 (hence, minimum quantization loss).
  165314. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165315. */
  165316. if (quality < 50)
  165317. quality = 5000 / quality;
  165318. else
  165319. quality = 200 - quality*2;
  165320. return quality;
  165321. }
  165322. GLOBAL(void)
  165323. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165324. /* Set or change the 'quality' (quantization) setting, using default tables.
  165325. * This is the standard quality-adjusting entry point for typical user
  165326. * interfaces; only those who want detailed control over quantization tables
  165327. * would use the preceding three routines directly.
  165328. */
  165329. {
  165330. /* Convert user 0-100 rating to percentage scaling */
  165331. quality = jpeg_quality_scaling(quality);
  165332. /* Set up standard quality tables */
  165333. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165334. }
  165335. /*
  165336. * Huffman table setup routines
  165337. */
  165338. LOCAL(void)
  165339. add_huff_table (j_compress_ptr cinfo,
  165340. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165341. /* Define a Huffman table */
  165342. {
  165343. int nsymbols, len;
  165344. if (*htblptr == NULL)
  165345. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165346. /* Copy the number-of-symbols-of-each-code-length counts */
  165347. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165348. /* Validate the counts. We do this here mainly so we can copy the right
  165349. * number of symbols from the val[] array, without risking marching off
  165350. * the end of memory. jchuff.c will do a more thorough test later.
  165351. */
  165352. nsymbols = 0;
  165353. for (len = 1; len <= 16; len++)
  165354. nsymbols += bits[len];
  165355. if (nsymbols < 1 || nsymbols > 256)
  165356. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165357. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165358. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165359. (*htblptr)->sent_table = FALSE;
  165360. }
  165361. LOCAL(void)
  165362. std_huff_tables (j_compress_ptr cinfo)
  165363. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165364. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165365. {
  165366. static const UINT8 bits_dc_luminance[17] =
  165367. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165368. static const UINT8 val_dc_luminance[] =
  165369. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165370. static const UINT8 bits_dc_chrominance[17] =
  165371. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165372. static const UINT8 val_dc_chrominance[] =
  165373. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165374. static const UINT8 bits_ac_luminance[17] =
  165375. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165376. static const UINT8 val_ac_luminance[] =
  165377. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165378. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165379. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165380. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165381. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165382. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165383. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165384. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165385. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165386. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165387. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165388. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165389. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165390. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165391. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165392. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165393. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165394. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165395. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165396. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165397. 0xf9, 0xfa };
  165398. static const UINT8 bits_ac_chrominance[17] =
  165399. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165400. static const UINT8 val_ac_chrominance[] =
  165401. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165402. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165403. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165404. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165405. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165406. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165407. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165408. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165409. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165410. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165411. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165412. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165413. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165414. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165415. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165416. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165417. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165418. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165419. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165420. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165421. 0xf9, 0xfa };
  165422. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165423. bits_dc_luminance, val_dc_luminance);
  165424. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165425. bits_ac_luminance, val_ac_luminance);
  165426. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165427. bits_dc_chrominance, val_dc_chrominance);
  165428. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165429. bits_ac_chrominance, val_ac_chrominance);
  165430. }
  165431. /*
  165432. * Default parameter setup for compression.
  165433. *
  165434. * Applications that don't choose to use this routine must do their
  165435. * own setup of all these parameters. Alternately, you can call this
  165436. * to establish defaults and then alter parameters selectively. This
  165437. * is the recommended approach since, if we add any new parameters,
  165438. * your code will still work (they'll be set to reasonable defaults).
  165439. */
  165440. GLOBAL(void)
  165441. jpeg_set_defaults (j_compress_ptr cinfo)
  165442. {
  165443. int i;
  165444. /* Safety check to ensure start_compress not called yet. */
  165445. if (cinfo->global_state != CSTATE_START)
  165446. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165447. /* Allocate comp_info array large enough for maximum component count.
  165448. * Array is made permanent in case application wants to compress
  165449. * multiple images at same param settings.
  165450. */
  165451. if (cinfo->comp_info == NULL)
  165452. cinfo->comp_info = (jpeg_component_info *)
  165453. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165454. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165455. /* Initialize everything not dependent on the color space */
  165456. cinfo->data_precision = BITS_IN_JSAMPLE;
  165457. /* Set up two quantization tables using default quality of 75 */
  165458. jpeg_set_quality(cinfo, 75, TRUE);
  165459. /* Set up two Huffman tables */
  165460. std_huff_tables(cinfo);
  165461. /* Initialize default arithmetic coding conditioning */
  165462. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165463. cinfo->arith_dc_L[i] = 0;
  165464. cinfo->arith_dc_U[i] = 1;
  165465. cinfo->arith_ac_K[i] = 5;
  165466. }
  165467. /* Default is no multiple-scan output */
  165468. cinfo->scan_info = NULL;
  165469. cinfo->num_scans = 0;
  165470. /* Expect normal source image, not raw downsampled data */
  165471. cinfo->raw_data_in = FALSE;
  165472. /* Use Huffman coding, not arithmetic coding, by default */
  165473. cinfo->arith_code = FALSE;
  165474. /* By default, don't do extra passes to optimize entropy coding */
  165475. cinfo->optimize_coding = FALSE;
  165476. /* The standard Huffman tables are only valid for 8-bit data precision.
  165477. * If the precision is higher, force optimization on so that usable
  165478. * tables will be computed. This test can be removed if default tables
  165479. * are supplied that are valid for the desired precision.
  165480. */
  165481. if (cinfo->data_precision > 8)
  165482. cinfo->optimize_coding = TRUE;
  165483. /* By default, use the simpler non-cosited sampling alignment */
  165484. cinfo->CCIR601_sampling = FALSE;
  165485. /* No input smoothing */
  165486. cinfo->smoothing_factor = 0;
  165487. /* DCT algorithm preference */
  165488. cinfo->dct_method = JDCT_DEFAULT;
  165489. /* No restart markers */
  165490. cinfo->restart_interval = 0;
  165491. cinfo->restart_in_rows = 0;
  165492. /* Fill in default JFIF marker parameters. Note that whether the marker
  165493. * will actually be written is determined by jpeg_set_colorspace.
  165494. *
  165495. * By default, the library emits JFIF version code 1.01.
  165496. * An application that wants to emit JFIF 1.02 extension markers should set
  165497. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165498. * to 1.02, but there may still be some decoders in use that will complain
  165499. * about that; saying 1.01 should minimize compatibility problems.
  165500. */
  165501. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165502. cinfo->JFIF_minor_version = 1;
  165503. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165504. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165505. cinfo->Y_density = 1;
  165506. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165507. jpeg_default_colorspace(cinfo);
  165508. }
  165509. /*
  165510. * Select an appropriate JPEG colorspace for in_color_space.
  165511. */
  165512. GLOBAL(void)
  165513. jpeg_default_colorspace (j_compress_ptr cinfo)
  165514. {
  165515. switch (cinfo->in_color_space) {
  165516. case JCS_GRAYSCALE:
  165517. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165518. break;
  165519. case JCS_RGB:
  165520. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165521. break;
  165522. case JCS_YCbCr:
  165523. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165524. break;
  165525. case JCS_CMYK:
  165526. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165527. break;
  165528. case JCS_YCCK:
  165529. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165530. break;
  165531. case JCS_UNKNOWN:
  165532. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165533. break;
  165534. default:
  165535. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165536. }
  165537. }
  165538. /*
  165539. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165540. */
  165541. GLOBAL(void)
  165542. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165543. {
  165544. jpeg_component_info * compptr;
  165545. int ci;
  165546. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165547. (compptr = &cinfo->comp_info[index], \
  165548. compptr->component_id = (id), \
  165549. compptr->h_samp_factor = (hsamp), \
  165550. compptr->v_samp_factor = (vsamp), \
  165551. compptr->quant_tbl_no = (quant), \
  165552. compptr->dc_tbl_no = (dctbl), \
  165553. compptr->ac_tbl_no = (actbl) )
  165554. /* Safety check to ensure start_compress not called yet. */
  165555. if (cinfo->global_state != CSTATE_START)
  165556. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165557. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165558. * tables 1 for chrominance components.
  165559. */
  165560. cinfo->jpeg_color_space = colorspace;
  165561. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165562. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165563. switch (colorspace) {
  165564. case JCS_GRAYSCALE:
  165565. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165566. cinfo->num_components = 1;
  165567. /* JFIF specifies component ID 1 */
  165568. SET_COMP(0, 1, 1,1, 0, 0,0);
  165569. break;
  165570. case JCS_RGB:
  165571. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165572. cinfo->num_components = 3;
  165573. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165574. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165575. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165576. break;
  165577. case JCS_YCbCr:
  165578. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165579. cinfo->num_components = 3;
  165580. /* JFIF specifies component IDs 1,2,3 */
  165581. /* We default to 2x2 subsamples of chrominance */
  165582. SET_COMP(0, 1, 2,2, 0, 0,0);
  165583. SET_COMP(1, 2, 1,1, 1, 1,1);
  165584. SET_COMP(2, 3, 1,1, 1, 1,1);
  165585. break;
  165586. case JCS_CMYK:
  165587. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165588. cinfo->num_components = 4;
  165589. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165590. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165591. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165592. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165593. break;
  165594. case JCS_YCCK:
  165595. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165596. cinfo->num_components = 4;
  165597. SET_COMP(0, 1, 2,2, 0, 0,0);
  165598. SET_COMP(1, 2, 1,1, 1, 1,1);
  165599. SET_COMP(2, 3, 1,1, 1, 1,1);
  165600. SET_COMP(3, 4, 2,2, 0, 0,0);
  165601. break;
  165602. case JCS_UNKNOWN:
  165603. cinfo->num_components = cinfo->input_components;
  165604. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165605. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165606. MAX_COMPONENTS);
  165607. for (ci = 0; ci < cinfo->num_components; ci++) {
  165608. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165609. }
  165610. break;
  165611. default:
  165612. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165613. }
  165614. }
  165615. #ifdef C_PROGRESSIVE_SUPPORTED
  165616. LOCAL(jpeg_scan_info *)
  165617. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165618. int Ss, int Se, int Ah, int Al)
  165619. /* Support routine: generate one scan for specified component */
  165620. {
  165621. scanptr->comps_in_scan = 1;
  165622. scanptr->component_index[0] = ci;
  165623. scanptr->Ss = Ss;
  165624. scanptr->Se = Se;
  165625. scanptr->Ah = Ah;
  165626. scanptr->Al = Al;
  165627. scanptr++;
  165628. return scanptr;
  165629. }
  165630. LOCAL(jpeg_scan_info *)
  165631. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165632. int Ss, int Se, int Ah, int Al)
  165633. /* Support routine: generate one scan for each component */
  165634. {
  165635. int ci;
  165636. for (ci = 0; ci < ncomps; ci++) {
  165637. scanptr->comps_in_scan = 1;
  165638. scanptr->component_index[0] = ci;
  165639. scanptr->Ss = Ss;
  165640. scanptr->Se = Se;
  165641. scanptr->Ah = Ah;
  165642. scanptr->Al = Al;
  165643. scanptr++;
  165644. }
  165645. return scanptr;
  165646. }
  165647. LOCAL(jpeg_scan_info *)
  165648. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165649. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165650. {
  165651. int ci;
  165652. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165653. /* Single interleaved DC scan */
  165654. scanptr->comps_in_scan = ncomps;
  165655. for (ci = 0; ci < ncomps; ci++)
  165656. scanptr->component_index[ci] = ci;
  165657. scanptr->Ss = scanptr->Se = 0;
  165658. scanptr->Ah = Ah;
  165659. scanptr->Al = Al;
  165660. scanptr++;
  165661. } else {
  165662. /* Noninterleaved DC scan for each component */
  165663. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165664. }
  165665. return scanptr;
  165666. }
  165667. /*
  165668. * Create a recommended progressive-JPEG script.
  165669. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165670. */
  165671. GLOBAL(void)
  165672. jpeg_simple_progression (j_compress_ptr cinfo)
  165673. {
  165674. int ncomps = cinfo->num_components;
  165675. int nscans;
  165676. jpeg_scan_info * scanptr;
  165677. /* Safety check to ensure start_compress not called yet. */
  165678. if (cinfo->global_state != CSTATE_START)
  165679. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165680. /* Figure space needed for script. Calculation must match code below! */
  165681. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165682. /* Custom script for YCbCr color images. */
  165683. nscans = 10;
  165684. } else {
  165685. /* All-purpose script for other color spaces. */
  165686. if (ncomps > MAX_COMPS_IN_SCAN)
  165687. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165688. else
  165689. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165690. }
  165691. /* Allocate space for script.
  165692. * We need to put it in the permanent pool in case the application performs
  165693. * multiple compressions without changing the settings. To avoid a memory
  165694. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165695. * object, we try to re-use previously allocated space, and we allocate
  165696. * enough space to handle YCbCr even if initially asked for grayscale.
  165697. */
  165698. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165699. cinfo->script_space_size = MAX(nscans, 10);
  165700. cinfo->script_space = (jpeg_scan_info *)
  165701. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165702. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165703. }
  165704. scanptr = cinfo->script_space;
  165705. cinfo->scan_info = scanptr;
  165706. cinfo->num_scans = nscans;
  165707. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165708. /* Custom script for YCbCr color images. */
  165709. /* Initial DC scan */
  165710. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165711. /* Initial AC scan: get some luma data out in a hurry */
  165712. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165713. /* Chroma data is too small to be worth expending many scans on */
  165714. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165715. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165716. /* Complete spectral selection for luma AC */
  165717. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165718. /* Refine next bit of luma AC */
  165719. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165720. /* Finish DC successive approximation */
  165721. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165722. /* Finish AC successive approximation */
  165723. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165724. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165725. /* Luma bottom bit comes last since it's usually largest scan */
  165726. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165727. } else {
  165728. /* All-purpose script for other color spaces. */
  165729. /* Successive approximation first pass */
  165730. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165731. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165732. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165733. /* Successive approximation second pass */
  165734. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165735. /* Successive approximation final pass */
  165736. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165737. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165738. }
  165739. }
  165740. #endif /* C_PROGRESSIVE_SUPPORTED */
  165741. /*** End of inlined file: jcparam.c ***/
  165742. /*** Start of inlined file: jcphuff.c ***/
  165743. #define JPEG_INTERNALS
  165744. #ifdef C_PROGRESSIVE_SUPPORTED
  165745. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165746. typedef struct {
  165747. struct jpeg_entropy_encoder pub; /* public fields */
  165748. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165749. boolean gather_statistics;
  165750. /* Bit-level coding status.
  165751. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165752. */
  165753. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165754. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165755. INT32 put_buffer; /* current bit-accumulation buffer */
  165756. int put_bits; /* # of bits now in it */
  165757. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165758. /* Coding status for DC components */
  165759. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165760. /* Coding status for AC components */
  165761. int ac_tbl_no; /* the table number of the single component */
  165762. unsigned int EOBRUN; /* run length of EOBs */
  165763. unsigned int BE; /* # of buffered correction bits before MCU */
  165764. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165765. /* packing correction bits tightly would save some space but cost time... */
  165766. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165767. int next_restart_num; /* next restart number to write (0-7) */
  165768. /* Pointers to derived tables (these workspaces have image lifespan).
  165769. * Since any one scan codes only DC or only AC, we only need one set
  165770. * of tables, not one for DC and one for AC.
  165771. */
  165772. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165773. /* Statistics tables for optimization; again, one set is enough */
  165774. long * count_ptrs[NUM_HUFF_TBLS];
  165775. } phuff_entropy_encoder;
  165776. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165777. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165778. * buffer can hold. Larger sizes may slightly improve compression, but
  165779. * 1000 is already well into the realm of overkill.
  165780. * The minimum safe size is 64 bits.
  165781. */
  165782. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165783. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165784. * We assume that int right shift is unsigned if INT32 right shift is,
  165785. * which should be safe.
  165786. */
  165787. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165788. #define ISHIFT_TEMPS int ishift_temp;
  165789. #define IRIGHT_SHIFT(x,shft) \
  165790. ((ishift_temp = (x)) < 0 ? \
  165791. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165792. (ishift_temp >> (shft)))
  165793. #else
  165794. #define ISHIFT_TEMPS
  165795. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165796. #endif
  165797. /* Forward declarations */
  165798. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165799. JBLOCKROW *MCU_data));
  165800. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165801. JBLOCKROW *MCU_data));
  165802. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165803. JBLOCKROW *MCU_data));
  165804. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165805. JBLOCKROW *MCU_data));
  165806. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165807. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165808. /*
  165809. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165810. */
  165811. METHODDEF(void)
  165812. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165813. {
  165814. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165815. boolean is_DC_band;
  165816. int ci, tbl;
  165817. jpeg_component_info * compptr;
  165818. entropy->cinfo = cinfo;
  165819. entropy->gather_statistics = gather_statistics;
  165820. is_DC_band = (cinfo->Ss == 0);
  165821. /* We assume jcmaster.c already validated the scan parameters. */
  165822. /* Select execution routines */
  165823. if (cinfo->Ah == 0) {
  165824. if (is_DC_band)
  165825. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165826. else
  165827. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165828. } else {
  165829. if (is_DC_band)
  165830. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165831. else {
  165832. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165833. /* AC refinement needs a correction bit buffer */
  165834. if (entropy->bit_buffer == NULL)
  165835. entropy->bit_buffer = (char *)
  165836. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165837. MAX_CORR_BITS * SIZEOF(char));
  165838. }
  165839. }
  165840. if (gather_statistics)
  165841. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165842. else
  165843. entropy->pub.finish_pass = finish_pass_phuff;
  165844. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165845. * for AC coefficients.
  165846. */
  165847. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165848. compptr = cinfo->cur_comp_info[ci];
  165849. /* Initialize DC predictions to 0 */
  165850. entropy->last_dc_val[ci] = 0;
  165851. /* Get table index */
  165852. if (is_DC_band) {
  165853. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165854. continue;
  165855. tbl = compptr->dc_tbl_no;
  165856. } else {
  165857. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165858. }
  165859. if (gather_statistics) {
  165860. /* Check for invalid table index */
  165861. /* (make_c_derived_tbl does this in the other path) */
  165862. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165863. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165864. /* Allocate and zero the statistics tables */
  165865. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165866. if (entropy->count_ptrs[tbl] == NULL)
  165867. entropy->count_ptrs[tbl] = (long *)
  165868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165869. 257 * SIZEOF(long));
  165870. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165871. } else {
  165872. /* Compute derived values for Huffman table */
  165873. /* We may do this more than once for a table, but it's not expensive */
  165874. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165875. & entropy->derived_tbls[tbl]);
  165876. }
  165877. }
  165878. /* Initialize AC stuff */
  165879. entropy->EOBRUN = 0;
  165880. entropy->BE = 0;
  165881. /* Initialize bit buffer to empty */
  165882. entropy->put_buffer = 0;
  165883. entropy->put_bits = 0;
  165884. /* Initialize restart stuff */
  165885. entropy->restarts_to_go = cinfo->restart_interval;
  165886. entropy->next_restart_num = 0;
  165887. }
  165888. /* Outputting bytes to the file.
  165889. * NB: these must be called only when actually outputting,
  165890. * that is, entropy->gather_statistics == FALSE.
  165891. */
  165892. /* Emit a byte */
  165893. #define emit_byte(entropy,val) \
  165894. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165895. if (--(entropy)->free_in_buffer == 0) \
  165896. dump_buffer_p(entropy); }
  165897. LOCAL(void)
  165898. dump_buffer_p (phuff_entropy_ptr entropy)
  165899. /* Empty the output buffer; we do not support suspension in this module. */
  165900. {
  165901. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165902. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165903. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165904. /* After a successful buffer dump, must reset buffer pointers */
  165905. entropy->next_output_byte = dest->next_output_byte;
  165906. entropy->free_in_buffer = dest->free_in_buffer;
  165907. }
  165908. /* Outputting bits to the file */
  165909. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165910. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165911. * in one call, and we never retain more than 7 bits in put_buffer
  165912. * between calls, so 24 bits are sufficient.
  165913. */
  165914. INLINE
  165915. LOCAL(void)
  165916. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165917. /* Emit some bits, unless we are in gather mode */
  165918. {
  165919. /* This routine is heavily used, so it's worth coding tightly. */
  165920. register INT32 put_buffer = (INT32) code;
  165921. register int put_bits = entropy->put_bits;
  165922. /* if size is 0, caller used an invalid Huffman table entry */
  165923. if (size == 0)
  165924. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165925. if (entropy->gather_statistics)
  165926. return; /* do nothing if we're only getting stats */
  165927. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165928. put_bits += size; /* new number of bits in buffer */
  165929. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165930. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165931. while (put_bits >= 8) {
  165932. int c = (int) ((put_buffer >> 16) & 0xFF);
  165933. emit_byte(entropy, c);
  165934. if (c == 0xFF) { /* need to stuff a zero byte? */
  165935. emit_byte(entropy, 0);
  165936. }
  165937. put_buffer <<= 8;
  165938. put_bits -= 8;
  165939. }
  165940. entropy->put_buffer = put_buffer; /* update variables */
  165941. entropy->put_bits = put_bits;
  165942. }
  165943. LOCAL(void)
  165944. flush_bits_p (phuff_entropy_ptr entropy)
  165945. {
  165946. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165947. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165948. entropy->put_bits = 0;
  165949. }
  165950. /*
  165951. * Emit (or just count) a Huffman symbol.
  165952. */
  165953. INLINE
  165954. LOCAL(void)
  165955. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165956. {
  165957. if (entropy->gather_statistics)
  165958. entropy->count_ptrs[tbl_no][symbol]++;
  165959. else {
  165960. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165961. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165962. }
  165963. }
  165964. /*
  165965. * Emit bits from a correction bit buffer.
  165966. */
  165967. LOCAL(void)
  165968. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165969. unsigned int nbits)
  165970. {
  165971. if (entropy->gather_statistics)
  165972. return; /* no real work */
  165973. while (nbits > 0) {
  165974. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165975. bufstart++;
  165976. nbits--;
  165977. }
  165978. }
  165979. /*
  165980. * Emit any pending EOBRUN symbol.
  165981. */
  165982. LOCAL(void)
  165983. emit_eobrun (phuff_entropy_ptr entropy)
  165984. {
  165985. register int temp, nbits;
  165986. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165987. temp = entropy->EOBRUN;
  165988. nbits = 0;
  165989. while ((temp >>= 1))
  165990. nbits++;
  165991. /* safety check: shouldn't happen given limited correction-bit buffer */
  165992. if (nbits > 14)
  165993. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165994. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165995. if (nbits)
  165996. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165997. entropy->EOBRUN = 0;
  165998. /* Emit any buffered correction bits */
  165999. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166000. entropy->BE = 0;
  166001. }
  166002. }
  166003. /*
  166004. * Emit a restart marker & resynchronize predictions.
  166005. */
  166006. LOCAL(void)
  166007. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166008. {
  166009. int ci;
  166010. emit_eobrun(entropy);
  166011. if (! entropy->gather_statistics) {
  166012. flush_bits_p(entropy);
  166013. emit_byte(entropy, 0xFF);
  166014. emit_byte(entropy, JPEG_RST0 + restart_num);
  166015. }
  166016. if (entropy->cinfo->Ss == 0) {
  166017. /* Re-initialize DC predictions to 0 */
  166018. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166019. entropy->last_dc_val[ci] = 0;
  166020. } else {
  166021. /* Re-initialize all AC-related fields to 0 */
  166022. entropy->EOBRUN = 0;
  166023. entropy->BE = 0;
  166024. }
  166025. }
  166026. /*
  166027. * MCU encoding for DC initial scan (either spectral selection,
  166028. * or first pass of successive approximation).
  166029. */
  166030. METHODDEF(boolean)
  166031. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166032. {
  166033. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166034. register int temp, temp2;
  166035. register int nbits;
  166036. int blkn, ci;
  166037. int Al = cinfo->Al;
  166038. JBLOCKROW block;
  166039. jpeg_component_info * compptr;
  166040. ISHIFT_TEMPS
  166041. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166042. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166043. /* Emit restart marker if needed */
  166044. if (cinfo->restart_interval)
  166045. if (entropy->restarts_to_go == 0)
  166046. emit_restart_p(entropy, entropy->next_restart_num);
  166047. /* Encode the MCU data blocks */
  166048. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166049. block = MCU_data[blkn];
  166050. ci = cinfo->MCU_membership[blkn];
  166051. compptr = cinfo->cur_comp_info[ci];
  166052. /* Compute the DC value after the required point transform by Al.
  166053. * This is simply an arithmetic right shift.
  166054. */
  166055. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166056. /* DC differences are figured on the point-transformed values. */
  166057. temp = temp2 - entropy->last_dc_val[ci];
  166058. entropy->last_dc_val[ci] = temp2;
  166059. /* Encode the DC coefficient difference per section G.1.2.1 */
  166060. temp2 = temp;
  166061. if (temp < 0) {
  166062. temp = -temp; /* temp is abs value of input */
  166063. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166064. /* This code assumes we are on a two's complement machine */
  166065. temp2--;
  166066. }
  166067. /* Find the number of bits needed for the magnitude of the coefficient */
  166068. nbits = 0;
  166069. while (temp) {
  166070. nbits++;
  166071. temp >>= 1;
  166072. }
  166073. /* Check for out-of-range coefficient values.
  166074. * Since we're encoding a difference, the range limit is twice as much.
  166075. */
  166076. if (nbits > MAX_COEF_BITS+1)
  166077. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166078. /* Count/emit the Huffman-coded symbol for the number of bits */
  166079. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166080. /* Emit that number of bits of the value, if positive, */
  166081. /* or the complement of its magnitude, if negative. */
  166082. if (nbits) /* emit_bits rejects calls with size 0 */
  166083. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166084. }
  166085. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166086. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166087. /* Update restart-interval state too */
  166088. if (cinfo->restart_interval) {
  166089. if (entropy->restarts_to_go == 0) {
  166090. entropy->restarts_to_go = cinfo->restart_interval;
  166091. entropy->next_restart_num++;
  166092. entropy->next_restart_num &= 7;
  166093. }
  166094. entropy->restarts_to_go--;
  166095. }
  166096. return TRUE;
  166097. }
  166098. /*
  166099. * MCU encoding for AC initial scan (either spectral selection,
  166100. * or first pass of successive approximation).
  166101. */
  166102. METHODDEF(boolean)
  166103. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166104. {
  166105. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166106. register int temp, temp2;
  166107. register int nbits;
  166108. register int r, k;
  166109. int Se = cinfo->Se;
  166110. int Al = cinfo->Al;
  166111. JBLOCKROW block;
  166112. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166113. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166114. /* Emit restart marker if needed */
  166115. if (cinfo->restart_interval)
  166116. if (entropy->restarts_to_go == 0)
  166117. emit_restart_p(entropy, entropy->next_restart_num);
  166118. /* Encode the MCU data block */
  166119. block = MCU_data[0];
  166120. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166121. r = 0; /* r = run length of zeros */
  166122. for (k = cinfo->Ss; k <= Se; k++) {
  166123. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166124. r++;
  166125. continue;
  166126. }
  166127. /* We must apply the point transform by Al. For AC coefficients this
  166128. * is an integer division with rounding towards 0. To do this portably
  166129. * in C, we shift after obtaining the absolute value; so the code is
  166130. * interwoven with finding the abs value (temp) and output bits (temp2).
  166131. */
  166132. if (temp < 0) {
  166133. temp = -temp; /* temp is abs value of input */
  166134. temp >>= Al; /* apply the point transform */
  166135. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166136. temp2 = ~temp;
  166137. } else {
  166138. temp >>= Al; /* apply the point transform */
  166139. temp2 = temp;
  166140. }
  166141. /* Watch out for case that nonzero coef is zero after point transform */
  166142. if (temp == 0) {
  166143. r++;
  166144. continue;
  166145. }
  166146. /* Emit any pending EOBRUN */
  166147. if (entropy->EOBRUN > 0)
  166148. emit_eobrun(entropy);
  166149. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166150. while (r > 15) {
  166151. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166152. r -= 16;
  166153. }
  166154. /* Find the number of bits needed for the magnitude of the coefficient */
  166155. nbits = 1; /* there must be at least one 1 bit */
  166156. while ((temp >>= 1))
  166157. nbits++;
  166158. /* Check for out-of-range coefficient values */
  166159. if (nbits > MAX_COEF_BITS)
  166160. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166161. /* Count/emit Huffman symbol for run length / number of bits */
  166162. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166163. /* Emit that number of bits of the value, if positive, */
  166164. /* or the complement of its magnitude, if negative. */
  166165. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166166. r = 0; /* reset zero run length */
  166167. }
  166168. if (r > 0) { /* If there are trailing zeroes, */
  166169. entropy->EOBRUN++; /* count an EOB */
  166170. if (entropy->EOBRUN == 0x7FFF)
  166171. emit_eobrun(entropy); /* force it out to avoid overflow */
  166172. }
  166173. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166174. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166175. /* Update restart-interval state too */
  166176. if (cinfo->restart_interval) {
  166177. if (entropy->restarts_to_go == 0) {
  166178. entropy->restarts_to_go = cinfo->restart_interval;
  166179. entropy->next_restart_num++;
  166180. entropy->next_restart_num &= 7;
  166181. }
  166182. entropy->restarts_to_go--;
  166183. }
  166184. return TRUE;
  166185. }
  166186. /*
  166187. * MCU encoding for DC successive approximation refinement scan.
  166188. * Note: we assume such scans can be multi-component, although the spec
  166189. * is not very clear on the point.
  166190. */
  166191. METHODDEF(boolean)
  166192. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166193. {
  166194. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166195. register int temp;
  166196. int blkn;
  166197. int Al = cinfo->Al;
  166198. JBLOCKROW block;
  166199. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166200. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166201. /* Emit restart marker if needed */
  166202. if (cinfo->restart_interval)
  166203. if (entropy->restarts_to_go == 0)
  166204. emit_restart_p(entropy, entropy->next_restart_num);
  166205. /* Encode the MCU data blocks */
  166206. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166207. block = MCU_data[blkn];
  166208. /* We simply emit the Al'th bit of the DC coefficient value. */
  166209. temp = (*block)[0];
  166210. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166211. }
  166212. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166213. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166214. /* Update restart-interval state too */
  166215. if (cinfo->restart_interval) {
  166216. if (entropy->restarts_to_go == 0) {
  166217. entropy->restarts_to_go = cinfo->restart_interval;
  166218. entropy->next_restart_num++;
  166219. entropy->next_restart_num &= 7;
  166220. }
  166221. entropy->restarts_to_go--;
  166222. }
  166223. return TRUE;
  166224. }
  166225. /*
  166226. * MCU encoding for AC successive approximation refinement scan.
  166227. */
  166228. METHODDEF(boolean)
  166229. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166230. {
  166231. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166232. register int temp;
  166233. register int r, k;
  166234. int EOB;
  166235. char *BR_buffer;
  166236. unsigned int BR;
  166237. int Se = cinfo->Se;
  166238. int Al = cinfo->Al;
  166239. JBLOCKROW block;
  166240. int absvalues[DCTSIZE2];
  166241. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166242. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166243. /* Emit restart marker if needed */
  166244. if (cinfo->restart_interval)
  166245. if (entropy->restarts_to_go == 0)
  166246. emit_restart_p(entropy, entropy->next_restart_num);
  166247. /* Encode the MCU data block */
  166248. block = MCU_data[0];
  166249. /* It is convenient to make a pre-pass to determine the transformed
  166250. * coefficients' absolute values and the EOB position.
  166251. */
  166252. EOB = 0;
  166253. for (k = cinfo->Ss; k <= Se; k++) {
  166254. temp = (*block)[jpeg_natural_order[k]];
  166255. /* We must apply the point transform by Al. For AC coefficients this
  166256. * is an integer division with rounding towards 0. To do this portably
  166257. * in C, we shift after obtaining the absolute value.
  166258. */
  166259. if (temp < 0)
  166260. temp = -temp; /* temp is abs value of input */
  166261. temp >>= Al; /* apply the point transform */
  166262. absvalues[k] = temp; /* save abs value for main pass */
  166263. if (temp == 1)
  166264. EOB = k; /* EOB = index of last newly-nonzero coef */
  166265. }
  166266. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166267. r = 0; /* r = run length of zeros */
  166268. BR = 0; /* BR = count of buffered bits added now */
  166269. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166270. for (k = cinfo->Ss; k <= Se; k++) {
  166271. if ((temp = absvalues[k]) == 0) {
  166272. r++;
  166273. continue;
  166274. }
  166275. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166276. while (r > 15 && k <= EOB) {
  166277. /* emit any pending EOBRUN and the BE correction bits */
  166278. emit_eobrun(entropy);
  166279. /* Emit ZRL */
  166280. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166281. r -= 16;
  166282. /* Emit buffered correction bits that must be associated with ZRL */
  166283. emit_buffered_bits(entropy, BR_buffer, BR);
  166284. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166285. BR = 0;
  166286. }
  166287. /* If the coef was previously nonzero, it only needs a correction bit.
  166288. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166289. * that we also need to test r > 15. But if r > 15, we can only get here
  166290. * if k > EOB, which implies that this coefficient is not 1.
  166291. */
  166292. if (temp > 1) {
  166293. /* The correction bit is the next bit of the absolute value. */
  166294. BR_buffer[BR++] = (char) (temp & 1);
  166295. continue;
  166296. }
  166297. /* Emit any pending EOBRUN and the BE correction bits */
  166298. emit_eobrun(entropy);
  166299. /* Count/emit Huffman symbol for run length / number of bits */
  166300. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166301. /* Emit output bit for newly-nonzero coef */
  166302. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166303. emit_bits_p(entropy, (unsigned int) temp, 1);
  166304. /* Emit buffered correction bits that must be associated with this code */
  166305. emit_buffered_bits(entropy, BR_buffer, BR);
  166306. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166307. BR = 0;
  166308. r = 0; /* reset zero run length */
  166309. }
  166310. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166311. entropy->EOBRUN++; /* count an EOB */
  166312. entropy->BE += BR; /* concat my correction bits to older ones */
  166313. /* We force out the EOB if we risk either:
  166314. * 1. overflow of the EOB counter;
  166315. * 2. overflow of the correction bit buffer during the next MCU.
  166316. */
  166317. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166318. emit_eobrun(entropy);
  166319. }
  166320. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166321. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166322. /* Update restart-interval state too */
  166323. if (cinfo->restart_interval) {
  166324. if (entropy->restarts_to_go == 0) {
  166325. entropy->restarts_to_go = cinfo->restart_interval;
  166326. entropy->next_restart_num++;
  166327. entropy->next_restart_num &= 7;
  166328. }
  166329. entropy->restarts_to_go--;
  166330. }
  166331. return TRUE;
  166332. }
  166333. /*
  166334. * Finish up at the end of a Huffman-compressed progressive scan.
  166335. */
  166336. METHODDEF(void)
  166337. finish_pass_phuff (j_compress_ptr cinfo)
  166338. {
  166339. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166340. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166341. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166342. /* Flush out any buffered data */
  166343. emit_eobrun(entropy);
  166344. flush_bits_p(entropy);
  166345. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166346. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166347. }
  166348. /*
  166349. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166350. */
  166351. METHODDEF(void)
  166352. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166353. {
  166354. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166355. boolean is_DC_band;
  166356. int ci, tbl;
  166357. jpeg_component_info * compptr;
  166358. JHUFF_TBL **htblptr;
  166359. boolean did[NUM_HUFF_TBLS];
  166360. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166361. emit_eobrun(entropy);
  166362. is_DC_band = (cinfo->Ss == 0);
  166363. /* It's important not to apply jpeg_gen_optimal_table more than once
  166364. * per table, because it clobbers the input frequency counts!
  166365. */
  166366. MEMZERO(did, SIZEOF(did));
  166367. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166368. compptr = cinfo->cur_comp_info[ci];
  166369. if (is_DC_band) {
  166370. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166371. continue;
  166372. tbl = compptr->dc_tbl_no;
  166373. } else {
  166374. tbl = compptr->ac_tbl_no;
  166375. }
  166376. if (! did[tbl]) {
  166377. if (is_DC_band)
  166378. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166379. else
  166380. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166381. if (*htblptr == NULL)
  166382. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166383. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166384. did[tbl] = TRUE;
  166385. }
  166386. }
  166387. }
  166388. /*
  166389. * Module initialization routine for progressive Huffman entropy encoding.
  166390. */
  166391. GLOBAL(void)
  166392. jinit_phuff_encoder (j_compress_ptr cinfo)
  166393. {
  166394. phuff_entropy_ptr entropy;
  166395. int i;
  166396. entropy = (phuff_entropy_ptr)
  166397. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166398. SIZEOF(phuff_entropy_encoder));
  166399. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166400. entropy->pub.start_pass = start_pass_phuff;
  166401. /* Mark tables unallocated */
  166402. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166403. entropy->derived_tbls[i] = NULL;
  166404. entropy->count_ptrs[i] = NULL;
  166405. }
  166406. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166407. }
  166408. #endif /* C_PROGRESSIVE_SUPPORTED */
  166409. /*** End of inlined file: jcphuff.c ***/
  166410. /*** Start of inlined file: jcprepct.c ***/
  166411. #define JPEG_INTERNALS
  166412. /* At present, jcsample.c can request context rows only for smoothing.
  166413. * In the future, we might also need context rows for CCIR601 sampling
  166414. * or other more-complex downsampling procedures. The code to support
  166415. * context rows should be compiled only if needed.
  166416. */
  166417. #ifdef INPUT_SMOOTHING_SUPPORTED
  166418. #define CONTEXT_ROWS_SUPPORTED
  166419. #endif
  166420. /*
  166421. * For the simple (no-context-row) case, we just need to buffer one
  166422. * row group's worth of pixels for the downsampling step. At the bottom of
  166423. * the image, we pad to a full row group by replicating the last pixel row.
  166424. * The downsampler's last output row is then replicated if needed to pad
  166425. * out to a full iMCU row.
  166426. *
  166427. * When providing context rows, we must buffer three row groups' worth of
  166428. * pixels. Three row groups are physically allocated, but the row pointer
  166429. * arrays are made five row groups high, with the extra pointers above and
  166430. * below "wrapping around" to point to the last and first real row groups.
  166431. * This allows the downsampler to access the proper context rows.
  166432. * At the top and bottom of the image, we create dummy context rows by
  166433. * copying the first or last real pixel row. This copying could be avoided
  166434. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166435. * trouble on the compression side.
  166436. */
  166437. /* Private buffer controller object */
  166438. typedef struct {
  166439. struct jpeg_c_prep_controller pub; /* public fields */
  166440. /* Downsampling input buffer. This buffer holds color-converted data
  166441. * until we have enough to do a downsample step.
  166442. */
  166443. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166444. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166445. int next_buf_row; /* index of next row to store in color_buf */
  166446. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166447. int this_row_group; /* starting row index of group to process */
  166448. int next_buf_stop; /* downsample when we reach this index */
  166449. #endif
  166450. } my_prep_controller;
  166451. typedef my_prep_controller * my_prep_ptr;
  166452. /*
  166453. * Initialize for a processing pass.
  166454. */
  166455. METHODDEF(void)
  166456. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166457. {
  166458. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166459. if (pass_mode != JBUF_PASS_THRU)
  166460. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166461. /* Initialize total-height counter for detecting bottom of image */
  166462. prep->rows_to_go = cinfo->image_height;
  166463. /* Mark the conversion buffer empty */
  166464. prep->next_buf_row = 0;
  166465. #ifdef CONTEXT_ROWS_SUPPORTED
  166466. /* Preset additional state variables for context mode.
  166467. * These aren't used in non-context mode, so we needn't test which mode.
  166468. */
  166469. prep->this_row_group = 0;
  166470. /* Set next_buf_stop to stop after two row groups have been read in. */
  166471. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166472. #endif
  166473. }
  166474. /*
  166475. * Expand an image vertically from height input_rows to height output_rows,
  166476. * by duplicating the bottom row.
  166477. */
  166478. LOCAL(void)
  166479. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166480. int input_rows, int output_rows)
  166481. {
  166482. register int row;
  166483. for (row = input_rows; row < output_rows; row++) {
  166484. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166485. 1, num_cols);
  166486. }
  166487. }
  166488. /*
  166489. * Process some data in the simple no-context case.
  166490. *
  166491. * Preprocessor output data is counted in "row groups". A row group
  166492. * is defined to be v_samp_factor sample rows of each component.
  166493. * Downsampling will produce this much data from each max_v_samp_factor
  166494. * input rows.
  166495. */
  166496. METHODDEF(void)
  166497. pre_process_data (j_compress_ptr cinfo,
  166498. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166499. JDIMENSION in_rows_avail,
  166500. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166501. JDIMENSION out_row_groups_avail)
  166502. {
  166503. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166504. int numrows, ci;
  166505. JDIMENSION inrows;
  166506. jpeg_component_info * compptr;
  166507. while (*in_row_ctr < in_rows_avail &&
  166508. *out_row_group_ctr < out_row_groups_avail) {
  166509. /* Do color conversion to fill the conversion buffer. */
  166510. inrows = in_rows_avail - *in_row_ctr;
  166511. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166512. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166513. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166514. prep->color_buf,
  166515. (JDIMENSION) prep->next_buf_row,
  166516. numrows);
  166517. *in_row_ctr += numrows;
  166518. prep->next_buf_row += numrows;
  166519. prep->rows_to_go -= numrows;
  166520. /* If at bottom of image, pad to fill the conversion buffer. */
  166521. if (prep->rows_to_go == 0 &&
  166522. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166523. for (ci = 0; ci < cinfo->num_components; ci++) {
  166524. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166525. prep->next_buf_row, cinfo->max_v_samp_factor);
  166526. }
  166527. prep->next_buf_row = cinfo->max_v_samp_factor;
  166528. }
  166529. /* If we've filled the conversion buffer, empty it. */
  166530. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166531. (*cinfo->downsample->downsample) (cinfo,
  166532. prep->color_buf, (JDIMENSION) 0,
  166533. output_buf, *out_row_group_ctr);
  166534. prep->next_buf_row = 0;
  166535. (*out_row_group_ctr)++;
  166536. }
  166537. /* If at bottom of image, pad the output to a full iMCU height.
  166538. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166539. */
  166540. if (prep->rows_to_go == 0 &&
  166541. *out_row_group_ctr < out_row_groups_avail) {
  166542. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166543. ci++, compptr++) {
  166544. expand_bottom_edge(output_buf[ci],
  166545. compptr->width_in_blocks * DCTSIZE,
  166546. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166547. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166548. }
  166549. *out_row_group_ctr = out_row_groups_avail;
  166550. break; /* can exit outer loop without test */
  166551. }
  166552. }
  166553. }
  166554. #ifdef CONTEXT_ROWS_SUPPORTED
  166555. /*
  166556. * Process some data in the context case.
  166557. */
  166558. METHODDEF(void)
  166559. pre_process_context (j_compress_ptr cinfo,
  166560. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166561. JDIMENSION in_rows_avail,
  166562. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166563. JDIMENSION out_row_groups_avail)
  166564. {
  166565. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166566. int numrows, ci;
  166567. int buf_height = cinfo->max_v_samp_factor * 3;
  166568. JDIMENSION inrows;
  166569. while (*out_row_group_ctr < out_row_groups_avail) {
  166570. if (*in_row_ctr < in_rows_avail) {
  166571. /* Do color conversion to fill the conversion buffer. */
  166572. inrows = in_rows_avail - *in_row_ctr;
  166573. numrows = prep->next_buf_stop - prep->next_buf_row;
  166574. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166575. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166576. prep->color_buf,
  166577. (JDIMENSION) prep->next_buf_row,
  166578. numrows);
  166579. /* Pad at top of image, if first time through */
  166580. if (prep->rows_to_go == cinfo->image_height) {
  166581. for (ci = 0; ci < cinfo->num_components; ci++) {
  166582. int row;
  166583. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166584. jcopy_sample_rows(prep->color_buf[ci], 0,
  166585. prep->color_buf[ci], -row,
  166586. 1, cinfo->image_width);
  166587. }
  166588. }
  166589. }
  166590. *in_row_ctr += numrows;
  166591. prep->next_buf_row += numrows;
  166592. prep->rows_to_go -= numrows;
  166593. } else {
  166594. /* Return for more data, unless we are at the bottom of the image. */
  166595. if (prep->rows_to_go != 0)
  166596. break;
  166597. /* When at bottom of image, pad to fill the conversion buffer. */
  166598. if (prep->next_buf_row < prep->next_buf_stop) {
  166599. for (ci = 0; ci < cinfo->num_components; ci++) {
  166600. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166601. prep->next_buf_row, prep->next_buf_stop);
  166602. }
  166603. prep->next_buf_row = prep->next_buf_stop;
  166604. }
  166605. }
  166606. /* If we've gotten enough data, downsample a row group. */
  166607. if (prep->next_buf_row == prep->next_buf_stop) {
  166608. (*cinfo->downsample->downsample) (cinfo,
  166609. prep->color_buf,
  166610. (JDIMENSION) prep->this_row_group,
  166611. output_buf, *out_row_group_ctr);
  166612. (*out_row_group_ctr)++;
  166613. /* Advance pointers with wraparound as necessary. */
  166614. prep->this_row_group += cinfo->max_v_samp_factor;
  166615. if (prep->this_row_group >= buf_height)
  166616. prep->this_row_group = 0;
  166617. if (prep->next_buf_row >= buf_height)
  166618. prep->next_buf_row = 0;
  166619. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166620. }
  166621. }
  166622. }
  166623. /*
  166624. * Create the wrapped-around downsampling input buffer needed for context mode.
  166625. */
  166626. LOCAL(void)
  166627. create_context_buffer (j_compress_ptr cinfo)
  166628. {
  166629. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166630. int rgroup_height = cinfo->max_v_samp_factor;
  166631. int ci, i;
  166632. jpeg_component_info * compptr;
  166633. JSAMPARRAY true_buffer, fake_buffer;
  166634. /* Grab enough space for fake row pointers for all the components;
  166635. * we need five row groups' worth of pointers for each component.
  166636. */
  166637. fake_buffer = (JSAMPARRAY)
  166638. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166639. (cinfo->num_components * 5 * rgroup_height) *
  166640. SIZEOF(JSAMPROW));
  166641. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166642. ci++, compptr++) {
  166643. /* Allocate the actual buffer space (3 row groups) for this component.
  166644. * We make the buffer wide enough to allow the downsampler to edge-expand
  166645. * horizontally within the buffer, if it so chooses.
  166646. */
  166647. true_buffer = (*cinfo->mem->alloc_sarray)
  166648. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166649. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166650. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166651. (JDIMENSION) (3 * rgroup_height));
  166652. /* Copy true buffer row pointers into the middle of the fake row array */
  166653. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166654. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166655. /* Fill in the above and below wraparound pointers */
  166656. for (i = 0; i < rgroup_height; i++) {
  166657. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166658. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166659. }
  166660. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166661. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166662. }
  166663. }
  166664. #endif /* CONTEXT_ROWS_SUPPORTED */
  166665. /*
  166666. * Initialize preprocessing controller.
  166667. */
  166668. GLOBAL(void)
  166669. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166670. {
  166671. my_prep_ptr prep;
  166672. int ci;
  166673. jpeg_component_info * compptr;
  166674. if (need_full_buffer) /* safety check */
  166675. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166676. prep = (my_prep_ptr)
  166677. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166678. SIZEOF(my_prep_controller));
  166679. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166680. prep->pub.start_pass = start_pass_prep;
  166681. /* Allocate the color conversion buffer.
  166682. * We make the buffer wide enough to allow the downsampler to edge-expand
  166683. * horizontally within the buffer, if it so chooses.
  166684. */
  166685. if (cinfo->downsample->need_context_rows) {
  166686. /* Set up to provide context rows */
  166687. #ifdef CONTEXT_ROWS_SUPPORTED
  166688. prep->pub.pre_process_data = pre_process_context;
  166689. create_context_buffer(cinfo);
  166690. #else
  166691. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166692. #endif
  166693. } else {
  166694. /* No context, just make it tall enough for one row group */
  166695. prep->pub.pre_process_data = pre_process_data;
  166696. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166697. ci++, compptr++) {
  166698. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166699. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166700. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166701. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166702. (JDIMENSION) cinfo->max_v_samp_factor);
  166703. }
  166704. }
  166705. }
  166706. /*** End of inlined file: jcprepct.c ***/
  166707. /*** Start of inlined file: jcsample.c ***/
  166708. #define JPEG_INTERNALS
  166709. /* Pointer to routine to downsample a single component */
  166710. typedef JMETHOD(void, downsample1_ptr,
  166711. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166712. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166713. /* Private subobject */
  166714. typedef struct {
  166715. struct jpeg_downsampler pub; /* public fields */
  166716. /* Downsampling method pointers, one per component */
  166717. downsample1_ptr methods[MAX_COMPONENTS];
  166718. } my_downsampler;
  166719. typedef my_downsampler * my_downsample_ptr;
  166720. /*
  166721. * Initialize for a downsampling pass.
  166722. */
  166723. METHODDEF(void)
  166724. start_pass_downsample (j_compress_ptr)
  166725. {
  166726. /* no work for now */
  166727. }
  166728. /*
  166729. * Expand a component horizontally from width input_cols to width output_cols,
  166730. * by duplicating the rightmost samples.
  166731. */
  166732. LOCAL(void)
  166733. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166734. JDIMENSION input_cols, JDIMENSION output_cols)
  166735. {
  166736. register JSAMPROW ptr;
  166737. register JSAMPLE pixval;
  166738. register int count;
  166739. int row;
  166740. int numcols = (int) (output_cols - input_cols);
  166741. if (numcols > 0) {
  166742. for (row = 0; row < num_rows; row++) {
  166743. ptr = image_data[row] + input_cols;
  166744. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166745. for (count = numcols; count > 0; count--)
  166746. *ptr++ = pixval;
  166747. }
  166748. }
  166749. }
  166750. /*
  166751. * Do downsampling for a whole row group (all components).
  166752. *
  166753. * In this version we simply downsample each component independently.
  166754. */
  166755. METHODDEF(void)
  166756. sep_downsample (j_compress_ptr cinfo,
  166757. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166758. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166759. {
  166760. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166761. int ci;
  166762. jpeg_component_info * compptr;
  166763. JSAMPARRAY in_ptr, out_ptr;
  166764. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166765. ci++, compptr++) {
  166766. in_ptr = input_buf[ci] + in_row_index;
  166767. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166768. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166769. }
  166770. }
  166771. /*
  166772. * Downsample pixel values of a single component.
  166773. * One row group is processed per call.
  166774. * This version handles arbitrary integral sampling ratios, without smoothing.
  166775. * Note that this version is not actually used for customary sampling ratios.
  166776. */
  166777. METHODDEF(void)
  166778. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166779. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166780. {
  166781. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166782. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166783. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166784. JSAMPROW inptr, outptr;
  166785. INT32 outvalue;
  166786. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166787. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166788. numpix = h_expand * v_expand;
  166789. numpix2 = numpix/2;
  166790. /* Expand input data enough to let all the output samples be generated
  166791. * by the standard loop. Special-casing padded output would be more
  166792. * efficient.
  166793. */
  166794. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166795. cinfo->image_width, output_cols * h_expand);
  166796. inrow = 0;
  166797. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166798. outptr = output_data[outrow];
  166799. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166800. outcol++, outcol_h += h_expand) {
  166801. outvalue = 0;
  166802. for (v = 0; v < v_expand; v++) {
  166803. inptr = input_data[inrow+v] + outcol_h;
  166804. for (h = 0; h < h_expand; h++) {
  166805. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166806. }
  166807. }
  166808. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166809. }
  166810. inrow += v_expand;
  166811. }
  166812. }
  166813. /*
  166814. * Downsample pixel values of a single component.
  166815. * This version handles the special case of a full-size component,
  166816. * without smoothing.
  166817. */
  166818. METHODDEF(void)
  166819. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166820. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166821. {
  166822. /* Copy the data */
  166823. jcopy_sample_rows(input_data, 0, output_data, 0,
  166824. cinfo->max_v_samp_factor, cinfo->image_width);
  166825. /* Edge-expand */
  166826. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166827. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166828. }
  166829. /*
  166830. * Downsample pixel values of a single component.
  166831. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166832. * without smoothing.
  166833. *
  166834. * A note about the "bias" calculations: when rounding fractional values to
  166835. * integer, we do not want to always round 0.5 up to the next integer.
  166836. * If we did that, we'd introduce a noticeable bias towards larger values.
  166837. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166838. * alternate pixel locations (a simple ordered dither pattern).
  166839. */
  166840. METHODDEF(void)
  166841. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166842. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166843. {
  166844. int outrow;
  166845. JDIMENSION outcol;
  166846. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166847. register JSAMPROW inptr, outptr;
  166848. register int bias;
  166849. /* Expand input data enough to let all the output samples be generated
  166850. * by the standard loop. Special-casing padded output would be more
  166851. * efficient.
  166852. */
  166853. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166854. cinfo->image_width, output_cols * 2);
  166855. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166856. outptr = output_data[outrow];
  166857. inptr = input_data[outrow];
  166858. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166859. for (outcol = 0; outcol < output_cols; outcol++) {
  166860. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166861. + bias) >> 1);
  166862. bias ^= 1; /* 0=>1, 1=>0 */
  166863. inptr += 2;
  166864. }
  166865. }
  166866. }
  166867. /*
  166868. * Downsample pixel values of a single component.
  166869. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166870. * without smoothing.
  166871. */
  166872. METHODDEF(void)
  166873. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166874. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166875. {
  166876. int inrow, outrow;
  166877. JDIMENSION outcol;
  166878. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166879. register JSAMPROW inptr0, inptr1, outptr;
  166880. register int bias;
  166881. /* Expand input data enough to let all the output samples be generated
  166882. * by the standard loop. Special-casing padded output would be more
  166883. * efficient.
  166884. */
  166885. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166886. cinfo->image_width, output_cols * 2);
  166887. inrow = 0;
  166888. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166889. outptr = output_data[outrow];
  166890. inptr0 = input_data[inrow];
  166891. inptr1 = input_data[inrow+1];
  166892. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166893. for (outcol = 0; outcol < output_cols; outcol++) {
  166894. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166895. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166896. + bias) >> 2);
  166897. bias ^= 3; /* 1=>2, 2=>1 */
  166898. inptr0 += 2; inptr1 += 2;
  166899. }
  166900. inrow += 2;
  166901. }
  166902. }
  166903. #ifdef INPUT_SMOOTHING_SUPPORTED
  166904. /*
  166905. * Downsample pixel values of a single component.
  166906. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166907. * with smoothing. One row of context is required.
  166908. */
  166909. METHODDEF(void)
  166910. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166911. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166912. {
  166913. int inrow, outrow;
  166914. JDIMENSION colctr;
  166915. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166916. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166917. INT32 membersum, neighsum, memberscale, neighscale;
  166918. /* Expand input data enough to let all the output samples be generated
  166919. * by the standard loop. Special-casing padded output would be more
  166920. * efficient.
  166921. */
  166922. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166923. cinfo->image_width, output_cols * 2);
  166924. /* We don't bother to form the individual "smoothed" input pixel values;
  166925. * we can directly compute the output which is the average of the four
  166926. * smoothed values. Each of the four member pixels contributes a fraction
  166927. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166928. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166929. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166930. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166931. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166932. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166933. * factors are scaled by 2^16 = 65536.
  166934. * Also recall that SF = smoothing_factor / 1024.
  166935. */
  166936. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166937. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166938. inrow = 0;
  166939. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166940. outptr = output_data[outrow];
  166941. inptr0 = input_data[inrow];
  166942. inptr1 = input_data[inrow+1];
  166943. above_ptr = input_data[inrow-1];
  166944. below_ptr = input_data[inrow+2];
  166945. /* Special case for first column: pretend column -1 is same as column 0 */
  166946. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166947. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166948. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166949. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166950. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166951. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166952. neighsum += neighsum;
  166953. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166954. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166955. membersum = membersum * memberscale + neighsum * neighscale;
  166956. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166957. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166958. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166959. /* sum of pixels directly mapped to this output element */
  166960. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166961. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166962. /* sum of edge-neighbor pixels */
  166963. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166964. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166965. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166966. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166967. /* The edge-neighbors count twice as much as corner-neighbors */
  166968. neighsum += neighsum;
  166969. /* Add in the corner-neighbors */
  166970. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166971. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166972. /* form final output scaled up by 2^16 */
  166973. membersum = membersum * memberscale + neighsum * neighscale;
  166974. /* round, descale and output it */
  166975. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166976. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166977. }
  166978. /* Special case for last column */
  166979. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166980. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166981. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166982. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166983. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166984. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166985. neighsum += neighsum;
  166986. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166987. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166988. membersum = membersum * memberscale + neighsum * neighscale;
  166989. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166990. inrow += 2;
  166991. }
  166992. }
  166993. /*
  166994. * Downsample pixel values of a single component.
  166995. * This version handles the special case of a full-size component,
  166996. * with smoothing. One row of context is required.
  166997. */
  166998. METHODDEF(void)
  166999. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167000. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167001. {
  167002. int outrow;
  167003. JDIMENSION colctr;
  167004. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167005. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167006. INT32 membersum, neighsum, memberscale, neighscale;
  167007. int colsum, lastcolsum, nextcolsum;
  167008. /* Expand input data enough to let all the output samples be generated
  167009. * by the standard loop. Special-casing padded output would be more
  167010. * efficient.
  167011. */
  167012. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167013. cinfo->image_width, output_cols);
  167014. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167015. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167016. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167017. * Also recall that SF = smoothing_factor / 1024.
  167018. */
  167019. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167020. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167021. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167022. outptr = output_data[outrow];
  167023. inptr = input_data[outrow];
  167024. above_ptr = input_data[outrow-1];
  167025. below_ptr = input_data[outrow+1];
  167026. /* Special case for first column */
  167027. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167028. GETJSAMPLE(*inptr);
  167029. membersum = GETJSAMPLE(*inptr++);
  167030. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167031. GETJSAMPLE(*inptr);
  167032. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167033. membersum = membersum * memberscale + neighsum * neighscale;
  167034. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167035. lastcolsum = colsum; colsum = nextcolsum;
  167036. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167037. membersum = GETJSAMPLE(*inptr++);
  167038. above_ptr++; below_ptr++;
  167039. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167040. GETJSAMPLE(*inptr);
  167041. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167042. membersum = membersum * memberscale + neighsum * neighscale;
  167043. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167044. lastcolsum = colsum; colsum = nextcolsum;
  167045. }
  167046. /* Special case for last column */
  167047. membersum = GETJSAMPLE(*inptr);
  167048. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167049. membersum = membersum * memberscale + neighsum * neighscale;
  167050. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167051. }
  167052. }
  167053. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167054. /*
  167055. * Module initialization routine for downsampling.
  167056. * Note that we must select a routine for each component.
  167057. */
  167058. GLOBAL(void)
  167059. jinit_downsampler (j_compress_ptr cinfo)
  167060. {
  167061. my_downsample_ptr downsample;
  167062. int ci;
  167063. jpeg_component_info * compptr;
  167064. boolean smoothok = TRUE;
  167065. downsample = (my_downsample_ptr)
  167066. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167067. SIZEOF(my_downsampler));
  167068. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167069. downsample->pub.start_pass = start_pass_downsample;
  167070. downsample->pub.downsample = sep_downsample;
  167071. downsample->pub.need_context_rows = FALSE;
  167072. if (cinfo->CCIR601_sampling)
  167073. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167074. /* Verify we can handle the sampling factors, and set up method pointers */
  167075. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167076. ci++, compptr++) {
  167077. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167078. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167079. #ifdef INPUT_SMOOTHING_SUPPORTED
  167080. if (cinfo->smoothing_factor) {
  167081. downsample->methods[ci] = fullsize_smooth_downsample;
  167082. downsample->pub.need_context_rows = TRUE;
  167083. } else
  167084. #endif
  167085. downsample->methods[ci] = fullsize_downsample;
  167086. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167087. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167088. smoothok = FALSE;
  167089. downsample->methods[ci] = h2v1_downsample;
  167090. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167091. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167092. #ifdef INPUT_SMOOTHING_SUPPORTED
  167093. if (cinfo->smoothing_factor) {
  167094. downsample->methods[ci] = h2v2_smooth_downsample;
  167095. downsample->pub.need_context_rows = TRUE;
  167096. } else
  167097. #endif
  167098. downsample->methods[ci] = h2v2_downsample;
  167099. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167100. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167101. smoothok = FALSE;
  167102. downsample->methods[ci] = int_downsample;
  167103. } else
  167104. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167105. }
  167106. #ifdef INPUT_SMOOTHING_SUPPORTED
  167107. if (cinfo->smoothing_factor && !smoothok)
  167108. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167109. #endif
  167110. }
  167111. /*** End of inlined file: jcsample.c ***/
  167112. /*** Start of inlined file: jctrans.c ***/
  167113. #define JPEG_INTERNALS
  167114. /* Forward declarations */
  167115. LOCAL(void) transencode_master_selection
  167116. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167117. LOCAL(void) transencode_coef_controller
  167118. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167119. /*
  167120. * Compression initialization for writing raw-coefficient data.
  167121. * Before calling this, all parameters and a data destination must be set up.
  167122. * Call jpeg_finish_compress() to actually write the data.
  167123. *
  167124. * The number of passed virtual arrays must match cinfo->num_components.
  167125. * Note that the virtual arrays need not be filled or even realized at
  167126. * the time write_coefficients is called; indeed, if the virtual arrays
  167127. * were requested from this compression object's memory manager, they
  167128. * typically will be realized during this routine and filled afterwards.
  167129. */
  167130. GLOBAL(void)
  167131. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167132. {
  167133. if (cinfo->global_state != CSTATE_START)
  167134. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167135. /* Mark all tables to be written */
  167136. jpeg_suppress_tables(cinfo, FALSE);
  167137. /* (Re)initialize error mgr and destination modules */
  167138. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167139. (*cinfo->dest->init_destination) (cinfo);
  167140. /* Perform master selection of active modules */
  167141. transencode_master_selection(cinfo, coef_arrays);
  167142. /* Wait for jpeg_finish_compress() call */
  167143. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167144. cinfo->global_state = CSTATE_WRCOEFS;
  167145. }
  167146. /*
  167147. * Initialize the compression object with default parameters,
  167148. * then copy from the source object all parameters needed for lossless
  167149. * transcoding. Parameters that can be varied without loss (such as
  167150. * scan script and Huffman optimization) are left in their default states.
  167151. */
  167152. GLOBAL(void)
  167153. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167154. j_compress_ptr dstinfo)
  167155. {
  167156. JQUANT_TBL ** qtblptr;
  167157. jpeg_component_info *incomp, *outcomp;
  167158. JQUANT_TBL *c_quant, *slot_quant;
  167159. int tblno, ci, coefi;
  167160. /* Safety check to ensure start_compress not called yet. */
  167161. if (dstinfo->global_state != CSTATE_START)
  167162. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167163. /* Copy fundamental image dimensions */
  167164. dstinfo->image_width = srcinfo->image_width;
  167165. dstinfo->image_height = srcinfo->image_height;
  167166. dstinfo->input_components = srcinfo->num_components;
  167167. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167168. /* Initialize all parameters to default values */
  167169. jpeg_set_defaults(dstinfo);
  167170. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167171. * Fix it to get the right header markers for the image colorspace.
  167172. */
  167173. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167174. dstinfo->data_precision = srcinfo->data_precision;
  167175. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167176. /* Copy the source's quantization tables. */
  167177. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167178. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167179. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167180. if (*qtblptr == NULL)
  167181. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167182. MEMCOPY((*qtblptr)->quantval,
  167183. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167184. SIZEOF((*qtblptr)->quantval));
  167185. (*qtblptr)->sent_table = FALSE;
  167186. }
  167187. }
  167188. /* Copy the source's per-component info.
  167189. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167190. */
  167191. dstinfo->num_components = srcinfo->num_components;
  167192. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167193. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167194. MAX_COMPONENTS);
  167195. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167196. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167197. outcomp->component_id = incomp->component_id;
  167198. outcomp->h_samp_factor = incomp->h_samp_factor;
  167199. outcomp->v_samp_factor = incomp->v_samp_factor;
  167200. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167201. /* Make sure saved quantization table for component matches the qtable
  167202. * slot. If not, the input file re-used this qtable slot.
  167203. * IJG encoder currently cannot duplicate this.
  167204. */
  167205. tblno = outcomp->quant_tbl_no;
  167206. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167207. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167208. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167209. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167210. c_quant = incomp->quant_table;
  167211. if (c_quant != NULL) {
  167212. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167213. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167214. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167215. }
  167216. }
  167217. /* Note: we do not copy the source's Huffman table assignments;
  167218. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167219. */
  167220. }
  167221. /* Also copy JFIF version and resolution information, if available.
  167222. * Strictly speaking this isn't "critical" info, but it's nearly
  167223. * always appropriate to copy it if available. In particular,
  167224. * if the application chooses to copy JFIF 1.02 extension markers from
  167225. * the source file, we need to copy the version to make sure we don't
  167226. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167227. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167228. */
  167229. if (srcinfo->saw_JFIF_marker) {
  167230. if (srcinfo->JFIF_major_version == 1) {
  167231. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167232. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167233. }
  167234. dstinfo->density_unit = srcinfo->density_unit;
  167235. dstinfo->X_density = srcinfo->X_density;
  167236. dstinfo->Y_density = srcinfo->Y_density;
  167237. }
  167238. }
  167239. /*
  167240. * Master selection of compression modules for transcoding.
  167241. * This substitutes for jcinit.c's initialization of the full compressor.
  167242. */
  167243. LOCAL(void)
  167244. transencode_master_selection (j_compress_ptr cinfo,
  167245. jvirt_barray_ptr * coef_arrays)
  167246. {
  167247. /* Although we don't actually use input_components for transcoding,
  167248. * jcmaster.c's initial_setup will complain if input_components is 0.
  167249. */
  167250. cinfo->input_components = 1;
  167251. /* Initialize master control (includes parameter checking/processing) */
  167252. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167253. /* Entropy encoding: either Huffman or arithmetic coding. */
  167254. if (cinfo->arith_code) {
  167255. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167256. } else {
  167257. if (cinfo->progressive_mode) {
  167258. #ifdef C_PROGRESSIVE_SUPPORTED
  167259. jinit_phuff_encoder(cinfo);
  167260. #else
  167261. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167262. #endif
  167263. } else
  167264. jinit_huff_encoder(cinfo);
  167265. }
  167266. /* We need a special coefficient buffer controller. */
  167267. transencode_coef_controller(cinfo, coef_arrays);
  167268. jinit_marker_writer(cinfo);
  167269. /* We can now tell the memory manager to allocate virtual arrays. */
  167270. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167271. /* Write the datastream header (SOI, JFIF) immediately.
  167272. * Frame and scan headers are postponed till later.
  167273. * This lets application insert special markers after the SOI.
  167274. */
  167275. (*cinfo->marker->write_file_header) (cinfo);
  167276. }
  167277. /*
  167278. * The rest of this file is a special implementation of the coefficient
  167279. * buffer controller. This is similar to jccoefct.c, but it handles only
  167280. * output from presupplied virtual arrays. Furthermore, we generate any
  167281. * dummy padding blocks on-the-fly rather than expecting them to be present
  167282. * in the arrays.
  167283. */
  167284. /* Private buffer controller object */
  167285. typedef struct {
  167286. struct jpeg_c_coef_controller pub; /* public fields */
  167287. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167288. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167289. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167290. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167291. /* Virtual block array for each component. */
  167292. jvirt_barray_ptr * whole_image;
  167293. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167294. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167295. } my_coef_controller2;
  167296. typedef my_coef_controller2 * my_coef_ptr2;
  167297. LOCAL(void)
  167298. start_iMCU_row2 (j_compress_ptr cinfo)
  167299. /* Reset within-iMCU-row counters for a new row */
  167300. {
  167301. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167302. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167303. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167304. * But at the bottom of the image, process only what's left.
  167305. */
  167306. if (cinfo->comps_in_scan > 1) {
  167307. coef->MCU_rows_per_iMCU_row = 1;
  167308. } else {
  167309. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167310. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167311. else
  167312. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167313. }
  167314. coef->mcu_ctr = 0;
  167315. coef->MCU_vert_offset = 0;
  167316. }
  167317. /*
  167318. * Initialize for a processing pass.
  167319. */
  167320. METHODDEF(void)
  167321. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167322. {
  167323. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167324. if (pass_mode != JBUF_CRANK_DEST)
  167325. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167326. coef->iMCU_row_num = 0;
  167327. start_iMCU_row2(cinfo);
  167328. }
  167329. /*
  167330. * Process some data.
  167331. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167332. * per call, ie, v_samp_factor block rows for each component in the scan.
  167333. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167334. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167335. *
  167336. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167337. */
  167338. METHODDEF(boolean)
  167339. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167340. {
  167341. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167342. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167343. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167344. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167345. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167346. JDIMENSION start_col;
  167347. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167348. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167349. JBLOCKROW buffer_ptr;
  167350. jpeg_component_info *compptr;
  167351. /* Align the virtual buffers for the components used in this scan. */
  167352. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167353. compptr = cinfo->cur_comp_info[ci];
  167354. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167355. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167356. coef->iMCU_row_num * compptr->v_samp_factor,
  167357. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167358. }
  167359. /* Loop to process one whole iMCU row */
  167360. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167361. yoffset++) {
  167362. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167363. MCU_col_num++) {
  167364. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167365. blkn = 0; /* index of current DCT block within MCU */
  167366. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167367. compptr = cinfo->cur_comp_info[ci];
  167368. start_col = MCU_col_num * compptr->MCU_width;
  167369. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167370. : compptr->last_col_width;
  167371. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167372. if (coef->iMCU_row_num < last_iMCU_row ||
  167373. yindex+yoffset < compptr->last_row_height) {
  167374. /* Fill in pointers to real blocks in this row */
  167375. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167376. for (xindex = 0; xindex < blockcnt; xindex++)
  167377. MCU_buffer[blkn++] = buffer_ptr++;
  167378. } else {
  167379. /* At bottom of image, need a whole row of dummy blocks */
  167380. xindex = 0;
  167381. }
  167382. /* Fill in any dummy blocks needed in this row.
  167383. * Dummy blocks are filled in the same way as in jccoefct.c:
  167384. * all zeroes in the AC entries, DC entries equal to previous
  167385. * block's DC value. The init routine has already zeroed the
  167386. * AC entries, so we need only set the DC entries correctly.
  167387. */
  167388. for (; xindex < compptr->MCU_width; xindex++) {
  167389. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167390. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167391. blkn++;
  167392. }
  167393. }
  167394. }
  167395. /* Try to write the MCU. */
  167396. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167397. /* Suspension forced; update state counters and exit */
  167398. coef->MCU_vert_offset = yoffset;
  167399. coef->mcu_ctr = MCU_col_num;
  167400. return FALSE;
  167401. }
  167402. }
  167403. /* Completed an MCU row, but perhaps not an iMCU row */
  167404. coef->mcu_ctr = 0;
  167405. }
  167406. /* Completed the iMCU row, advance counters for next one */
  167407. coef->iMCU_row_num++;
  167408. start_iMCU_row2(cinfo);
  167409. return TRUE;
  167410. }
  167411. /*
  167412. * Initialize coefficient buffer controller.
  167413. *
  167414. * Each passed coefficient array must be the right size for that
  167415. * coefficient: width_in_blocks wide and height_in_blocks high,
  167416. * with unitheight at least v_samp_factor.
  167417. */
  167418. LOCAL(void)
  167419. transencode_coef_controller (j_compress_ptr cinfo,
  167420. jvirt_barray_ptr * coef_arrays)
  167421. {
  167422. my_coef_ptr2 coef;
  167423. JBLOCKROW buffer;
  167424. int i;
  167425. coef = (my_coef_ptr2)
  167426. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167427. SIZEOF(my_coef_controller2));
  167428. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167429. coef->pub.start_pass = start_pass_coef2;
  167430. coef->pub.compress_data = compress_output2;
  167431. /* Save pointer to virtual arrays */
  167432. coef->whole_image = coef_arrays;
  167433. /* Allocate and pre-zero space for dummy DCT blocks. */
  167434. buffer = (JBLOCKROW)
  167435. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167436. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167437. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167438. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167439. coef->dummy_buffer[i] = buffer + i;
  167440. }
  167441. }
  167442. /*** End of inlined file: jctrans.c ***/
  167443. /*** Start of inlined file: jdapistd.c ***/
  167444. #define JPEG_INTERNALS
  167445. /* Forward declarations */
  167446. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167447. /*
  167448. * Decompression initialization.
  167449. * jpeg_read_header must be completed before calling this.
  167450. *
  167451. * If a multipass operating mode was selected, this will do all but the
  167452. * last pass, and thus may take a great deal of time.
  167453. *
  167454. * Returns FALSE if suspended. The return value need be inspected only if
  167455. * a suspending data source is used.
  167456. */
  167457. GLOBAL(boolean)
  167458. jpeg_start_decompress (j_decompress_ptr cinfo)
  167459. {
  167460. if (cinfo->global_state == DSTATE_READY) {
  167461. /* First call: initialize master control, select active modules */
  167462. jinit_master_decompress(cinfo);
  167463. if (cinfo->buffered_image) {
  167464. /* No more work here; expecting jpeg_start_output next */
  167465. cinfo->global_state = DSTATE_BUFIMAGE;
  167466. return TRUE;
  167467. }
  167468. cinfo->global_state = DSTATE_PRELOAD;
  167469. }
  167470. if (cinfo->global_state == DSTATE_PRELOAD) {
  167471. /* If file has multiple scans, absorb them all into the coef buffer */
  167472. if (cinfo->inputctl->has_multiple_scans) {
  167473. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167474. for (;;) {
  167475. int retcode;
  167476. /* Call progress monitor hook if present */
  167477. if (cinfo->progress != NULL)
  167478. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167479. /* Absorb some more input */
  167480. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167481. if (retcode == JPEG_SUSPENDED)
  167482. return FALSE;
  167483. if (retcode == JPEG_REACHED_EOI)
  167484. break;
  167485. /* Advance progress counter if appropriate */
  167486. if (cinfo->progress != NULL &&
  167487. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167488. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167489. /* jdmaster underestimated number of scans; ratchet up one scan */
  167490. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167491. }
  167492. }
  167493. }
  167494. #else
  167495. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167496. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167497. }
  167498. cinfo->output_scan_number = cinfo->input_scan_number;
  167499. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167500. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167501. /* Perform any dummy output passes, and set up for the final pass */
  167502. return output_pass_setup(cinfo);
  167503. }
  167504. /*
  167505. * Set up for an output pass, and perform any dummy pass(es) needed.
  167506. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167507. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167508. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167509. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167510. */
  167511. LOCAL(boolean)
  167512. output_pass_setup (j_decompress_ptr cinfo)
  167513. {
  167514. if (cinfo->global_state != DSTATE_PRESCAN) {
  167515. /* First call: do pass setup */
  167516. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167517. cinfo->output_scanline = 0;
  167518. cinfo->global_state = DSTATE_PRESCAN;
  167519. }
  167520. /* Loop over any required dummy passes */
  167521. while (cinfo->master->is_dummy_pass) {
  167522. #ifdef QUANT_2PASS_SUPPORTED
  167523. /* Crank through the dummy pass */
  167524. while (cinfo->output_scanline < cinfo->output_height) {
  167525. JDIMENSION last_scanline;
  167526. /* Call progress monitor hook if present */
  167527. if (cinfo->progress != NULL) {
  167528. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167529. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167530. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167531. }
  167532. /* Process some data */
  167533. last_scanline = cinfo->output_scanline;
  167534. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167535. &cinfo->output_scanline, (JDIMENSION) 0);
  167536. if (cinfo->output_scanline == last_scanline)
  167537. return FALSE; /* No progress made, must suspend */
  167538. }
  167539. /* Finish up dummy pass, and set up for another one */
  167540. (*cinfo->master->finish_output_pass) (cinfo);
  167541. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167542. cinfo->output_scanline = 0;
  167543. #else
  167544. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167545. #endif /* QUANT_2PASS_SUPPORTED */
  167546. }
  167547. /* Ready for application to drive output pass through
  167548. * jpeg_read_scanlines or jpeg_read_raw_data.
  167549. */
  167550. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167551. return TRUE;
  167552. }
  167553. /*
  167554. * Read some scanlines of data from the JPEG decompressor.
  167555. *
  167556. * The return value will be the number of lines actually read.
  167557. * This may be less than the number requested in several cases,
  167558. * including bottom of image, data source suspension, and operating
  167559. * modes that emit multiple scanlines at a time.
  167560. *
  167561. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167562. * this likely signals an application programmer error. However,
  167563. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167564. */
  167565. GLOBAL(JDIMENSION)
  167566. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167567. JDIMENSION max_lines)
  167568. {
  167569. JDIMENSION row_ctr;
  167570. if (cinfo->global_state != DSTATE_SCANNING)
  167571. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167572. if (cinfo->output_scanline >= cinfo->output_height) {
  167573. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167574. return 0;
  167575. }
  167576. /* Call progress monitor hook if present */
  167577. if (cinfo->progress != NULL) {
  167578. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167579. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167580. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167581. }
  167582. /* Process some data */
  167583. row_ctr = 0;
  167584. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167585. cinfo->output_scanline += row_ctr;
  167586. return row_ctr;
  167587. }
  167588. /*
  167589. * Alternate entry point to read raw data.
  167590. * Processes exactly one iMCU row per call, unless suspended.
  167591. */
  167592. GLOBAL(JDIMENSION)
  167593. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167594. JDIMENSION max_lines)
  167595. {
  167596. JDIMENSION lines_per_iMCU_row;
  167597. if (cinfo->global_state != DSTATE_RAW_OK)
  167598. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167599. if (cinfo->output_scanline >= cinfo->output_height) {
  167600. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167601. return 0;
  167602. }
  167603. /* Call progress monitor hook if present */
  167604. if (cinfo->progress != NULL) {
  167605. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167606. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167607. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167608. }
  167609. /* Verify that at least one iMCU row can be returned. */
  167610. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167611. if (max_lines < lines_per_iMCU_row)
  167612. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167613. /* Decompress directly into user's buffer. */
  167614. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167615. return 0; /* suspension forced, can do nothing more */
  167616. /* OK, we processed one iMCU row. */
  167617. cinfo->output_scanline += lines_per_iMCU_row;
  167618. return lines_per_iMCU_row;
  167619. }
  167620. /* Additional entry points for buffered-image mode. */
  167621. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167622. /*
  167623. * Initialize for an output pass in buffered-image mode.
  167624. */
  167625. GLOBAL(boolean)
  167626. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167627. {
  167628. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167629. cinfo->global_state != DSTATE_PRESCAN)
  167630. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167631. /* Limit scan number to valid range */
  167632. if (scan_number <= 0)
  167633. scan_number = 1;
  167634. if (cinfo->inputctl->eoi_reached &&
  167635. scan_number > cinfo->input_scan_number)
  167636. scan_number = cinfo->input_scan_number;
  167637. cinfo->output_scan_number = scan_number;
  167638. /* Perform any dummy output passes, and set up for the real pass */
  167639. return output_pass_setup(cinfo);
  167640. }
  167641. /*
  167642. * Finish up after an output pass in buffered-image mode.
  167643. *
  167644. * Returns FALSE if suspended. The return value need be inspected only if
  167645. * a suspending data source is used.
  167646. */
  167647. GLOBAL(boolean)
  167648. jpeg_finish_output (j_decompress_ptr cinfo)
  167649. {
  167650. if ((cinfo->global_state == DSTATE_SCANNING ||
  167651. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167652. /* Terminate this pass. */
  167653. /* We do not require the whole pass to have been completed. */
  167654. (*cinfo->master->finish_output_pass) (cinfo);
  167655. cinfo->global_state = DSTATE_BUFPOST;
  167656. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167657. /* BUFPOST = repeat call after a suspension, anything else is error */
  167658. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167659. }
  167660. /* Read markers looking for SOS or EOI */
  167661. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167662. ! cinfo->inputctl->eoi_reached) {
  167663. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167664. return FALSE; /* Suspend, come back later */
  167665. }
  167666. cinfo->global_state = DSTATE_BUFIMAGE;
  167667. return TRUE;
  167668. }
  167669. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167670. /*** End of inlined file: jdapistd.c ***/
  167671. /*** Start of inlined file: jdapimin.c ***/
  167672. #define JPEG_INTERNALS
  167673. /*
  167674. * Initialization of a JPEG decompression object.
  167675. * The error manager must already be set up (in case memory manager fails).
  167676. */
  167677. GLOBAL(void)
  167678. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167679. {
  167680. int i;
  167681. /* Guard against version mismatches between library and caller. */
  167682. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167683. if (version != JPEG_LIB_VERSION)
  167684. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167685. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167686. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167687. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167688. /* For debugging purposes, we zero the whole master structure.
  167689. * But the application has already set the err pointer, and may have set
  167690. * client_data, so we have to save and restore those fields.
  167691. * Note: if application hasn't set client_data, tools like Purify may
  167692. * complain here.
  167693. */
  167694. {
  167695. struct jpeg_error_mgr * err = cinfo->err;
  167696. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167697. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167698. cinfo->err = err;
  167699. cinfo->client_data = client_data;
  167700. }
  167701. cinfo->is_decompressor = TRUE;
  167702. /* Initialize a memory manager instance for this object */
  167703. jinit_memory_mgr((j_common_ptr) cinfo);
  167704. /* Zero out pointers to permanent structures. */
  167705. cinfo->progress = NULL;
  167706. cinfo->src = NULL;
  167707. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167708. cinfo->quant_tbl_ptrs[i] = NULL;
  167709. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167710. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167711. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167712. }
  167713. /* Initialize marker processor so application can override methods
  167714. * for COM, APPn markers before calling jpeg_read_header.
  167715. */
  167716. cinfo->marker_list = NULL;
  167717. jinit_marker_reader(cinfo);
  167718. /* And initialize the overall input controller. */
  167719. jinit_input_controller(cinfo);
  167720. /* OK, I'm ready */
  167721. cinfo->global_state = DSTATE_START;
  167722. }
  167723. /*
  167724. * Destruction of a JPEG decompression object
  167725. */
  167726. GLOBAL(void)
  167727. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167728. {
  167729. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167730. }
  167731. /*
  167732. * Abort processing of a JPEG decompression operation,
  167733. * but don't destroy the object itself.
  167734. */
  167735. GLOBAL(void)
  167736. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167737. {
  167738. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167739. }
  167740. /*
  167741. * Set default decompression parameters.
  167742. */
  167743. LOCAL(void)
  167744. default_decompress_parms (j_decompress_ptr cinfo)
  167745. {
  167746. /* Guess the input colorspace, and set output colorspace accordingly. */
  167747. /* (Wish JPEG committee had provided a real way to specify this...) */
  167748. /* Note application may override our guesses. */
  167749. switch (cinfo->num_components) {
  167750. case 1:
  167751. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167752. cinfo->out_color_space = JCS_GRAYSCALE;
  167753. break;
  167754. case 3:
  167755. if (cinfo->saw_JFIF_marker) {
  167756. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167757. } else if (cinfo->saw_Adobe_marker) {
  167758. switch (cinfo->Adobe_transform) {
  167759. case 0:
  167760. cinfo->jpeg_color_space = JCS_RGB;
  167761. break;
  167762. case 1:
  167763. cinfo->jpeg_color_space = JCS_YCbCr;
  167764. break;
  167765. default:
  167766. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167767. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167768. break;
  167769. }
  167770. } else {
  167771. /* Saw no special markers, try to guess from the component IDs */
  167772. int cid0 = cinfo->comp_info[0].component_id;
  167773. int cid1 = cinfo->comp_info[1].component_id;
  167774. int cid2 = cinfo->comp_info[2].component_id;
  167775. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167776. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167777. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167778. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167779. else {
  167780. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167781. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167782. }
  167783. }
  167784. /* Always guess RGB is proper output colorspace. */
  167785. cinfo->out_color_space = JCS_RGB;
  167786. break;
  167787. case 4:
  167788. if (cinfo->saw_Adobe_marker) {
  167789. switch (cinfo->Adobe_transform) {
  167790. case 0:
  167791. cinfo->jpeg_color_space = JCS_CMYK;
  167792. break;
  167793. case 2:
  167794. cinfo->jpeg_color_space = JCS_YCCK;
  167795. break;
  167796. default:
  167797. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167798. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167799. break;
  167800. }
  167801. } else {
  167802. /* No special markers, assume straight CMYK. */
  167803. cinfo->jpeg_color_space = JCS_CMYK;
  167804. }
  167805. cinfo->out_color_space = JCS_CMYK;
  167806. break;
  167807. default:
  167808. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167809. cinfo->out_color_space = JCS_UNKNOWN;
  167810. break;
  167811. }
  167812. /* Set defaults for other decompression parameters. */
  167813. cinfo->scale_num = 1; /* 1:1 scaling */
  167814. cinfo->scale_denom = 1;
  167815. cinfo->output_gamma = 1.0;
  167816. cinfo->buffered_image = FALSE;
  167817. cinfo->raw_data_out = FALSE;
  167818. cinfo->dct_method = JDCT_DEFAULT;
  167819. cinfo->do_fancy_upsampling = TRUE;
  167820. cinfo->do_block_smoothing = TRUE;
  167821. cinfo->quantize_colors = FALSE;
  167822. /* We set these in case application only sets quantize_colors. */
  167823. cinfo->dither_mode = JDITHER_FS;
  167824. #ifdef QUANT_2PASS_SUPPORTED
  167825. cinfo->two_pass_quantize = TRUE;
  167826. #else
  167827. cinfo->two_pass_quantize = FALSE;
  167828. #endif
  167829. cinfo->desired_number_of_colors = 256;
  167830. cinfo->colormap = NULL;
  167831. /* Initialize for no mode change in buffered-image mode. */
  167832. cinfo->enable_1pass_quant = FALSE;
  167833. cinfo->enable_external_quant = FALSE;
  167834. cinfo->enable_2pass_quant = FALSE;
  167835. }
  167836. /*
  167837. * Decompression startup: read start of JPEG datastream to see what's there.
  167838. * Need only initialize JPEG object and supply a data source before calling.
  167839. *
  167840. * This routine will read as far as the first SOS marker (ie, actual start of
  167841. * compressed data), and will save all tables and parameters in the JPEG
  167842. * object. It will also initialize the decompression parameters to default
  167843. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167844. * adjust the decompression parameters and then call jpeg_start_decompress.
  167845. * (Or, if the application only wanted to determine the image parameters,
  167846. * the data need not be decompressed. In that case, call jpeg_abort or
  167847. * jpeg_destroy to release any temporary space.)
  167848. * If an abbreviated (tables only) datastream is presented, the routine will
  167849. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167850. * re-use the JPEG object to read the abbreviated image datastream(s).
  167851. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167852. * The JPEG_SUSPENDED return code only occurs if the data source module
  167853. * requests suspension of the decompressor. In this case the application
  167854. * should load more source data and then re-call jpeg_read_header to resume
  167855. * processing.
  167856. * If a non-suspending data source is used and require_image is TRUE, then the
  167857. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167858. *
  167859. * This routine is now just a front end to jpeg_consume_input, with some
  167860. * extra error checking.
  167861. */
  167862. GLOBAL(int)
  167863. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167864. {
  167865. int retcode;
  167866. if (cinfo->global_state != DSTATE_START &&
  167867. cinfo->global_state != DSTATE_INHEADER)
  167868. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167869. retcode = jpeg_consume_input(cinfo);
  167870. switch (retcode) {
  167871. case JPEG_REACHED_SOS:
  167872. retcode = JPEG_HEADER_OK;
  167873. break;
  167874. case JPEG_REACHED_EOI:
  167875. if (require_image) /* Complain if application wanted an image */
  167876. ERREXIT(cinfo, JERR_NO_IMAGE);
  167877. /* Reset to start state; it would be safer to require the application to
  167878. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167879. * A side effect is to free any temporary memory (there shouldn't be any).
  167880. */
  167881. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167882. retcode = JPEG_HEADER_TABLES_ONLY;
  167883. break;
  167884. case JPEG_SUSPENDED:
  167885. /* no work */
  167886. break;
  167887. }
  167888. return retcode;
  167889. }
  167890. /*
  167891. * Consume data in advance of what the decompressor requires.
  167892. * This can be called at any time once the decompressor object has
  167893. * been created and a data source has been set up.
  167894. *
  167895. * This routine is essentially a state machine that handles a couple
  167896. * of critical state-transition actions, namely initial setup and
  167897. * transition from header scanning to ready-for-start_decompress.
  167898. * All the actual input is done via the input controller's consume_input
  167899. * method.
  167900. */
  167901. GLOBAL(int)
  167902. jpeg_consume_input (j_decompress_ptr cinfo)
  167903. {
  167904. int retcode = JPEG_SUSPENDED;
  167905. /* NB: every possible DSTATE value should be listed in this switch */
  167906. switch (cinfo->global_state) {
  167907. case DSTATE_START:
  167908. /* Start-of-datastream actions: reset appropriate modules */
  167909. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167910. /* Initialize application's data source module */
  167911. (*cinfo->src->init_source) (cinfo);
  167912. cinfo->global_state = DSTATE_INHEADER;
  167913. /*FALLTHROUGH*/
  167914. case DSTATE_INHEADER:
  167915. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167916. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167917. /* Set up default parameters based on header data */
  167918. default_decompress_parms(cinfo);
  167919. /* Set global state: ready for start_decompress */
  167920. cinfo->global_state = DSTATE_READY;
  167921. }
  167922. break;
  167923. case DSTATE_READY:
  167924. /* Can't advance past first SOS until start_decompress is called */
  167925. retcode = JPEG_REACHED_SOS;
  167926. break;
  167927. case DSTATE_PRELOAD:
  167928. case DSTATE_PRESCAN:
  167929. case DSTATE_SCANNING:
  167930. case DSTATE_RAW_OK:
  167931. case DSTATE_BUFIMAGE:
  167932. case DSTATE_BUFPOST:
  167933. case DSTATE_STOPPING:
  167934. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167935. break;
  167936. default:
  167937. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167938. }
  167939. return retcode;
  167940. }
  167941. /*
  167942. * Have we finished reading the input file?
  167943. */
  167944. GLOBAL(boolean)
  167945. jpeg_input_complete (j_decompress_ptr cinfo)
  167946. {
  167947. /* Check for valid jpeg object */
  167948. if (cinfo->global_state < DSTATE_START ||
  167949. cinfo->global_state > DSTATE_STOPPING)
  167950. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167951. return cinfo->inputctl->eoi_reached;
  167952. }
  167953. /*
  167954. * Is there more than one scan?
  167955. */
  167956. GLOBAL(boolean)
  167957. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167958. {
  167959. /* Only valid after jpeg_read_header completes */
  167960. if (cinfo->global_state < DSTATE_READY ||
  167961. cinfo->global_state > DSTATE_STOPPING)
  167962. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167963. return cinfo->inputctl->has_multiple_scans;
  167964. }
  167965. /*
  167966. * Finish JPEG decompression.
  167967. *
  167968. * This will normally just verify the file trailer and release temp storage.
  167969. *
  167970. * Returns FALSE if suspended. The return value need be inspected only if
  167971. * a suspending data source is used.
  167972. */
  167973. GLOBAL(boolean)
  167974. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167975. {
  167976. if ((cinfo->global_state == DSTATE_SCANNING ||
  167977. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167978. /* Terminate final pass of non-buffered mode */
  167979. if (cinfo->output_scanline < cinfo->output_height)
  167980. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167981. (*cinfo->master->finish_output_pass) (cinfo);
  167982. cinfo->global_state = DSTATE_STOPPING;
  167983. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167984. /* Finishing after a buffered-image operation */
  167985. cinfo->global_state = DSTATE_STOPPING;
  167986. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167987. /* STOPPING = repeat call after a suspension, anything else is error */
  167988. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167989. }
  167990. /* Read until EOI */
  167991. while (! cinfo->inputctl->eoi_reached) {
  167992. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167993. return FALSE; /* Suspend, come back later */
  167994. }
  167995. /* Do final cleanup */
  167996. (*cinfo->src->term_source) (cinfo);
  167997. /* We can use jpeg_abort to release memory and reset global_state */
  167998. jpeg_abort((j_common_ptr) cinfo);
  167999. return TRUE;
  168000. }
  168001. /*** End of inlined file: jdapimin.c ***/
  168002. /*** Start of inlined file: jdatasrc.c ***/
  168003. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168004. /*** Start of inlined file: jerror.h ***/
  168005. /*
  168006. * To define the enum list of message codes, include this file without
  168007. * defining macro JMESSAGE. To create a message string table, include it
  168008. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168009. */
  168010. #ifndef JMESSAGE
  168011. #ifndef JERROR_H
  168012. /* First time through, define the enum list */
  168013. #define JMAKE_ENUM_LIST
  168014. #else
  168015. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168016. #define JMESSAGE(code,string)
  168017. #endif /* JERROR_H */
  168018. #endif /* JMESSAGE */
  168019. #ifdef JMAKE_ENUM_LIST
  168020. typedef enum {
  168021. #define JMESSAGE(code,string) code ,
  168022. #endif /* JMAKE_ENUM_LIST */
  168023. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168024. /* For maintenance convenience, list is alphabetical by message code name */
  168025. JMESSAGE(JERR_ARITH_NOTIMPL,
  168026. "Sorry, there are legal restrictions on arithmetic coding")
  168027. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168028. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168029. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168030. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168031. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168032. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168033. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168034. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168035. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168036. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168037. JMESSAGE(JERR_BAD_LIB_VERSION,
  168038. "Wrong JPEG library version: library is %d, caller expects %d")
  168039. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168040. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168041. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168042. JMESSAGE(JERR_BAD_PROGRESSION,
  168043. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168044. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168045. "Invalid progressive parameters at scan script entry %d")
  168046. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168047. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168048. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168049. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168050. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168051. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168052. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168053. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168054. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168055. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168056. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168057. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168058. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168059. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168060. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168061. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168062. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168063. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168064. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168065. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168066. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168067. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168068. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168069. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168070. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168071. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168072. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168073. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168074. "Cannot transcode due to multiple use of quantization table %d")
  168075. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168076. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168077. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168078. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168079. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168080. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168081. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168082. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168083. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168084. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168085. JMESSAGE(JERR_QUANT_COMPONENTS,
  168086. "Cannot quantize more than %d color components")
  168087. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168088. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168089. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168090. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168091. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168092. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168093. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168094. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168095. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168096. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168097. JMESSAGE(JERR_TFILE_WRITE,
  168098. "Write failed on temporary file --- out of disk space?")
  168099. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168100. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168101. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168102. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168103. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168104. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168105. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168106. JMESSAGE(JMSG_VERSION, JVERSION)
  168107. JMESSAGE(JTRC_16BIT_TABLES,
  168108. "Caution: quantization tables are too coarse for baseline JPEG")
  168109. JMESSAGE(JTRC_ADOBE,
  168110. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168111. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168112. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168113. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168114. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168115. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168116. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168117. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168118. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168119. JMESSAGE(JTRC_EOI, "End Of Image")
  168120. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168121. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168122. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168123. "Warning: thumbnail image size does not match data length %u")
  168124. JMESSAGE(JTRC_JFIF_EXTENSION,
  168125. "JFIF extension marker: type 0x%02x, length %u")
  168126. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168127. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168128. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168129. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168130. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168131. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168132. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168133. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168134. JMESSAGE(JTRC_RST, "RST%d")
  168135. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168136. "Smoothing not supported with nonstandard sampling ratios")
  168137. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168138. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168139. JMESSAGE(JTRC_SOI, "Start of Image")
  168140. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168141. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168142. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168143. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168144. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168145. JMESSAGE(JTRC_THUMB_JPEG,
  168146. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168147. JMESSAGE(JTRC_THUMB_PALETTE,
  168148. "JFIF extension marker: palette thumbnail image, length %u")
  168149. JMESSAGE(JTRC_THUMB_RGB,
  168150. "JFIF extension marker: RGB thumbnail image, length %u")
  168151. JMESSAGE(JTRC_UNKNOWN_IDS,
  168152. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168153. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168154. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168155. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168156. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168157. "Inconsistent progression sequence for component %d coefficient %d")
  168158. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168159. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168160. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168161. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168162. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168163. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168164. JMESSAGE(JWRN_MUST_RESYNC,
  168165. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168166. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168167. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168168. #ifdef JMAKE_ENUM_LIST
  168169. JMSG_LASTMSGCODE
  168170. } J_MESSAGE_CODE;
  168171. #undef JMAKE_ENUM_LIST
  168172. #endif /* JMAKE_ENUM_LIST */
  168173. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168174. #undef JMESSAGE
  168175. #ifndef JERROR_H
  168176. #define JERROR_H
  168177. /* Macros to simplify using the error and trace message stuff */
  168178. /* The first parameter is either type of cinfo pointer */
  168179. /* Fatal errors (print message and exit) */
  168180. #define ERREXIT(cinfo,code) \
  168181. ((cinfo)->err->msg_code = (code), \
  168182. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168183. #define ERREXIT1(cinfo,code,p1) \
  168184. ((cinfo)->err->msg_code = (code), \
  168185. (cinfo)->err->msg_parm.i[0] = (p1), \
  168186. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168187. #define ERREXIT2(cinfo,code,p1,p2) \
  168188. ((cinfo)->err->msg_code = (code), \
  168189. (cinfo)->err->msg_parm.i[0] = (p1), \
  168190. (cinfo)->err->msg_parm.i[1] = (p2), \
  168191. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168192. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168193. ((cinfo)->err->msg_code = (code), \
  168194. (cinfo)->err->msg_parm.i[0] = (p1), \
  168195. (cinfo)->err->msg_parm.i[1] = (p2), \
  168196. (cinfo)->err->msg_parm.i[2] = (p3), \
  168197. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168198. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168199. ((cinfo)->err->msg_code = (code), \
  168200. (cinfo)->err->msg_parm.i[0] = (p1), \
  168201. (cinfo)->err->msg_parm.i[1] = (p2), \
  168202. (cinfo)->err->msg_parm.i[2] = (p3), \
  168203. (cinfo)->err->msg_parm.i[3] = (p4), \
  168204. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168205. #define ERREXITS(cinfo,code,str) \
  168206. ((cinfo)->err->msg_code = (code), \
  168207. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168208. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168209. #define MAKESTMT(stuff) do { stuff } while (0)
  168210. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168211. #define WARNMS(cinfo,code) \
  168212. ((cinfo)->err->msg_code = (code), \
  168213. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168214. #define WARNMS1(cinfo,code,p1) \
  168215. ((cinfo)->err->msg_code = (code), \
  168216. (cinfo)->err->msg_parm.i[0] = (p1), \
  168217. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168218. #define WARNMS2(cinfo,code,p1,p2) \
  168219. ((cinfo)->err->msg_code = (code), \
  168220. (cinfo)->err->msg_parm.i[0] = (p1), \
  168221. (cinfo)->err->msg_parm.i[1] = (p2), \
  168222. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168223. /* Informational/debugging messages */
  168224. #define TRACEMS(cinfo,lvl,code) \
  168225. ((cinfo)->err->msg_code = (code), \
  168226. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168227. #define TRACEMS1(cinfo,lvl,code,p1) \
  168228. ((cinfo)->err->msg_code = (code), \
  168229. (cinfo)->err->msg_parm.i[0] = (p1), \
  168230. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168231. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168232. ((cinfo)->err->msg_code = (code), \
  168233. (cinfo)->err->msg_parm.i[0] = (p1), \
  168234. (cinfo)->err->msg_parm.i[1] = (p2), \
  168235. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168236. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168237. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168238. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168239. (cinfo)->err->msg_code = (code); \
  168240. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168241. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168242. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168243. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168244. (cinfo)->err->msg_code = (code); \
  168245. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168246. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168247. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168248. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168249. _mp[4] = (p5); \
  168250. (cinfo)->err->msg_code = (code); \
  168251. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168252. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168253. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168254. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168255. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168256. (cinfo)->err->msg_code = (code); \
  168257. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168258. #define TRACEMSS(cinfo,lvl,code,str) \
  168259. ((cinfo)->err->msg_code = (code), \
  168260. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168261. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168262. #endif /* JERROR_H */
  168263. /*** End of inlined file: jerror.h ***/
  168264. /* Expanded data source object for stdio input */
  168265. typedef struct {
  168266. struct jpeg_source_mgr pub; /* public fields */
  168267. FILE * infile; /* source stream */
  168268. JOCTET * buffer; /* start of buffer */
  168269. boolean start_of_file; /* have we gotten any data yet? */
  168270. } my_source_mgr;
  168271. typedef my_source_mgr * my_src_ptr;
  168272. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168273. /*
  168274. * Initialize source --- called by jpeg_read_header
  168275. * before any data is actually read.
  168276. */
  168277. METHODDEF(void)
  168278. init_source (j_decompress_ptr cinfo)
  168279. {
  168280. my_src_ptr src = (my_src_ptr) cinfo->src;
  168281. /* We reset the empty-input-file flag for each image,
  168282. * but we don't clear the input buffer.
  168283. * This is correct behavior for reading a series of images from one source.
  168284. */
  168285. src->start_of_file = TRUE;
  168286. }
  168287. /*
  168288. * Fill the input buffer --- called whenever buffer is emptied.
  168289. *
  168290. * In typical applications, this should read fresh data into the buffer
  168291. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168292. * reset the pointer & count to the start of the buffer, and return TRUE
  168293. * indicating that the buffer has been reloaded. It is not necessary to
  168294. * fill the buffer entirely, only to obtain at least one more byte.
  168295. *
  168296. * There is no such thing as an EOF return. If the end of the file has been
  168297. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168298. * the buffer. In most cases, generating a warning message and inserting a
  168299. * fake EOI marker is the best course of action --- this will allow the
  168300. * decompressor to output however much of the image is there. However,
  168301. * the resulting error message is misleading if the real problem is an empty
  168302. * input file, so we handle that case specially.
  168303. *
  168304. * In applications that need to be able to suspend compression due to input
  168305. * not being available yet, a FALSE return indicates that no more data can be
  168306. * obtained right now, but more may be forthcoming later. In this situation,
  168307. * the decompressor will return to its caller (with an indication of the
  168308. * number of scanlines it has read, if any). The application should resume
  168309. * decompression after it has loaded more data into the input buffer. Note
  168310. * that there are substantial restrictions on the use of suspension --- see
  168311. * the documentation.
  168312. *
  168313. * When suspending, the decompressor will back up to a convenient restart point
  168314. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168315. * indicate where the restart point will be if the current call returns FALSE.
  168316. * Data beyond this point must be rescanned after resumption, so move it to
  168317. * the front of the buffer rather than discarding it.
  168318. */
  168319. METHODDEF(boolean)
  168320. fill_input_buffer (j_decompress_ptr cinfo)
  168321. {
  168322. my_src_ptr src = (my_src_ptr) cinfo->src;
  168323. size_t nbytes;
  168324. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168325. if (nbytes <= 0) {
  168326. if (src->start_of_file) /* Treat empty input file as fatal error */
  168327. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168328. WARNMS(cinfo, JWRN_JPEG_EOF);
  168329. /* Insert a fake EOI marker */
  168330. src->buffer[0] = (JOCTET) 0xFF;
  168331. src->buffer[1] = (JOCTET) JPEG_EOI;
  168332. nbytes = 2;
  168333. }
  168334. src->pub.next_input_byte = src->buffer;
  168335. src->pub.bytes_in_buffer = nbytes;
  168336. src->start_of_file = FALSE;
  168337. return TRUE;
  168338. }
  168339. /*
  168340. * Skip data --- used to skip over a potentially large amount of
  168341. * uninteresting data (such as an APPn marker).
  168342. *
  168343. * Writers of suspendable-input applications must note that skip_input_data
  168344. * is not granted the right to give a suspension return. If the skip extends
  168345. * beyond the data currently in the buffer, the buffer can be marked empty so
  168346. * that the next read will cause a fill_input_buffer call that can suspend.
  168347. * Arranging for additional bytes to be discarded before reloading the input
  168348. * buffer is the application writer's problem.
  168349. */
  168350. METHODDEF(void)
  168351. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168352. {
  168353. my_src_ptr src = (my_src_ptr) cinfo->src;
  168354. /* Just a dumb implementation for now. Could use fseek() except
  168355. * it doesn't work on pipes. Not clear that being smart is worth
  168356. * any trouble anyway --- large skips are infrequent.
  168357. */
  168358. if (num_bytes > 0) {
  168359. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168360. num_bytes -= (long) src->pub.bytes_in_buffer;
  168361. (void) fill_input_buffer(cinfo);
  168362. /* note we assume that fill_input_buffer will never return FALSE,
  168363. * so suspension need not be handled.
  168364. */
  168365. }
  168366. src->pub.next_input_byte += (size_t) num_bytes;
  168367. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168368. }
  168369. }
  168370. /*
  168371. * An additional method that can be provided by data source modules is the
  168372. * resync_to_restart method for error recovery in the presence of RST markers.
  168373. * For the moment, this source module just uses the default resync method
  168374. * provided by the JPEG library. That method assumes that no backtracking
  168375. * is possible.
  168376. */
  168377. /*
  168378. * Terminate source --- called by jpeg_finish_decompress
  168379. * after all data has been read. Often a no-op.
  168380. *
  168381. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168382. * application must deal with any cleanup that should happen even
  168383. * for error exit.
  168384. */
  168385. METHODDEF(void)
  168386. term_source (j_decompress_ptr)
  168387. {
  168388. /* no work necessary here */
  168389. }
  168390. /*
  168391. * Prepare for input from a stdio stream.
  168392. * The caller must have already opened the stream, and is responsible
  168393. * for closing it after finishing decompression.
  168394. */
  168395. GLOBAL(void)
  168396. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168397. {
  168398. my_src_ptr src;
  168399. /* The source object and input buffer are made permanent so that a series
  168400. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168401. * only before the first one. (If we discarded the buffer at the end of
  168402. * one image, we'd likely lose the start of the next one.)
  168403. * This makes it unsafe to use this manager and a different source
  168404. * manager serially with the same JPEG object. Caveat programmer.
  168405. */
  168406. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168407. cinfo->src = (struct jpeg_source_mgr *)
  168408. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168409. SIZEOF(my_source_mgr));
  168410. src = (my_src_ptr) cinfo->src;
  168411. src->buffer = (JOCTET *)
  168412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168413. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168414. }
  168415. src = (my_src_ptr) cinfo->src;
  168416. src->pub.init_source = init_source;
  168417. src->pub.fill_input_buffer = fill_input_buffer;
  168418. src->pub.skip_input_data = skip_input_data;
  168419. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168420. src->pub.term_source = term_source;
  168421. src->infile = infile;
  168422. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168423. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168424. }
  168425. /*** End of inlined file: jdatasrc.c ***/
  168426. /*** Start of inlined file: jdcoefct.c ***/
  168427. #define JPEG_INTERNALS
  168428. /* Block smoothing is only applicable for progressive JPEG, so: */
  168429. #ifndef D_PROGRESSIVE_SUPPORTED
  168430. #undef BLOCK_SMOOTHING_SUPPORTED
  168431. #endif
  168432. /* Private buffer controller object */
  168433. typedef struct {
  168434. struct jpeg_d_coef_controller pub; /* public fields */
  168435. /* These variables keep track of the current location of the input side. */
  168436. /* cinfo->input_iMCU_row is also used for this. */
  168437. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168438. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168439. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168440. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168441. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168442. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168443. * and let the entropy decoder write into that workspace each time.
  168444. * (On 80x86, the workspace is FAR even though it's not really very big;
  168445. * this is to keep the module interfaces unchanged when a large coefficient
  168446. * buffer is necessary.)
  168447. * In multi-pass modes, this array points to the current MCU's blocks
  168448. * within the virtual arrays; it is used only by the input side.
  168449. */
  168450. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168451. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168452. /* In multi-pass modes, we need a virtual block array for each component. */
  168453. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168454. #endif
  168455. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168456. /* When doing block smoothing, we latch coefficient Al values here */
  168457. int * coef_bits_latch;
  168458. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168459. #endif
  168460. } my_coef_controller3;
  168461. typedef my_coef_controller3 * my_coef_ptr3;
  168462. /* Forward declarations */
  168463. METHODDEF(int) decompress_onepass
  168464. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168465. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168466. METHODDEF(int) decompress_data
  168467. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168468. #endif
  168469. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168470. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168471. METHODDEF(int) decompress_smooth_data
  168472. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168473. #endif
  168474. LOCAL(void)
  168475. start_iMCU_row3 (j_decompress_ptr cinfo)
  168476. /* Reset within-iMCU-row counters for a new row (input side) */
  168477. {
  168478. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168479. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168480. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168481. * But at the bottom of the image, process only what's left.
  168482. */
  168483. if (cinfo->comps_in_scan > 1) {
  168484. coef->MCU_rows_per_iMCU_row = 1;
  168485. } else {
  168486. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168487. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168488. else
  168489. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168490. }
  168491. coef->MCU_ctr = 0;
  168492. coef->MCU_vert_offset = 0;
  168493. }
  168494. /*
  168495. * Initialize for an input processing pass.
  168496. */
  168497. METHODDEF(void)
  168498. start_input_pass (j_decompress_ptr cinfo)
  168499. {
  168500. cinfo->input_iMCU_row = 0;
  168501. start_iMCU_row3(cinfo);
  168502. }
  168503. /*
  168504. * Initialize for an output processing pass.
  168505. */
  168506. METHODDEF(void)
  168507. start_output_pass (j_decompress_ptr cinfo)
  168508. {
  168509. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168510. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168511. /* If multipass, check to see whether to use block smoothing on this pass */
  168512. if (coef->pub.coef_arrays != NULL) {
  168513. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168514. coef->pub.decompress_data = decompress_smooth_data;
  168515. else
  168516. coef->pub.decompress_data = decompress_data;
  168517. }
  168518. #endif
  168519. cinfo->output_iMCU_row = 0;
  168520. }
  168521. /*
  168522. * Decompress and return some data in the single-pass case.
  168523. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168524. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168525. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168526. *
  168527. * NB: output_buf contains a plane for each component in image,
  168528. * which we index according to the component's SOF position.
  168529. */
  168530. METHODDEF(int)
  168531. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168532. {
  168533. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168534. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168535. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168536. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168537. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168538. JSAMPARRAY output_ptr;
  168539. JDIMENSION start_col, output_col;
  168540. jpeg_component_info *compptr;
  168541. inverse_DCT_method_ptr inverse_DCT;
  168542. /* Loop to process as much as one whole iMCU row */
  168543. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168544. yoffset++) {
  168545. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168546. MCU_col_num++) {
  168547. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168548. jzero_far((void FAR *) coef->MCU_buffer[0],
  168549. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168550. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168551. /* Suspension forced; update state counters and exit */
  168552. coef->MCU_vert_offset = yoffset;
  168553. coef->MCU_ctr = MCU_col_num;
  168554. return JPEG_SUSPENDED;
  168555. }
  168556. /* Determine where data should go in output_buf and do the IDCT thing.
  168557. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168558. * incremented past them!). Note the inner loop relies on having
  168559. * allocated the MCU_buffer[] blocks sequentially.
  168560. */
  168561. blkn = 0; /* index of current DCT block within MCU */
  168562. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168563. compptr = cinfo->cur_comp_info[ci];
  168564. /* Don't bother to IDCT an uninteresting component. */
  168565. if (! compptr->component_needed) {
  168566. blkn += compptr->MCU_blocks;
  168567. continue;
  168568. }
  168569. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168570. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168571. : compptr->last_col_width;
  168572. output_ptr = output_buf[compptr->component_index] +
  168573. yoffset * compptr->DCT_scaled_size;
  168574. start_col = MCU_col_num * compptr->MCU_sample_width;
  168575. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168576. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168577. yoffset+yindex < compptr->last_row_height) {
  168578. output_col = start_col;
  168579. for (xindex = 0; xindex < useful_width; xindex++) {
  168580. (*inverse_DCT) (cinfo, compptr,
  168581. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168582. output_ptr, output_col);
  168583. output_col += compptr->DCT_scaled_size;
  168584. }
  168585. }
  168586. blkn += compptr->MCU_width;
  168587. output_ptr += compptr->DCT_scaled_size;
  168588. }
  168589. }
  168590. }
  168591. /* Completed an MCU row, but perhaps not an iMCU row */
  168592. coef->MCU_ctr = 0;
  168593. }
  168594. /* Completed the iMCU row, advance counters for next one */
  168595. cinfo->output_iMCU_row++;
  168596. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168597. start_iMCU_row3(cinfo);
  168598. return JPEG_ROW_COMPLETED;
  168599. }
  168600. /* Completed the scan */
  168601. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168602. return JPEG_SCAN_COMPLETED;
  168603. }
  168604. /*
  168605. * Dummy consume-input routine for single-pass operation.
  168606. */
  168607. METHODDEF(int)
  168608. dummy_consume_data (j_decompress_ptr)
  168609. {
  168610. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168611. }
  168612. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168613. /*
  168614. * Consume input data and store it in the full-image coefficient buffer.
  168615. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168616. * ie, v_samp_factor block rows for each component in the scan.
  168617. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168618. */
  168619. METHODDEF(int)
  168620. consume_data (j_decompress_ptr cinfo)
  168621. {
  168622. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168623. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168624. int blkn, ci, xindex, yindex, yoffset;
  168625. JDIMENSION start_col;
  168626. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168627. JBLOCKROW buffer_ptr;
  168628. jpeg_component_info *compptr;
  168629. /* Align the virtual buffers for the components used in this scan. */
  168630. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168631. compptr = cinfo->cur_comp_info[ci];
  168632. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168633. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168634. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168635. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168636. /* Note: entropy decoder expects buffer to be zeroed,
  168637. * but this is handled automatically by the memory manager
  168638. * because we requested a pre-zeroed array.
  168639. */
  168640. }
  168641. /* Loop to process one whole iMCU row */
  168642. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168643. yoffset++) {
  168644. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168645. MCU_col_num++) {
  168646. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168647. blkn = 0; /* index of current DCT block within MCU */
  168648. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168649. compptr = cinfo->cur_comp_info[ci];
  168650. start_col = MCU_col_num * compptr->MCU_width;
  168651. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168652. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168653. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168654. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168655. }
  168656. }
  168657. }
  168658. /* Try to fetch the MCU. */
  168659. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168660. /* Suspension forced; update state counters and exit */
  168661. coef->MCU_vert_offset = yoffset;
  168662. coef->MCU_ctr = MCU_col_num;
  168663. return JPEG_SUSPENDED;
  168664. }
  168665. }
  168666. /* Completed an MCU row, but perhaps not an iMCU row */
  168667. coef->MCU_ctr = 0;
  168668. }
  168669. /* Completed the iMCU row, advance counters for next one */
  168670. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168671. start_iMCU_row3(cinfo);
  168672. return JPEG_ROW_COMPLETED;
  168673. }
  168674. /* Completed the scan */
  168675. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168676. return JPEG_SCAN_COMPLETED;
  168677. }
  168678. /*
  168679. * Decompress and return some data in the multi-pass case.
  168680. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168681. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168682. *
  168683. * NB: output_buf contains a plane for each component in image.
  168684. */
  168685. METHODDEF(int)
  168686. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168687. {
  168688. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168689. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168690. JDIMENSION block_num;
  168691. int ci, block_row, block_rows;
  168692. JBLOCKARRAY buffer;
  168693. JBLOCKROW buffer_ptr;
  168694. JSAMPARRAY output_ptr;
  168695. JDIMENSION output_col;
  168696. jpeg_component_info *compptr;
  168697. inverse_DCT_method_ptr inverse_DCT;
  168698. /* Force some input to be done if we are getting ahead of the input. */
  168699. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168700. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168701. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168702. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168703. return JPEG_SUSPENDED;
  168704. }
  168705. /* OK, output from the virtual arrays. */
  168706. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168707. ci++, compptr++) {
  168708. /* Don't bother to IDCT an uninteresting component. */
  168709. if (! compptr->component_needed)
  168710. continue;
  168711. /* Align the virtual buffer for this component. */
  168712. buffer = (*cinfo->mem->access_virt_barray)
  168713. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168714. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168715. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168716. /* Count non-dummy DCT block rows in this iMCU row. */
  168717. if (cinfo->output_iMCU_row < last_iMCU_row)
  168718. block_rows = compptr->v_samp_factor;
  168719. else {
  168720. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168721. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168722. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168723. }
  168724. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168725. output_ptr = output_buf[ci];
  168726. /* Loop over all DCT blocks to be processed. */
  168727. for (block_row = 0; block_row < block_rows; block_row++) {
  168728. buffer_ptr = buffer[block_row];
  168729. output_col = 0;
  168730. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168731. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168732. output_ptr, output_col);
  168733. buffer_ptr++;
  168734. output_col += compptr->DCT_scaled_size;
  168735. }
  168736. output_ptr += compptr->DCT_scaled_size;
  168737. }
  168738. }
  168739. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168740. return JPEG_ROW_COMPLETED;
  168741. return JPEG_SCAN_COMPLETED;
  168742. }
  168743. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168744. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168745. /*
  168746. * This code applies interblock smoothing as described by section K.8
  168747. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168748. * the DC values of a DCT block and its 8 neighboring blocks.
  168749. * We apply smoothing only for progressive JPEG decoding, and only if
  168750. * the coefficients it can estimate are not yet known to full precision.
  168751. */
  168752. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168753. #define Q01_POS 1
  168754. #define Q10_POS 8
  168755. #define Q20_POS 16
  168756. #define Q11_POS 9
  168757. #define Q02_POS 2
  168758. /*
  168759. * Determine whether block smoothing is applicable and safe.
  168760. * We also latch the current states of the coef_bits[] entries for the
  168761. * AC coefficients; otherwise, if the input side of the decompressor
  168762. * advances into a new scan, we might think the coefficients are known
  168763. * more accurately than they really are.
  168764. */
  168765. LOCAL(boolean)
  168766. smoothing_ok (j_decompress_ptr cinfo)
  168767. {
  168768. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168769. boolean smoothing_useful = FALSE;
  168770. int ci, coefi;
  168771. jpeg_component_info *compptr;
  168772. JQUANT_TBL * qtable;
  168773. int * coef_bits;
  168774. int * coef_bits_latch;
  168775. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168776. return FALSE;
  168777. /* Allocate latch area if not already done */
  168778. if (coef->coef_bits_latch == NULL)
  168779. coef->coef_bits_latch = (int *)
  168780. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168781. cinfo->num_components *
  168782. (SAVED_COEFS * SIZEOF(int)));
  168783. coef_bits_latch = coef->coef_bits_latch;
  168784. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168785. ci++, compptr++) {
  168786. /* All components' quantization values must already be latched. */
  168787. if ((qtable = compptr->quant_table) == NULL)
  168788. return FALSE;
  168789. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168790. if (qtable->quantval[0] == 0 ||
  168791. qtable->quantval[Q01_POS] == 0 ||
  168792. qtable->quantval[Q10_POS] == 0 ||
  168793. qtable->quantval[Q20_POS] == 0 ||
  168794. qtable->quantval[Q11_POS] == 0 ||
  168795. qtable->quantval[Q02_POS] == 0)
  168796. return FALSE;
  168797. /* DC values must be at least partly known for all components. */
  168798. coef_bits = cinfo->coef_bits[ci];
  168799. if (coef_bits[0] < 0)
  168800. return FALSE;
  168801. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168802. for (coefi = 1; coefi <= 5; coefi++) {
  168803. coef_bits_latch[coefi] = coef_bits[coefi];
  168804. if (coef_bits[coefi] != 0)
  168805. smoothing_useful = TRUE;
  168806. }
  168807. coef_bits_latch += SAVED_COEFS;
  168808. }
  168809. return smoothing_useful;
  168810. }
  168811. /*
  168812. * Variant of decompress_data for use when doing block smoothing.
  168813. */
  168814. METHODDEF(int)
  168815. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168816. {
  168817. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168818. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168819. JDIMENSION block_num, last_block_column;
  168820. int ci, block_row, block_rows, access_rows;
  168821. JBLOCKARRAY buffer;
  168822. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168823. JSAMPARRAY output_ptr;
  168824. JDIMENSION output_col;
  168825. jpeg_component_info *compptr;
  168826. inverse_DCT_method_ptr inverse_DCT;
  168827. boolean first_row, last_row;
  168828. JBLOCK workspace;
  168829. int *coef_bits;
  168830. JQUANT_TBL *quanttbl;
  168831. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168832. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168833. int Al, pred;
  168834. /* Force some input to be done if we are getting ahead of the input. */
  168835. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168836. ! cinfo->inputctl->eoi_reached) {
  168837. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168838. /* If input is working on current scan, we ordinarily want it to
  168839. * have completed the current row. But if input scan is DC,
  168840. * we want it to keep one row ahead so that next block row's DC
  168841. * values are up to date.
  168842. */
  168843. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168844. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168845. break;
  168846. }
  168847. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168848. return JPEG_SUSPENDED;
  168849. }
  168850. /* OK, output from the virtual arrays. */
  168851. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168852. ci++, compptr++) {
  168853. /* Don't bother to IDCT an uninteresting component. */
  168854. if (! compptr->component_needed)
  168855. continue;
  168856. /* Count non-dummy DCT block rows in this iMCU row. */
  168857. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168858. block_rows = compptr->v_samp_factor;
  168859. access_rows = block_rows * 2; /* this and next iMCU row */
  168860. last_row = FALSE;
  168861. } else {
  168862. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168863. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168864. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168865. access_rows = block_rows; /* this iMCU row only */
  168866. last_row = TRUE;
  168867. }
  168868. /* Align the virtual buffer for this component. */
  168869. if (cinfo->output_iMCU_row > 0) {
  168870. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168871. buffer = (*cinfo->mem->access_virt_barray)
  168872. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168873. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168874. (JDIMENSION) access_rows, FALSE);
  168875. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168876. first_row = FALSE;
  168877. } else {
  168878. buffer = (*cinfo->mem->access_virt_barray)
  168879. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168880. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168881. first_row = TRUE;
  168882. }
  168883. /* Fetch component-dependent info */
  168884. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168885. quanttbl = compptr->quant_table;
  168886. Q00 = quanttbl->quantval[0];
  168887. Q01 = quanttbl->quantval[Q01_POS];
  168888. Q10 = quanttbl->quantval[Q10_POS];
  168889. Q20 = quanttbl->quantval[Q20_POS];
  168890. Q11 = quanttbl->quantval[Q11_POS];
  168891. Q02 = quanttbl->quantval[Q02_POS];
  168892. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168893. output_ptr = output_buf[ci];
  168894. /* Loop over all DCT blocks to be processed. */
  168895. for (block_row = 0; block_row < block_rows; block_row++) {
  168896. buffer_ptr = buffer[block_row];
  168897. if (first_row && block_row == 0)
  168898. prev_block_row = buffer_ptr;
  168899. else
  168900. prev_block_row = buffer[block_row-1];
  168901. if (last_row && block_row == block_rows-1)
  168902. next_block_row = buffer_ptr;
  168903. else
  168904. next_block_row = buffer[block_row+1];
  168905. /* We fetch the surrounding DC values using a sliding-register approach.
  168906. * Initialize all nine here so as to do the right thing on narrow pics.
  168907. */
  168908. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168909. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168910. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168911. output_col = 0;
  168912. last_block_column = compptr->width_in_blocks - 1;
  168913. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168914. /* Fetch current DCT block into workspace so we can modify it. */
  168915. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168916. /* Update DC values */
  168917. if (block_num < last_block_column) {
  168918. DC3 = (int) prev_block_row[1][0];
  168919. DC6 = (int) buffer_ptr[1][0];
  168920. DC9 = (int) next_block_row[1][0];
  168921. }
  168922. /* Compute coefficient estimates per K.8.
  168923. * An estimate is applied only if coefficient is still zero,
  168924. * and is not known to be fully accurate.
  168925. */
  168926. /* AC01 */
  168927. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168928. num = 36 * Q00 * (DC4 - DC6);
  168929. if (num >= 0) {
  168930. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168931. if (Al > 0 && pred >= (1<<Al))
  168932. pred = (1<<Al)-1;
  168933. } else {
  168934. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168935. if (Al > 0 && pred >= (1<<Al))
  168936. pred = (1<<Al)-1;
  168937. pred = -pred;
  168938. }
  168939. workspace[1] = (JCOEF) pred;
  168940. }
  168941. /* AC10 */
  168942. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168943. num = 36 * Q00 * (DC2 - DC8);
  168944. if (num >= 0) {
  168945. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168946. if (Al > 0 && pred >= (1<<Al))
  168947. pred = (1<<Al)-1;
  168948. } else {
  168949. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168950. if (Al > 0 && pred >= (1<<Al))
  168951. pred = (1<<Al)-1;
  168952. pred = -pred;
  168953. }
  168954. workspace[8] = (JCOEF) pred;
  168955. }
  168956. /* AC20 */
  168957. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168958. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168959. if (num >= 0) {
  168960. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168961. if (Al > 0 && pred >= (1<<Al))
  168962. pred = (1<<Al)-1;
  168963. } else {
  168964. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168965. if (Al > 0 && pred >= (1<<Al))
  168966. pred = (1<<Al)-1;
  168967. pred = -pred;
  168968. }
  168969. workspace[16] = (JCOEF) pred;
  168970. }
  168971. /* AC11 */
  168972. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168973. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168974. if (num >= 0) {
  168975. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168976. if (Al > 0 && pred >= (1<<Al))
  168977. pred = (1<<Al)-1;
  168978. } else {
  168979. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168980. if (Al > 0 && pred >= (1<<Al))
  168981. pred = (1<<Al)-1;
  168982. pred = -pred;
  168983. }
  168984. workspace[9] = (JCOEF) pred;
  168985. }
  168986. /* AC02 */
  168987. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168988. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168989. if (num >= 0) {
  168990. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168991. if (Al > 0 && pred >= (1<<Al))
  168992. pred = (1<<Al)-1;
  168993. } else {
  168994. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168995. if (Al > 0 && pred >= (1<<Al))
  168996. pred = (1<<Al)-1;
  168997. pred = -pred;
  168998. }
  168999. workspace[2] = (JCOEF) pred;
  169000. }
  169001. /* OK, do the IDCT */
  169002. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169003. output_ptr, output_col);
  169004. /* Advance for next column */
  169005. DC1 = DC2; DC2 = DC3;
  169006. DC4 = DC5; DC5 = DC6;
  169007. DC7 = DC8; DC8 = DC9;
  169008. buffer_ptr++, prev_block_row++, next_block_row++;
  169009. output_col += compptr->DCT_scaled_size;
  169010. }
  169011. output_ptr += compptr->DCT_scaled_size;
  169012. }
  169013. }
  169014. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169015. return JPEG_ROW_COMPLETED;
  169016. return JPEG_SCAN_COMPLETED;
  169017. }
  169018. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169019. /*
  169020. * Initialize coefficient buffer controller.
  169021. */
  169022. GLOBAL(void)
  169023. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169024. {
  169025. my_coef_ptr3 coef;
  169026. coef = (my_coef_ptr3)
  169027. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169028. SIZEOF(my_coef_controller3));
  169029. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169030. coef->pub.start_input_pass = start_input_pass;
  169031. coef->pub.start_output_pass = start_output_pass;
  169032. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169033. coef->coef_bits_latch = NULL;
  169034. #endif
  169035. /* Create the coefficient buffer. */
  169036. if (need_full_buffer) {
  169037. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169038. /* Allocate a full-image virtual array for each component, */
  169039. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169040. /* Note we ask for a pre-zeroed array. */
  169041. int ci, access_rows;
  169042. jpeg_component_info *compptr;
  169043. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169044. ci++, compptr++) {
  169045. access_rows = compptr->v_samp_factor;
  169046. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169047. /* If block smoothing could be used, need a bigger window */
  169048. if (cinfo->progressive_mode)
  169049. access_rows *= 3;
  169050. #endif
  169051. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169052. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169053. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169054. (long) compptr->h_samp_factor),
  169055. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169056. (long) compptr->v_samp_factor),
  169057. (JDIMENSION) access_rows);
  169058. }
  169059. coef->pub.consume_data = consume_data;
  169060. coef->pub.decompress_data = decompress_data;
  169061. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169062. #else
  169063. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169064. #endif
  169065. } else {
  169066. /* We only need a single-MCU buffer. */
  169067. JBLOCKROW buffer;
  169068. int i;
  169069. buffer = (JBLOCKROW)
  169070. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169071. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169072. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169073. coef->MCU_buffer[i] = buffer + i;
  169074. }
  169075. coef->pub.consume_data = dummy_consume_data;
  169076. coef->pub.decompress_data = decompress_onepass;
  169077. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169078. }
  169079. }
  169080. /*** End of inlined file: jdcoefct.c ***/
  169081. #undef FIX
  169082. /*** Start of inlined file: jdcolor.c ***/
  169083. #define JPEG_INTERNALS
  169084. /* Private subobject */
  169085. typedef struct {
  169086. struct jpeg_color_deconverter pub; /* public fields */
  169087. /* Private state for YCC->RGB conversion */
  169088. int * Cr_r_tab; /* => table for Cr to R conversion */
  169089. int * Cb_b_tab; /* => table for Cb to B conversion */
  169090. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169091. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169092. } my_color_deconverter2;
  169093. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169094. /**************** YCbCr -> RGB conversion: most common case **************/
  169095. /*
  169096. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169097. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169098. * The conversion equations to be implemented are therefore
  169099. * R = Y + 1.40200 * Cr
  169100. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169101. * B = Y + 1.77200 * Cb
  169102. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169103. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169104. *
  169105. * To avoid floating-point arithmetic, we represent the fractional constants
  169106. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169107. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169108. * Notice that Y, being an integral input, does not contribute any fraction
  169109. * so it need not participate in the rounding.
  169110. *
  169111. * For even more speed, we avoid doing any multiplications in the inner loop
  169112. * by precalculating the constants times Cb and Cr for all possible values.
  169113. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169114. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169115. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169116. * colorspace anyway.
  169117. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169118. * values for the G calculation are left scaled up, since we must add them
  169119. * together before rounding.
  169120. */
  169121. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169122. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169123. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169124. /*
  169125. * Initialize tables for YCC->RGB colorspace conversion.
  169126. */
  169127. LOCAL(void)
  169128. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169129. {
  169130. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169131. int i;
  169132. INT32 x;
  169133. SHIFT_TEMPS
  169134. cconvert->Cr_r_tab = (int *)
  169135. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169136. (MAXJSAMPLE+1) * SIZEOF(int));
  169137. cconvert->Cb_b_tab = (int *)
  169138. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169139. (MAXJSAMPLE+1) * SIZEOF(int));
  169140. cconvert->Cr_g_tab = (INT32 *)
  169141. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169142. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169143. cconvert->Cb_g_tab = (INT32 *)
  169144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169145. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169146. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169147. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169148. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169149. /* Cr=>R value is nearest int to 1.40200 * x */
  169150. cconvert->Cr_r_tab[i] = (int)
  169151. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169152. /* Cb=>B value is nearest int to 1.77200 * x */
  169153. cconvert->Cb_b_tab[i] = (int)
  169154. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169155. /* Cr=>G value is scaled-up -0.71414 * x */
  169156. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169157. /* Cb=>G value is scaled-up -0.34414 * x */
  169158. /* We also add in ONE_HALF so that need not do it in inner loop */
  169159. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169160. }
  169161. }
  169162. /*
  169163. * Convert some rows of samples to the output colorspace.
  169164. *
  169165. * Note that we change from noninterleaved, one-plane-per-component format
  169166. * to interleaved-pixel format. The output buffer is therefore three times
  169167. * as wide as the input buffer.
  169168. * A starting row offset is provided only for the input buffer. The caller
  169169. * can easily adjust the passed output_buf value to accommodate any row
  169170. * offset required on that side.
  169171. */
  169172. METHODDEF(void)
  169173. ycc_rgb_convert (j_decompress_ptr cinfo,
  169174. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169175. JSAMPARRAY output_buf, int num_rows)
  169176. {
  169177. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169178. register int y, cb, cr;
  169179. register JSAMPROW outptr;
  169180. register JSAMPROW inptr0, inptr1, inptr2;
  169181. register JDIMENSION col;
  169182. JDIMENSION num_cols = cinfo->output_width;
  169183. /* copy these pointers into registers if possible */
  169184. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169185. register int * Crrtab = cconvert->Cr_r_tab;
  169186. register int * Cbbtab = cconvert->Cb_b_tab;
  169187. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169188. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169189. SHIFT_TEMPS
  169190. while (--num_rows >= 0) {
  169191. inptr0 = input_buf[0][input_row];
  169192. inptr1 = input_buf[1][input_row];
  169193. inptr2 = input_buf[2][input_row];
  169194. input_row++;
  169195. outptr = *output_buf++;
  169196. for (col = 0; col < num_cols; col++) {
  169197. y = GETJSAMPLE(inptr0[col]);
  169198. cb = GETJSAMPLE(inptr1[col]);
  169199. cr = GETJSAMPLE(inptr2[col]);
  169200. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169201. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169202. outptr[RGB_GREEN] = range_limit[y +
  169203. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169204. SCALEBITS))];
  169205. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169206. outptr += RGB_PIXELSIZE;
  169207. }
  169208. }
  169209. }
  169210. /**************** Cases other than YCbCr -> RGB **************/
  169211. /*
  169212. * Color conversion for no colorspace change: just copy the data,
  169213. * converting from separate-planes to interleaved representation.
  169214. */
  169215. METHODDEF(void)
  169216. null_convert2 (j_decompress_ptr cinfo,
  169217. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169218. JSAMPARRAY output_buf, int num_rows)
  169219. {
  169220. register JSAMPROW inptr, outptr;
  169221. register JDIMENSION count;
  169222. register int num_components = cinfo->num_components;
  169223. JDIMENSION num_cols = cinfo->output_width;
  169224. int ci;
  169225. while (--num_rows >= 0) {
  169226. for (ci = 0; ci < num_components; ci++) {
  169227. inptr = input_buf[ci][input_row];
  169228. outptr = output_buf[0] + ci;
  169229. for (count = num_cols; count > 0; count--) {
  169230. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169231. outptr += num_components;
  169232. }
  169233. }
  169234. input_row++;
  169235. output_buf++;
  169236. }
  169237. }
  169238. /*
  169239. * Color conversion for grayscale: just copy the data.
  169240. * This also works for YCbCr -> grayscale conversion, in which
  169241. * we just copy the Y (luminance) component and ignore chrominance.
  169242. */
  169243. METHODDEF(void)
  169244. grayscale_convert2 (j_decompress_ptr cinfo,
  169245. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169246. JSAMPARRAY output_buf, int num_rows)
  169247. {
  169248. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169249. num_rows, cinfo->output_width);
  169250. }
  169251. /*
  169252. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169253. * This is provided to support applications that don't want to cope
  169254. * with grayscale as a separate case.
  169255. */
  169256. METHODDEF(void)
  169257. gray_rgb_convert (j_decompress_ptr cinfo,
  169258. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169259. JSAMPARRAY output_buf, int num_rows)
  169260. {
  169261. register JSAMPROW inptr, outptr;
  169262. register JDIMENSION col;
  169263. JDIMENSION num_cols = cinfo->output_width;
  169264. while (--num_rows >= 0) {
  169265. inptr = input_buf[0][input_row++];
  169266. outptr = *output_buf++;
  169267. for (col = 0; col < num_cols; col++) {
  169268. /* We can dispense with GETJSAMPLE() here */
  169269. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169270. outptr += RGB_PIXELSIZE;
  169271. }
  169272. }
  169273. }
  169274. /*
  169275. * Adobe-style YCCK->CMYK conversion.
  169276. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169277. * conversion as above, while passing K (black) unchanged.
  169278. * We assume build_ycc_rgb_table has been called.
  169279. */
  169280. METHODDEF(void)
  169281. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169282. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169283. JSAMPARRAY output_buf, int num_rows)
  169284. {
  169285. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169286. register int y, cb, cr;
  169287. register JSAMPROW outptr;
  169288. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169289. register JDIMENSION col;
  169290. JDIMENSION num_cols = cinfo->output_width;
  169291. /* copy these pointers into registers if possible */
  169292. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169293. register int * Crrtab = cconvert->Cr_r_tab;
  169294. register int * Cbbtab = cconvert->Cb_b_tab;
  169295. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169296. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169297. SHIFT_TEMPS
  169298. while (--num_rows >= 0) {
  169299. inptr0 = input_buf[0][input_row];
  169300. inptr1 = input_buf[1][input_row];
  169301. inptr2 = input_buf[2][input_row];
  169302. inptr3 = input_buf[3][input_row];
  169303. input_row++;
  169304. outptr = *output_buf++;
  169305. for (col = 0; col < num_cols; col++) {
  169306. y = GETJSAMPLE(inptr0[col]);
  169307. cb = GETJSAMPLE(inptr1[col]);
  169308. cr = GETJSAMPLE(inptr2[col]);
  169309. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169310. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169311. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169312. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169313. SCALEBITS)))];
  169314. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169315. /* K passes through unchanged */
  169316. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169317. outptr += 4;
  169318. }
  169319. }
  169320. }
  169321. /*
  169322. * Empty method for start_pass.
  169323. */
  169324. METHODDEF(void)
  169325. start_pass_dcolor (j_decompress_ptr)
  169326. {
  169327. /* no work needed */
  169328. }
  169329. /*
  169330. * Module initialization routine for output colorspace conversion.
  169331. */
  169332. GLOBAL(void)
  169333. jinit_color_deconverter (j_decompress_ptr cinfo)
  169334. {
  169335. my_cconvert_ptr2 cconvert;
  169336. int ci;
  169337. cconvert = (my_cconvert_ptr2)
  169338. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169339. SIZEOF(my_color_deconverter2));
  169340. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169341. cconvert->pub.start_pass = start_pass_dcolor;
  169342. /* Make sure num_components agrees with jpeg_color_space */
  169343. switch (cinfo->jpeg_color_space) {
  169344. case JCS_GRAYSCALE:
  169345. if (cinfo->num_components != 1)
  169346. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169347. break;
  169348. case JCS_RGB:
  169349. case JCS_YCbCr:
  169350. if (cinfo->num_components != 3)
  169351. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169352. break;
  169353. case JCS_CMYK:
  169354. case JCS_YCCK:
  169355. if (cinfo->num_components != 4)
  169356. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169357. break;
  169358. default: /* JCS_UNKNOWN can be anything */
  169359. if (cinfo->num_components < 1)
  169360. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169361. break;
  169362. }
  169363. /* Set out_color_components and conversion method based on requested space.
  169364. * Also clear the component_needed flags for any unused components,
  169365. * so that earlier pipeline stages can avoid useless computation.
  169366. */
  169367. switch (cinfo->out_color_space) {
  169368. case JCS_GRAYSCALE:
  169369. cinfo->out_color_components = 1;
  169370. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169371. cinfo->jpeg_color_space == JCS_YCbCr) {
  169372. cconvert->pub.color_convert = grayscale_convert2;
  169373. /* For color->grayscale conversion, only the Y (0) component is needed */
  169374. for (ci = 1; ci < cinfo->num_components; ci++)
  169375. cinfo->comp_info[ci].component_needed = FALSE;
  169376. } else
  169377. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169378. break;
  169379. case JCS_RGB:
  169380. cinfo->out_color_components = RGB_PIXELSIZE;
  169381. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169382. cconvert->pub.color_convert = ycc_rgb_convert;
  169383. build_ycc_rgb_table(cinfo);
  169384. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169385. cconvert->pub.color_convert = gray_rgb_convert;
  169386. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169387. cconvert->pub.color_convert = null_convert2;
  169388. } else
  169389. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169390. break;
  169391. case JCS_CMYK:
  169392. cinfo->out_color_components = 4;
  169393. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169394. cconvert->pub.color_convert = ycck_cmyk_convert;
  169395. build_ycc_rgb_table(cinfo);
  169396. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169397. cconvert->pub.color_convert = null_convert2;
  169398. } else
  169399. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169400. break;
  169401. default:
  169402. /* Permit null conversion to same output space */
  169403. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169404. cinfo->out_color_components = cinfo->num_components;
  169405. cconvert->pub.color_convert = null_convert2;
  169406. } else /* unsupported non-null conversion */
  169407. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169408. break;
  169409. }
  169410. if (cinfo->quantize_colors)
  169411. cinfo->output_components = 1; /* single colormapped output component */
  169412. else
  169413. cinfo->output_components = cinfo->out_color_components;
  169414. }
  169415. /*** End of inlined file: jdcolor.c ***/
  169416. #undef FIX
  169417. /*** Start of inlined file: jddctmgr.c ***/
  169418. #define JPEG_INTERNALS
  169419. /*
  169420. * The decompressor input side (jdinput.c) saves away the appropriate
  169421. * quantization table for each component at the start of the first scan
  169422. * involving that component. (This is necessary in order to correctly
  169423. * decode files that reuse Q-table slots.)
  169424. * When we are ready to make an output pass, the saved Q-table is converted
  169425. * to a multiplier table that will actually be used by the IDCT routine.
  169426. * The multiplier table contents are IDCT-method-dependent. To support
  169427. * application changes in IDCT method between scans, we can remake the
  169428. * multiplier tables if necessary.
  169429. * In buffered-image mode, the first output pass may occur before any data
  169430. * has been seen for some components, and thus before their Q-tables have
  169431. * been saved away. To handle this case, multiplier tables are preset
  169432. * to zeroes; the result of the IDCT will be a neutral gray level.
  169433. */
  169434. /* Private subobject for this module */
  169435. typedef struct {
  169436. struct jpeg_inverse_dct pub; /* public fields */
  169437. /* This array contains the IDCT method code that each multiplier table
  169438. * is currently set up for, or -1 if it's not yet set up.
  169439. * The actual multiplier tables are pointed to by dct_table in the
  169440. * per-component comp_info structures.
  169441. */
  169442. int cur_method[MAX_COMPONENTS];
  169443. } my_idct_controller;
  169444. typedef my_idct_controller * my_idct_ptr;
  169445. /* Allocated multiplier tables: big enough for any supported variant */
  169446. typedef union {
  169447. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169448. #ifdef DCT_IFAST_SUPPORTED
  169449. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169450. #endif
  169451. #ifdef DCT_FLOAT_SUPPORTED
  169452. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169453. #endif
  169454. } multiplier_table;
  169455. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169456. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169457. */
  169458. #ifdef DCT_ISLOW_SUPPORTED
  169459. #define PROVIDE_ISLOW_TABLES
  169460. #else
  169461. #ifdef IDCT_SCALING_SUPPORTED
  169462. #define PROVIDE_ISLOW_TABLES
  169463. #endif
  169464. #endif
  169465. /*
  169466. * Prepare for an output pass.
  169467. * Here we select the proper IDCT routine for each component and build
  169468. * a matching multiplier table.
  169469. */
  169470. METHODDEF(void)
  169471. start_pass (j_decompress_ptr cinfo)
  169472. {
  169473. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169474. int ci, i;
  169475. jpeg_component_info *compptr;
  169476. int method = 0;
  169477. inverse_DCT_method_ptr method_ptr = NULL;
  169478. JQUANT_TBL * qtbl;
  169479. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169480. ci++, compptr++) {
  169481. /* Select the proper IDCT routine for this component's scaling */
  169482. switch (compptr->DCT_scaled_size) {
  169483. #ifdef IDCT_SCALING_SUPPORTED
  169484. case 1:
  169485. method_ptr = jpeg_idct_1x1;
  169486. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169487. break;
  169488. case 2:
  169489. method_ptr = jpeg_idct_2x2;
  169490. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169491. break;
  169492. case 4:
  169493. method_ptr = jpeg_idct_4x4;
  169494. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169495. break;
  169496. #endif
  169497. case DCTSIZE:
  169498. switch (cinfo->dct_method) {
  169499. #ifdef DCT_ISLOW_SUPPORTED
  169500. case JDCT_ISLOW:
  169501. method_ptr = jpeg_idct_islow;
  169502. method = JDCT_ISLOW;
  169503. break;
  169504. #endif
  169505. #ifdef DCT_IFAST_SUPPORTED
  169506. case JDCT_IFAST:
  169507. method_ptr = jpeg_idct_ifast;
  169508. method = JDCT_IFAST;
  169509. break;
  169510. #endif
  169511. #ifdef DCT_FLOAT_SUPPORTED
  169512. case JDCT_FLOAT:
  169513. method_ptr = jpeg_idct_float;
  169514. method = JDCT_FLOAT;
  169515. break;
  169516. #endif
  169517. default:
  169518. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169519. break;
  169520. }
  169521. break;
  169522. default:
  169523. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169524. break;
  169525. }
  169526. idct->pub.inverse_DCT[ci] = method_ptr;
  169527. /* Create multiplier table from quant table.
  169528. * However, we can skip this if the component is uninteresting
  169529. * or if we already built the table. Also, if no quant table
  169530. * has yet been saved for the component, we leave the
  169531. * multiplier table all-zero; we'll be reading zeroes from the
  169532. * coefficient controller's buffer anyway.
  169533. */
  169534. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169535. continue;
  169536. qtbl = compptr->quant_table;
  169537. if (qtbl == NULL) /* happens if no data yet for component */
  169538. continue;
  169539. idct->cur_method[ci] = method;
  169540. switch (method) {
  169541. #ifdef PROVIDE_ISLOW_TABLES
  169542. case JDCT_ISLOW:
  169543. {
  169544. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169545. * coefficients, but are stored as ints to ensure access efficiency.
  169546. */
  169547. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169548. for (i = 0; i < DCTSIZE2; i++) {
  169549. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169550. }
  169551. }
  169552. break;
  169553. #endif
  169554. #ifdef DCT_IFAST_SUPPORTED
  169555. case JDCT_IFAST:
  169556. {
  169557. /* For AA&N IDCT method, multipliers are equal to quantization
  169558. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169559. * scalefactor[0] = 1
  169560. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169561. * For integer operation, the multiplier table is to be scaled by
  169562. * IFAST_SCALE_BITS.
  169563. */
  169564. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169565. #define CONST_BITS 14
  169566. static const INT16 aanscales[DCTSIZE2] = {
  169567. /* precomputed values scaled up by 14 bits */
  169568. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169569. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169570. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169571. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169572. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169573. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169574. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169575. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169576. };
  169577. SHIFT_TEMPS
  169578. for (i = 0; i < DCTSIZE2; i++) {
  169579. ifmtbl[i] = (IFAST_MULT_TYPE)
  169580. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169581. (INT32) aanscales[i]),
  169582. CONST_BITS-IFAST_SCALE_BITS);
  169583. }
  169584. }
  169585. break;
  169586. #endif
  169587. #ifdef DCT_FLOAT_SUPPORTED
  169588. case JDCT_FLOAT:
  169589. {
  169590. /* For float AA&N IDCT method, multipliers are equal to quantization
  169591. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169592. * scalefactor[0] = 1
  169593. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169594. */
  169595. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169596. int row, col;
  169597. static const double aanscalefactor[DCTSIZE] = {
  169598. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169599. 1.0, 0.785694958, 0.541196100, 0.275899379
  169600. };
  169601. i = 0;
  169602. for (row = 0; row < DCTSIZE; row++) {
  169603. for (col = 0; col < DCTSIZE; col++) {
  169604. fmtbl[i] = (FLOAT_MULT_TYPE)
  169605. ((double) qtbl->quantval[i] *
  169606. aanscalefactor[row] * aanscalefactor[col]);
  169607. i++;
  169608. }
  169609. }
  169610. }
  169611. break;
  169612. #endif
  169613. default:
  169614. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169615. break;
  169616. }
  169617. }
  169618. }
  169619. /*
  169620. * Initialize IDCT manager.
  169621. */
  169622. GLOBAL(void)
  169623. jinit_inverse_dct (j_decompress_ptr cinfo)
  169624. {
  169625. my_idct_ptr idct;
  169626. int ci;
  169627. jpeg_component_info *compptr;
  169628. idct = (my_idct_ptr)
  169629. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169630. SIZEOF(my_idct_controller));
  169631. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169632. idct->pub.start_pass = start_pass;
  169633. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169634. ci++, compptr++) {
  169635. /* Allocate and pre-zero a multiplier table for each component */
  169636. compptr->dct_table =
  169637. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169638. SIZEOF(multiplier_table));
  169639. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169640. /* Mark multiplier table not yet set up for any method */
  169641. idct->cur_method[ci] = -1;
  169642. }
  169643. }
  169644. /*** End of inlined file: jddctmgr.c ***/
  169645. #undef CONST_BITS
  169646. #undef ASSIGN_STATE
  169647. /*** Start of inlined file: jdhuff.c ***/
  169648. #define JPEG_INTERNALS
  169649. /*** Start of inlined file: jdhuff.h ***/
  169650. /* Short forms of external names for systems with brain-damaged linkers. */
  169651. #ifndef __jdhuff_h__
  169652. #define __jdhuff_h__
  169653. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169654. #define jpeg_make_d_derived_tbl jMkDDerived
  169655. #define jpeg_fill_bit_buffer jFilBitBuf
  169656. #define jpeg_huff_decode jHufDecode
  169657. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169658. /* Derived data constructed for each Huffman table */
  169659. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169660. typedef struct {
  169661. /* Basic tables: (element [0] of each array is unused) */
  169662. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169663. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169664. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169665. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169666. * the smallest code of length k; so given a code of length k, the
  169667. * corresponding symbol is huffval[code + valoffset[k]]
  169668. */
  169669. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169670. JHUFF_TBL *pub;
  169671. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169672. * the input data stream. If the next Huffman code is no more
  169673. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169674. * the corresponding symbol directly from these tables.
  169675. */
  169676. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169677. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169678. } d_derived_tbl;
  169679. /* Expand a Huffman table definition into the derived format */
  169680. EXTERN(void) jpeg_make_d_derived_tbl
  169681. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169682. d_derived_tbl ** pdtbl));
  169683. /*
  169684. * Fetching the next N bits from the input stream is a time-critical operation
  169685. * for the Huffman decoders. We implement it with a combination of inline
  169686. * macros and out-of-line subroutines. Note that N (the number of bits
  169687. * demanded at one time) never exceeds 15 for JPEG use.
  169688. *
  169689. * We read source bytes into get_buffer and dole out bits as needed.
  169690. * If get_buffer already contains enough bits, they are fetched in-line
  169691. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169692. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169693. * as full as possible (not just to the number of bits needed; this
  169694. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169695. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169696. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169697. * at least the requested number of bits --- dummy zeroes are inserted if
  169698. * necessary.
  169699. */
  169700. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169701. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169702. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169703. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169704. * appropriately should be a win. Unfortunately we can't define the size
  169705. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169706. * because not all machines measure sizeof in 8-bit bytes.
  169707. */
  169708. typedef struct { /* Bitreading state saved across MCUs */
  169709. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169710. int bits_left; /* # of unused bits in it */
  169711. } bitread_perm_state;
  169712. typedef struct { /* Bitreading working state within an MCU */
  169713. /* Current data source location */
  169714. /* We need a copy, rather than munging the original, in case of suspension */
  169715. const JOCTET * next_input_byte; /* => next byte to read from source */
  169716. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169717. /* Bit input buffer --- note these values are kept in register variables,
  169718. * not in this struct, inside the inner loops.
  169719. */
  169720. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169721. int bits_left; /* # of unused bits in it */
  169722. /* Pointer needed by jpeg_fill_bit_buffer. */
  169723. j_decompress_ptr cinfo; /* back link to decompress master record */
  169724. } bitread_working_state;
  169725. /* Macros to declare and load/save bitread local variables. */
  169726. #define BITREAD_STATE_VARS \
  169727. register bit_buf_type get_buffer; \
  169728. register int bits_left; \
  169729. bitread_working_state br_state
  169730. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169731. br_state.cinfo = cinfop; \
  169732. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169733. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169734. get_buffer = permstate.get_buffer; \
  169735. bits_left = permstate.bits_left;
  169736. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169737. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169738. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169739. permstate.get_buffer = get_buffer; \
  169740. permstate.bits_left = bits_left
  169741. /*
  169742. * These macros provide the in-line portion of bit fetching.
  169743. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169744. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169745. * The variables get_buffer and bits_left are assumed to be locals,
  169746. * but the state struct might not be (jpeg_huff_decode needs this).
  169747. * CHECK_BIT_BUFFER(state,n,action);
  169748. * Ensure there are N bits in get_buffer; if suspend, take action.
  169749. * val = GET_BITS(n);
  169750. * Fetch next N bits.
  169751. * val = PEEK_BITS(n);
  169752. * Fetch next N bits without removing them from the buffer.
  169753. * DROP_BITS(n);
  169754. * Discard next N bits.
  169755. * The value N should be a simple variable, not an expression, because it
  169756. * is evaluated multiple times.
  169757. */
  169758. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169759. { if (bits_left < (nbits)) { \
  169760. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169761. { action; } \
  169762. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169763. #define GET_BITS(nbits) \
  169764. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169765. #define PEEK_BITS(nbits) \
  169766. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169767. #define DROP_BITS(nbits) \
  169768. (bits_left -= (nbits))
  169769. /* Load up the bit buffer to a depth of at least nbits */
  169770. EXTERN(boolean) jpeg_fill_bit_buffer
  169771. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169772. register int bits_left, int nbits));
  169773. /*
  169774. * Code for extracting next Huffman-coded symbol from input bit stream.
  169775. * Again, this is time-critical and we make the main paths be macros.
  169776. *
  169777. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169778. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169779. * or fewer bits long. The few overlength codes are handled with a loop,
  169780. * which need not be inline code.
  169781. *
  169782. * Notes about the HUFF_DECODE macro:
  169783. * 1. Near the end of the data segment, we may fail to get enough bits
  169784. * for a lookahead. In that case, we do it the hard way.
  169785. * 2. If the lookahead table contains no entry, the next code must be
  169786. * more than HUFF_LOOKAHEAD bits long.
  169787. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169788. */
  169789. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169790. { register int nb, look; \
  169791. if (bits_left < HUFF_LOOKAHEAD) { \
  169792. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169793. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169794. if (bits_left < HUFF_LOOKAHEAD) { \
  169795. nb = 1; goto slowlabel; \
  169796. } \
  169797. } \
  169798. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169799. if ((nb = htbl->look_nbits[look]) != 0) { \
  169800. DROP_BITS(nb); \
  169801. result = htbl->look_sym[look]; \
  169802. } else { \
  169803. nb = HUFF_LOOKAHEAD+1; \
  169804. slowlabel: \
  169805. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169806. { failaction; } \
  169807. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169808. } \
  169809. }
  169810. /* Out-of-line case for Huffman code fetching */
  169811. EXTERN(int) jpeg_huff_decode
  169812. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169813. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169814. #endif
  169815. /*** End of inlined file: jdhuff.h ***/
  169816. /* Declarations shared with jdphuff.c */
  169817. /*
  169818. * Expanded entropy decoder object for Huffman decoding.
  169819. *
  169820. * The savable_state subrecord contains fields that change within an MCU,
  169821. * but must not be updated permanently until we complete the MCU.
  169822. */
  169823. typedef struct {
  169824. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169825. } savable_state2;
  169826. /* This macro is to work around compilers with missing or broken
  169827. * structure assignment. You'll need to fix this code if you have
  169828. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169829. */
  169830. #ifndef NO_STRUCT_ASSIGN
  169831. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169832. #else
  169833. #if MAX_COMPS_IN_SCAN == 4
  169834. #define ASSIGN_STATE(dest,src) \
  169835. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169836. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169837. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169838. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169839. #endif
  169840. #endif
  169841. typedef struct {
  169842. struct jpeg_entropy_decoder pub; /* public fields */
  169843. /* These fields are loaded into local variables at start of each MCU.
  169844. * In case of suspension, we exit WITHOUT updating them.
  169845. */
  169846. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169847. savable_state2 saved; /* Other state at start of MCU */
  169848. /* These fields are NOT loaded into local working state. */
  169849. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169850. /* Pointers to derived tables (these workspaces have image lifespan) */
  169851. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169852. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169853. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169854. /* Pointers to derived tables to be used for each block within an MCU */
  169855. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169856. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169857. /* Whether we care about the DC and AC coefficient values for each block */
  169858. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169859. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169860. } huff_entropy_decoder2;
  169861. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169862. /*
  169863. * Initialize for a Huffman-compressed scan.
  169864. */
  169865. METHODDEF(void)
  169866. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169867. {
  169868. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169869. int ci, blkn, dctbl, actbl;
  169870. jpeg_component_info * compptr;
  169871. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169872. * This ought to be an error condition, but we make it a warning because
  169873. * there are some baseline files out there with all zeroes in these bytes.
  169874. */
  169875. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169876. cinfo->Ah != 0 || cinfo->Al != 0)
  169877. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169878. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169879. compptr = cinfo->cur_comp_info[ci];
  169880. dctbl = compptr->dc_tbl_no;
  169881. actbl = compptr->ac_tbl_no;
  169882. /* Compute derived values for Huffman tables */
  169883. /* We may do this more than once for a table, but it's not expensive */
  169884. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169885. & entropy->dc_derived_tbls[dctbl]);
  169886. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169887. & entropy->ac_derived_tbls[actbl]);
  169888. /* Initialize DC predictions to 0 */
  169889. entropy->saved.last_dc_val[ci] = 0;
  169890. }
  169891. /* Precalculate decoding info for each block in an MCU of this scan */
  169892. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169893. ci = cinfo->MCU_membership[blkn];
  169894. compptr = cinfo->cur_comp_info[ci];
  169895. /* Precalculate which table to use for each block */
  169896. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169897. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169898. /* Decide whether we really care about the coefficient values */
  169899. if (compptr->component_needed) {
  169900. entropy->dc_needed[blkn] = TRUE;
  169901. /* we don't need the ACs if producing a 1/8th-size image */
  169902. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169903. } else {
  169904. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169905. }
  169906. }
  169907. /* Initialize bitread state variables */
  169908. entropy->bitstate.bits_left = 0;
  169909. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169910. entropy->pub.insufficient_data = FALSE;
  169911. /* Initialize restart counter */
  169912. entropy->restarts_to_go = cinfo->restart_interval;
  169913. }
  169914. /*
  169915. * Compute the derived values for a Huffman table.
  169916. * This routine also performs some validation checks on the table.
  169917. *
  169918. * Note this is also used by jdphuff.c.
  169919. */
  169920. GLOBAL(void)
  169921. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169922. d_derived_tbl ** pdtbl)
  169923. {
  169924. JHUFF_TBL *htbl;
  169925. d_derived_tbl *dtbl;
  169926. int p, i, l, si, numsymbols;
  169927. int lookbits, ctr;
  169928. char huffsize[257];
  169929. unsigned int huffcode[257];
  169930. unsigned int code;
  169931. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169932. * paralleling the order of the symbols themselves in htbl->huffval[].
  169933. */
  169934. /* Find the input Huffman table */
  169935. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169936. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169937. htbl =
  169938. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169939. if (htbl == NULL)
  169940. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169941. /* Allocate a workspace if we haven't already done so. */
  169942. if (*pdtbl == NULL)
  169943. *pdtbl = (d_derived_tbl *)
  169944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169945. SIZEOF(d_derived_tbl));
  169946. dtbl = *pdtbl;
  169947. dtbl->pub = htbl; /* fill in back link */
  169948. /* Figure C.1: make table of Huffman code length for each symbol */
  169949. p = 0;
  169950. for (l = 1; l <= 16; l++) {
  169951. i = (int) htbl->bits[l];
  169952. if (i < 0 || p + i > 256) /* protect against table overrun */
  169953. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169954. while (i--)
  169955. huffsize[p++] = (char) l;
  169956. }
  169957. huffsize[p] = 0;
  169958. numsymbols = p;
  169959. /* Figure C.2: generate the codes themselves */
  169960. /* We also validate that the counts represent a legal Huffman code tree. */
  169961. code = 0;
  169962. si = huffsize[0];
  169963. p = 0;
  169964. while (huffsize[p]) {
  169965. while (((int) huffsize[p]) == si) {
  169966. huffcode[p++] = code;
  169967. code++;
  169968. }
  169969. /* code is now 1 more than the last code used for codelength si; but
  169970. * it must still fit in si bits, since no code is allowed to be all ones.
  169971. */
  169972. if (((INT32) code) >= (((INT32) 1) << si))
  169973. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169974. code <<= 1;
  169975. si++;
  169976. }
  169977. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169978. p = 0;
  169979. for (l = 1; l <= 16; l++) {
  169980. if (htbl->bits[l]) {
  169981. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169982. * minus the minimum code of length l
  169983. */
  169984. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169985. p += htbl->bits[l];
  169986. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169987. } else {
  169988. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169989. }
  169990. }
  169991. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169992. /* Compute lookahead tables to speed up decoding.
  169993. * First we set all the table entries to 0, indicating "too long";
  169994. * then we iterate through the Huffman codes that are short enough and
  169995. * fill in all the entries that correspond to bit sequences starting
  169996. * with that code.
  169997. */
  169998. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169999. p = 0;
  170000. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170001. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170002. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170003. /* Generate left-justified code followed by all possible bit sequences */
  170004. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170005. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170006. dtbl->look_nbits[lookbits] = l;
  170007. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170008. lookbits++;
  170009. }
  170010. }
  170011. }
  170012. /* Validate symbols as being reasonable.
  170013. * For AC tables, we make no check, but accept all byte values 0..255.
  170014. * For DC tables, we require the symbols to be in range 0..15.
  170015. * (Tighter bounds could be applied depending on the data depth and mode,
  170016. * but this is sufficient to ensure safe decoding.)
  170017. */
  170018. if (isDC) {
  170019. for (i = 0; i < numsymbols; i++) {
  170020. int sym = htbl->huffval[i];
  170021. if (sym < 0 || sym > 15)
  170022. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170023. }
  170024. }
  170025. }
  170026. /*
  170027. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170028. * See jdhuff.h for info about usage.
  170029. * Note: current values of get_buffer and bits_left are passed as parameters,
  170030. * but are returned in the corresponding fields of the state struct.
  170031. *
  170032. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170033. * of get_buffer to be used. (On machines with wider words, an even larger
  170034. * buffer could be used.) However, on some machines 32-bit shifts are
  170035. * quite slow and take time proportional to the number of places shifted.
  170036. * (This is true with most PC compilers, for instance.) In this case it may
  170037. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170038. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170039. */
  170040. #ifdef SLOW_SHIFT_32
  170041. #define MIN_GET_BITS 15 /* minimum allowable value */
  170042. #else
  170043. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170044. #endif
  170045. GLOBAL(boolean)
  170046. jpeg_fill_bit_buffer (bitread_working_state * state,
  170047. register bit_buf_type get_buffer, register int bits_left,
  170048. int nbits)
  170049. /* Load up the bit buffer to a depth of at least nbits */
  170050. {
  170051. /* Copy heavily used state fields into locals (hopefully registers) */
  170052. register const JOCTET * next_input_byte = state->next_input_byte;
  170053. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170054. j_decompress_ptr cinfo = state->cinfo;
  170055. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170056. /* (It is assumed that no request will be for more than that many bits.) */
  170057. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170058. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170059. while (bits_left < MIN_GET_BITS) {
  170060. register int c;
  170061. /* Attempt to read a byte */
  170062. if (bytes_in_buffer == 0) {
  170063. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170064. return FALSE;
  170065. next_input_byte = cinfo->src->next_input_byte;
  170066. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170067. }
  170068. bytes_in_buffer--;
  170069. c = GETJOCTET(*next_input_byte++);
  170070. /* If it's 0xFF, check and discard stuffed zero byte */
  170071. if (c == 0xFF) {
  170072. /* Loop here to discard any padding FF's on terminating marker,
  170073. * so that we can save a valid unread_marker value. NOTE: we will
  170074. * accept multiple FF's followed by a 0 as meaning a single FF data
  170075. * byte. This data pattern is not valid according to the standard.
  170076. */
  170077. do {
  170078. if (bytes_in_buffer == 0) {
  170079. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170080. return FALSE;
  170081. next_input_byte = cinfo->src->next_input_byte;
  170082. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170083. }
  170084. bytes_in_buffer--;
  170085. c = GETJOCTET(*next_input_byte++);
  170086. } while (c == 0xFF);
  170087. if (c == 0) {
  170088. /* Found FF/00, which represents an FF data byte */
  170089. c = 0xFF;
  170090. } else {
  170091. /* Oops, it's actually a marker indicating end of compressed data.
  170092. * Save the marker code for later use.
  170093. * Fine point: it might appear that we should save the marker into
  170094. * bitread working state, not straight into permanent state. But
  170095. * once we have hit a marker, we cannot need to suspend within the
  170096. * current MCU, because we will read no more bytes from the data
  170097. * source. So it is OK to update permanent state right away.
  170098. */
  170099. cinfo->unread_marker = c;
  170100. /* See if we need to insert some fake zero bits. */
  170101. goto no_more_bytes;
  170102. }
  170103. }
  170104. /* OK, load c into get_buffer */
  170105. get_buffer = (get_buffer << 8) | c;
  170106. bits_left += 8;
  170107. } /* end while */
  170108. } else {
  170109. no_more_bytes:
  170110. /* We get here if we've read the marker that terminates the compressed
  170111. * data segment. There should be enough bits in the buffer register
  170112. * to satisfy the request; if so, no problem.
  170113. */
  170114. if (nbits > bits_left) {
  170115. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170116. * the data stream, so that we can produce some kind of image.
  170117. * We use a nonvolatile flag to ensure that only one warning message
  170118. * appears per data segment.
  170119. */
  170120. if (! cinfo->entropy->insufficient_data) {
  170121. WARNMS(cinfo, JWRN_HIT_MARKER);
  170122. cinfo->entropy->insufficient_data = TRUE;
  170123. }
  170124. /* Fill the buffer with zero bits */
  170125. get_buffer <<= MIN_GET_BITS - bits_left;
  170126. bits_left = MIN_GET_BITS;
  170127. }
  170128. }
  170129. /* Unload the local registers */
  170130. state->next_input_byte = next_input_byte;
  170131. state->bytes_in_buffer = bytes_in_buffer;
  170132. state->get_buffer = get_buffer;
  170133. state->bits_left = bits_left;
  170134. return TRUE;
  170135. }
  170136. /*
  170137. * Out-of-line code for Huffman code decoding.
  170138. * See jdhuff.h for info about usage.
  170139. */
  170140. GLOBAL(int)
  170141. jpeg_huff_decode (bitread_working_state * state,
  170142. register bit_buf_type get_buffer, register int bits_left,
  170143. d_derived_tbl * htbl, int min_bits)
  170144. {
  170145. register int l = min_bits;
  170146. register INT32 code;
  170147. /* HUFF_DECODE has determined that the code is at least min_bits */
  170148. /* bits long, so fetch that many bits in one swoop. */
  170149. CHECK_BIT_BUFFER(*state, l, return -1);
  170150. code = GET_BITS(l);
  170151. /* Collect the rest of the Huffman code one bit at a time. */
  170152. /* This is per Figure F.16 in the JPEG spec. */
  170153. while (code > htbl->maxcode[l]) {
  170154. code <<= 1;
  170155. CHECK_BIT_BUFFER(*state, 1, return -1);
  170156. code |= GET_BITS(1);
  170157. l++;
  170158. }
  170159. /* Unload the local registers */
  170160. state->get_buffer = get_buffer;
  170161. state->bits_left = bits_left;
  170162. /* With garbage input we may reach the sentinel value l = 17. */
  170163. if (l > 16) {
  170164. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170165. return 0; /* fake a zero as the safest result */
  170166. }
  170167. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170168. }
  170169. /*
  170170. * Check for a restart marker & resynchronize decoder.
  170171. * Returns FALSE if must suspend.
  170172. */
  170173. LOCAL(boolean)
  170174. process_restart (j_decompress_ptr cinfo)
  170175. {
  170176. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170177. int ci;
  170178. /* Throw away any unused bits remaining in bit buffer; */
  170179. /* include any full bytes in next_marker's count of discarded bytes */
  170180. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170181. entropy->bitstate.bits_left = 0;
  170182. /* Advance past the RSTn marker */
  170183. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170184. return FALSE;
  170185. /* Re-initialize DC predictions to 0 */
  170186. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170187. entropy->saved.last_dc_val[ci] = 0;
  170188. /* Reset restart counter */
  170189. entropy->restarts_to_go = cinfo->restart_interval;
  170190. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170191. * against a marker. In that case we will end up treating the next data
  170192. * segment as empty, and we can avoid producing bogus output pixels by
  170193. * leaving the flag set.
  170194. */
  170195. if (cinfo->unread_marker == 0)
  170196. entropy->pub.insufficient_data = FALSE;
  170197. return TRUE;
  170198. }
  170199. /*
  170200. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170201. * The coefficients are reordered from zigzag order into natural array order,
  170202. * but are not dequantized.
  170203. *
  170204. * The i'th block of the MCU is stored into the block pointed to by
  170205. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170206. * (Wholesale zeroing is usually a little faster than retail...)
  170207. *
  170208. * Returns FALSE if data source requested suspension. In that case no
  170209. * changes have been made to permanent state. (Exception: some output
  170210. * coefficients may already have been assigned. This is harmless for
  170211. * this module, since we'll just re-assign them on the next call.)
  170212. */
  170213. METHODDEF(boolean)
  170214. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170215. {
  170216. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170217. int blkn;
  170218. BITREAD_STATE_VARS;
  170219. savable_state2 state;
  170220. /* Process restart marker if needed; may have to suspend */
  170221. if (cinfo->restart_interval) {
  170222. if (entropy->restarts_to_go == 0)
  170223. if (! process_restart(cinfo))
  170224. return FALSE;
  170225. }
  170226. /* If we've run out of data, just leave the MCU set to zeroes.
  170227. * This way, we return uniform gray for the remainder of the segment.
  170228. */
  170229. if (! entropy->pub.insufficient_data) {
  170230. /* Load up working state */
  170231. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170232. ASSIGN_STATE(state, entropy->saved);
  170233. /* Outer loop handles each block in the MCU */
  170234. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170235. JBLOCKROW block = MCU_data[blkn];
  170236. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170237. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170238. register int s, k, r;
  170239. /* Decode a single block's worth of coefficients */
  170240. /* Section F.2.2.1: decode the DC coefficient difference */
  170241. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170242. if (s) {
  170243. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170244. r = GET_BITS(s);
  170245. s = HUFF_EXTEND(r, s);
  170246. }
  170247. if (entropy->dc_needed[blkn]) {
  170248. /* Convert DC difference to actual value, update last_dc_val */
  170249. int ci = cinfo->MCU_membership[blkn];
  170250. s += state.last_dc_val[ci];
  170251. state.last_dc_val[ci] = s;
  170252. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170253. (*block)[0] = (JCOEF) s;
  170254. }
  170255. if (entropy->ac_needed[blkn]) {
  170256. /* Section F.2.2.2: decode the AC coefficients */
  170257. /* Since zeroes are skipped, output area must be cleared beforehand */
  170258. for (k = 1; k < DCTSIZE2; k++) {
  170259. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170260. r = s >> 4;
  170261. s &= 15;
  170262. if (s) {
  170263. k += r;
  170264. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170265. r = GET_BITS(s);
  170266. s = HUFF_EXTEND(r, s);
  170267. /* Output coefficient in natural (dezigzagged) order.
  170268. * Note: the extra entries in jpeg_natural_order[] will save us
  170269. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170270. */
  170271. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170272. } else {
  170273. if (r != 15)
  170274. break;
  170275. k += 15;
  170276. }
  170277. }
  170278. } else {
  170279. /* Section F.2.2.2: decode the AC coefficients */
  170280. /* In this path we just discard the values */
  170281. for (k = 1; k < DCTSIZE2; k++) {
  170282. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170283. r = s >> 4;
  170284. s &= 15;
  170285. if (s) {
  170286. k += r;
  170287. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170288. DROP_BITS(s);
  170289. } else {
  170290. if (r != 15)
  170291. break;
  170292. k += 15;
  170293. }
  170294. }
  170295. }
  170296. }
  170297. /* Completed MCU, so update state */
  170298. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170299. ASSIGN_STATE(entropy->saved, state);
  170300. }
  170301. /* Account for restart interval (no-op if not using restarts) */
  170302. entropy->restarts_to_go--;
  170303. return TRUE;
  170304. }
  170305. /*
  170306. * Module initialization routine for Huffman entropy decoding.
  170307. */
  170308. GLOBAL(void)
  170309. jinit_huff_decoder (j_decompress_ptr cinfo)
  170310. {
  170311. huff_entropy_ptr2 entropy;
  170312. int i;
  170313. entropy = (huff_entropy_ptr2)
  170314. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170315. SIZEOF(huff_entropy_decoder2));
  170316. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170317. entropy->pub.start_pass = start_pass_huff_decoder;
  170318. entropy->pub.decode_mcu = decode_mcu;
  170319. /* Mark tables unallocated */
  170320. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170321. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170322. }
  170323. }
  170324. /*** End of inlined file: jdhuff.c ***/
  170325. /*** Start of inlined file: jdinput.c ***/
  170326. #define JPEG_INTERNALS
  170327. /* Private state */
  170328. typedef struct {
  170329. struct jpeg_input_controller pub; /* public fields */
  170330. boolean inheaders; /* TRUE until first SOS is reached */
  170331. } my_input_controller;
  170332. typedef my_input_controller * my_inputctl_ptr;
  170333. /* Forward declarations */
  170334. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170335. /*
  170336. * Routines to calculate various quantities related to the size of the image.
  170337. */
  170338. LOCAL(void)
  170339. initial_setup2 (j_decompress_ptr cinfo)
  170340. /* Called once, when first SOS marker is reached */
  170341. {
  170342. int ci;
  170343. jpeg_component_info *compptr;
  170344. /* Make sure image isn't bigger than I can handle */
  170345. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170346. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170347. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170348. /* For now, precision must match compiled-in value... */
  170349. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170350. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170351. /* Check that number of components won't exceed internal array sizes */
  170352. if (cinfo->num_components > MAX_COMPONENTS)
  170353. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170354. MAX_COMPONENTS);
  170355. /* Compute maximum sampling factors; check factor validity */
  170356. cinfo->max_h_samp_factor = 1;
  170357. cinfo->max_v_samp_factor = 1;
  170358. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170359. ci++, compptr++) {
  170360. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170361. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170362. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170363. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170364. compptr->h_samp_factor);
  170365. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170366. compptr->v_samp_factor);
  170367. }
  170368. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170369. * In the full decompressor, this will be overridden by jdmaster.c;
  170370. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170371. */
  170372. cinfo->min_DCT_scaled_size = DCTSIZE;
  170373. /* Compute dimensions of components */
  170374. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170375. ci++, compptr++) {
  170376. compptr->DCT_scaled_size = DCTSIZE;
  170377. /* Size in DCT blocks */
  170378. compptr->width_in_blocks = (JDIMENSION)
  170379. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170380. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170381. compptr->height_in_blocks = (JDIMENSION)
  170382. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170383. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170384. /* downsampled_width and downsampled_height will also be overridden by
  170385. * jdmaster.c if we are doing full decompression. The transcoder library
  170386. * doesn't use these values, but the calling application might.
  170387. */
  170388. /* Size in samples */
  170389. compptr->downsampled_width = (JDIMENSION)
  170390. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170391. (long) cinfo->max_h_samp_factor);
  170392. compptr->downsampled_height = (JDIMENSION)
  170393. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170394. (long) cinfo->max_v_samp_factor);
  170395. /* Mark component needed, until color conversion says otherwise */
  170396. compptr->component_needed = TRUE;
  170397. /* Mark no quantization table yet saved for component */
  170398. compptr->quant_table = NULL;
  170399. }
  170400. /* Compute number of fully interleaved MCU rows. */
  170401. cinfo->total_iMCU_rows = (JDIMENSION)
  170402. jdiv_round_up((long) cinfo->image_height,
  170403. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170404. /* Decide whether file contains multiple scans */
  170405. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170406. cinfo->inputctl->has_multiple_scans = TRUE;
  170407. else
  170408. cinfo->inputctl->has_multiple_scans = FALSE;
  170409. }
  170410. LOCAL(void)
  170411. per_scan_setup2 (j_decompress_ptr cinfo)
  170412. /* Do computations that are needed before processing a JPEG scan */
  170413. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170414. {
  170415. int ci, mcublks, tmp;
  170416. jpeg_component_info *compptr;
  170417. if (cinfo->comps_in_scan == 1) {
  170418. /* Noninterleaved (single-component) scan */
  170419. compptr = cinfo->cur_comp_info[0];
  170420. /* Overall image size in MCUs */
  170421. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170422. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170423. /* For noninterleaved scan, always one block per MCU */
  170424. compptr->MCU_width = 1;
  170425. compptr->MCU_height = 1;
  170426. compptr->MCU_blocks = 1;
  170427. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170428. compptr->last_col_width = 1;
  170429. /* For noninterleaved scans, it is convenient to define last_row_height
  170430. * as the number of block rows present in the last iMCU row.
  170431. */
  170432. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170433. if (tmp == 0) tmp = compptr->v_samp_factor;
  170434. compptr->last_row_height = tmp;
  170435. /* Prepare array describing MCU composition */
  170436. cinfo->blocks_in_MCU = 1;
  170437. cinfo->MCU_membership[0] = 0;
  170438. } else {
  170439. /* Interleaved (multi-component) scan */
  170440. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170441. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170442. MAX_COMPS_IN_SCAN);
  170443. /* Overall image size in MCUs */
  170444. cinfo->MCUs_per_row = (JDIMENSION)
  170445. jdiv_round_up((long) cinfo->image_width,
  170446. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170447. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170448. jdiv_round_up((long) cinfo->image_height,
  170449. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170450. cinfo->blocks_in_MCU = 0;
  170451. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170452. compptr = cinfo->cur_comp_info[ci];
  170453. /* Sampling factors give # of blocks of component in each MCU */
  170454. compptr->MCU_width = compptr->h_samp_factor;
  170455. compptr->MCU_height = compptr->v_samp_factor;
  170456. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170457. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170458. /* Figure number of non-dummy blocks in last MCU column & row */
  170459. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170460. if (tmp == 0) tmp = compptr->MCU_width;
  170461. compptr->last_col_width = tmp;
  170462. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170463. if (tmp == 0) tmp = compptr->MCU_height;
  170464. compptr->last_row_height = tmp;
  170465. /* Prepare array describing MCU composition */
  170466. mcublks = compptr->MCU_blocks;
  170467. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170468. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170469. while (mcublks-- > 0) {
  170470. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170471. }
  170472. }
  170473. }
  170474. }
  170475. /*
  170476. * Save away a copy of the Q-table referenced by each component present
  170477. * in the current scan, unless already saved during a prior scan.
  170478. *
  170479. * In a multiple-scan JPEG file, the encoder could assign different components
  170480. * the same Q-table slot number, but change table definitions between scans
  170481. * so that each component uses a different Q-table. (The IJG encoder is not
  170482. * currently capable of doing this, but other encoders might.) Since we want
  170483. * to be able to dequantize all the components at the end of the file, this
  170484. * means that we have to save away the table actually used for each component.
  170485. * We do this by copying the table at the start of the first scan containing
  170486. * the component.
  170487. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170488. * slot between scans of a component using that slot. If the encoder does so
  170489. * anyway, this decoder will simply use the Q-table values that were current
  170490. * at the start of the first scan for the component.
  170491. *
  170492. * The decompressor output side looks only at the saved quant tables,
  170493. * not at the current Q-table slots.
  170494. */
  170495. LOCAL(void)
  170496. latch_quant_tables (j_decompress_ptr cinfo)
  170497. {
  170498. int ci, qtblno;
  170499. jpeg_component_info *compptr;
  170500. JQUANT_TBL * qtbl;
  170501. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170502. compptr = cinfo->cur_comp_info[ci];
  170503. /* No work if we already saved Q-table for this component */
  170504. if (compptr->quant_table != NULL)
  170505. continue;
  170506. /* Make sure specified quantization table is present */
  170507. qtblno = compptr->quant_tbl_no;
  170508. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170509. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170510. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170511. /* OK, save away the quantization table */
  170512. qtbl = (JQUANT_TBL *)
  170513. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170514. SIZEOF(JQUANT_TBL));
  170515. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170516. compptr->quant_table = qtbl;
  170517. }
  170518. }
  170519. /*
  170520. * Initialize the input modules to read a scan of compressed data.
  170521. * The first call to this is done by jdmaster.c after initializing
  170522. * the entire decompressor (during jpeg_start_decompress).
  170523. * Subsequent calls come from consume_markers, below.
  170524. */
  170525. METHODDEF(void)
  170526. start_input_pass2 (j_decompress_ptr cinfo)
  170527. {
  170528. per_scan_setup2(cinfo);
  170529. latch_quant_tables(cinfo);
  170530. (*cinfo->entropy->start_pass) (cinfo);
  170531. (*cinfo->coef->start_input_pass) (cinfo);
  170532. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170533. }
  170534. /*
  170535. * Finish up after inputting a compressed-data scan.
  170536. * This is called by the coefficient controller after it's read all
  170537. * the expected data of the scan.
  170538. */
  170539. METHODDEF(void)
  170540. finish_input_pass (j_decompress_ptr cinfo)
  170541. {
  170542. cinfo->inputctl->consume_input = consume_markers;
  170543. }
  170544. /*
  170545. * Read JPEG markers before, between, or after compressed-data scans.
  170546. * Change state as necessary when a new scan is reached.
  170547. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170548. *
  170549. * The consume_input method pointer points either here or to the
  170550. * coefficient controller's consume_data routine, depending on whether
  170551. * we are reading a compressed data segment or inter-segment markers.
  170552. */
  170553. METHODDEF(int)
  170554. consume_markers (j_decompress_ptr cinfo)
  170555. {
  170556. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170557. int val;
  170558. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170559. return JPEG_REACHED_EOI;
  170560. val = (*cinfo->marker->read_markers) (cinfo);
  170561. switch (val) {
  170562. case JPEG_REACHED_SOS: /* Found SOS */
  170563. if (inputctl->inheaders) { /* 1st SOS */
  170564. initial_setup2(cinfo);
  170565. inputctl->inheaders = FALSE;
  170566. /* Note: start_input_pass must be called by jdmaster.c
  170567. * before any more input can be consumed. jdapimin.c is
  170568. * responsible for enforcing this sequencing.
  170569. */
  170570. } else { /* 2nd or later SOS marker */
  170571. if (! inputctl->pub.has_multiple_scans)
  170572. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170573. start_input_pass2(cinfo);
  170574. }
  170575. break;
  170576. case JPEG_REACHED_EOI: /* Found EOI */
  170577. inputctl->pub.eoi_reached = TRUE;
  170578. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170579. if (cinfo->marker->saw_SOF)
  170580. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170581. } else {
  170582. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170583. * if user set output_scan_number larger than number of scans.
  170584. */
  170585. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170586. cinfo->output_scan_number = cinfo->input_scan_number;
  170587. }
  170588. break;
  170589. case JPEG_SUSPENDED:
  170590. break;
  170591. }
  170592. return val;
  170593. }
  170594. /*
  170595. * Reset state to begin a fresh datastream.
  170596. */
  170597. METHODDEF(void)
  170598. reset_input_controller (j_decompress_ptr cinfo)
  170599. {
  170600. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170601. inputctl->pub.consume_input = consume_markers;
  170602. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170603. inputctl->pub.eoi_reached = FALSE;
  170604. inputctl->inheaders = TRUE;
  170605. /* Reset other modules */
  170606. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170607. (*cinfo->marker->reset_marker_reader) (cinfo);
  170608. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170609. cinfo->coef_bits = NULL;
  170610. }
  170611. /*
  170612. * Initialize the input controller module.
  170613. * This is called only once, when the decompression object is created.
  170614. */
  170615. GLOBAL(void)
  170616. jinit_input_controller (j_decompress_ptr cinfo)
  170617. {
  170618. my_inputctl_ptr inputctl;
  170619. /* Create subobject in permanent pool */
  170620. inputctl = (my_inputctl_ptr)
  170621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170622. SIZEOF(my_input_controller));
  170623. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170624. /* Initialize method pointers */
  170625. inputctl->pub.consume_input = consume_markers;
  170626. inputctl->pub.reset_input_controller = reset_input_controller;
  170627. inputctl->pub.start_input_pass = start_input_pass2;
  170628. inputctl->pub.finish_input_pass = finish_input_pass;
  170629. /* Initialize state: can't use reset_input_controller since we don't
  170630. * want to try to reset other modules yet.
  170631. */
  170632. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170633. inputctl->pub.eoi_reached = FALSE;
  170634. inputctl->inheaders = TRUE;
  170635. }
  170636. /*** End of inlined file: jdinput.c ***/
  170637. /*** Start of inlined file: jdmainct.c ***/
  170638. #define JPEG_INTERNALS
  170639. /*
  170640. * In the current system design, the main buffer need never be a full-image
  170641. * buffer; any full-height buffers will be found inside the coefficient or
  170642. * postprocessing controllers. Nonetheless, the main controller is not
  170643. * trivial. Its responsibility is to provide context rows for upsampling/
  170644. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170645. *
  170646. * Postprocessor input data is counted in "row groups". A row group
  170647. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170648. * sample rows of each component. (We require DCT_scaled_size values to be
  170649. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170650. * values will likely be powers of two, so we actually have the stronger
  170651. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170652. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170653. * row group (times any additional scale factor that the upsampler is
  170654. * applying).
  170655. *
  170656. * The coefficient controller will deliver data to us one iMCU row at a time;
  170657. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170658. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170659. * to one row of MCUs when the image is fully interleaved.) Note that the
  170660. * number of sample rows varies across components, but the number of row
  170661. * groups does not. Some garbage sample rows may be included in the last iMCU
  170662. * row at the bottom of the image.
  170663. *
  170664. * Depending on the vertical scaling algorithm used, the upsampler may need
  170665. * access to the sample row(s) above and below its current input row group.
  170666. * The upsampler is required to set need_context_rows TRUE at global selection
  170667. * time if so. When need_context_rows is FALSE, this controller can simply
  170668. * obtain one iMCU row at a time from the coefficient controller and dole it
  170669. * out as row groups to the postprocessor.
  170670. *
  170671. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170672. * passed to postprocessing contains at least one row group's worth of samples
  170673. * above and below the row group(s) being processed. Note that the context
  170674. * rows "above" the first passed row group appear at negative row offsets in
  170675. * the passed buffer. At the top and bottom of the image, the required
  170676. * context rows are manufactured by duplicating the first or last real sample
  170677. * row; this avoids having special cases in the upsampling inner loops.
  170678. *
  170679. * The amount of context is fixed at one row group just because that's a
  170680. * convenient number for this controller to work with. The existing
  170681. * upsamplers really only need one sample row of context. An upsampler
  170682. * supporting arbitrary output rescaling might wish for more than one row
  170683. * group of context when shrinking the image; tough, we don't handle that.
  170684. * (This is justified by the assumption that downsizing will be handled mostly
  170685. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170686. * the upsample step needn't be much less than one.)
  170687. *
  170688. * To provide the desired context, we have to retain the last two row groups
  170689. * of one iMCU row while reading in the next iMCU row. (The last row group
  170690. * can't be processed until we have another row group for its below-context,
  170691. * and so we have to save the next-to-last group too for its above-context.)
  170692. * We could do this most simply by copying data around in our buffer, but
  170693. * that'd be very slow. We can avoid copying any data by creating a rather
  170694. * strange pointer structure. Here's how it works. We allocate a workspace
  170695. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170696. * of row groups per iMCU row). We create two sets of redundant pointers to
  170697. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170698. * pointer lists look like this:
  170699. * M+1 M-1
  170700. * master pointer --> 0 master pointer --> 0
  170701. * 1 1
  170702. * ... ...
  170703. * M-3 M-3
  170704. * M-2 M
  170705. * M-1 M+1
  170706. * M M-2
  170707. * M+1 M-1
  170708. * 0 0
  170709. * We read alternate iMCU rows using each master pointer; thus the last two
  170710. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170711. * The pointer lists are set up so that the required context rows appear to
  170712. * be adjacent to the proper places when we pass the pointer lists to the
  170713. * upsampler.
  170714. *
  170715. * The above pictures describe the normal state of the pointer lists.
  170716. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170717. * the first or last sample row as necessary (this is cheaper than copying
  170718. * sample rows around).
  170719. *
  170720. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170721. * situation each iMCU row provides only one row group so the buffering logic
  170722. * must be different (eg, we must read two iMCU rows before we can emit the
  170723. * first row group). For now, we simply do not support providing context
  170724. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170725. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170726. * want it quick and dirty, so a context-free upsampler is sufficient.
  170727. */
  170728. /* Private buffer controller object */
  170729. typedef struct {
  170730. struct jpeg_d_main_controller pub; /* public fields */
  170731. /* Pointer to allocated workspace (M or M+2 row groups). */
  170732. JSAMPARRAY buffer[MAX_COMPONENTS];
  170733. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170734. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170735. /* Remaining fields are only used in the context case. */
  170736. /* These are the master pointers to the funny-order pointer lists. */
  170737. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170738. int whichptr; /* indicates which pointer set is now in use */
  170739. int context_state; /* process_data state machine status */
  170740. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170741. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170742. } my_main_controller4;
  170743. typedef my_main_controller4 * my_main_ptr4;
  170744. /* context_state values: */
  170745. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170746. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170747. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170748. /* Forward declarations */
  170749. METHODDEF(void) process_data_simple_main2
  170750. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170751. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170752. METHODDEF(void) process_data_context_main
  170753. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170754. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170755. #ifdef QUANT_2PASS_SUPPORTED
  170756. METHODDEF(void) process_data_crank_post
  170757. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170758. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170759. #endif
  170760. LOCAL(void)
  170761. alloc_funny_pointers (j_decompress_ptr cinfo)
  170762. /* Allocate space for the funny pointer lists.
  170763. * This is done only once, not once per pass.
  170764. */
  170765. {
  170766. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170767. int ci, rgroup;
  170768. int M = cinfo->min_DCT_scaled_size;
  170769. jpeg_component_info *compptr;
  170770. JSAMPARRAY xbuf;
  170771. /* Get top-level space for component array pointers.
  170772. * We alloc both arrays with one call to save a few cycles.
  170773. */
  170774. main_->xbuffer[0] = (JSAMPIMAGE)
  170775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170776. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170777. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170778. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170779. ci++, compptr++) {
  170780. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170781. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170782. /* Get space for pointer lists --- M+4 row groups in each list.
  170783. * We alloc both pointer lists with one call to save a few cycles.
  170784. */
  170785. xbuf = (JSAMPARRAY)
  170786. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170787. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170788. xbuf += rgroup; /* want one row group at negative offsets */
  170789. main_->xbuffer[0][ci] = xbuf;
  170790. xbuf += rgroup * (M + 4);
  170791. main_->xbuffer[1][ci] = xbuf;
  170792. }
  170793. }
  170794. LOCAL(void)
  170795. make_funny_pointers (j_decompress_ptr cinfo)
  170796. /* Create the funny pointer lists discussed in the comments above.
  170797. * The actual workspace is already allocated (in main->buffer),
  170798. * and the space for the pointer lists is allocated too.
  170799. * This routine just fills in the curiously ordered lists.
  170800. * This will be repeated at the beginning of each pass.
  170801. */
  170802. {
  170803. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170804. int ci, i, rgroup;
  170805. int M = cinfo->min_DCT_scaled_size;
  170806. jpeg_component_info *compptr;
  170807. JSAMPARRAY buf, xbuf0, xbuf1;
  170808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170809. ci++, compptr++) {
  170810. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170811. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170812. xbuf0 = main_->xbuffer[0][ci];
  170813. xbuf1 = main_->xbuffer[1][ci];
  170814. /* First copy the workspace pointers as-is */
  170815. buf = main_->buffer[ci];
  170816. for (i = 0; i < rgroup * (M + 2); i++) {
  170817. xbuf0[i] = xbuf1[i] = buf[i];
  170818. }
  170819. /* In the second list, put the last four row groups in swapped order */
  170820. for (i = 0; i < rgroup * 2; i++) {
  170821. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170822. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170823. }
  170824. /* The wraparound pointers at top and bottom will be filled later
  170825. * (see set_wraparound_pointers, below). Initially we want the "above"
  170826. * pointers to duplicate the first actual data line. This only needs
  170827. * to happen in xbuffer[0].
  170828. */
  170829. for (i = 0; i < rgroup; i++) {
  170830. xbuf0[i - rgroup] = xbuf0[0];
  170831. }
  170832. }
  170833. }
  170834. LOCAL(void)
  170835. set_wraparound_pointers (j_decompress_ptr cinfo)
  170836. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170837. * This changes the pointer list state from top-of-image to the normal state.
  170838. */
  170839. {
  170840. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170841. int ci, i, rgroup;
  170842. int M = cinfo->min_DCT_scaled_size;
  170843. jpeg_component_info *compptr;
  170844. JSAMPARRAY xbuf0, xbuf1;
  170845. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170846. ci++, compptr++) {
  170847. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170848. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170849. xbuf0 = main_->xbuffer[0][ci];
  170850. xbuf1 = main_->xbuffer[1][ci];
  170851. for (i = 0; i < rgroup; i++) {
  170852. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170853. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170854. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170855. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170856. }
  170857. }
  170858. }
  170859. LOCAL(void)
  170860. set_bottom_pointers (j_decompress_ptr cinfo)
  170861. /* Change the pointer lists to duplicate the last sample row at the bottom
  170862. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170863. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170864. */
  170865. {
  170866. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170867. int ci, i, rgroup, iMCUheight, rows_left;
  170868. jpeg_component_info *compptr;
  170869. JSAMPARRAY xbuf;
  170870. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170871. ci++, compptr++) {
  170872. /* Count sample rows in one iMCU row and in one row group */
  170873. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170874. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170875. /* Count nondummy sample rows remaining for this component */
  170876. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170877. if (rows_left == 0) rows_left = iMCUheight;
  170878. /* Count nondummy row groups. Should get same answer for each component,
  170879. * so we need only do it once.
  170880. */
  170881. if (ci == 0) {
  170882. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170883. }
  170884. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170885. * last partial rowgroup and ensures at least one full rowgroup of context.
  170886. */
  170887. xbuf = main_->xbuffer[main_->whichptr][ci];
  170888. for (i = 0; i < rgroup * 2; i++) {
  170889. xbuf[rows_left + i] = xbuf[rows_left-1];
  170890. }
  170891. }
  170892. }
  170893. /*
  170894. * Initialize for a processing pass.
  170895. */
  170896. METHODDEF(void)
  170897. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170898. {
  170899. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170900. switch (pass_mode) {
  170901. case JBUF_PASS_THRU:
  170902. if (cinfo->upsample->need_context_rows) {
  170903. main_->pub.process_data = process_data_context_main;
  170904. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170905. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170906. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170907. main_->iMCU_row_ctr = 0;
  170908. } else {
  170909. /* Simple case with no context needed */
  170910. main_->pub.process_data = process_data_simple_main2;
  170911. }
  170912. main_->buffer_full = FALSE; /* Mark buffer empty */
  170913. main_->rowgroup_ctr = 0;
  170914. break;
  170915. #ifdef QUANT_2PASS_SUPPORTED
  170916. case JBUF_CRANK_DEST:
  170917. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170918. main_->pub.process_data = process_data_crank_post;
  170919. break;
  170920. #endif
  170921. default:
  170922. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170923. break;
  170924. }
  170925. }
  170926. /*
  170927. * Process some data.
  170928. * This handles the simple case where no context is required.
  170929. */
  170930. METHODDEF(void)
  170931. process_data_simple_main2 (j_decompress_ptr cinfo,
  170932. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170933. JDIMENSION out_rows_avail)
  170934. {
  170935. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170936. JDIMENSION rowgroups_avail;
  170937. /* Read input data if we haven't filled the main buffer yet */
  170938. if (! main_->buffer_full) {
  170939. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170940. return; /* suspension forced, can do nothing more */
  170941. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170942. }
  170943. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170944. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170945. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170946. * to the postprocessor. The postprocessor has to check for bottom
  170947. * of image anyway (at row resolution), so no point in us doing it too.
  170948. */
  170949. /* Feed the postprocessor */
  170950. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170951. &main_->rowgroup_ctr, rowgroups_avail,
  170952. output_buf, out_row_ctr, out_rows_avail);
  170953. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170954. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170955. main_->buffer_full = FALSE;
  170956. main_->rowgroup_ctr = 0;
  170957. }
  170958. }
  170959. /*
  170960. * Process some data.
  170961. * This handles the case where context rows must be provided.
  170962. */
  170963. METHODDEF(void)
  170964. process_data_context_main (j_decompress_ptr cinfo,
  170965. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170966. JDIMENSION out_rows_avail)
  170967. {
  170968. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170969. /* Read input data if we haven't filled the main buffer yet */
  170970. if (! main_->buffer_full) {
  170971. if (! (*cinfo->coef->decompress_data) (cinfo,
  170972. main_->xbuffer[main_->whichptr]))
  170973. return; /* suspension forced, can do nothing more */
  170974. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170975. main_->iMCU_row_ctr++; /* count rows received */
  170976. }
  170977. /* Postprocessor typically will not swallow all the input data it is handed
  170978. * in one call (due to filling the output buffer first). Must be prepared
  170979. * to exit and restart. This switch lets us keep track of how far we got.
  170980. * Note that each case falls through to the next on successful completion.
  170981. */
  170982. switch (main_->context_state) {
  170983. case CTX_POSTPONED_ROW:
  170984. /* Call postprocessor using previously set pointers for postponed row */
  170985. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170986. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170987. output_buf, out_row_ctr, out_rows_avail);
  170988. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170989. return; /* Need to suspend */
  170990. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170991. if (*out_row_ctr >= out_rows_avail)
  170992. return; /* Postprocessor exactly filled output buf */
  170993. /*FALLTHROUGH*/
  170994. case CTX_PREPARE_FOR_IMCU:
  170995. /* Prepare to process first M-1 row groups of this iMCU row */
  170996. main_->rowgroup_ctr = 0;
  170997. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170998. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170999. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171000. */
  171001. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171002. set_bottom_pointers(cinfo);
  171003. main_->context_state = CTX_PROCESS_IMCU;
  171004. /*FALLTHROUGH*/
  171005. case CTX_PROCESS_IMCU:
  171006. /* Call postprocessor using previously set pointers */
  171007. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171008. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171009. output_buf, out_row_ctr, out_rows_avail);
  171010. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171011. return; /* Need to suspend */
  171012. /* After the first iMCU, change wraparound pointers to normal state */
  171013. if (main_->iMCU_row_ctr == 1)
  171014. set_wraparound_pointers(cinfo);
  171015. /* Prepare to load new iMCU row using other xbuffer list */
  171016. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171017. main_->buffer_full = FALSE;
  171018. /* Still need to process last row group of this iMCU row, */
  171019. /* which is saved at index M+1 of the other xbuffer */
  171020. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171021. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171022. main_->context_state = CTX_POSTPONED_ROW;
  171023. }
  171024. }
  171025. /*
  171026. * Process some data.
  171027. * Final pass of two-pass quantization: just call the postprocessor.
  171028. * Source data will be the postprocessor controller's internal buffer.
  171029. */
  171030. #ifdef QUANT_2PASS_SUPPORTED
  171031. METHODDEF(void)
  171032. process_data_crank_post (j_decompress_ptr cinfo,
  171033. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171034. JDIMENSION out_rows_avail)
  171035. {
  171036. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171037. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171038. output_buf, out_row_ctr, out_rows_avail);
  171039. }
  171040. #endif /* QUANT_2PASS_SUPPORTED */
  171041. /*
  171042. * Initialize main buffer controller.
  171043. */
  171044. GLOBAL(void)
  171045. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171046. {
  171047. my_main_ptr4 main_;
  171048. int ci, rgroup, ngroups;
  171049. jpeg_component_info *compptr;
  171050. main_ = (my_main_ptr4)
  171051. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171052. SIZEOF(my_main_controller4));
  171053. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171054. main_->pub.start_pass = start_pass_main2;
  171055. if (need_full_buffer) /* shouldn't happen */
  171056. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171057. /* Allocate the workspace.
  171058. * ngroups is the number of row groups we need.
  171059. */
  171060. if (cinfo->upsample->need_context_rows) {
  171061. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171062. ERREXIT(cinfo, JERR_NOTIMPL);
  171063. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171064. ngroups = cinfo->min_DCT_scaled_size + 2;
  171065. } else {
  171066. ngroups = cinfo->min_DCT_scaled_size;
  171067. }
  171068. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171069. ci++, compptr++) {
  171070. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171071. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171072. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171073. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171074. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171075. (JDIMENSION) (rgroup * ngroups));
  171076. }
  171077. }
  171078. /*** End of inlined file: jdmainct.c ***/
  171079. /*** Start of inlined file: jdmarker.c ***/
  171080. #define JPEG_INTERNALS
  171081. /* Private state */
  171082. typedef struct {
  171083. struct jpeg_marker_reader pub; /* public fields */
  171084. /* Application-overridable marker processing methods */
  171085. jpeg_marker_parser_method process_COM;
  171086. jpeg_marker_parser_method process_APPn[16];
  171087. /* Limit on marker data length to save for each marker type */
  171088. unsigned int length_limit_COM;
  171089. unsigned int length_limit_APPn[16];
  171090. /* Status of COM/APPn marker saving */
  171091. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171092. unsigned int bytes_read; /* data bytes read so far in marker */
  171093. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171094. } my_marker_reader;
  171095. typedef my_marker_reader * my_marker_ptr2;
  171096. /*
  171097. * Macros for fetching data from the data source module.
  171098. *
  171099. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171100. * the current restart point; we update them only when we have reached a
  171101. * suitable place to restart if a suspension occurs.
  171102. */
  171103. /* Declare and initialize local copies of input pointer/count */
  171104. #define INPUT_VARS(cinfo) \
  171105. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171106. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171107. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171108. /* Unload the local copies --- do this only at a restart boundary */
  171109. #define INPUT_SYNC(cinfo) \
  171110. ( datasrc->next_input_byte = next_input_byte, \
  171111. datasrc->bytes_in_buffer = bytes_in_buffer )
  171112. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171113. #define INPUT_RELOAD(cinfo) \
  171114. ( next_input_byte = datasrc->next_input_byte, \
  171115. bytes_in_buffer = datasrc->bytes_in_buffer )
  171116. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171117. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171118. * but we must reload the local copies after a successful fill.
  171119. */
  171120. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171121. if (bytes_in_buffer == 0) { \
  171122. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171123. { action; } \
  171124. INPUT_RELOAD(cinfo); \
  171125. }
  171126. /* Read a byte into variable V.
  171127. * If must suspend, take the specified action (typically "return FALSE").
  171128. */
  171129. #define INPUT_BYTE(cinfo,V,action) \
  171130. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171131. bytes_in_buffer--; \
  171132. V = GETJOCTET(*next_input_byte++); )
  171133. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171134. * V should be declared unsigned int or perhaps INT32.
  171135. */
  171136. #define INPUT_2BYTES(cinfo,V,action) \
  171137. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171138. bytes_in_buffer--; \
  171139. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171140. MAKE_BYTE_AVAIL(cinfo,action); \
  171141. bytes_in_buffer--; \
  171142. V += GETJOCTET(*next_input_byte++); )
  171143. /*
  171144. * Routines to process JPEG markers.
  171145. *
  171146. * Entry condition: JPEG marker itself has been read and its code saved
  171147. * in cinfo->unread_marker; input restart point is just after the marker.
  171148. *
  171149. * Exit: if return TRUE, have read and processed any parameters, and have
  171150. * updated the restart point to point after the parameters.
  171151. * If return FALSE, was forced to suspend before reaching end of
  171152. * marker parameters; restart point has not been moved. Same routine
  171153. * will be called again after application supplies more input data.
  171154. *
  171155. * This approach to suspension assumes that all of a marker's parameters
  171156. * can fit into a single input bufferload. This should hold for "normal"
  171157. * markers. Some COM/APPn markers might have large parameter segments
  171158. * that might not fit. If we are simply dropping such a marker, we use
  171159. * skip_input_data to get past it, and thereby put the problem on the
  171160. * source manager's shoulders. If we are saving the marker's contents
  171161. * into memory, we use a slightly different convention: when forced to
  171162. * suspend, the marker processor updates the restart point to the end of
  171163. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171164. * On resumption, cinfo->unread_marker still contains the marker code,
  171165. * but the data source will point to the next chunk of marker data.
  171166. * The marker processor must retain internal state to deal with this.
  171167. *
  171168. * Note that we don't bother to avoid duplicate trace messages if a
  171169. * suspension occurs within marker parameters. Other side effects
  171170. * require more care.
  171171. */
  171172. LOCAL(boolean)
  171173. get_soi (j_decompress_ptr cinfo)
  171174. /* Process an SOI marker */
  171175. {
  171176. int i;
  171177. TRACEMS(cinfo, 1, JTRC_SOI);
  171178. if (cinfo->marker->saw_SOI)
  171179. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171180. /* Reset all parameters that are defined to be reset by SOI */
  171181. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171182. cinfo->arith_dc_L[i] = 0;
  171183. cinfo->arith_dc_U[i] = 1;
  171184. cinfo->arith_ac_K[i] = 5;
  171185. }
  171186. cinfo->restart_interval = 0;
  171187. /* Set initial assumptions for colorspace etc */
  171188. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171189. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171190. cinfo->saw_JFIF_marker = FALSE;
  171191. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171192. cinfo->JFIF_minor_version = 1;
  171193. cinfo->density_unit = 0;
  171194. cinfo->X_density = 1;
  171195. cinfo->Y_density = 1;
  171196. cinfo->saw_Adobe_marker = FALSE;
  171197. cinfo->Adobe_transform = 0;
  171198. cinfo->marker->saw_SOI = TRUE;
  171199. return TRUE;
  171200. }
  171201. LOCAL(boolean)
  171202. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171203. /* Process a SOFn marker */
  171204. {
  171205. INT32 length;
  171206. int c, ci;
  171207. jpeg_component_info * compptr;
  171208. INPUT_VARS(cinfo);
  171209. cinfo->progressive_mode = is_prog;
  171210. cinfo->arith_code = is_arith;
  171211. INPUT_2BYTES(cinfo, length, return FALSE);
  171212. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171213. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171214. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171215. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171216. length -= 8;
  171217. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171218. (int) cinfo->image_width, (int) cinfo->image_height,
  171219. cinfo->num_components);
  171220. if (cinfo->marker->saw_SOF)
  171221. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171222. /* We don't support files in which the image height is initially specified */
  171223. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171224. /* might as well have a general sanity check. */
  171225. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171226. || cinfo->num_components <= 0)
  171227. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171228. if (length != (cinfo->num_components * 3))
  171229. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171230. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171231. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171232. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171233. cinfo->num_components * SIZEOF(jpeg_component_info));
  171234. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171235. ci++, compptr++) {
  171236. compptr->component_index = ci;
  171237. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171238. INPUT_BYTE(cinfo, c, return FALSE);
  171239. compptr->h_samp_factor = (c >> 4) & 15;
  171240. compptr->v_samp_factor = (c ) & 15;
  171241. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171242. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171243. compptr->component_id, compptr->h_samp_factor,
  171244. compptr->v_samp_factor, compptr->quant_tbl_no);
  171245. }
  171246. cinfo->marker->saw_SOF = TRUE;
  171247. INPUT_SYNC(cinfo);
  171248. return TRUE;
  171249. }
  171250. LOCAL(boolean)
  171251. get_sos (j_decompress_ptr cinfo)
  171252. /* Process a SOS marker */
  171253. {
  171254. INT32 length;
  171255. int i, ci, n, c, cc;
  171256. jpeg_component_info * compptr;
  171257. INPUT_VARS(cinfo);
  171258. if (! cinfo->marker->saw_SOF)
  171259. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171260. INPUT_2BYTES(cinfo, length, return FALSE);
  171261. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171262. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171263. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171264. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171265. cinfo->comps_in_scan = n;
  171266. /* Collect the component-spec parameters */
  171267. for (i = 0; i < n; i++) {
  171268. INPUT_BYTE(cinfo, cc, return FALSE);
  171269. INPUT_BYTE(cinfo, c, return FALSE);
  171270. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171271. ci++, compptr++) {
  171272. if (cc == compptr->component_id)
  171273. goto id_found;
  171274. }
  171275. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171276. id_found:
  171277. cinfo->cur_comp_info[i] = compptr;
  171278. compptr->dc_tbl_no = (c >> 4) & 15;
  171279. compptr->ac_tbl_no = (c ) & 15;
  171280. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171281. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171282. }
  171283. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171284. INPUT_BYTE(cinfo, c, return FALSE);
  171285. cinfo->Ss = c;
  171286. INPUT_BYTE(cinfo, c, return FALSE);
  171287. cinfo->Se = c;
  171288. INPUT_BYTE(cinfo, c, return FALSE);
  171289. cinfo->Ah = (c >> 4) & 15;
  171290. cinfo->Al = (c ) & 15;
  171291. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171292. cinfo->Ah, cinfo->Al);
  171293. /* Prepare to scan data & restart markers */
  171294. cinfo->marker->next_restart_num = 0;
  171295. /* Count another SOS marker */
  171296. cinfo->input_scan_number++;
  171297. INPUT_SYNC(cinfo);
  171298. return TRUE;
  171299. }
  171300. #ifdef D_ARITH_CODING_SUPPORTED
  171301. LOCAL(boolean)
  171302. get_dac (j_decompress_ptr cinfo)
  171303. /* Process a DAC marker */
  171304. {
  171305. INT32 length;
  171306. int index, val;
  171307. INPUT_VARS(cinfo);
  171308. INPUT_2BYTES(cinfo, length, return FALSE);
  171309. length -= 2;
  171310. while (length > 0) {
  171311. INPUT_BYTE(cinfo, index, return FALSE);
  171312. INPUT_BYTE(cinfo, val, return FALSE);
  171313. length -= 2;
  171314. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171315. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171316. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171317. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171318. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171319. } else { /* define DC table */
  171320. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171321. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171322. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171323. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171324. }
  171325. }
  171326. if (length != 0)
  171327. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171328. INPUT_SYNC(cinfo);
  171329. return TRUE;
  171330. }
  171331. #else /* ! D_ARITH_CODING_SUPPORTED */
  171332. #define get_dac(cinfo) skip_variable(cinfo)
  171333. #endif /* D_ARITH_CODING_SUPPORTED */
  171334. LOCAL(boolean)
  171335. get_dht (j_decompress_ptr cinfo)
  171336. /* Process a DHT marker */
  171337. {
  171338. INT32 length;
  171339. UINT8 bits[17];
  171340. UINT8 huffval[256];
  171341. int i, index, count;
  171342. JHUFF_TBL **htblptr;
  171343. INPUT_VARS(cinfo);
  171344. INPUT_2BYTES(cinfo, length, return FALSE);
  171345. length -= 2;
  171346. while (length > 16) {
  171347. INPUT_BYTE(cinfo, index, return FALSE);
  171348. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171349. bits[0] = 0;
  171350. count = 0;
  171351. for (i = 1; i <= 16; i++) {
  171352. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171353. count += bits[i];
  171354. }
  171355. length -= 1 + 16;
  171356. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171357. bits[1], bits[2], bits[3], bits[4],
  171358. bits[5], bits[6], bits[7], bits[8]);
  171359. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171360. bits[9], bits[10], bits[11], bits[12],
  171361. bits[13], bits[14], bits[15], bits[16]);
  171362. /* Here we just do minimal validation of the counts to avoid walking
  171363. * off the end of our table space. jdhuff.c will check more carefully.
  171364. */
  171365. if (count > 256 || ((INT32) count) > length)
  171366. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171367. for (i = 0; i < count; i++)
  171368. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171369. length -= count;
  171370. if (index & 0x10) { /* AC table definition */
  171371. index -= 0x10;
  171372. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171373. } else { /* DC table definition */
  171374. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171375. }
  171376. if (index < 0 || index >= NUM_HUFF_TBLS)
  171377. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171378. if (*htblptr == NULL)
  171379. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171380. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171381. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171382. }
  171383. if (length != 0)
  171384. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171385. INPUT_SYNC(cinfo);
  171386. return TRUE;
  171387. }
  171388. LOCAL(boolean)
  171389. get_dqt (j_decompress_ptr cinfo)
  171390. /* Process a DQT marker */
  171391. {
  171392. INT32 length;
  171393. int n, i, prec;
  171394. unsigned int tmp;
  171395. JQUANT_TBL *quant_ptr;
  171396. INPUT_VARS(cinfo);
  171397. INPUT_2BYTES(cinfo, length, return FALSE);
  171398. length -= 2;
  171399. while (length > 0) {
  171400. INPUT_BYTE(cinfo, n, return FALSE);
  171401. prec = n >> 4;
  171402. n &= 0x0F;
  171403. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171404. if (n >= NUM_QUANT_TBLS)
  171405. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171406. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171407. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171408. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171409. for (i = 0; i < DCTSIZE2; i++) {
  171410. if (prec)
  171411. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171412. else
  171413. INPUT_BYTE(cinfo, tmp, return FALSE);
  171414. /* We convert the zigzag-order table to natural array order. */
  171415. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171416. }
  171417. if (cinfo->err->trace_level >= 2) {
  171418. for (i = 0; i < DCTSIZE2; i += 8) {
  171419. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171420. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171421. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171422. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171423. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171424. }
  171425. }
  171426. length -= DCTSIZE2+1;
  171427. if (prec) length -= DCTSIZE2;
  171428. }
  171429. if (length != 0)
  171430. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171431. INPUT_SYNC(cinfo);
  171432. return TRUE;
  171433. }
  171434. LOCAL(boolean)
  171435. get_dri (j_decompress_ptr cinfo)
  171436. /* Process a DRI marker */
  171437. {
  171438. INT32 length;
  171439. unsigned int tmp;
  171440. INPUT_VARS(cinfo);
  171441. INPUT_2BYTES(cinfo, length, return FALSE);
  171442. if (length != 4)
  171443. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171444. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171445. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171446. cinfo->restart_interval = tmp;
  171447. INPUT_SYNC(cinfo);
  171448. return TRUE;
  171449. }
  171450. /*
  171451. * Routines for processing APPn and COM markers.
  171452. * These are either saved in memory or discarded, per application request.
  171453. * APP0 and APP14 are specially checked to see if they are
  171454. * JFIF and Adobe markers, respectively.
  171455. */
  171456. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171457. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171458. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171459. LOCAL(void)
  171460. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171461. unsigned int datalen, INT32 remaining)
  171462. /* Examine first few bytes from an APP0.
  171463. * Take appropriate action if it is a JFIF marker.
  171464. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171465. */
  171466. {
  171467. INT32 totallen = (INT32) datalen + remaining;
  171468. if (datalen >= APP0_DATA_LEN &&
  171469. GETJOCTET(data[0]) == 0x4A &&
  171470. GETJOCTET(data[1]) == 0x46 &&
  171471. GETJOCTET(data[2]) == 0x49 &&
  171472. GETJOCTET(data[3]) == 0x46 &&
  171473. GETJOCTET(data[4]) == 0) {
  171474. /* Found JFIF APP0 marker: save info */
  171475. cinfo->saw_JFIF_marker = TRUE;
  171476. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171477. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171478. cinfo->density_unit = GETJOCTET(data[7]);
  171479. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171480. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171481. /* Check version.
  171482. * Major version must be 1, anything else signals an incompatible change.
  171483. * (We used to treat this as an error, but now it's a nonfatal warning,
  171484. * because some bozo at Hijaak couldn't read the spec.)
  171485. * Minor version should be 0..2, but process anyway if newer.
  171486. */
  171487. if (cinfo->JFIF_major_version != 1)
  171488. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171489. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171490. /* Generate trace messages */
  171491. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171492. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171493. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171494. /* Validate thumbnail dimensions and issue appropriate messages */
  171495. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171496. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171497. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171498. totallen -= APP0_DATA_LEN;
  171499. if (totallen !=
  171500. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171501. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171502. } else if (datalen >= 6 &&
  171503. GETJOCTET(data[0]) == 0x4A &&
  171504. GETJOCTET(data[1]) == 0x46 &&
  171505. GETJOCTET(data[2]) == 0x58 &&
  171506. GETJOCTET(data[3]) == 0x58 &&
  171507. GETJOCTET(data[4]) == 0) {
  171508. /* Found JFIF "JFXX" extension APP0 marker */
  171509. /* The library doesn't actually do anything with these,
  171510. * but we try to produce a helpful trace message.
  171511. */
  171512. switch (GETJOCTET(data[5])) {
  171513. case 0x10:
  171514. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171515. break;
  171516. case 0x11:
  171517. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171518. break;
  171519. case 0x13:
  171520. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171521. break;
  171522. default:
  171523. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171524. GETJOCTET(data[5]), (int) totallen);
  171525. break;
  171526. }
  171527. } else {
  171528. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171529. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171530. }
  171531. }
  171532. LOCAL(void)
  171533. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171534. unsigned int datalen, INT32 remaining)
  171535. /* Examine first few bytes from an APP14.
  171536. * Take appropriate action if it is an Adobe marker.
  171537. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171538. */
  171539. {
  171540. unsigned int version, flags0, flags1, transform;
  171541. if (datalen >= APP14_DATA_LEN &&
  171542. GETJOCTET(data[0]) == 0x41 &&
  171543. GETJOCTET(data[1]) == 0x64 &&
  171544. GETJOCTET(data[2]) == 0x6F &&
  171545. GETJOCTET(data[3]) == 0x62 &&
  171546. GETJOCTET(data[4]) == 0x65) {
  171547. /* Found Adobe APP14 marker */
  171548. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171549. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171550. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171551. transform = GETJOCTET(data[11]);
  171552. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171553. cinfo->saw_Adobe_marker = TRUE;
  171554. cinfo->Adobe_transform = (UINT8) transform;
  171555. } else {
  171556. /* Start of APP14 does not match "Adobe", or too short */
  171557. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171558. }
  171559. }
  171560. METHODDEF(boolean)
  171561. get_interesting_appn (j_decompress_ptr cinfo)
  171562. /* Process an APP0 or APP14 marker without saving it */
  171563. {
  171564. INT32 length;
  171565. JOCTET b[APPN_DATA_LEN];
  171566. unsigned int i, numtoread;
  171567. INPUT_VARS(cinfo);
  171568. INPUT_2BYTES(cinfo, length, return FALSE);
  171569. length -= 2;
  171570. /* get the interesting part of the marker data */
  171571. if (length >= APPN_DATA_LEN)
  171572. numtoread = APPN_DATA_LEN;
  171573. else if (length > 0)
  171574. numtoread = (unsigned int) length;
  171575. else
  171576. numtoread = 0;
  171577. for (i = 0; i < numtoread; i++)
  171578. INPUT_BYTE(cinfo, b[i], return FALSE);
  171579. length -= numtoread;
  171580. /* process it */
  171581. switch (cinfo->unread_marker) {
  171582. case M_APP0:
  171583. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171584. break;
  171585. case M_APP14:
  171586. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171587. break;
  171588. default:
  171589. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171590. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171591. break;
  171592. }
  171593. /* skip any remaining data -- could be lots */
  171594. INPUT_SYNC(cinfo);
  171595. if (length > 0)
  171596. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171597. return TRUE;
  171598. }
  171599. #ifdef SAVE_MARKERS_SUPPORTED
  171600. METHODDEF(boolean)
  171601. save_marker (j_decompress_ptr cinfo)
  171602. /* Save an APPn or COM marker into the marker list */
  171603. {
  171604. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171605. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171606. unsigned int bytes_read, data_length;
  171607. JOCTET FAR * data;
  171608. INT32 length = 0;
  171609. INPUT_VARS(cinfo);
  171610. if (cur_marker == NULL) {
  171611. /* begin reading a marker */
  171612. INPUT_2BYTES(cinfo, length, return FALSE);
  171613. length -= 2;
  171614. if (length >= 0) { /* watch out for bogus length word */
  171615. /* figure out how much we want to save */
  171616. unsigned int limit;
  171617. if (cinfo->unread_marker == (int) M_COM)
  171618. limit = marker->length_limit_COM;
  171619. else
  171620. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171621. if ((unsigned int) length < limit)
  171622. limit = (unsigned int) length;
  171623. /* allocate and initialize the marker item */
  171624. cur_marker = (jpeg_saved_marker_ptr)
  171625. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171626. SIZEOF(struct jpeg_marker_struct) + limit);
  171627. cur_marker->next = NULL;
  171628. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171629. cur_marker->original_length = (unsigned int) length;
  171630. cur_marker->data_length = limit;
  171631. /* data area is just beyond the jpeg_marker_struct */
  171632. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171633. marker->cur_marker = cur_marker;
  171634. marker->bytes_read = 0;
  171635. bytes_read = 0;
  171636. data_length = limit;
  171637. } else {
  171638. /* deal with bogus length word */
  171639. bytes_read = data_length = 0;
  171640. data = NULL;
  171641. }
  171642. } else {
  171643. /* resume reading a marker */
  171644. bytes_read = marker->bytes_read;
  171645. data_length = cur_marker->data_length;
  171646. data = cur_marker->data + bytes_read;
  171647. }
  171648. while (bytes_read < data_length) {
  171649. INPUT_SYNC(cinfo); /* move the restart point to here */
  171650. marker->bytes_read = bytes_read;
  171651. /* If there's not at least one byte in buffer, suspend */
  171652. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171653. /* Copy bytes with reasonable rapidity */
  171654. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171655. *data++ = *next_input_byte++;
  171656. bytes_in_buffer--;
  171657. bytes_read++;
  171658. }
  171659. }
  171660. /* Done reading what we want to read */
  171661. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171662. /* Add new marker to end of list */
  171663. if (cinfo->marker_list == NULL) {
  171664. cinfo->marker_list = cur_marker;
  171665. } else {
  171666. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171667. while (prev->next != NULL)
  171668. prev = prev->next;
  171669. prev->next = cur_marker;
  171670. }
  171671. /* Reset pointer & calc remaining data length */
  171672. data = cur_marker->data;
  171673. length = cur_marker->original_length - data_length;
  171674. }
  171675. /* Reset to initial state for next marker */
  171676. marker->cur_marker = NULL;
  171677. /* Process the marker if interesting; else just make a generic trace msg */
  171678. switch (cinfo->unread_marker) {
  171679. case M_APP0:
  171680. examine_app0(cinfo, data, data_length, length);
  171681. break;
  171682. case M_APP14:
  171683. examine_app14(cinfo, data, data_length, length);
  171684. break;
  171685. default:
  171686. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171687. (int) (data_length + length));
  171688. break;
  171689. }
  171690. /* skip any remaining data -- could be lots */
  171691. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171692. if (length > 0)
  171693. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171694. return TRUE;
  171695. }
  171696. #endif /* SAVE_MARKERS_SUPPORTED */
  171697. METHODDEF(boolean)
  171698. skip_variable (j_decompress_ptr cinfo)
  171699. /* Skip over an unknown or uninteresting variable-length marker */
  171700. {
  171701. INT32 length;
  171702. INPUT_VARS(cinfo);
  171703. INPUT_2BYTES(cinfo, length, return FALSE);
  171704. length -= 2;
  171705. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171706. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171707. if (length > 0)
  171708. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171709. return TRUE;
  171710. }
  171711. /*
  171712. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171713. * Returns FALSE if had to suspend before reaching a marker;
  171714. * in that case cinfo->unread_marker is unchanged.
  171715. *
  171716. * Note that the result might not be a valid marker code,
  171717. * but it will never be 0 or FF.
  171718. */
  171719. LOCAL(boolean)
  171720. next_marker (j_decompress_ptr cinfo)
  171721. {
  171722. int c;
  171723. INPUT_VARS(cinfo);
  171724. for (;;) {
  171725. INPUT_BYTE(cinfo, c, return FALSE);
  171726. /* Skip any non-FF bytes.
  171727. * This may look a bit inefficient, but it will not occur in a valid file.
  171728. * We sync after each discarded byte so that a suspending data source
  171729. * can discard the byte from its buffer.
  171730. */
  171731. while (c != 0xFF) {
  171732. cinfo->marker->discarded_bytes++;
  171733. INPUT_SYNC(cinfo);
  171734. INPUT_BYTE(cinfo, c, return FALSE);
  171735. }
  171736. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171737. * pad bytes, so don't count them in discarded_bytes. We assume there
  171738. * will not be so many consecutive FF bytes as to overflow a suspending
  171739. * data source's input buffer.
  171740. */
  171741. do {
  171742. INPUT_BYTE(cinfo, c, return FALSE);
  171743. } while (c == 0xFF);
  171744. if (c != 0)
  171745. break; /* found a valid marker, exit loop */
  171746. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171747. * Discard it and loop back to try again.
  171748. */
  171749. cinfo->marker->discarded_bytes += 2;
  171750. INPUT_SYNC(cinfo);
  171751. }
  171752. if (cinfo->marker->discarded_bytes != 0) {
  171753. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171754. cinfo->marker->discarded_bytes = 0;
  171755. }
  171756. cinfo->unread_marker = c;
  171757. INPUT_SYNC(cinfo);
  171758. return TRUE;
  171759. }
  171760. LOCAL(boolean)
  171761. first_marker (j_decompress_ptr cinfo)
  171762. /* Like next_marker, but used to obtain the initial SOI marker. */
  171763. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171764. * we might well scan an entire input file before realizing it ain't JPEG.
  171765. * If an application wants to process non-JFIF files, it must seek to the
  171766. * SOI before calling the JPEG library.
  171767. */
  171768. {
  171769. int c, c2;
  171770. INPUT_VARS(cinfo);
  171771. INPUT_BYTE(cinfo, c, return FALSE);
  171772. INPUT_BYTE(cinfo, c2, return FALSE);
  171773. if (c != 0xFF || c2 != (int) M_SOI)
  171774. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171775. cinfo->unread_marker = c2;
  171776. INPUT_SYNC(cinfo);
  171777. return TRUE;
  171778. }
  171779. /*
  171780. * Read markers until SOS or EOI.
  171781. *
  171782. * Returns same codes as are defined for jpeg_consume_input:
  171783. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171784. */
  171785. METHODDEF(int)
  171786. read_markers (j_decompress_ptr cinfo)
  171787. {
  171788. /* Outer loop repeats once for each marker. */
  171789. for (;;) {
  171790. /* Collect the marker proper, unless we already did. */
  171791. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171792. if (cinfo->unread_marker == 0) {
  171793. if (! cinfo->marker->saw_SOI) {
  171794. if (! first_marker(cinfo))
  171795. return JPEG_SUSPENDED;
  171796. } else {
  171797. if (! next_marker(cinfo))
  171798. return JPEG_SUSPENDED;
  171799. }
  171800. }
  171801. /* At this point cinfo->unread_marker contains the marker code and the
  171802. * input point is just past the marker proper, but before any parameters.
  171803. * A suspension will cause us to return with this state still true.
  171804. */
  171805. switch (cinfo->unread_marker) {
  171806. case M_SOI:
  171807. if (! get_soi(cinfo))
  171808. return JPEG_SUSPENDED;
  171809. break;
  171810. case M_SOF0: /* Baseline */
  171811. case M_SOF1: /* Extended sequential, Huffman */
  171812. if (! get_sof(cinfo, FALSE, FALSE))
  171813. return JPEG_SUSPENDED;
  171814. break;
  171815. case M_SOF2: /* Progressive, Huffman */
  171816. if (! get_sof(cinfo, TRUE, FALSE))
  171817. return JPEG_SUSPENDED;
  171818. break;
  171819. case M_SOF9: /* Extended sequential, arithmetic */
  171820. if (! get_sof(cinfo, FALSE, TRUE))
  171821. return JPEG_SUSPENDED;
  171822. break;
  171823. case M_SOF10: /* Progressive, arithmetic */
  171824. if (! get_sof(cinfo, TRUE, TRUE))
  171825. return JPEG_SUSPENDED;
  171826. break;
  171827. /* Currently unsupported SOFn types */
  171828. case M_SOF3: /* Lossless, Huffman */
  171829. case M_SOF5: /* Differential sequential, Huffman */
  171830. case M_SOF6: /* Differential progressive, Huffman */
  171831. case M_SOF7: /* Differential lossless, Huffman */
  171832. case M_JPG: /* Reserved for JPEG extensions */
  171833. case M_SOF11: /* Lossless, arithmetic */
  171834. case M_SOF13: /* Differential sequential, arithmetic */
  171835. case M_SOF14: /* Differential progressive, arithmetic */
  171836. case M_SOF15: /* Differential lossless, arithmetic */
  171837. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171838. break;
  171839. case M_SOS:
  171840. if (! get_sos(cinfo))
  171841. return JPEG_SUSPENDED;
  171842. cinfo->unread_marker = 0; /* processed the marker */
  171843. return JPEG_REACHED_SOS;
  171844. case M_EOI:
  171845. TRACEMS(cinfo, 1, JTRC_EOI);
  171846. cinfo->unread_marker = 0; /* processed the marker */
  171847. return JPEG_REACHED_EOI;
  171848. case M_DAC:
  171849. if (! get_dac(cinfo))
  171850. return JPEG_SUSPENDED;
  171851. break;
  171852. case M_DHT:
  171853. if (! get_dht(cinfo))
  171854. return JPEG_SUSPENDED;
  171855. break;
  171856. case M_DQT:
  171857. if (! get_dqt(cinfo))
  171858. return JPEG_SUSPENDED;
  171859. break;
  171860. case M_DRI:
  171861. if (! get_dri(cinfo))
  171862. return JPEG_SUSPENDED;
  171863. break;
  171864. case M_APP0:
  171865. case M_APP1:
  171866. case M_APP2:
  171867. case M_APP3:
  171868. case M_APP4:
  171869. case M_APP5:
  171870. case M_APP6:
  171871. case M_APP7:
  171872. case M_APP8:
  171873. case M_APP9:
  171874. case M_APP10:
  171875. case M_APP11:
  171876. case M_APP12:
  171877. case M_APP13:
  171878. case M_APP14:
  171879. case M_APP15:
  171880. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171881. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171882. return JPEG_SUSPENDED;
  171883. break;
  171884. case M_COM:
  171885. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171886. return JPEG_SUSPENDED;
  171887. break;
  171888. case M_RST0: /* these are all parameterless */
  171889. case M_RST1:
  171890. case M_RST2:
  171891. case M_RST3:
  171892. case M_RST4:
  171893. case M_RST5:
  171894. case M_RST6:
  171895. case M_RST7:
  171896. case M_TEM:
  171897. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171898. break;
  171899. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171900. if (! skip_variable(cinfo))
  171901. return JPEG_SUSPENDED;
  171902. break;
  171903. default: /* must be DHP, EXP, JPGn, or RESn */
  171904. /* For now, we treat the reserved markers as fatal errors since they are
  171905. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171906. * Once the JPEG 3 version-number marker is well defined, this code
  171907. * ought to change!
  171908. */
  171909. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171910. break;
  171911. }
  171912. /* Successfully processed marker, so reset state variable */
  171913. cinfo->unread_marker = 0;
  171914. } /* end loop */
  171915. }
  171916. /*
  171917. * Read a restart marker, which is expected to appear next in the datastream;
  171918. * if the marker is not there, take appropriate recovery action.
  171919. * Returns FALSE if suspension is required.
  171920. *
  171921. * This is called by the entropy decoder after it has read an appropriate
  171922. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171923. * has already read a marker from the data source. Under normal conditions
  171924. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171925. * it holds a marker which the decoder will be unable to read past.
  171926. */
  171927. METHODDEF(boolean)
  171928. read_restart_marker (j_decompress_ptr cinfo)
  171929. {
  171930. /* Obtain a marker unless we already did. */
  171931. /* Note that next_marker will complain if it skips any data. */
  171932. if (cinfo->unread_marker == 0) {
  171933. if (! next_marker(cinfo))
  171934. return FALSE;
  171935. }
  171936. if (cinfo->unread_marker ==
  171937. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171938. /* Normal case --- swallow the marker and let entropy decoder continue */
  171939. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171940. cinfo->unread_marker = 0;
  171941. } else {
  171942. /* Uh-oh, the restart markers have been messed up. */
  171943. /* Let the data source manager determine how to resync. */
  171944. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171945. cinfo->marker->next_restart_num))
  171946. return FALSE;
  171947. }
  171948. /* Update next-restart state */
  171949. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171950. return TRUE;
  171951. }
  171952. /*
  171953. * This is the default resync_to_restart method for data source managers
  171954. * to use if they don't have any better approach. Some data source managers
  171955. * may be able to back up, or may have additional knowledge about the data
  171956. * which permits a more intelligent recovery strategy; such managers would
  171957. * presumably supply their own resync method.
  171958. *
  171959. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171960. * the restart marker it was expecting. (This code is *not* used unless
  171961. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171962. * the marker code actually found (might be anything, except 0 or FF).
  171963. * The desired restart marker number (0..7) is passed as a parameter.
  171964. * This routine is supposed to apply whatever error recovery strategy seems
  171965. * appropriate in order to position the input stream to the next data segment.
  171966. * Note that cinfo->unread_marker is treated as a marker appearing before
  171967. * the current data-source input point; usually it should be reset to zero
  171968. * before returning.
  171969. * Returns FALSE if suspension is required.
  171970. *
  171971. * This implementation is substantially constrained by wanting to treat the
  171972. * input as a data stream; this means we can't back up. Therefore, we have
  171973. * only the following actions to work with:
  171974. * 1. Simply discard the marker and let the entropy decoder resume at next
  171975. * byte of file.
  171976. * 2. Read forward until we find another marker, discarding intervening
  171977. * data. (In theory we could look ahead within the current bufferload,
  171978. * without having to discard data if we don't find the desired marker.
  171979. * This idea is not implemented here, in part because it makes behavior
  171980. * dependent on buffer size and chance buffer-boundary positions.)
  171981. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171982. * This will cause the entropy decoder to process an empty data segment,
  171983. * inserting dummy zeroes, and then we will reprocess the marker.
  171984. *
  171985. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171986. * appropriate if the found marker is a future restart marker (indicating
  171987. * that we have missed the desired restart marker, probably because it got
  171988. * corrupted).
  171989. * We apply #2 or #3 if the found marker is a restart marker no more than
  171990. * two counts behind or ahead of the expected one. We also apply #2 if the
  171991. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171992. * If the found marker is a restart marker more than 2 counts away, we do #1
  171993. * (too much risk that the marker is erroneous; with luck we will be able to
  171994. * resync at some future point).
  171995. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171996. * overrunning the end of a scan. An implementation limited to single-scan
  171997. * files might find it better to apply #2 for markers other than EOI, since
  171998. * any other marker would have to be bogus data in that case.
  171999. */
  172000. GLOBAL(boolean)
  172001. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172002. {
  172003. int marker = cinfo->unread_marker;
  172004. int action = 1;
  172005. /* Always put up a warning. */
  172006. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172007. /* Outer loop handles repeated decision after scanning forward. */
  172008. for (;;) {
  172009. if (marker < (int) M_SOF0)
  172010. action = 2; /* invalid marker */
  172011. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172012. action = 3; /* valid non-restart marker */
  172013. else {
  172014. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172015. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172016. action = 3; /* one of the next two expected restarts */
  172017. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172018. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172019. action = 2; /* a prior restart, so advance */
  172020. else
  172021. action = 1; /* desired restart or too far away */
  172022. }
  172023. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172024. switch (action) {
  172025. case 1:
  172026. /* Discard marker and let entropy decoder resume processing. */
  172027. cinfo->unread_marker = 0;
  172028. return TRUE;
  172029. case 2:
  172030. /* Scan to the next marker, and repeat the decision loop. */
  172031. if (! next_marker(cinfo))
  172032. return FALSE;
  172033. marker = cinfo->unread_marker;
  172034. break;
  172035. case 3:
  172036. /* Return without advancing past this marker. */
  172037. /* Entropy decoder will be forced to process an empty segment. */
  172038. return TRUE;
  172039. }
  172040. } /* end loop */
  172041. }
  172042. /*
  172043. * Reset marker processing state to begin a fresh datastream.
  172044. */
  172045. METHODDEF(void)
  172046. reset_marker_reader (j_decompress_ptr cinfo)
  172047. {
  172048. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172049. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172050. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172051. cinfo->unread_marker = 0; /* no pending marker */
  172052. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172053. marker->pub.saw_SOF = FALSE;
  172054. marker->pub.discarded_bytes = 0;
  172055. marker->cur_marker = NULL;
  172056. }
  172057. /*
  172058. * Initialize the marker reader module.
  172059. * This is called only once, when the decompression object is created.
  172060. */
  172061. GLOBAL(void)
  172062. jinit_marker_reader (j_decompress_ptr cinfo)
  172063. {
  172064. my_marker_ptr2 marker;
  172065. int i;
  172066. /* Create subobject in permanent pool */
  172067. marker = (my_marker_ptr2)
  172068. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172069. SIZEOF(my_marker_reader));
  172070. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172071. /* Initialize public method pointers */
  172072. marker->pub.reset_marker_reader = reset_marker_reader;
  172073. marker->pub.read_markers = read_markers;
  172074. marker->pub.read_restart_marker = read_restart_marker;
  172075. /* Initialize COM/APPn processing.
  172076. * By default, we examine and then discard APP0 and APP14,
  172077. * but simply discard COM and all other APPn.
  172078. */
  172079. marker->process_COM = skip_variable;
  172080. marker->length_limit_COM = 0;
  172081. for (i = 0; i < 16; i++) {
  172082. marker->process_APPn[i] = skip_variable;
  172083. marker->length_limit_APPn[i] = 0;
  172084. }
  172085. marker->process_APPn[0] = get_interesting_appn;
  172086. marker->process_APPn[14] = get_interesting_appn;
  172087. /* Reset marker processing state */
  172088. reset_marker_reader(cinfo);
  172089. }
  172090. /*
  172091. * Control saving of COM and APPn markers into marker_list.
  172092. */
  172093. #ifdef SAVE_MARKERS_SUPPORTED
  172094. GLOBAL(void)
  172095. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172096. unsigned int length_limit)
  172097. {
  172098. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172099. long maxlength;
  172100. jpeg_marker_parser_method processor;
  172101. /* Length limit mustn't be larger than what we can allocate
  172102. * (should only be a concern in a 16-bit environment).
  172103. */
  172104. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172105. if (((long) length_limit) > maxlength)
  172106. length_limit = (unsigned int) maxlength;
  172107. /* Choose processor routine to use.
  172108. * APP0/APP14 have special requirements.
  172109. */
  172110. if (length_limit) {
  172111. processor = save_marker;
  172112. /* If saving APP0/APP14, save at least enough for our internal use. */
  172113. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172114. length_limit = APP0_DATA_LEN;
  172115. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172116. length_limit = APP14_DATA_LEN;
  172117. } else {
  172118. processor = skip_variable;
  172119. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172120. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172121. processor = get_interesting_appn;
  172122. }
  172123. if (marker_code == (int) M_COM) {
  172124. marker->process_COM = processor;
  172125. marker->length_limit_COM = length_limit;
  172126. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172127. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172128. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172129. } else
  172130. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172131. }
  172132. #endif /* SAVE_MARKERS_SUPPORTED */
  172133. /*
  172134. * Install a special processing method for COM or APPn markers.
  172135. */
  172136. GLOBAL(void)
  172137. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172138. jpeg_marker_parser_method routine)
  172139. {
  172140. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172141. if (marker_code == (int) M_COM)
  172142. marker->process_COM = routine;
  172143. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172144. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172145. else
  172146. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172147. }
  172148. /*** End of inlined file: jdmarker.c ***/
  172149. /*** Start of inlined file: jdmaster.c ***/
  172150. #define JPEG_INTERNALS
  172151. /* Private state */
  172152. typedef struct {
  172153. struct jpeg_decomp_master pub; /* public fields */
  172154. int pass_number; /* # of passes completed */
  172155. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172156. /* Saved references to initialized quantizer modules,
  172157. * in case we need to switch modes.
  172158. */
  172159. struct jpeg_color_quantizer * quantizer_1pass;
  172160. struct jpeg_color_quantizer * quantizer_2pass;
  172161. } my_decomp_master;
  172162. typedef my_decomp_master * my_master_ptr6;
  172163. /*
  172164. * Determine whether merged upsample/color conversion should be used.
  172165. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172166. */
  172167. LOCAL(boolean)
  172168. use_merged_upsample (j_decompress_ptr cinfo)
  172169. {
  172170. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172171. /* Merging is the equivalent of plain box-filter upsampling */
  172172. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172173. return FALSE;
  172174. /* jdmerge.c only supports YCC=>RGB color conversion */
  172175. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172176. cinfo->out_color_space != JCS_RGB ||
  172177. cinfo->out_color_components != RGB_PIXELSIZE)
  172178. return FALSE;
  172179. /* and it only handles 2h1v or 2h2v sampling ratios */
  172180. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172181. cinfo->comp_info[1].h_samp_factor != 1 ||
  172182. cinfo->comp_info[2].h_samp_factor != 1 ||
  172183. cinfo->comp_info[0].v_samp_factor > 2 ||
  172184. cinfo->comp_info[1].v_samp_factor != 1 ||
  172185. cinfo->comp_info[2].v_samp_factor != 1)
  172186. return FALSE;
  172187. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172188. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172189. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172190. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172191. return FALSE;
  172192. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172193. return TRUE; /* by golly, it'll work... */
  172194. #else
  172195. return FALSE;
  172196. #endif
  172197. }
  172198. /*
  172199. * Compute output image dimensions and related values.
  172200. * NOTE: this is exported for possible use by application.
  172201. * Hence it mustn't do anything that can't be done twice.
  172202. * Also note that it may be called before the master module is initialized!
  172203. */
  172204. GLOBAL(void)
  172205. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172206. /* Do computations that are needed before master selection phase */
  172207. {
  172208. #ifdef IDCT_SCALING_SUPPORTED
  172209. int ci;
  172210. jpeg_component_info *compptr;
  172211. #endif
  172212. /* Prevent application from calling me at wrong times */
  172213. if (cinfo->global_state != DSTATE_READY)
  172214. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172215. #ifdef IDCT_SCALING_SUPPORTED
  172216. /* Compute actual output image dimensions and DCT scaling choices. */
  172217. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172218. /* Provide 1/8 scaling */
  172219. cinfo->output_width = (JDIMENSION)
  172220. jdiv_round_up((long) cinfo->image_width, 8L);
  172221. cinfo->output_height = (JDIMENSION)
  172222. jdiv_round_up((long) cinfo->image_height, 8L);
  172223. cinfo->min_DCT_scaled_size = 1;
  172224. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172225. /* Provide 1/4 scaling */
  172226. cinfo->output_width = (JDIMENSION)
  172227. jdiv_round_up((long) cinfo->image_width, 4L);
  172228. cinfo->output_height = (JDIMENSION)
  172229. jdiv_round_up((long) cinfo->image_height, 4L);
  172230. cinfo->min_DCT_scaled_size = 2;
  172231. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172232. /* Provide 1/2 scaling */
  172233. cinfo->output_width = (JDIMENSION)
  172234. jdiv_round_up((long) cinfo->image_width, 2L);
  172235. cinfo->output_height = (JDIMENSION)
  172236. jdiv_round_up((long) cinfo->image_height, 2L);
  172237. cinfo->min_DCT_scaled_size = 4;
  172238. } else {
  172239. /* Provide 1/1 scaling */
  172240. cinfo->output_width = cinfo->image_width;
  172241. cinfo->output_height = cinfo->image_height;
  172242. cinfo->min_DCT_scaled_size = DCTSIZE;
  172243. }
  172244. /* In selecting the actual DCT scaling for each component, we try to
  172245. * scale up the chroma components via IDCT scaling rather than upsampling.
  172246. * This saves time if the upsampler gets to use 1:1 scaling.
  172247. * Note this code assumes that the supported DCT scalings are powers of 2.
  172248. */
  172249. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172250. ci++, compptr++) {
  172251. int ssize = cinfo->min_DCT_scaled_size;
  172252. while (ssize < DCTSIZE &&
  172253. (compptr->h_samp_factor * ssize * 2 <=
  172254. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172255. (compptr->v_samp_factor * ssize * 2 <=
  172256. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172257. ssize = ssize * 2;
  172258. }
  172259. compptr->DCT_scaled_size = ssize;
  172260. }
  172261. /* Recompute downsampled dimensions of components;
  172262. * application needs to know these if using raw downsampled data.
  172263. */
  172264. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172265. ci++, compptr++) {
  172266. /* Size in samples, after IDCT scaling */
  172267. compptr->downsampled_width = (JDIMENSION)
  172268. jdiv_round_up((long) cinfo->image_width *
  172269. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172270. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172271. compptr->downsampled_height = (JDIMENSION)
  172272. jdiv_round_up((long) cinfo->image_height *
  172273. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172274. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172275. }
  172276. #else /* !IDCT_SCALING_SUPPORTED */
  172277. /* Hardwire it to "no scaling" */
  172278. cinfo->output_width = cinfo->image_width;
  172279. cinfo->output_height = cinfo->image_height;
  172280. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172281. * and has computed unscaled downsampled_width and downsampled_height.
  172282. */
  172283. #endif /* IDCT_SCALING_SUPPORTED */
  172284. /* Report number of components in selected colorspace. */
  172285. /* Probably this should be in the color conversion module... */
  172286. switch (cinfo->out_color_space) {
  172287. case JCS_GRAYSCALE:
  172288. cinfo->out_color_components = 1;
  172289. break;
  172290. case JCS_RGB:
  172291. #if RGB_PIXELSIZE != 3
  172292. cinfo->out_color_components = RGB_PIXELSIZE;
  172293. break;
  172294. #endif /* else share code with YCbCr */
  172295. case JCS_YCbCr:
  172296. cinfo->out_color_components = 3;
  172297. break;
  172298. case JCS_CMYK:
  172299. case JCS_YCCK:
  172300. cinfo->out_color_components = 4;
  172301. break;
  172302. default: /* else must be same colorspace as in file */
  172303. cinfo->out_color_components = cinfo->num_components;
  172304. break;
  172305. }
  172306. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172307. cinfo->out_color_components);
  172308. /* See if upsampler will want to emit more than one row at a time */
  172309. if (use_merged_upsample(cinfo))
  172310. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172311. else
  172312. cinfo->rec_outbuf_height = 1;
  172313. }
  172314. /*
  172315. * Several decompression processes need to range-limit values to the range
  172316. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172317. * due to noise introduced by quantization, roundoff error, etc. These
  172318. * processes are inner loops and need to be as fast as possible. On most
  172319. * machines, particularly CPUs with pipelines or instruction prefetch,
  172320. * a (subscript-check-less) C table lookup
  172321. * x = sample_range_limit[x];
  172322. * is faster than explicit tests
  172323. * if (x < 0) x = 0;
  172324. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172325. * These processes all use a common table prepared by the routine below.
  172326. *
  172327. * For most steps we can mathematically guarantee that the initial value
  172328. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172329. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172330. * limiting step (just after the IDCT), a wildly out-of-range value is
  172331. * possible if the input data is corrupt. To avoid any chance of indexing
  172332. * off the end of memory and getting a bad-pointer trap, we perform the
  172333. * post-IDCT limiting thus:
  172334. * x = range_limit[x & MASK];
  172335. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172336. * samples. Under normal circumstances this is more than enough range and
  172337. * a correct output will be generated; with bogus input data the mask will
  172338. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172339. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172340. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172341. * So the post-IDCT limiting table ends up looking like this:
  172342. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172343. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172344. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172345. * 0,1,...,CENTERJSAMPLE-1
  172346. * Negative inputs select values from the upper half of the table after
  172347. * masking.
  172348. *
  172349. * We can save some space by overlapping the start of the post-IDCT table
  172350. * with the simpler range limiting table. The post-IDCT table begins at
  172351. * sample_range_limit + CENTERJSAMPLE.
  172352. *
  172353. * Note that the table is allocated in near data space on PCs; it's small
  172354. * enough and used often enough to justify this.
  172355. */
  172356. LOCAL(void)
  172357. prepare_range_limit_table (j_decompress_ptr cinfo)
  172358. /* Allocate and fill in the sample_range_limit table */
  172359. {
  172360. JSAMPLE * table;
  172361. int i;
  172362. table = (JSAMPLE *)
  172363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172364. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172365. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172366. cinfo->sample_range_limit = table;
  172367. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172368. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172369. /* Main part of "simple" table: limit[x] = x */
  172370. for (i = 0; i <= MAXJSAMPLE; i++)
  172371. table[i] = (JSAMPLE) i;
  172372. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172373. /* End of simple table, rest of first half of post-IDCT table */
  172374. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172375. table[i] = MAXJSAMPLE;
  172376. /* Second half of post-IDCT table */
  172377. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172378. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172379. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172380. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172381. }
  172382. /*
  172383. * Master selection of decompression modules.
  172384. * This is done once at jpeg_start_decompress time. We determine
  172385. * which modules will be used and give them appropriate initialization calls.
  172386. * We also initialize the decompressor input side to begin consuming data.
  172387. *
  172388. * Since jpeg_read_header has finished, we know what is in the SOF
  172389. * and (first) SOS markers. We also have all the application parameter
  172390. * settings.
  172391. */
  172392. LOCAL(void)
  172393. master_selection (j_decompress_ptr cinfo)
  172394. {
  172395. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172396. boolean use_c_buffer;
  172397. long samplesperrow;
  172398. JDIMENSION jd_samplesperrow;
  172399. /* Initialize dimensions and other stuff */
  172400. jpeg_calc_output_dimensions(cinfo);
  172401. prepare_range_limit_table(cinfo);
  172402. /* Width of an output scanline must be representable as JDIMENSION. */
  172403. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172404. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172405. if ((long) jd_samplesperrow != samplesperrow)
  172406. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172407. /* Initialize my private state */
  172408. master->pass_number = 0;
  172409. master->using_merged_upsample = use_merged_upsample(cinfo);
  172410. /* Color quantizer selection */
  172411. master->quantizer_1pass = NULL;
  172412. master->quantizer_2pass = NULL;
  172413. /* No mode changes if not using buffered-image mode. */
  172414. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172415. cinfo->enable_1pass_quant = FALSE;
  172416. cinfo->enable_external_quant = FALSE;
  172417. cinfo->enable_2pass_quant = FALSE;
  172418. }
  172419. if (cinfo->quantize_colors) {
  172420. if (cinfo->raw_data_out)
  172421. ERREXIT(cinfo, JERR_NOTIMPL);
  172422. /* 2-pass quantizer only works in 3-component color space. */
  172423. if (cinfo->out_color_components != 3) {
  172424. cinfo->enable_1pass_quant = TRUE;
  172425. cinfo->enable_external_quant = FALSE;
  172426. cinfo->enable_2pass_quant = FALSE;
  172427. cinfo->colormap = NULL;
  172428. } else if (cinfo->colormap != NULL) {
  172429. cinfo->enable_external_quant = TRUE;
  172430. } else if (cinfo->two_pass_quantize) {
  172431. cinfo->enable_2pass_quant = TRUE;
  172432. } else {
  172433. cinfo->enable_1pass_quant = TRUE;
  172434. }
  172435. if (cinfo->enable_1pass_quant) {
  172436. #ifdef QUANT_1PASS_SUPPORTED
  172437. jinit_1pass_quantizer(cinfo);
  172438. master->quantizer_1pass = cinfo->cquantize;
  172439. #else
  172440. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172441. #endif
  172442. }
  172443. /* We use the 2-pass code to map to external colormaps. */
  172444. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172445. #ifdef QUANT_2PASS_SUPPORTED
  172446. jinit_2pass_quantizer(cinfo);
  172447. master->quantizer_2pass = cinfo->cquantize;
  172448. #else
  172449. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172450. #endif
  172451. }
  172452. /* If both quantizers are initialized, the 2-pass one is left active;
  172453. * this is necessary for starting with quantization to an external map.
  172454. */
  172455. }
  172456. /* Post-processing: in particular, color conversion first */
  172457. if (! cinfo->raw_data_out) {
  172458. if (master->using_merged_upsample) {
  172459. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172460. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172461. #else
  172462. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172463. #endif
  172464. } else {
  172465. jinit_color_deconverter(cinfo);
  172466. jinit_upsampler(cinfo);
  172467. }
  172468. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172469. }
  172470. /* Inverse DCT */
  172471. jinit_inverse_dct(cinfo);
  172472. /* Entropy decoding: either Huffman or arithmetic coding. */
  172473. if (cinfo->arith_code) {
  172474. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172475. } else {
  172476. if (cinfo->progressive_mode) {
  172477. #ifdef D_PROGRESSIVE_SUPPORTED
  172478. jinit_phuff_decoder(cinfo);
  172479. #else
  172480. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172481. #endif
  172482. } else
  172483. jinit_huff_decoder(cinfo);
  172484. }
  172485. /* Initialize principal buffer controllers. */
  172486. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172487. jinit_d_coef_controller(cinfo, use_c_buffer);
  172488. if (! cinfo->raw_data_out)
  172489. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172490. /* We can now tell the memory manager to allocate virtual arrays. */
  172491. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172492. /* Initialize input side of decompressor to consume first scan. */
  172493. (*cinfo->inputctl->start_input_pass) (cinfo);
  172494. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172495. /* If jpeg_start_decompress will read the whole file, initialize
  172496. * progress monitoring appropriately. The input step is counted
  172497. * as one pass.
  172498. */
  172499. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172500. cinfo->inputctl->has_multiple_scans) {
  172501. int nscans;
  172502. /* Estimate number of scans to set pass_limit. */
  172503. if (cinfo->progressive_mode) {
  172504. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172505. nscans = 2 + 3 * cinfo->num_components;
  172506. } else {
  172507. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172508. nscans = cinfo->num_components;
  172509. }
  172510. cinfo->progress->pass_counter = 0L;
  172511. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172512. cinfo->progress->completed_passes = 0;
  172513. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172514. /* Count the input pass as done */
  172515. master->pass_number++;
  172516. }
  172517. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172518. }
  172519. /*
  172520. * Per-pass setup.
  172521. * This is called at the beginning of each output pass. We determine which
  172522. * modules will be active during this pass and give them appropriate
  172523. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172524. * is a "real" output pass or a dummy pass for color quantization.
  172525. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172526. */
  172527. METHODDEF(void)
  172528. prepare_for_output_pass (j_decompress_ptr cinfo)
  172529. {
  172530. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172531. if (master->pub.is_dummy_pass) {
  172532. #ifdef QUANT_2PASS_SUPPORTED
  172533. /* Final pass of 2-pass quantization */
  172534. master->pub.is_dummy_pass = FALSE;
  172535. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172536. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172537. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172538. #else
  172539. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172540. #endif /* QUANT_2PASS_SUPPORTED */
  172541. } else {
  172542. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172543. /* Select new quantization method */
  172544. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172545. cinfo->cquantize = master->quantizer_2pass;
  172546. master->pub.is_dummy_pass = TRUE;
  172547. } else if (cinfo->enable_1pass_quant) {
  172548. cinfo->cquantize = master->quantizer_1pass;
  172549. } else {
  172550. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172551. }
  172552. }
  172553. (*cinfo->idct->start_pass) (cinfo);
  172554. (*cinfo->coef->start_output_pass) (cinfo);
  172555. if (! cinfo->raw_data_out) {
  172556. if (! master->using_merged_upsample)
  172557. (*cinfo->cconvert->start_pass) (cinfo);
  172558. (*cinfo->upsample->start_pass) (cinfo);
  172559. if (cinfo->quantize_colors)
  172560. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172561. (*cinfo->post->start_pass) (cinfo,
  172562. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172563. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172564. }
  172565. }
  172566. /* Set up progress monitor's pass info if present */
  172567. if (cinfo->progress != NULL) {
  172568. cinfo->progress->completed_passes = master->pass_number;
  172569. cinfo->progress->total_passes = master->pass_number +
  172570. (master->pub.is_dummy_pass ? 2 : 1);
  172571. /* In buffered-image mode, we assume one more output pass if EOI not
  172572. * yet reached, but no more passes if EOI has been reached.
  172573. */
  172574. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172575. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172576. }
  172577. }
  172578. }
  172579. /*
  172580. * Finish up at end of an output pass.
  172581. */
  172582. METHODDEF(void)
  172583. finish_output_pass (j_decompress_ptr cinfo)
  172584. {
  172585. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172586. if (cinfo->quantize_colors)
  172587. (*cinfo->cquantize->finish_pass) (cinfo);
  172588. master->pass_number++;
  172589. }
  172590. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172591. /*
  172592. * Switch to a new external colormap between output passes.
  172593. */
  172594. GLOBAL(void)
  172595. jpeg_new_colormap (j_decompress_ptr cinfo)
  172596. {
  172597. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172598. /* Prevent application from calling me at wrong times */
  172599. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172600. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172601. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172602. cinfo->colormap != NULL) {
  172603. /* Select 2-pass quantizer for external colormap use */
  172604. cinfo->cquantize = master->quantizer_2pass;
  172605. /* Notify quantizer of colormap change */
  172606. (*cinfo->cquantize->new_color_map) (cinfo);
  172607. master->pub.is_dummy_pass = FALSE; /* just in case */
  172608. } else
  172609. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172610. }
  172611. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172612. /*
  172613. * Initialize master decompression control and select active modules.
  172614. * This is performed at the start of jpeg_start_decompress.
  172615. */
  172616. GLOBAL(void)
  172617. jinit_master_decompress (j_decompress_ptr cinfo)
  172618. {
  172619. my_master_ptr6 master;
  172620. master = (my_master_ptr6)
  172621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172622. SIZEOF(my_decomp_master));
  172623. cinfo->master = (struct jpeg_decomp_master *) master;
  172624. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172625. master->pub.finish_output_pass = finish_output_pass;
  172626. master->pub.is_dummy_pass = FALSE;
  172627. master_selection(cinfo);
  172628. }
  172629. /*** End of inlined file: jdmaster.c ***/
  172630. #undef FIX
  172631. /*** Start of inlined file: jdmerge.c ***/
  172632. #define JPEG_INTERNALS
  172633. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172634. /* Private subobject */
  172635. typedef struct {
  172636. struct jpeg_upsampler pub; /* public fields */
  172637. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172638. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172639. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172640. JSAMPARRAY output_buf));
  172641. /* Private state for YCC->RGB conversion */
  172642. int * Cr_r_tab; /* => table for Cr to R conversion */
  172643. int * Cb_b_tab; /* => table for Cb to B conversion */
  172644. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172645. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172646. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172647. * We need a "spare" row buffer to hold the second output row if the
  172648. * application provides just a one-row buffer; we also use the spare
  172649. * to discard the dummy last row if the image height is odd.
  172650. */
  172651. JSAMPROW spare_row;
  172652. boolean spare_full; /* T if spare buffer is occupied */
  172653. JDIMENSION out_row_width; /* samples per output row */
  172654. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172655. } my_upsampler;
  172656. typedef my_upsampler * my_upsample_ptr;
  172657. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172658. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172659. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172660. /*
  172661. * Initialize tables for YCC->RGB colorspace conversion.
  172662. * This is taken directly from jdcolor.c; see that file for more info.
  172663. */
  172664. LOCAL(void)
  172665. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172666. {
  172667. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172668. int i;
  172669. INT32 x;
  172670. SHIFT_TEMPS
  172671. upsample->Cr_r_tab = (int *)
  172672. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172673. (MAXJSAMPLE+1) * SIZEOF(int));
  172674. upsample->Cb_b_tab = (int *)
  172675. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172676. (MAXJSAMPLE+1) * SIZEOF(int));
  172677. upsample->Cr_g_tab = (INT32 *)
  172678. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172679. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172680. upsample->Cb_g_tab = (INT32 *)
  172681. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172682. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172683. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172684. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172685. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172686. /* Cr=>R value is nearest int to 1.40200 * x */
  172687. upsample->Cr_r_tab[i] = (int)
  172688. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172689. /* Cb=>B value is nearest int to 1.77200 * x */
  172690. upsample->Cb_b_tab[i] = (int)
  172691. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172692. /* Cr=>G value is scaled-up -0.71414 * x */
  172693. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172694. /* Cb=>G value is scaled-up -0.34414 * x */
  172695. /* We also add in ONE_HALF so that need not do it in inner loop */
  172696. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172697. }
  172698. }
  172699. /*
  172700. * Initialize for an upsampling pass.
  172701. */
  172702. METHODDEF(void)
  172703. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172704. {
  172705. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172706. /* Mark the spare buffer empty */
  172707. upsample->spare_full = FALSE;
  172708. /* Initialize total-height counter for detecting bottom of image */
  172709. upsample->rows_to_go = cinfo->output_height;
  172710. }
  172711. /*
  172712. * Control routine to do upsampling (and color conversion).
  172713. *
  172714. * The control routine just handles the row buffering considerations.
  172715. */
  172716. METHODDEF(void)
  172717. merged_2v_upsample (j_decompress_ptr cinfo,
  172718. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172719. JDIMENSION,
  172720. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172721. JDIMENSION out_rows_avail)
  172722. /* 2:1 vertical sampling case: may need a spare row. */
  172723. {
  172724. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172725. JSAMPROW work_ptrs[2];
  172726. JDIMENSION num_rows; /* number of rows returned to caller */
  172727. if (upsample->spare_full) {
  172728. /* If we have a spare row saved from a previous cycle, just return it. */
  172729. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172730. 1, upsample->out_row_width);
  172731. num_rows = 1;
  172732. upsample->spare_full = FALSE;
  172733. } else {
  172734. /* Figure number of rows to return to caller. */
  172735. num_rows = 2;
  172736. /* Not more than the distance to the end of the image. */
  172737. if (num_rows > upsample->rows_to_go)
  172738. num_rows = upsample->rows_to_go;
  172739. /* And not more than what the client can accept: */
  172740. out_rows_avail -= *out_row_ctr;
  172741. if (num_rows > out_rows_avail)
  172742. num_rows = out_rows_avail;
  172743. /* Create output pointer array for upsampler. */
  172744. work_ptrs[0] = output_buf[*out_row_ctr];
  172745. if (num_rows > 1) {
  172746. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172747. } else {
  172748. work_ptrs[1] = upsample->spare_row;
  172749. upsample->spare_full = TRUE;
  172750. }
  172751. /* Now do the upsampling. */
  172752. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172753. }
  172754. /* Adjust counts */
  172755. *out_row_ctr += num_rows;
  172756. upsample->rows_to_go -= num_rows;
  172757. /* When the buffer is emptied, declare this input row group consumed */
  172758. if (! upsample->spare_full)
  172759. (*in_row_group_ctr)++;
  172760. }
  172761. METHODDEF(void)
  172762. merged_1v_upsample (j_decompress_ptr cinfo,
  172763. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172764. JDIMENSION,
  172765. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172766. JDIMENSION)
  172767. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172768. {
  172769. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172770. /* Just do the upsampling. */
  172771. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172772. output_buf + *out_row_ctr);
  172773. /* Adjust counts */
  172774. (*out_row_ctr)++;
  172775. (*in_row_group_ctr)++;
  172776. }
  172777. /*
  172778. * These are the routines invoked by the control routines to do
  172779. * the actual upsampling/conversion. One row group is processed per call.
  172780. *
  172781. * Note: since we may be writing directly into application-supplied buffers,
  172782. * we have to be honest about the output width; we can't assume the buffer
  172783. * has been rounded up to an even width.
  172784. */
  172785. /*
  172786. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172787. */
  172788. METHODDEF(void)
  172789. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172790. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172791. JSAMPARRAY output_buf)
  172792. {
  172793. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172794. register int y, cred, cgreen, cblue;
  172795. int cb, cr;
  172796. register JSAMPROW outptr;
  172797. JSAMPROW inptr0, inptr1, inptr2;
  172798. JDIMENSION col;
  172799. /* copy these pointers into registers if possible */
  172800. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172801. int * Crrtab = upsample->Cr_r_tab;
  172802. int * Cbbtab = upsample->Cb_b_tab;
  172803. INT32 * Crgtab = upsample->Cr_g_tab;
  172804. INT32 * Cbgtab = upsample->Cb_g_tab;
  172805. SHIFT_TEMPS
  172806. inptr0 = input_buf[0][in_row_group_ctr];
  172807. inptr1 = input_buf[1][in_row_group_ctr];
  172808. inptr2 = input_buf[2][in_row_group_ctr];
  172809. outptr = output_buf[0];
  172810. /* Loop for each pair of output pixels */
  172811. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172812. /* Do the chroma part of the calculation */
  172813. cb = GETJSAMPLE(*inptr1++);
  172814. cr = GETJSAMPLE(*inptr2++);
  172815. cred = Crrtab[cr];
  172816. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172817. cblue = Cbbtab[cb];
  172818. /* Fetch 2 Y values and emit 2 pixels */
  172819. y = GETJSAMPLE(*inptr0++);
  172820. outptr[RGB_RED] = range_limit[y + cred];
  172821. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172822. outptr[RGB_BLUE] = range_limit[y + cblue];
  172823. outptr += RGB_PIXELSIZE;
  172824. y = GETJSAMPLE(*inptr0++);
  172825. outptr[RGB_RED] = range_limit[y + cred];
  172826. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172827. outptr[RGB_BLUE] = range_limit[y + cblue];
  172828. outptr += RGB_PIXELSIZE;
  172829. }
  172830. /* If image width is odd, do the last output column separately */
  172831. if (cinfo->output_width & 1) {
  172832. cb = GETJSAMPLE(*inptr1);
  172833. cr = GETJSAMPLE(*inptr2);
  172834. cred = Crrtab[cr];
  172835. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172836. cblue = Cbbtab[cb];
  172837. y = GETJSAMPLE(*inptr0);
  172838. outptr[RGB_RED] = range_limit[y + cred];
  172839. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172840. outptr[RGB_BLUE] = range_limit[y + cblue];
  172841. }
  172842. }
  172843. /*
  172844. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172845. */
  172846. METHODDEF(void)
  172847. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172848. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172849. JSAMPARRAY output_buf)
  172850. {
  172851. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172852. register int y, cred, cgreen, cblue;
  172853. int cb, cr;
  172854. register JSAMPROW outptr0, outptr1;
  172855. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172856. JDIMENSION col;
  172857. /* copy these pointers into registers if possible */
  172858. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172859. int * Crrtab = upsample->Cr_r_tab;
  172860. int * Cbbtab = upsample->Cb_b_tab;
  172861. INT32 * Crgtab = upsample->Cr_g_tab;
  172862. INT32 * Cbgtab = upsample->Cb_g_tab;
  172863. SHIFT_TEMPS
  172864. inptr00 = input_buf[0][in_row_group_ctr*2];
  172865. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172866. inptr1 = input_buf[1][in_row_group_ctr];
  172867. inptr2 = input_buf[2][in_row_group_ctr];
  172868. outptr0 = output_buf[0];
  172869. outptr1 = output_buf[1];
  172870. /* Loop for each group of output pixels */
  172871. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172872. /* Do the chroma part of the calculation */
  172873. cb = GETJSAMPLE(*inptr1++);
  172874. cr = GETJSAMPLE(*inptr2++);
  172875. cred = Crrtab[cr];
  172876. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172877. cblue = Cbbtab[cb];
  172878. /* Fetch 4 Y values and emit 4 pixels */
  172879. y = GETJSAMPLE(*inptr00++);
  172880. outptr0[RGB_RED] = range_limit[y + cred];
  172881. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172882. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172883. outptr0 += RGB_PIXELSIZE;
  172884. y = GETJSAMPLE(*inptr00++);
  172885. outptr0[RGB_RED] = range_limit[y + cred];
  172886. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172887. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172888. outptr0 += RGB_PIXELSIZE;
  172889. y = GETJSAMPLE(*inptr01++);
  172890. outptr1[RGB_RED] = range_limit[y + cred];
  172891. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172892. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172893. outptr1 += RGB_PIXELSIZE;
  172894. y = GETJSAMPLE(*inptr01++);
  172895. outptr1[RGB_RED] = range_limit[y + cred];
  172896. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172897. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172898. outptr1 += RGB_PIXELSIZE;
  172899. }
  172900. /* If image width is odd, do the last output column separately */
  172901. if (cinfo->output_width & 1) {
  172902. cb = GETJSAMPLE(*inptr1);
  172903. cr = GETJSAMPLE(*inptr2);
  172904. cred = Crrtab[cr];
  172905. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172906. cblue = Cbbtab[cb];
  172907. y = GETJSAMPLE(*inptr00);
  172908. outptr0[RGB_RED] = range_limit[y + cred];
  172909. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172910. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172911. y = GETJSAMPLE(*inptr01);
  172912. outptr1[RGB_RED] = range_limit[y + cred];
  172913. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172914. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172915. }
  172916. }
  172917. /*
  172918. * Module initialization routine for merged upsampling/color conversion.
  172919. *
  172920. * NB: this is called under the conditions determined by use_merged_upsample()
  172921. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172922. * of this module; no safety checks are made here.
  172923. */
  172924. GLOBAL(void)
  172925. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172926. {
  172927. my_upsample_ptr upsample;
  172928. upsample = (my_upsample_ptr)
  172929. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172930. SIZEOF(my_upsampler));
  172931. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172932. upsample->pub.start_pass = start_pass_merged_upsample;
  172933. upsample->pub.need_context_rows = FALSE;
  172934. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172935. if (cinfo->max_v_samp_factor == 2) {
  172936. upsample->pub.upsample = merged_2v_upsample;
  172937. upsample->upmethod = h2v2_merged_upsample;
  172938. /* Allocate a spare row buffer */
  172939. upsample->spare_row = (JSAMPROW)
  172940. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172941. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172942. } else {
  172943. upsample->pub.upsample = merged_1v_upsample;
  172944. upsample->upmethod = h2v1_merged_upsample;
  172945. /* No spare row needed */
  172946. upsample->spare_row = NULL;
  172947. }
  172948. build_ycc_rgb_table2(cinfo);
  172949. }
  172950. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172951. /*** End of inlined file: jdmerge.c ***/
  172952. #undef ASSIGN_STATE
  172953. /*** Start of inlined file: jdphuff.c ***/
  172954. #define JPEG_INTERNALS
  172955. #ifdef D_PROGRESSIVE_SUPPORTED
  172956. /*
  172957. * Expanded entropy decoder object for progressive Huffman decoding.
  172958. *
  172959. * The savable_state subrecord contains fields that change within an MCU,
  172960. * but must not be updated permanently until we complete the MCU.
  172961. */
  172962. typedef struct {
  172963. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172964. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172965. } savable_state3;
  172966. /* This macro is to work around compilers with missing or broken
  172967. * structure assignment. You'll need to fix this code if you have
  172968. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172969. */
  172970. #ifndef NO_STRUCT_ASSIGN
  172971. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172972. #else
  172973. #if MAX_COMPS_IN_SCAN == 4
  172974. #define ASSIGN_STATE(dest,src) \
  172975. ((dest).EOBRUN = (src).EOBRUN, \
  172976. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172977. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172978. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172979. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172980. #endif
  172981. #endif
  172982. typedef struct {
  172983. struct jpeg_entropy_decoder pub; /* public fields */
  172984. /* These fields are loaded into local variables at start of each MCU.
  172985. * In case of suspension, we exit WITHOUT updating them.
  172986. */
  172987. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172988. savable_state3 saved; /* Other state at start of MCU */
  172989. /* These fields are NOT loaded into local working state. */
  172990. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172991. /* Pointers to derived tables (these workspaces have image lifespan) */
  172992. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172993. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172994. } phuff_entropy_decoder;
  172995. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172996. /* Forward declarations */
  172997. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172998. JBLOCKROW *MCU_data));
  172999. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173000. JBLOCKROW *MCU_data));
  173001. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173002. JBLOCKROW *MCU_data));
  173003. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173004. JBLOCKROW *MCU_data));
  173005. /*
  173006. * Initialize for a Huffman-compressed scan.
  173007. */
  173008. METHODDEF(void)
  173009. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173010. {
  173011. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173012. boolean is_DC_band, bad;
  173013. int ci, coefi, tbl;
  173014. int *coef_bit_ptr;
  173015. jpeg_component_info * compptr;
  173016. is_DC_band = (cinfo->Ss == 0);
  173017. /* Validate scan parameters */
  173018. bad = FALSE;
  173019. if (is_DC_band) {
  173020. if (cinfo->Se != 0)
  173021. bad = TRUE;
  173022. } else {
  173023. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173024. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173025. bad = TRUE;
  173026. /* AC scans may have only one component */
  173027. if (cinfo->comps_in_scan != 1)
  173028. bad = TRUE;
  173029. }
  173030. if (cinfo->Ah != 0) {
  173031. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173032. if (cinfo->Al != cinfo->Ah-1)
  173033. bad = TRUE;
  173034. }
  173035. if (cinfo->Al > 13) /* need not check for < 0 */
  173036. bad = TRUE;
  173037. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173038. * but the spec doesn't say so, and we try to be liberal about what we
  173039. * accept. Note: large Al values could result in out-of-range DC
  173040. * coefficients during early scans, leading to bizarre displays due to
  173041. * overflows in the IDCT math. But we won't crash.
  173042. */
  173043. if (bad)
  173044. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173045. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173046. /* Update progression status, and verify that scan order is legal.
  173047. * Note that inter-scan inconsistencies are treated as warnings
  173048. * not fatal errors ... not clear if this is right way to behave.
  173049. */
  173050. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173051. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173052. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173053. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173054. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173055. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173056. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173057. if (cinfo->Ah != expected)
  173058. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173059. coef_bit_ptr[coefi] = cinfo->Al;
  173060. }
  173061. }
  173062. /* Select MCU decoding routine */
  173063. if (cinfo->Ah == 0) {
  173064. if (is_DC_band)
  173065. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173066. else
  173067. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173068. } else {
  173069. if (is_DC_band)
  173070. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173071. else
  173072. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173073. }
  173074. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173075. compptr = cinfo->cur_comp_info[ci];
  173076. /* Make sure requested tables are present, and compute derived tables.
  173077. * We may build same derived table more than once, but it's not expensive.
  173078. */
  173079. if (is_DC_band) {
  173080. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173081. tbl = compptr->dc_tbl_no;
  173082. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173083. & entropy->derived_tbls[tbl]);
  173084. }
  173085. } else {
  173086. tbl = compptr->ac_tbl_no;
  173087. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173088. & entropy->derived_tbls[tbl]);
  173089. /* remember the single active table */
  173090. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173091. }
  173092. /* Initialize DC predictions to 0 */
  173093. entropy->saved.last_dc_val[ci] = 0;
  173094. }
  173095. /* Initialize bitread state variables */
  173096. entropy->bitstate.bits_left = 0;
  173097. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173098. entropy->pub.insufficient_data = FALSE;
  173099. /* Initialize private state variables */
  173100. entropy->saved.EOBRUN = 0;
  173101. /* Initialize restart counter */
  173102. entropy->restarts_to_go = cinfo->restart_interval;
  173103. }
  173104. /*
  173105. * Check for a restart marker & resynchronize decoder.
  173106. * Returns FALSE if must suspend.
  173107. */
  173108. LOCAL(boolean)
  173109. process_restartp (j_decompress_ptr cinfo)
  173110. {
  173111. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173112. int ci;
  173113. /* Throw away any unused bits remaining in bit buffer; */
  173114. /* include any full bytes in next_marker's count of discarded bytes */
  173115. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173116. entropy->bitstate.bits_left = 0;
  173117. /* Advance past the RSTn marker */
  173118. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173119. return FALSE;
  173120. /* Re-initialize DC predictions to 0 */
  173121. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173122. entropy->saved.last_dc_val[ci] = 0;
  173123. /* Re-init EOB run count, too */
  173124. entropy->saved.EOBRUN = 0;
  173125. /* Reset restart counter */
  173126. entropy->restarts_to_go = cinfo->restart_interval;
  173127. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173128. * against a marker. In that case we will end up treating the next data
  173129. * segment as empty, and we can avoid producing bogus output pixels by
  173130. * leaving the flag set.
  173131. */
  173132. if (cinfo->unread_marker == 0)
  173133. entropy->pub.insufficient_data = FALSE;
  173134. return TRUE;
  173135. }
  173136. /*
  173137. * Huffman MCU decoding.
  173138. * Each of these routines decodes and returns one MCU's worth of
  173139. * Huffman-compressed coefficients.
  173140. * The coefficients are reordered from zigzag order into natural array order,
  173141. * but are not dequantized.
  173142. *
  173143. * The i'th block of the MCU is stored into the block pointed to by
  173144. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173145. *
  173146. * We return FALSE if data source requested suspension. In that case no
  173147. * changes have been made to permanent state. (Exception: some output
  173148. * coefficients may already have been assigned. This is harmless for
  173149. * spectral selection, since we'll just re-assign them on the next call.
  173150. * Successive approximation AC refinement has to be more careful, however.)
  173151. */
  173152. /*
  173153. * MCU decoding for DC initial scan (either spectral selection,
  173154. * or first pass of successive approximation).
  173155. */
  173156. METHODDEF(boolean)
  173157. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173158. {
  173159. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173160. int Al = cinfo->Al;
  173161. register int s, r;
  173162. int blkn, ci;
  173163. JBLOCKROW block;
  173164. BITREAD_STATE_VARS;
  173165. savable_state3 state;
  173166. d_derived_tbl * tbl;
  173167. jpeg_component_info * compptr;
  173168. /* Process restart marker if needed; may have to suspend */
  173169. if (cinfo->restart_interval) {
  173170. if (entropy->restarts_to_go == 0)
  173171. if (! process_restartp(cinfo))
  173172. return FALSE;
  173173. }
  173174. /* If we've run out of data, just leave the MCU set to zeroes.
  173175. * This way, we return uniform gray for the remainder of the segment.
  173176. */
  173177. if (! entropy->pub.insufficient_data) {
  173178. /* Load up working state */
  173179. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173180. ASSIGN_STATE(state, entropy->saved);
  173181. /* Outer loop handles each block in the MCU */
  173182. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173183. block = MCU_data[blkn];
  173184. ci = cinfo->MCU_membership[blkn];
  173185. compptr = cinfo->cur_comp_info[ci];
  173186. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173187. /* Decode a single block's worth of coefficients */
  173188. /* Section F.2.2.1: decode the DC coefficient difference */
  173189. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173190. if (s) {
  173191. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173192. r = GET_BITS(s);
  173193. s = HUFF_EXTEND(r, s);
  173194. }
  173195. /* Convert DC difference to actual value, update last_dc_val */
  173196. s += state.last_dc_val[ci];
  173197. state.last_dc_val[ci] = s;
  173198. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173199. (*block)[0] = (JCOEF) (s << Al);
  173200. }
  173201. /* Completed MCU, so update state */
  173202. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173203. ASSIGN_STATE(entropy->saved, state);
  173204. }
  173205. /* Account for restart interval (no-op if not using restarts) */
  173206. entropy->restarts_to_go--;
  173207. return TRUE;
  173208. }
  173209. /*
  173210. * MCU decoding for AC initial scan (either spectral selection,
  173211. * or first pass of successive approximation).
  173212. */
  173213. METHODDEF(boolean)
  173214. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173215. {
  173216. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173217. int Se = cinfo->Se;
  173218. int Al = cinfo->Al;
  173219. register int s, k, r;
  173220. unsigned int EOBRUN;
  173221. JBLOCKROW block;
  173222. BITREAD_STATE_VARS;
  173223. d_derived_tbl * tbl;
  173224. /* Process restart marker if needed; may have to suspend */
  173225. if (cinfo->restart_interval) {
  173226. if (entropy->restarts_to_go == 0)
  173227. if (! process_restartp(cinfo))
  173228. return FALSE;
  173229. }
  173230. /* If we've run out of data, just leave the MCU set to zeroes.
  173231. * This way, we return uniform gray for the remainder of the segment.
  173232. */
  173233. if (! entropy->pub.insufficient_data) {
  173234. /* Load up working state.
  173235. * We can avoid loading/saving bitread state if in an EOB run.
  173236. */
  173237. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173238. /* There is always only one block per MCU */
  173239. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173240. EOBRUN--; /* ...process it now (we do nothing) */
  173241. else {
  173242. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173243. block = MCU_data[0];
  173244. tbl = entropy->ac_derived_tbl;
  173245. for (k = cinfo->Ss; k <= Se; k++) {
  173246. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173247. r = s >> 4;
  173248. s &= 15;
  173249. if (s) {
  173250. k += r;
  173251. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173252. r = GET_BITS(s);
  173253. s = HUFF_EXTEND(r, s);
  173254. /* Scale and output coefficient in natural (dezigzagged) order */
  173255. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173256. } else {
  173257. if (r == 15) { /* ZRL */
  173258. k += 15; /* skip 15 zeroes in band */
  173259. } else { /* EOBr, run length is 2^r + appended bits */
  173260. EOBRUN = 1 << r;
  173261. if (r) { /* EOBr, r > 0 */
  173262. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173263. r = GET_BITS(r);
  173264. EOBRUN += r;
  173265. }
  173266. EOBRUN--; /* this band is processed at this moment */
  173267. break; /* force end-of-band */
  173268. }
  173269. }
  173270. }
  173271. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173272. }
  173273. /* Completed MCU, so update state */
  173274. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173275. }
  173276. /* Account for restart interval (no-op if not using restarts) */
  173277. entropy->restarts_to_go--;
  173278. return TRUE;
  173279. }
  173280. /*
  173281. * MCU decoding for DC successive approximation refinement scan.
  173282. * Note: we assume such scans can be multi-component, although the spec
  173283. * is not very clear on the point.
  173284. */
  173285. METHODDEF(boolean)
  173286. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173287. {
  173288. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173289. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173290. int blkn;
  173291. JBLOCKROW block;
  173292. BITREAD_STATE_VARS;
  173293. /* Process restart marker if needed; may have to suspend */
  173294. if (cinfo->restart_interval) {
  173295. if (entropy->restarts_to_go == 0)
  173296. if (! process_restartp(cinfo))
  173297. return FALSE;
  173298. }
  173299. /* Not worth the cycles to check insufficient_data here,
  173300. * since we will not change the data anyway if we read zeroes.
  173301. */
  173302. /* Load up working state */
  173303. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173304. /* Outer loop handles each block in the MCU */
  173305. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173306. block = MCU_data[blkn];
  173307. /* Encoded data is simply the next bit of the two's-complement DC value */
  173308. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173309. if (GET_BITS(1))
  173310. (*block)[0] |= p1;
  173311. /* Note: since we use |=, repeating the assignment later is safe */
  173312. }
  173313. /* Completed MCU, so update state */
  173314. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173315. /* Account for restart interval (no-op if not using restarts) */
  173316. entropy->restarts_to_go--;
  173317. return TRUE;
  173318. }
  173319. /*
  173320. * MCU decoding for AC successive approximation refinement scan.
  173321. */
  173322. METHODDEF(boolean)
  173323. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173324. {
  173325. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173326. int Se = cinfo->Se;
  173327. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173328. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173329. register int s, k, r;
  173330. unsigned int EOBRUN;
  173331. JBLOCKROW block;
  173332. JCOEFPTR thiscoef;
  173333. BITREAD_STATE_VARS;
  173334. d_derived_tbl * tbl;
  173335. int num_newnz;
  173336. int newnz_pos[DCTSIZE2];
  173337. /* Process restart marker if needed; may have to suspend */
  173338. if (cinfo->restart_interval) {
  173339. if (entropy->restarts_to_go == 0)
  173340. if (! process_restartp(cinfo))
  173341. return FALSE;
  173342. }
  173343. /* If we've run out of data, don't modify the MCU.
  173344. */
  173345. if (! entropy->pub.insufficient_data) {
  173346. /* Load up working state */
  173347. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173348. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173349. /* There is always only one block per MCU */
  173350. block = MCU_data[0];
  173351. tbl = entropy->ac_derived_tbl;
  173352. /* If we are forced to suspend, we must undo the assignments to any newly
  173353. * nonzero coefficients in the block, because otherwise we'd get confused
  173354. * next time about which coefficients were already nonzero.
  173355. * But we need not undo addition of bits to already-nonzero coefficients;
  173356. * instead, we can test the current bit to see if we already did it.
  173357. */
  173358. num_newnz = 0;
  173359. /* initialize coefficient loop counter to start of band */
  173360. k = cinfo->Ss;
  173361. if (EOBRUN == 0) {
  173362. for (; k <= Se; k++) {
  173363. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173364. r = s >> 4;
  173365. s &= 15;
  173366. if (s) {
  173367. if (s != 1) /* size of new coef should always be 1 */
  173368. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173369. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173370. if (GET_BITS(1))
  173371. s = p1; /* newly nonzero coef is positive */
  173372. else
  173373. s = m1; /* newly nonzero coef is negative */
  173374. } else {
  173375. if (r != 15) {
  173376. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173377. if (r) {
  173378. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173379. r = GET_BITS(r);
  173380. EOBRUN += r;
  173381. }
  173382. break; /* rest of block is handled by EOB logic */
  173383. }
  173384. /* note s = 0 for processing ZRL */
  173385. }
  173386. /* Advance over already-nonzero coefs and r still-zero coefs,
  173387. * appending correction bits to the nonzeroes. A correction bit is 1
  173388. * if the absolute value of the coefficient must be increased.
  173389. */
  173390. do {
  173391. thiscoef = *block + jpeg_natural_order[k];
  173392. if (*thiscoef != 0) {
  173393. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173394. if (GET_BITS(1)) {
  173395. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173396. if (*thiscoef >= 0)
  173397. *thiscoef += p1;
  173398. else
  173399. *thiscoef += m1;
  173400. }
  173401. }
  173402. } else {
  173403. if (--r < 0)
  173404. break; /* reached target zero coefficient */
  173405. }
  173406. k++;
  173407. } while (k <= Se);
  173408. if (s) {
  173409. int pos = jpeg_natural_order[k];
  173410. /* Output newly nonzero coefficient */
  173411. (*block)[pos] = (JCOEF) s;
  173412. /* Remember its position in case we have to suspend */
  173413. newnz_pos[num_newnz++] = pos;
  173414. }
  173415. }
  173416. }
  173417. if (EOBRUN > 0) {
  173418. /* Scan any remaining coefficient positions after the end-of-band
  173419. * (the last newly nonzero coefficient, if any). Append a correction
  173420. * bit to each already-nonzero coefficient. A correction bit is 1
  173421. * if the absolute value of the coefficient must be increased.
  173422. */
  173423. for (; k <= Se; k++) {
  173424. thiscoef = *block + jpeg_natural_order[k];
  173425. if (*thiscoef != 0) {
  173426. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173427. if (GET_BITS(1)) {
  173428. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173429. if (*thiscoef >= 0)
  173430. *thiscoef += p1;
  173431. else
  173432. *thiscoef += m1;
  173433. }
  173434. }
  173435. }
  173436. }
  173437. /* Count one block completed in EOB run */
  173438. EOBRUN--;
  173439. }
  173440. /* Completed MCU, so update state */
  173441. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173442. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173443. }
  173444. /* Account for restart interval (no-op if not using restarts) */
  173445. entropy->restarts_to_go--;
  173446. return TRUE;
  173447. undoit:
  173448. /* Re-zero any output coefficients that we made newly nonzero */
  173449. while (num_newnz > 0)
  173450. (*block)[newnz_pos[--num_newnz]] = 0;
  173451. return FALSE;
  173452. }
  173453. /*
  173454. * Module initialization routine for progressive Huffman entropy decoding.
  173455. */
  173456. GLOBAL(void)
  173457. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173458. {
  173459. phuff_entropy_ptr2 entropy;
  173460. int *coef_bit_ptr;
  173461. int ci, i;
  173462. entropy = (phuff_entropy_ptr2)
  173463. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173464. SIZEOF(phuff_entropy_decoder));
  173465. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173466. entropy->pub.start_pass = start_pass_phuff_decoder;
  173467. /* Mark derived tables unallocated */
  173468. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173469. entropy->derived_tbls[i] = NULL;
  173470. }
  173471. /* Create progression status table */
  173472. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173473. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173474. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173475. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173476. for (ci = 0; ci < cinfo->num_components; ci++)
  173477. for (i = 0; i < DCTSIZE2; i++)
  173478. *coef_bit_ptr++ = -1;
  173479. }
  173480. #endif /* D_PROGRESSIVE_SUPPORTED */
  173481. /*** End of inlined file: jdphuff.c ***/
  173482. /*** Start of inlined file: jdpostct.c ***/
  173483. #define JPEG_INTERNALS
  173484. /* Private buffer controller object */
  173485. typedef struct {
  173486. struct jpeg_d_post_controller pub; /* public fields */
  173487. /* Color quantization source buffer: this holds output data from
  173488. * the upsample/color conversion step to be passed to the quantizer.
  173489. * For two-pass color quantization, we need a full-image buffer;
  173490. * for one-pass operation, a strip buffer is sufficient.
  173491. */
  173492. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173493. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173494. JDIMENSION strip_height; /* buffer size in rows */
  173495. /* for two-pass mode only: */
  173496. JDIMENSION starting_row; /* row # of first row in current strip */
  173497. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173498. } my_post_controller;
  173499. typedef my_post_controller * my_post_ptr;
  173500. /* Forward declarations */
  173501. METHODDEF(void) post_process_1pass
  173502. JPP((j_decompress_ptr cinfo,
  173503. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173504. JDIMENSION in_row_groups_avail,
  173505. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173506. JDIMENSION out_rows_avail));
  173507. #ifdef QUANT_2PASS_SUPPORTED
  173508. METHODDEF(void) post_process_prepass
  173509. JPP((j_decompress_ptr cinfo,
  173510. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173511. JDIMENSION in_row_groups_avail,
  173512. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173513. JDIMENSION out_rows_avail));
  173514. METHODDEF(void) post_process_2pass
  173515. JPP((j_decompress_ptr cinfo,
  173516. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173517. JDIMENSION in_row_groups_avail,
  173518. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173519. JDIMENSION out_rows_avail));
  173520. #endif
  173521. /*
  173522. * Initialize for a processing pass.
  173523. */
  173524. METHODDEF(void)
  173525. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173526. {
  173527. my_post_ptr post = (my_post_ptr) cinfo->post;
  173528. switch (pass_mode) {
  173529. case JBUF_PASS_THRU:
  173530. if (cinfo->quantize_colors) {
  173531. /* Single-pass processing with color quantization. */
  173532. post->pub.post_process_data = post_process_1pass;
  173533. /* We could be doing buffered-image output before starting a 2-pass
  173534. * color quantization; in that case, jinit_d_post_controller did not
  173535. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173536. */
  173537. if (post->buffer == NULL) {
  173538. post->buffer = (*cinfo->mem->access_virt_sarray)
  173539. ((j_common_ptr) cinfo, post->whole_image,
  173540. (JDIMENSION) 0, post->strip_height, TRUE);
  173541. }
  173542. } else {
  173543. /* For single-pass processing without color quantization,
  173544. * I have no work to do; just call the upsampler directly.
  173545. */
  173546. post->pub.post_process_data = cinfo->upsample->upsample;
  173547. }
  173548. break;
  173549. #ifdef QUANT_2PASS_SUPPORTED
  173550. case JBUF_SAVE_AND_PASS:
  173551. /* First pass of 2-pass quantization */
  173552. if (post->whole_image == NULL)
  173553. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173554. post->pub.post_process_data = post_process_prepass;
  173555. break;
  173556. case JBUF_CRANK_DEST:
  173557. /* Second pass of 2-pass quantization */
  173558. if (post->whole_image == NULL)
  173559. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173560. post->pub.post_process_data = post_process_2pass;
  173561. break;
  173562. #endif /* QUANT_2PASS_SUPPORTED */
  173563. default:
  173564. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173565. break;
  173566. }
  173567. post->starting_row = post->next_row = 0;
  173568. }
  173569. /*
  173570. * Process some data in the one-pass (strip buffer) case.
  173571. * This is used for color precision reduction as well as one-pass quantization.
  173572. */
  173573. METHODDEF(void)
  173574. post_process_1pass (j_decompress_ptr cinfo,
  173575. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173576. JDIMENSION in_row_groups_avail,
  173577. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173578. JDIMENSION out_rows_avail)
  173579. {
  173580. my_post_ptr post = (my_post_ptr) cinfo->post;
  173581. JDIMENSION num_rows, max_rows;
  173582. /* Fill the buffer, but not more than what we can dump out in one go. */
  173583. /* Note we rely on the upsampler to detect bottom of image. */
  173584. max_rows = out_rows_avail - *out_row_ctr;
  173585. if (max_rows > post->strip_height)
  173586. max_rows = post->strip_height;
  173587. num_rows = 0;
  173588. (*cinfo->upsample->upsample) (cinfo,
  173589. input_buf, in_row_group_ctr, in_row_groups_avail,
  173590. post->buffer, &num_rows, max_rows);
  173591. /* Quantize and emit data. */
  173592. (*cinfo->cquantize->color_quantize) (cinfo,
  173593. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173594. *out_row_ctr += num_rows;
  173595. }
  173596. #ifdef QUANT_2PASS_SUPPORTED
  173597. /*
  173598. * Process some data in the first pass of 2-pass quantization.
  173599. */
  173600. METHODDEF(void)
  173601. post_process_prepass (j_decompress_ptr cinfo,
  173602. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173603. JDIMENSION in_row_groups_avail,
  173604. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173605. JDIMENSION)
  173606. {
  173607. my_post_ptr post = (my_post_ptr) cinfo->post;
  173608. JDIMENSION old_next_row, num_rows;
  173609. /* Reposition virtual buffer if at start of strip. */
  173610. if (post->next_row == 0) {
  173611. post->buffer = (*cinfo->mem->access_virt_sarray)
  173612. ((j_common_ptr) cinfo, post->whole_image,
  173613. post->starting_row, post->strip_height, TRUE);
  173614. }
  173615. /* Upsample some data (up to a strip height's worth). */
  173616. old_next_row = post->next_row;
  173617. (*cinfo->upsample->upsample) (cinfo,
  173618. input_buf, in_row_group_ctr, in_row_groups_avail,
  173619. post->buffer, &post->next_row, post->strip_height);
  173620. /* Allow quantizer to scan new data. No data is emitted, */
  173621. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173622. if (post->next_row > old_next_row) {
  173623. num_rows = post->next_row - old_next_row;
  173624. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173625. (JSAMPARRAY) NULL, (int) num_rows);
  173626. *out_row_ctr += num_rows;
  173627. }
  173628. /* Advance if we filled the strip. */
  173629. if (post->next_row >= post->strip_height) {
  173630. post->starting_row += post->strip_height;
  173631. post->next_row = 0;
  173632. }
  173633. }
  173634. /*
  173635. * Process some data in the second pass of 2-pass quantization.
  173636. */
  173637. METHODDEF(void)
  173638. post_process_2pass (j_decompress_ptr cinfo,
  173639. JSAMPIMAGE, JDIMENSION *,
  173640. JDIMENSION,
  173641. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173642. JDIMENSION out_rows_avail)
  173643. {
  173644. my_post_ptr post = (my_post_ptr) cinfo->post;
  173645. JDIMENSION num_rows, max_rows;
  173646. /* Reposition virtual buffer if at start of strip. */
  173647. if (post->next_row == 0) {
  173648. post->buffer = (*cinfo->mem->access_virt_sarray)
  173649. ((j_common_ptr) cinfo, post->whole_image,
  173650. post->starting_row, post->strip_height, FALSE);
  173651. }
  173652. /* Determine number of rows to emit. */
  173653. num_rows = post->strip_height - post->next_row; /* available in strip */
  173654. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173655. if (num_rows > max_rows)
  173656. num_rows = max_rows;
  173657. /* We have to check bottom of image here, can't depend on upsampler. */
  173658. max_rows = cinfo->output_height - post->starting_row;
  173659. if (num_rows > max_rows)
  173660. num_rows = max_rows;
  173661. /* Quantize and emit data. */
  173662. (*cinfo->cquantize->color_quantize) (cinfo,
  173663. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173664. (int) num_rows);
  173665. *out_row_ctr += num_rows;
  173666. /* Advance if we filled the strip. */
  173667. post->next_row += num_rows;
  173668. if (post->next_row >= post->strip_height) {
  173669. post->starting_row += post->strip_height;
  173670. post->next_row = 0;
  173671. }
  173672. }
  173673. #endif /* QUANT_2PASS_SUPPORTED */
  173674. /*
  173675. * Initialize postprocessing controller.
  173676. */
  173677. GLOBAL(void)
  173678. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173679. {
  173680. my_post_ptr post;
  173681. post = (my_post_ptr)
  173682. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173683. SIZEOF(my_post_controller));
  173684. cinfo->post = (struct jpeg_d_post_controller *) post;
  173685. post->pub.start_pass = start_pass_dpost;
  173686. post->whole_image = NULL; /* flag for no virtual arrays */
  173687. post->buffer = NULL; /* flag for no strip buffer */
  173688. /* Create the quantization buffer, if needed */
  173689. if (cinfo->quantize_colors) {
  173690. /* The buffer strip height is max_v_samp_factor, which is typically
  173691. * an efficient number of rows for upsampling to return.
  173692. * (In the presence of output rescaling, we might want to be smarter?)
  173693. */
  173694. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173695. if (need_full_buffer) {
  173696. /* Two-pass color quantization: need full-image storage. */
  173697. /* We round up the number of rows to a multiple of the strip height. */
  173698. #ifdef QUANT_2PASS_SUPPORTED
  173699. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173700. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173701. cinfo->output_width * cinfo->out_color_components,
  173702. (JDIMENSION) jround_up((long) cinfo->output_height,
  173703. (long) post->strip_height),
  173704. post->strip_height);
  173705. #else
  173706. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173707. #endif /* QUANT_2PASS_SUPPORTED */
  173708. } else {
  173709. /* One-pass color quantization: just make a strip buffer. */
  173710. post->buffer = (*cinfo->mem->alloc_sarray)
  173711. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173712. cinfo->output_width * cinfo->out_color_components,
  173713. post->strip_height);
  173714. }
  173715. }
  173716. }
  173717. /*** End of inlined file: jdpostct.c ***/
  173718. #undef FIX
  173719. /*** Start of inlined file: jdsample.c ***/
  173720. #define JPEG_INTERNALS
  173721. /* Pointer to routine to upsample a single component */
  173722. typedef JMETHOD(void, upsample1_ptr,
  173723. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173724. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173725. /* Private subobject */
  173726. typedef struct {
  173727. struct jpeg_upsampler pub; /* public fields */
  173728. /* Color conversion buffer. When using separate upsampling and color
  173729. * conversion steps, this buffer holds one upsampled row group until it
  173730. * has been color converted and output.
  173731. * Note: we do not allocate any storage for component(s) which are full-size,
  173732. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173733. * simply set to point to the input data array, thereby avoiding copying.
  173734. */
  173735. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173736. /* Per-component upsampling method pointers */
  173737. upsample1_ptr methods[MAX_COMPONENTS];
  173738. int next_row_out; /* counts rows emitted from color_buf */
  173739. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173740. /* Height of an input row group for each component. */
  173741. int rowgroup_height[MAX_COMPONENTS];
  173742. /* These arrays save pixel expansion factors so that int_expand need not
  173743. * recompute them each time. They are unused for other upsampling methods.
  173744. */
  173745. UINT8 h_expand[MAX_COMPONENTS];
  173746. UINT8 v_expand[MAX_COMPONENTS];
  173747. } my_upsampler2;
  173748. typedef my_upsampler2 * my_upsample_ptr2;
  173749. /*
  173750. * Initialize for an upsampling pass.
  173751. */
  173752. METHODDEF(void)
  173753. start_pass_upsample (j_decompress_ptr cinfo)
  173754. {
  173755. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173756. /* Mark the conversion buffer empty */
  173757. upsample->next_row_out = cinfo->max_v_samp_factor;
  173758. /* Initialize total-height counter for detecting bottom of image */
  173759. upsample->rows_to_go = cinfo->output_height;
  173760. }
  173761. /*
  173762. * Control routine to do upsampling (and color conversion).
  173763. *
  173764. * In this version we upsample each component independently.
  173765. * We upsample one row group into the conversion buffer, then apply
  173766. * color conversion a row at a time.
  173767. */
  173768. METHODDEF(void)
  173769. sep_upsample (j_decompress_ptr cinfo,
  173770. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173771. JDIMENSION,
  173772. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173773. JDIMENSION out_rows_avail)
  173774. {
  173775. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173776. int ci;
  173777. jpeg_component_info * compptr;
  173778. JDIMENSION num_rows;
  173779. /* Fill the conversion buffer, if it's empty */
  173780. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173781. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173782. ci++, compptr++) {
  173783. /* Invoke per-component upsample method. Notice we pass a POINTER
  173784. * to color_buf[ci], so that fullsize_upsample can change it.
  173785. */
  173786. (*upsample->methods[ci]) (cinfo, compptr,
  173787. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173788. upsample->color_buf + ci);
  173789. }
  173790. upsample->next_row_out = 0;
  173791. }
  173792. /* Color-convert and emit rows */
  173793. /* How many we have in the buffer: */
  173794. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173795. /* Not more than the distance to the end of the image. Need this test
  173796. * in case the image height is not a multiple of max_v_samp_factor:
  173797. */
  173798. if (num_rows > upsample->rows_to_go)
  173799. num_rows = upsample->rows_to_go;
  173800. /* And not more than what the client can accept: */
  173801. out_rows_avail -= *out_row_ctr;
  173802. if (num_rows > out_rows_avail)
  173803. num_rows = out_rows_avail;
  173804. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173805. (JDIMENSION) upsample->next_row_out,
  173806. output_buf + *out_row_ctr,
  173807. (int) num_rows);
  173808. /* Adjust counts */
  173809. *out_row_ctr += num_rows;
  173810. upsample->rows_to_go -= num_rows;
  173811. upsample->next_row_out += num_rows;
  173812. /* When the buffer is emptied, declare this input row group consumed */
  173813. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173814. (*in_row_group_ctr)++;
  173815. }
  173816. /*
  173817. * These are the routines invoked by sep_upsample to upsample pixel values
  173818. * of a single component. One row group is processed per call.
  173819. */
  173820. /*
  173821. * For full-size components, we just make color_buf[ci] point at the
  173822. * input buffer, and thus avoid copying any data. Note that this is
  173823. * safe only because sep_upsample doesn't declare the input row group
  173824. * "consumed" until we are done color converting and emitting it.
  173825. */
  173826. METHODDEF(void)
  173827. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173828. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173829. {
  173830. *output_data_ptr = input_data;
  173831. }
  173832. /*
  173833. * This is a no-op version used for "uninteresting" components.
  173834. * These components will not be referenced by color conversion.
  173835. */
  173836. METHODDEF(void)
  173837. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173838. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173839. {
  173840. *output_data_ptr = NULL; /* safety check */
  173841. }
  173842. /*
  173843. * This version handles any integral sampling ratios.
  173844. * This is not used for typical JPEG files, so it need not be fast.
  173845. * Nor, for that matter, is it particularly accurate: the algorithm is
  173846. * simple replication of the input pixel onto the corresponding output
  173847. * pixels. The hi-falutin sampling literature refers to this as a
  173848. * "box filter". A box filter tends to introduce visible artifacts,
  173849. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173850. * you would be well advised to improve this code.
  173851. */
  173852. METHODDEF(void)
  173853. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173854. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173855. {
  173856. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173857. JSAMPARRAY output_data = *output_data_ptr;
  173858. register JSAMPROW inptr, outptr;
  173859. register JSAMPLE invalue;
  173860. register int h;
  173861. JSAMPROW outend;
  173862. int h_expand, v_expand;
  173863. int inrow, outrow;
  173864. h_expand = upsample->h_expand[compptr->component_index];
  173865. v_expand = upsample->v_expand[compptr->component_index];
  173866. inrow = outrow = 0;
  173867. while (outrow < cinfo->max_v_samp_factor) {
  173868. /* Generate one output row with proper horizontal expansion */
  173869. inptr = input_data[inrow];
  173870. outptr = output_data[outrow];
  173871. outend = outptr + cinfo->output_width;
  173872. while (outptr < outend) {
  173873. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173874. for (h = h_expand; h > 0; h--) {
  173875. *outptr++ = invalue;
  173876. }
  173877. }
  173878. /* Generate any additional output rows by duplicating the first one */
  173879. if (v_expand > 1) {
  173880. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173881. v_expand-1, cinfo->output_width);
  173882. }
  173883. inrow++;
  173884. outrow += v_expand;
  173885. }
  173886. }
  173887. /*
  173888. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173889. * It's still a box filter.
  173890. */
  173891. METHODDEF(void)
  173892. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173893. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173894. {
  173895. JSAMPARRAY output_data = *output_data_ptr;
  173896. register JSAMPROW inptr, outptr;
  173897. register JSAMPLE invalue;
  173898. JSAMPROW outend;
  173899. int inrow;
  173900. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173901. inptr = input_data[inrow];
  173902. outptr = output_data[inrow];
  173903. outend = outptr + cinfo->output_width;
  173904. while (outptr < outend) {
  173905. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173906. *outptr++ = invalue;
  173907. *outptr++ = invalue;
  173908. }
  173909. }
  173910. }
  173911. /*
  173912. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173913. * It's still a box filter.
  173914. */
  173915. METHODDEF(void)
  173916. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173917. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173918. {
  173919. JSAMPARRAY output_data = *output_data_ptr;
  173920. register JSAMPROW inptr, outptr;
  173921. register JSAMPLE invalue;
  173922. JSAMPROW outend;
  173923. int inrow, outrow;
  173924. inrow = outrow = 0;
  173925. while (outrow < cinfo->max_v_samp_factor) {
  173926. inptr = input_data[inrow];
  173927. outptr = output_data[outrow];
  173928. outend = outptr + cinfo->output_width;
  173929. while (outptr < outend) {
  173930. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173931. *outptr++ = invalue;
  173932. *outptr++ = invalue;
  173933. }
  173934. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173935. 1, cinfo->output_width);
  173936. inrow++;
  173937. outrow += 2;
  173938. }
  173939. }
  173940. /*
  173941. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173942. *
  173943. * The upsampling algorithm is linear interpolation between pixel centers,
  173944. * also known as a "triangle filter". This is a good compromise between
  173945. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173946. * of the way between input pixel centers.
  173947. *
  173948. * A note about the "bias" calculations: when rounding fractional values to
  173949. * integer, we do not want to always round 0.5 up to the next integer.
  173950. * If we did that, we'd introduce a noticeable bias towards larger values.
  173951. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173952. * alternate pixel locations (a simple ordered dither pattern).
  173953. */
  173954. METHODDEF(void)
  173955. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173956. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173957. {
  173958. JSAMPARRAY output_data = *output_data_ptr;
  173959. register JSAMPROW inptr, outptr;
  173960. register int invalue;
  173961. register JDIMENSION colctr;
  173962. int inrow;
  173963. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173964. inptr = input_data[inrow];
  173965. outptr = output_data[inrow];
  173966. /* Special case for first column */
  173967. invalue = GETJSAMPLE(*inptr++);
  173968. *outptr++ = (JSAMPLE) invalue;
  173969. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173970. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173971. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173972. invalue = GETJSAMPLE(*inptr++) * 3;
  173973. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173974. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173975. }
  173976. /* Special case for last column */
  173977. invalue = GETJSAMPLE(*inptr);
  173978. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173979. *outptr++ = (JSAMPLE) invalue;
  173980. }
  173981. }
  173982. /*
  173983. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173984. * Again a triangle filter; see comments for h2v1 case, above.
  173985. *
  173986. * It is OK for us to reference the adjacent input rows because we demanded
  173987. * context from the main buffer controller (see initialization code).
  173988. */
  173989. METHODDEF(void)
  173990. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173991. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173992. {
  173993. JSAMPARRAY output_data = *output_data_ptr;
  173994. register JSAMPROW inptr0, inptr1, outptr;
  173995. #if BITS_IN_JSAMPLE == 8
  173996. register int thiscolsum, lastcolsum, nextcolsum;
  173997. #else
  173998. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173999. #endif
  174000. register JDIMENSION colctr;
  174001. int inrow, outrow, v;
  174002. inrow = outrow = 0;
  174003. while (outrow < cinfo->max_v_samp_factor) {
  174004. for (v = 0; v < 2; v++) {
  174005. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174006. inptr0 = input_data[inrow];
  174007. if (v == 0) /* next nearest is row above */
  174008. inptr1 = input_data[inrow-1];
  174009. else /* next nearest is row below */
  174010. inptr1 = input_data[inrow+1];
  174011. outptr = output_data[outrow++];
  174012. /* Special case for first column */
  174013. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174014. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174015. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174016. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174017. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174018. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174019. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174020. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174021. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174022. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174023. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174024. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174025. }
  174026. /* Special case for last column */
  174027. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174028. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174029. }
  174030. inrow++;
  174031. }
  174032. }
  174033. /*
  174034. * Module initialization routine for upsampling.
  174035. */
  174036. GLOBAL(void)
  174037. jinit_upsampler (j_decompress_ptr cinfo)
  174038. {
  174039. my_upsample_ptr2 upsample;
  174040. int ci;
  174041. jpeg_component_info * compptr;
  174042. boolean need_buffer, do_fancy;
  174043. int h_in_group, v_in_group, h_out_group, v_out_group;
  174044. upsample = (my_upsample_ptr2)
  174045. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174046. SIZEOF(my_upsampler2));
  174047. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174048. upsample->pub.start_pass = start_pass_upsample;
  174049. upsample->pub.upsample = sep_upsample;
  174050. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174051. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174052. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174053. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174054. * so don't ask for it.
  174055. */
  174056. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174057. /* Verify we can handle the sampling factors, select per-component methods,
  174058. * and create storage as needed.
  174059. */
  174060. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174061. ci++, compptr++) {
  174062. /* Compute size of an "input group" after IDCT scaling. This many samples
  174063. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174064. */
  174065. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174066. cinfo->min_DCT_scaled_size;
  174067. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174068. cinfo->min_DCT_scaled_size;
  174069. h_out_group = cinfo->max_h_samp_factor;
  174070. v_out_group = cinfo->max_v_samp_factor;
  174071. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174072. need_buffer = TRUE;
  174073. if (! compptr->component_needed) {
  174074. /* Don't bother to upsample an uninteresting component. */
  174075. upsample->methods[ci] = noop_upsample;
  174076. need_buffer = FALSE;
  174077. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174078. /* Fullsize components can be processed without any work. */
  174079. upsample->methods[ci] = fullsize_upsample;
  174080. need_buffer = FALSE;
  174081. } else if (h_in_group * 2 == h_out_group &&
  174082. v_in_group == v_out_group) {
  174083. /* Special cases for 2h1v upsampling */
  174084. if (do_fancy && compptr->downsampled_width > 2)
  174085. upsample->methods[ci] = h2v1_fancy_upsample;
  174086. else
  174087. upsample->methods[ci] = h2v1_upsample;
  174088. } else if (h_in_group * 2 == h_out_group &&
  174089. v_in_group * 2 == v_out_group) {
  174090. /* Special cases for 2h2v upsampling */
  174091. if (do_fancy && compptr->downsampled_width > 2) {
  174092. upsample->methods[ci] = h2v2_fancy_upsample;
  174093. upsample->pub.need_context_rows = TRUE;
  174094. } else
  174095. upsample->methods[ci] = h2v2_upsample;
  174096. } else if ((h_out_group % h_in_group) == 0 &&
  174097. (v_out_group % v_in_group) == 0) {
  174098. /* Generic integral-factors upsampling method */
  174099. upsample->methods[ci] = int_upsample;
  174100. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174101. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174102. } else
  174103. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174104. if (need_buffer) {
  174105. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174106. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174107. (JDIMENSION) jround_up((long) cinfo->output_width,
  174108. (long) cinfo->max_h_samp_factor),
  174109. (JDIMENSION) cinfo->max_v_samp_factor);
  174110. }
  174111. }
  174112. }
  174113. /*** End of inlined file: jdsample.c ***/
  174114. /*** Start of inlined file: jdtrans.c ***/
  174115. #define JPEG_INTERNALS
  174116. /* Forward declarations */
  174117. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174118. /*
  174119. * Read the coefficient arrays from a JPEG file.
  174120. * jpeg_read_header must be completed before calling this.
  174121. *
  174122. * The entire image is read into a set of virtual coefficient-block arrays,
  174123. * one per component. The return value is a pointer to the array of
  174124. * virtual-array descriptors. These can be manipulated directly via the
  174125. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174126. * To release the memory occupied by the virtual arrays, call
  174127. * jpeg_finish_decompress() when done with the data.
  174128. *
  174129. * An alternative usage is to simply obtain access to the coefficient arrays
  174130. * during a buffered-image-mode decompression operation. This is allowed
  174131. * after any jpeg_finish_output() call. The arrays can be accessed until
  174132. * jpeg_finish_decompress() is called. (Note that any call to the library
  174133. * may reposition the arrays, so don't rely on access_virt_barray() results
  174134. * to stay valid across library calls.)
  174135. *
  174136. * Returns NULL if suspended. This case need be checked only if
  174137. * a suspending data source is used.
  174138. */
  174139. GLOBAL(jvirt_barray_ptr *)
  174140. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174141. {
  174142. if (cinfo->global_state == DSTATE_READY) {
  174143. /* First call: initialize active modules */
  174144. transdecode_master_selection(cinfo);
  174145. cinfo->global_state = DSTATE_RDCOEFS;
  174146. }
  174147. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174148. /* Absorb whole file into the coef buffer */
  174149. for (;;) {
  174150. int retcode;
  174151. /* Call progress monitor hook if present */
  174152. if (cinfo->progress != NULL)
  174153. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174154. /* Absorb some more input */
  174155. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174156. if (retcode == JPEG_SUSPENDED)
  174157. return NULL;
  174158. if (retcode == JPEG_REACHED_EOI)
  174159. break;
  174160. /* Advance progress counter if appropriate */
  174161. if (cinfo->progress != NULL &&
  174162. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174163. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174164. /* startup underestimated number of scans; ratchet up one scan */
  174165. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174166. }
  174167. }
  174168. }
  174169. /* Set state so that jpeg_finish_decompress does the right thing */
  174170. cinfo->global_state = DSTATE_STOPPING;
  174171. }
  174172. /* At this point we should be in state DSTATE_STOPPING if being used
  174173. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174174. * to the coefficients during a full buffered-image-mode decompression.
  174175. */
  174176. if ((cinfo->global_state == DSTATE_STOPPING ||
  174177. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174178. return cinfo->coef->coef_arrays;
  174179. }
  174180. /* Oops, improper usage */
  174181. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174182. return NULL; /* keep compiler happy */
  174183. }
  174184. /*
  174185. * Master selection of decompression modules for transcoding.
  174186. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174187. */
  174188. LOCAL(void)
  174189. transdecode_master_selection (j_decompress_ptr cinfo)
  174190. {
  174191. /* This is effectively a buffered-image operation. */
  174192. cinfo->buffered_image = TRUE;
  174193. /* Entropy decoding: either Huffman or arithmetic coding. */
  174194. if (cinfo->arith_code) {
  174195. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174196. } else {
  174197. if (cinfo->progressive_mode) {
  174198. #ifdef D_PROGRESSIVE_SUPPORTED
  174199. jinit_phuff_decoder(cinfo);
  174200. #else
  174201. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174202. #endif
  174203. } else
  174204. jinit_huff_decoder(cinfo);
  174205. }
  174206. /* Always get a full-image coefficient buffer. */
  174207. jinit_d_coef_controller(cinfo, TRUE);
  174208. /* We can now tell the memory manager to allocate virtual arrays. */
  174209. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174210. /* Initialize input side of decompressor to consume first scan. */
  174211. (*cinfo->inputctl->start_input_pass) (cinfo);
  174212. /* Initialize progress monitoring. */
  174213. if (cinfo->progress != NULL) {
  174214. int nscans;
  174215. /* Estimate number of scans to set pass_limit. */
  174216. if (cinfo->progressive_mode) {
  174217. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174218. nscans = 2 + 3 * cinfo->num_components;
  174219. } else if (cinfo->inputctl->has_multiple_scans) {
  174220. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174221. nscans = cinfo->num_components;
  174222. } else {
  174223. nscans = 1;
  174224. }
  174225. cinfo->progress->pass_counter = 0L;
  174226. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174227. cinfo->progress->completed_passes = 0;
  174228. cinfo->progress->total_passes = 1;
  174229. }
  174230. }
  174231. /*** End of inlined file: jdtrans.c ***/
  174232. /*** Start of inlined file: jfdctflt.c ***/
  174233. #define JPEG_INTERNALS
  174234. #ifdef DCT_FLOAT_SUPPORTED
  174235. /*
  174236. * This module is specialized to the case DCTSIZE = 8.
  174237. */
  174238. #if DCTSIZE != 8
  174239. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174240. #endif
  174241. /*
  174242. * Perform the forward DCT on one block of samples.
  174243. */
  174244. GLOBAL(void)
  174245. jpeg_fdct_float (FAST_FLOAT * data)
  174246. {
  174247. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174248. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174249. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174250. FAST_FLOAT *dataptr;
  174251. int ctr;
  174252. /* Pass 1: process rows. */
  174253. dataptr = data;
  174254. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174255. tmp0 = dataptr[0] + dataptr[7];
  174256. tmp7 = dataptr[0] - dataptr[7];
  174257. tmp1 = dataptr[1] + dataptr[6];
  174258. tmp6 = dataptr[1] - dataptr[6];
  174259. tmp2 = dataptr[2] + dataptr[5];
  174260. tmp5 = dataptr[2] - dataptr[5];
  174261. tmp3 = dataptr[3] + dataptr[4];
  174262. tmp4 = dataptr[3] - dataptr[4];
  174263. /* Even part */
  174264. tmp10 = tmp0 + tmp3; /* phase 2 */
  174265. tmp13 = tmp0 - tmp3;
  174266. tmp11 = tmp1 + tmp2;
  174267. tmp12 = tmp1 - tmp2;
  174268. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174269. dataptr[4] = tmp10 - tmp11;
  174270. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174271. dataptr[2] = tmp13 + z1; /* phase 5 */
  174272. dataptr[6] = tmp13 - z1;
  174273. /* Odd part */
  174274. tmp10 = tmp4 + tmp5; /* phase 2 */
  174275. tmp11 = tmp5 + tmp6;
  174276. tmp12 = tmp6 + tmp7;
  174277. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174278. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174279. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174280. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174281. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174282. z11 = tmp7 + z3; /* phase 5 */
  174283. z13 = tmp7 - z3;
  174284. dataptr[5] = z13 + z2; /* phase 6 */
  174285. dataptr[3] = z13 - z2;
  174286. dataptr[1] = z11 + z4;
  174287. dataptr[7] = z11 - z4;
  174288. dataptr += DCTSIZE; /* advance pointer to next row */
  174289. }
  174290. /* Pass 2: process columns. */
  174291. dataptr = data;
  174292. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174293. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174294. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174295. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174296. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174297. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174298. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174299. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174300. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174301. /* Even part */
  174302. tmp10 = tmp0 + tmp3; /* phase 2 */
  174303. tmp13 = tmp0 - tmp3;
  174304. tmp11 = tmp1 + tmp2;
  174305. tmp12 = tmp1 - tmp2;
  174306. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174307. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174308. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174309. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174310. dataptr[DCTSIZE*6] = tmp13 - z1;
  174311. /* Odd part */
  174312. tmp10 = tmp4 + tmp5; /* phase 2 */
  174313. tmp11 = tmp5 + tmp6;
  174314. tmp12 = tmp6 + tmp7;
  174315. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174316. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174317. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174318. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174319. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174320. z11 = tmp7 + z3; /* phase 5 */
  174321. z13 = tmp7 - z3;
  174322. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174323. dataptr[DCTSIZE*3] = z13 - z2;
  174324. dataptr[DCTSIZE*1] = z11 + z4;
  174325. dataptr[DCTSIZE*7] = z11 - z4;
  174326. dataptr++; /* advance pointer to next column */
  174327. }
  174328. }
  174329. #endif /* DCT_FLOAT_SUPPORTED */
  174330. /*** End of inlined file: jfdctflt.c ***/
  174331. /*** Start of inlined file: jfdctint.c ***/
  174332. #define JPEG_INTERNALS
  174333. #ifdef DCT_ISLOW_SUPPORTED
  174334. /*
  174335. * This module is specialized to the case DCTSIZE = 8.
  174336. */
  174337. #if DCTSIZE != 8
  174338. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174339. #endif
  174340. /*
  174341. * The poop on this scaling stuff is as follows:
  174342. *
  174343. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174344. * larger than the true DCT outputs. The final outputs are therefore
  174345. * a factor of N larger than desired; since N=8 this can be cured by
  174346. * a simple right shift at the end of the algorithm. The advantage of
  174347. * this arrangement is that we save two multiplications per 1-D DCT,
  174348. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174349. * In the IJG code, this factor of 8 is removed by the quantization step
  174350. * (in jcdctmgr.c), NOT in this module.
  174351. *
  174352. * We have to do addition and subtraction of the integer inputs, which
  174353. * is no problem, and multiplication by fractional constants, which is
  174354. * a problem to do in integer arithmetic. We multiply all the constants
  174355. * by CONST_SCALE and convert them to integer constants (thus retaining
  174356. * CONST_BITS bits of precision in the constants). After doing a
  174357. * multiplication we have to divide the product by CONST_SCALE, with proper
  174358. * rounding, to produce the correct output. This division can be done
  174359. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174360. * as long as possible so that partial sums can be added together with
  174361. * full fractional precision.
  174362. *
  174363. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174364. * they are represented to better-than-integral precision. These outputs
  174365. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174366. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174367. * array is INT32 anyway.)
  174368. *
  174369. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174370. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174371. * shows that the values given below are the most effective.
  174372. */
  174373. #if BITS_IN_JSAMPLE == 8
  174374. #define CONST_BITS 13
  174375. #define PASS1_BITS 2
  174376. #else
  174377. #define CONST_BITS 13
  174378. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174379. #endif
  174380. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174381. * causing a lot of useless floating-point operations at run time.
  174382. * To get around this we use the following pre-calculated constants.
  174383. * If you change CONST_BITS you may want to add appropriate values.
  174384. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174385. */
  174386. #if CONST_BITS == 13
  174387. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174388. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174389. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174390. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174391. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174392. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174393. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174394. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174395. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174396. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174397. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174398. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174399. #else
  174400. #define FIX_0_298631336 FIX(0.298631336)
  174401. #define FIX_0_390180644 FIX(0.390180644)
  174402. #define FIX_0_541196100 FIX(0.541196100)
  174403. #define FIX_0_765366865 FIX(0.765366865)
  174404. #define FIX_0_899976223 FIX(0.899976223)
  174405. #define FIX_1_175875602 FIX(1.175875602)
  174406. #define FIX_1_501321110 FIX(1.501321110)
  174407. #define FIX_1_847759065 FIX(1.847759065)
  174408. #define FIX_1_961570560 FIX(1.961570560)
  174409. #define FIX_2_053119869 FIX(2.053119869)
  174410. #define FIX_2_562915447 FIX(2.562915447)
  174411. #define FIX_3_072711026 FIX(3.072711026)
  174412. #endif
  174413. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174414. * For 8-bit samples with the recommended scaling, all the variable
  174415. * and constant values involved are no more than 16 bits wide, so a
  174416. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174417. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174418. */
  174419. #if BITS_IN_JSAMPLE == 8
  174420. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174421. #else
  174422. #define MULTIPLY(var,const) ((var) * (const))
  174423. #endif
  174424. /*
  174425. * Perform the forward DCT on one block of samples.
  174426. */
  174427. GLOBAL(void)
  174428. jpeg_fdct_islow (DCTELEM * data)
  174429. {
  174430. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174431. INT32 tmp10, tmp11, tmp12, tmp13;
  174432. INT32 z1, z2, z3, z4, z5;
  174433. DCTELEM *dataptr;
  174434. int ctr;
  174435. SHIFT_TEMPS
  174436. /* Pass 1: process rows. */
  174437. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174438. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174439. dataptr = data;
  174440. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174441. tmp0 = dataptr[0] + dataptr[7];
  174442. tmp7 = dataptr[0] - dataptr[7];
  174443. tmp1 = dataptr[1] + dataptr[6];
  174444. tmp6 = dataptr[1] - dataptr[6];
  174445. tmp2 = dataptr[2] + dataptr[5];
  174446. tmp5 = dataptr[2] - dataptr[5];
  174447. tmp3 = dataptr[3] + dataptr[4];
  174448. tmp4 = dataptr[3] - dataptr[4];
  174449. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174450. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174451. */
  174452. tmp10 = tmp0 + tmp3;
  174453. tmp13 = tmp0 - tmp3;
  174454. tmp11 = tmp1 + tmp2;
  174455. tmp12 = tmp1 - tmp2;
  174456. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174457. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174458. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174459. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174460. CONST_BITS-PASS1_BITS);
  174461. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174462. CONST_BITS-PASS1_BITS);
  174463. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174464. * cK represents cos(K*pi/16).
  174465. * i0..i3 in the paper are tmp4..tmp7 here.
  174466. */
  174467. z1 = tmp4 + tmp7;
  174468. z2 = tmp5 + tmp6;
  174469. z3 = tmp4 + tmp6;
  174470. z4 = tmp5 + tmp7;
  174471. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174472. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174473. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174474. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174475. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174476. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174477. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174478. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174479. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174480. z3 += z5;
  174481. z4 += z5;
  174482. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174483. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174484. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174485. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174486. dataptr += DCTSIZE; /* advance pointer to next row */
  174487. }
  174488. /* Pass 2: process columns.
  174489. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174490. * by an overall factor of 8.
  174491. */
  174492. dataptr = data;
  174493. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174494. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174495. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174496. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174497. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174498. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174499. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174500. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174501. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174502. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174503. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174504. */
  174505. tmp10 = tmp0 + tmp3;
  174506. tmp13 = tmp0 - tmp3;
  174507. tmp11 = tmp1 + tmp2;
  174508. tmp12 = tmp1 - tmp2;
  174509. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174510. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174511. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174512. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174513. CONST_BITS+PASS1_BITS);
  174514. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174515. CONST_BITS+PASS1_BITS);
  174516. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174517. * cK represents cos(K*pi/16).
  174518. * i0..i3 in the paper are tmp4..tmp7 here.
  174519. */
  174520. z1 = tmp4 + tmp7;
  174521. z2 = tmp5 + tmp6;
  174522. z3 = tmp4 + tmp6;
  174523. z4 = tmp5 + tmp7;
  174524. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174525. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174526. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174527. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174528. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174529. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174530. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174531. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174532. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174533. z3 += z5;
  174534. z4 += z5;
  174535. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174536. CONST_BITS+PASS1_BITS);
  174537. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174538. CONST_BITS+PASS1_BITS);
  174539. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174540. CONST_BITS+PASS1_BITS);
  174541. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174542. CONST_BITS+PASS1_BITS);
  174543. dataptr++; /* advance pointer to next column */
  174544. }
  174545. }
  174546. #endif /* DCT_ISLOW_SUPPORTED */
  174547. /*** End of inlined file: jfdctint.c ***/
  174548. #undef CONST_BITS
  174549. #undef MULTIPLY
  174550. #undef FIX_0_541196100
  174551. /*** Start of inlined file: jfdctfst.c ***/
  174552. #define JPEG_INTERNALS
  174553. #ifdef DCT_IFAST_SUPPORTED
  174554. /*
  174555. * This module is specialized to the case DCTSIZE = 8.
  174556. */
  174557. #if DCTSIZE != 8
  174558. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174559. #endif
  174560. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174561. * see jfdctint.c for more details. However, we choose to descale
  174562. * (right shift) multiplication products as soon as they are formed,
  174563. * rather than carrying additional fractional bits into subsequent additions.
  174564. * This compromises accuracy slightly, but it lets us save a few shifts.
  174565. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174566. * everywhere except in the multiplications proper; this saves a good deal
  174567. * of work on 16-bit-int machines.
  174568. *
  174569. * Again to save a few shifts, the intermediate results between pass 1 and
  174570. * pass 2 are not upscaled, but are represented only to integral precision.
  174571. *
  174572. * A final compromise is to represent the multiplicative constants to only
  174573. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174574. * machines, and may also reduce the cost of multiplication (since there
  174575. * are fewer one-bits in the constants).
  174576. */
  174577. #define CONST_BITS 8
  174578. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174579. * causing a lot of useless floating-point operations at run time.
  174580. * To get around this we use the following pre-calculated constants.
  174581. * If you change CONST_BITS you may want to add appropriate values.
  174582. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174583. */
  174584. #if CONST_BITS == 8
  174585. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174586. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174587. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174588. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174589. #else
  174590. #define FIX_0_382683433 FIX(0.382683433)
  174591. #define FIX_0_541196100 FIX(0.541196100)
  174592. #define FIX_0_707106781 FIX(0.707106781)
  174593. #define FIX_1_306562965 FIX(1.306562965)
  174594. #endif
  174595. /* We can gain a little more speed, with a further compromise in accuracy,
  174596. * by omitting the addition in a descaling shift. This yields an incorrectly
  174597. * rounded result half the time...
  174598. */
  174599. #ifndef USE_ACCURATE_ROUNDING
  174600. #undef DESCALE
  174601. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174602. #endif
  174603. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174604. * descale to yield a DCTELEM result.
  174605. */
  174606. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174607. /*
  174608. * Perform the forward DCT on one block of samples.
  174609. */
  174610. GLOBAL(void)
  174611. jpeg_fdct_ifast (DCTELEM * data)
  174612. {
  174613. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174614. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174615. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174616. DCTELEM *dataptr;
  174617. int ctr;
  174618. SHIFT_TEMPS
  174619. /* Pass 1: process rows. */
  174620. dataptr = data;
  174621. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174622. tmp0 = dataptr[0] + dataptr[7];
  174623. tmp7 = dataptr[0] - dataptr[7];
  174624. tmp1 = dataptr[1] + dataptr[6];
  174625. tmp6 = dataptr[1] - dataptr[6];
  174626. tmp2 = dataptr[2] + dataptr[5];
  174627. tmp5 = dataptr[2] - dataptr[5];
  174628. tmp3 = dataptr[3] + dataptr[4];
  174629. tmp4 = dataptr[3] - dataptr[4];
  174630. /* Even part */
  174631. tmp10 = tmp0 + tmp3; /* phase 2 */
  174632. tmp13 = tmp0 - tmp3;
  174633. tmp11 = tmp1 + tmp2;
  174634. tmp12 = tmp1 - tmp2;
  174635. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174636. dataptr[4] = tmp10 - tmp11;
  174637. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174638. dataptr[2] = tmp13 + z1; /* phase 5 */
  174639. dataptr[6] = tmp13 - z1;
  174640. /* Odd part */
  174641. tmp10 = tmp4 + tmp5; /* phase 2 */
  174642. tmp11 = tmp5 + tmp6;
  174643. tmp12 = tmp6 + tmp7;
  174644. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174645. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174646. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174647. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174648. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174649. z11 = tmp7 + z3; /* phase 5 */
  174650. z13 = tmp7 - z3;
  174651. dataptr[5] = z13 + z2; /* phase 6 */
  174652. dataptr[3] = z13 - z2;
  174653. dataptr[1] = z11 + z4;
  174654. dataptr[7] = z11 - z4;
  174655. dataptr += DCTSIZE; /* advance pointer to next row */
  174656. }
  174657. /* Pass 2: process columns. */
  174658. dataptr = data;
  174659. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174660. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174661. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174662. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174663. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174664. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174665. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174666. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174667. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174668. /* Even part */
  174669. tmp10 = tmp0 + tmp3; /* phase 2 */
  174670. tmp13 = tmp0 - tmp3;
  174671. tmp11 = tmp1 + tmp2;
  174672. tmp12 = tmp1 - tmp2;
  174673. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174674. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174675. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174676. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174677. dataptr[DCTSIZE*6] = tmp13 - z1;
  174678. /* Odd part */
  174679. tmp10 = tmp4 + tmp5; /* phase 2 */
  174680. tmp11 = tmp5 + tmp6;
  174681. tmp12 = tmp6 + tmp7;
  174682. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174683. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174684. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174685. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174686. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174687. z11 = tmp7 + z3; /* phase 5 */
  174688. z13 = tmp7 - z3;
  174689. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174690. dataptr[DCTSIZE*3] = z13 - z2;
  174691. dataptr[DCTSIZE*1] = z11 + z4;
  174692. dataptr[DCTSIZE*7] = z11 - z4;
  174693. dataptr++; /* advance pointer to next column */
  174694. }
  174695. }
  174696. #endif /* DCT_IFAST_SUPPORTED */
  174697. /*** End of inlined file: jfdctfst.c ***/
  174698. #undef FIX_0_541196100
  174699. /*** Start of inlined file: jidctflt.c ***/
  174700. #define JPEG_INTERNALS
  174701. #ifdef DCT_FLOAT_SUPPORTED
  174702. /*
  174703. * This module is specialized to the case DCTSIZE = 8.
  174704. */
  174705. #if DCTSIZE != 8
  174706. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174707. #endif
  174708. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174709. * entry; produce a float result.
  174710. */
  174711. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174712. /*
  174713. * Perform dequantization and inverse DCT on one block of coefficients.
  174714. */
  174715. GLOBAL(void)
  174716. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174717. JCOEFPTR coef_block,
  174718. JSAMPARRAY output_buf, JDIMENSION output_col)
  174719. {
  174720. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174721. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174722. FAST_FLOAT z5, z10, z11, z12, z13;
  174723. JCOEFPTR inptr;
  174724. FLOAT_MULT_TYPE * quantptr;
  174725. FAST_FLOAT * wsptr;
  174726. JSAMPROW outptr;
  174727. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174728. int ctr;
  174729. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174730. SHIFT_TEMPS
  174731. /* Pass 1: process columns from input, store into work array. */
  174732. inptr = coef_block;
  174733. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174734. wsptr = workspace;
  174735. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174736. /* Due to quantization, we will usually find that many of the input
  174737. * coefficients are zero, especially the AC terms. We can exploit this
  174738. * by short-circuiting the IDCT calculation for any column in which all
  174739. * the AC terms are zero. In that case each output is equal to the
  174740. * DC coefficient (with scale factor as needed).
  174741. * With typical images and quantization tables, half or more of the
  174742. * column DCT calculations can be simplified this way.
  174743. */
  174744. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174745. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174746. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174747. inptr[DCTSIZE*7] == 0) {
  174748. /* AC terms all zero */
  174749. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174750. wsptr[DCTSIZE*0] = dcval;
  174751. wsptr[DCTSIZE*1] = dcval;
  174752. wsptr[DCTSIZE*2] = dcval;
  174753. wsptr[DCTSIZE*3] = dcval;
  174754. wsptr[DCTSIZE*4] = dcval;
  174755. wsptr[DCTSIZE*5] = dcval;
  174756. wsptr[DCTSIZE*6] = dcval;
  174757. wsptr[DCTSIZE*7] = dcval;
  174758. inptr++; /* advance pointers to next column */
  174759. quantptr++;
  174760. wsptr++;
  174761. continue;
  174762. }
  174763. /* Even part */
  174764. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174765. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174766. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174767. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174768. tmp10 = tmp0 + tmp2; /* phase 3 */
  174769. tmp11 = tmp0 - tmp2;
  174770. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174771. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174772. tmp0 = tmp10 + tmp13; /* phase 2 */
  174773. tmp3 = tmp10 - tmp13;
  174774. tmp1 = tmp11 + tmp12;
  174775. tmp2 = tmp11 - tmp12;
  174776. /* Odd part */
  174777. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174778. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174779. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174780. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174781. z13 = tmp6 + tmp5; /* phase 6 */
  174782. z10 = tmp6 - tmp5;
  174783. z11 = tmp4 + tmp7;
  174784. z12 = tmp4 - tmp7;
  174785. tmp7 = z11 + z13; /* phase 5 */
  174786. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174787. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174788. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174789. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174790. tmp6 = tmp12 - tmp7; /* phase 2 */
  174791. tmp5 = tmp11 - tmp6;
  174792. tmp4 = tmp10 + tmp5;
  174793. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174794. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174795. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174796. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174797. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174798. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174799. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174800. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174801. inptr++; /* advance pointers to next column */
  174802. quantptr++;
  174803. wsptr++;
  174804. }
  174805. /* Pass 2: process rows from work array, store into output array. */
  174806. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174807. wsptr = workspace;
  174808. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174809. outptr = output_buf[ctr] + output_col;
  174810. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174811. * However, the column calculation has created many nonzero AC terms, so
  174812. * the simplification applies less often (typically 5% to 10% of the time).
  174813. * And testing floats for zero is relatively expensive, so we don't bother.
  174814. */
  174815. /* Even part */
  174816. tmp10 = wsptr[0] + wsptr[4];
  174817. tmp11 = wsptr[0] - wsptr[4];
  174818. tmp13 = wsptr[2] + wsptr[6];
  174819. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174820. tmp0 = tmp10 + tmp13;
  174821. tmp3 = tmp10 - tmp13;
  174822. tmp1 = tmp11 + tmp12;
  174823. tmp2 = tmp11 - tmp12;
  174824. /* Odd part */
  174825. z13 = wsptr[5] + wsptr[3];
  174826. z10 = wsptr[5] - wsptr[3];
  174827. z11 = wsptr[1] + wsptr[7];
  174828. z12 = wsptr[1] - wsptr[7];
  174829. tmp7 = z11 + z13;
  174830. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174831. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174832. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174833. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174834. tmp6 = tmp12 - tmp7;
  174835. tmp5 = tmp11 - tmp6;
  174836. tmp4 = tmp10 + tmp5;
  174837. /* Final output stage: scale down by a factor of 8 and range-limit */
  174838. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174839. & RANGE_MASK];
  174840. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174841. & RANGE_MASK];
  174842. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174843. & RANGE_MASK];
  174844. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174845. & RANGE_MASK];
  174846. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174847. & RANGE_MASK];
  174848. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174849. & RANGE_MASK];
  174850. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174851. & RANGE_MASK];
  174852. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174853. & RANGE_MASK];
  174854. wsptr += DCTSIZE; /* advance pointer to next row */
  174855. }
  174856. }
  174857. #endif /* DCT_FLOAT_SUPPORTED */
  174858. /*** End of inlined file: jidctflt.c ***/
  174859. #undef CONST_BITS
  174860. #undef FIX_1_847759065
  174861. #undef MULTIPLY
  174862. #undef DEQUANTIZE
  174863. #undef DESCALE
  174864. /*** Start of inlined file: jidctfst.c ***/
  174865. #define JPEG_INTERNALS
  174866. #ifdef DCT_IFAST_SUPPORTED
  174867. /*
  174868. * This module is specialized to the case DCTSIZE = 8.
  174869. */
  174870. #if DCTSIZE != 8
  174871. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174872. #endif
  174873. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174874. * see jidctint.c for more details. However, we choose to descale
  174875. * (right shift) multiplication products as soon as they are formed,
  174876. * rather than carrying additional fractional bits into subsequent additions.
  174877. * This compromises accuracy slightly, but it lets us save a few shifts.
  174878. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174879. * everywhere except in the multiplications proper; this saves a good deal
  174880. * of work on 16-bit-int machines.
  174881. *
  174882. * The dequantized coefficients are not integers because the AA&N scaling
  174883. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174884. * so that the first and second IDCT rounds have the same input scaling.
  174885. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174886. * avoid a descaling shift; this compromises accuracy rather drastically
  174887. * for small quantization table entries, but it saves a lot of shifts.
  174888. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174889. * so we use a much larger scaling factor to preserve accuracy.
  174890. *
  174891. * A final compromise is to represent the multiplicative constants to only
  174892. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174893. * machines, and may also reduce the cost of multiplication (since there
  174894. * are fewer one-bits in the constants).
  174895. */
  174896. #if BITS_IN_JSAMPLE == 8
  174897. #define CONST_BITS 8
  174898. #define PASS1_BITS 2
  174899. #else
  174900. #define CONST_BITS 8
  174901. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174902. #endif
  174903. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174904. * causing a lot of useless floating-point operations at run time.
  174905. * To get around this we use the following pre-calculated constants.
  174906. * If you change CONST_BITS you may want to add appropriate values.
  174907. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174908. */
  174909. #if CONST_BITS == 8
  174910. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174911. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174912. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174913. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174914. #else
  174915. #define FIX_1_082392200 FIX(1.082392200)
  174916. #define FIX_1_414213562 FIX(1.414213562)
  174917. #define FIX_1_847759065 FIX(1.847759065)
  174918. #define FIX_2_613125930 FIX(2.613125930)
  174919. #endif
  174920. /* We can gain a little more speed, with a further compromise in accuracy,
  174921. * by omitting the addition in a descaling shift. This yields an incorrectly
  174922. * rounded result half the time...
  174923. */
  174924. #ifndef USE_ACCURATE_ROUNDING
  174925. #undef DESCALE
  174926. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174927. #endif
  174928. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174929. * descale to yield a DCTELEM result.
  174930. */
  174931. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174932. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174933. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174934. * multiplication will do. For 12-bit data, the multiplier table is
  174935. * declared INT32, so a 32-bit multiply will be used.
  174936. */
  174937. #if BITS_IN_JSAMPLE == 8
  174938. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174939. #else
  174940. #define DEQUANTIZE(coef,quantval) \
  174941. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174942. #endif
  174943. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174944. * We assume that int right shift is unsigned if INT32 right shift is.
  174945. */
  174946. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174947. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174948. #if BITS_IN_JSAMPLE == 8
  174949. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174950. #else
  174951. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174952. #endif
  174953. #define IRIGHT_SHIFT(x,shft) \
  174954. ((ishift_temp = (x)) < 0 ? \
  174955. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174956. (ishift_temp >> (shft)))
  174957. #else
  174958. #define ISHIFT_TEMPS
  174959. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174960. #endif
  174961. #ifdef USE_ACCURATE_ROUNDING
  174962. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174963. #else
  174964. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174965. #endif
  174966. /*
  174967. * Perform dequantization and inverse DCT on one block of coefficients.
  174968. */
  174969. GLOBAL(void)
  174970. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174971. JCOEFPTR coef_block,
  174972. JSAMPARRAY output_buf, JDIMENSION output_col)
  174973. {
  174974. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174975. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174976. DCTELEM z5, z10, z11, z12, z13;
  174977. JCOEFPTR inptr;
  174978. IFAST_MULT_TYPE * quantptr;
  174979. int * wsptr;
  174980. JSAMPROW outptr;
  174981. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174982. int ctr;
  174983. int workspace[DCTSIZE2]; /* buffers data between passes */
  174984. SHIFT_TEMPS /* for DESCALE */
  174985. ISHIFT_TEMPS /* for IDESCALE */
  174986. /* Pass 1: process columns from input, store into work array. */
  174987. inptr = coef_block;
  174988. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174989. wsptr = workspace;
  174990. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174991. /* Due to quantization, we will usually find that many of the input
  174992. * coefficients are zero, especially the AC terms. We can exploit this
  174993. * by short-circuiting the IDCT calculation for any column in which all
  174994. * the AC terms are zero. In that case each output is equal to the
  174995. * DC coefficient (with scale factor as needed).
  174996. * With typical images and quantization tables, half or more of the
  174997. * column DCT calculations can be simplified this way.
  174998. */
  174999. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175000. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175001. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175002. inptr[DCTSIZE*7] == 0) {
  175003. /* AC terms all zero */
  175004. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175005. wsptr[DCTSIZE*0] = dcval;
  175006. wsptr[DCTSIZE*1] = dcval;
  175007. wsptr[DCTSIZE*2] = dcval;
  175008. wsptr[DCTSIZE*3] = dcval;
  175009. wsptr[DCTSIZE*4] = dcval;
  175010. wsptr[DCTSIZE*5] = dcval;
  175011. wsptr[DCTSIZE*6] = dcval;
  175012. wsptr[DCTSIZE*7] = dcval;
  175013. inptr++; /* advance pointers to next column */
  175014. quantptr++;
  175015. wsptr++;
  175016. continue;
  175017. }
  175018. /* Even part */
  175019. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175020. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175021. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175022. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175023. tmp10 = tmp0 + tmp2; /* phase 3 */
  175024. tmp11 = tmp0 - tmp2;
  175025. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175026. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175027. tmp0 = tmp10 + tmp13; /* phase 2 */
  175028. tmp3 = tmp10 - tmp13;
  175029. tmp1 = tmp11 + tmp12;
  175030. tmp2 = tmp11 - tmp12;
  175031. /* Odd part */
  175032. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175033. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175034. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175035. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175036. z13 = tmp6 + tmp5; /* phase 6 */
  175037. z10 = tmp6 - tmp5;
  175038. z11 = tmp4 + tmp7;
  175039. z12 = tmp4 - tmp7;
  175040. tmp7 = z11 + z13; /* phase 5 */
  175041. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175042. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175043. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175044. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175045. tmp6 = tmp12 - tmp7; /* phase 2 */
  175046. tmp5 = tmp11 - tmp6;
  175047. tmp4 = tmp10 + tmp5;
  175048. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175049. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175050. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175051. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175052. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175053. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175054. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175055. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175056. inptr++; /* advance pointers to next column */
  175057. quantptr++;
  175058. wsptr++;
  175059. }
  175060. /* Pass 2: process rows from work array, store into output array. */
  175061. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175062. /* and also undo the PASS1_BITS scaling. */
  175063. wsptr = workspace;
  175064. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175065. outptr = output_buf[ctr] + output_col;
  175066. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175067. * However, the column calculation has created many nonzero AC terms, so
  175068. * the simplification applies less often (typically 5% to 10% of the time).
  175069. * On machines with very fast multiplication, it's possible that the
  175070. * test takes more time than it's worth. In that case this section
  175071. * may be commented out.
  175072. */
  175073. #ifndef NO_ZERO_ROW_TEST
  175074. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175075. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175076. /* AC terms all zero */
  175077. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175078. & RANGE_MASK];
  175079. outptr[0] = dcval;
  175080. outptr[1] = dcval;
  175081. outptr[2] = dcval;
  175082. outptr[3] = dcval;
  175083. outptr[4] = dcval;
  175084. outptr[5] = dcval;
  175085. outptr[6] = dcval;
  175086. outptr[7] = dcval;
  175087. wsptr += DCTSIZE; /* advance pointer to next row */
  175088. continue;
  175089. }
  175090. #endif
  175091. /* Even part */
  175092. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175093. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175094. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175095. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175096. - tmp13;
  175097. tmp0 = tmp10 + tmp13;
  175098. tmp3 = tmp10 - tmp13;
  175099. tmp1 = tmp11 + tmp12;
  175100. tmp2 = tmp11 - tmp12;
  175101. /* Odd part */
  175102. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175103. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175104. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175105. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175106. tmp7 = z11 + z13; /* phase 5 */
  175107. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175108. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175109. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175110. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175111. tmp6 = tmp12 - tmp7; /* phase 2 */
  175112. tmp5 = tmp11 - tmp6;
  175113. tmp4 = tmp10 + tmp5;
  175114. /* Final output stage: scale down by a factor of 8 and range-limit */
  175115. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175116. & RANGE_MASK];
  175117. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175118. & RANGE_MASK];
  175119. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175120. & RANGE_MASK];
  175121. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175122. & RANGE_MASK];
  175123. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175124. & RANGE_MASK];
  175125. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175126. & RANGE_MASK];
  175127. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175128. & RANGE_MASK];
  175129. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175130. & RANGE_MASK];
  175131. wsptr += DCTSIZE; /* advance pointer to next row */
  175132. }
  175133. }
  175134. #endif /* DCT_IFAST_SUPPORTED */
  175135. /*** End of inlined file: jidctfst.c ***/
  175136. #undef CONST_BITS
  175137. #undef FIX_1_847759065
  175138. #undef MULTIPLY
  175139. #undef DEQUANTIZE
  175140. /*** Start of inlined file: jidctint.c ***/
  175141. #define JPEG_INTERNALS
  175142. #ifdef DCT_ISLOW_SUPPORTED
  175143. /*
  175144. * This module is specialized to the case DCTSIZE = 8.
  175145. */
  175146. #if DCTSIZE != 8
  175147. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175148. #endif
  175149. /*
  175150. * The poop on this scaling stuff is as follows:
  175151. *
  175152. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175153. * larger than the true IDCT outputs. The final outputs are therefore
  175154. * a factor of N larger than desired; since N=8 this can be cured by
  175155. * a simple right shift at the end of the algorithm. The advantage of
  175156. * this arrangement is that we save two multiplications per 1-D IDCT,
  175157. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175158. *
  175159. * We have to do addition and subtraction of the integer inputs, which
  175160. * is no problem, and multiplication by fractional constants, which is
  175161. * a problem to do in integer arithmetic. We multiply all the constants
  175162. * by CONST_SCALE and convert them to integer constants (thus retaining
  175163. * CONST_BITS bits of precision in the constants). After doing a
  175164. * multiplication we have to divide the product by CONST_SCALE, with proper
  175165. * rounding, to produce the correct output. This division can be done
  175166. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175167. * as long as possible so that partial sums can be added together with
  175168. * full fractional precision.
  175169. *
  175170. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175171. * they are represented to better-than-integral precision. These outputs
  175172. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175173. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175174. * intermediate INT32 array would be needed.)
  175175. *
  175176. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175177. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175178. * shows that the values given below are the most effective.
  175179. */
  175180. #if BITS_IN_JSAMPLE == 8
  175181. #define CONST_BITS 13
  175182. #define PASS1_BITS 2
  175183. #else
  175184. #define CONST_BITS 13
  175185. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175186. #endif
  175187. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175188. * causing a lot of useless floating-point operations at run time.
  175189. * To get around this we use the following pre-calculated constants.
  175190. * If you change CONST_BITS you may want to add appropriate values.
  175191. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175192. */
  175193. #if CONST_BITS == 13
  175194. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175195. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175196. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175197. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175198. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175199. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175200. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175201. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175202. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175203. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175204. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175205. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175206. #else
  175207. #define FIX_0_298631336 FIX(0.298631336)
  175208. #define FIX_0_390180644 FIX(0.390180644)
  175209. #define FIX_0_541196100 FIX(0.541196100)
  175210. #define FIX_0_765366865 FIX(0.765366865)
  175211. #define FIX_0_899976223 FIX(0.899976223)
  175212. #define FIX_1_175875602 FIX(1.175875602)
  175213. #define FIX_1_501321110 FIX(1.501321110)
  175214. #define FIX_1_847759065 FIX(1.847759065)
  175215. #define FIX_1_961570560 FIX(1.961570560)
  175216. #define FIX_2_053119869 FIX(2.053119869)
  175217. #define FIX_2_562915447 FIX(2.562915447)
  175218. #define FIX_3_072711026 FIX(3.072711026)
  175219. #endif
  175220. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175221. * For 8-bit samples with the recommended scaling, all the variable
  175222. * and constant values involved are no more than 16 bits wide, so a
  175223. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175224. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175225. */
  175226. #if BITS_IN_JSAMPLE == 8
  175227. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175228. #else
  175229. #define MULTIPLY(var,const) ((var) * (const))
  175230. #endif
  175231. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175232. * entry; produce an int result. In this module, both inputs and result
  175233. * are 16 bits or less, so either int or short multiply will work.
  175234. */
  175235. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175236. /*
  175237. * Perform dequantization and inverse DCT on one block of coefficients.
  175238. */
  175239. GLOBAL(void)
  175240. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175241. JCOEFPTR coef_block,
  175242. JSAMPARRAY output_buf, JDIMENSION output_col)
  175243. {
  175244. INT32 tmp0, tmp1, tmp2, tmp3;
  175245. INT32 tmp10, tmp11, tmp12, tmp13;
  175246. INT32 z1, z2, z3, z4, z5;
  175247. JCOEFPTR inptr;
  175248. ISLOW_MULT_TYPE * quantptr;
  175249. int * wsptr;
  175250. JSAMPROW outptr;
  175251. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175252. int ctr;
  175253. int workspace[DCTSIZE2]; /* buffers data between passes */
  175254. SHIFT_TEMPS
  175255. /* Pass 1: process columns from input, store into work array. */
  175256. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175257. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175258. inptr = coef_block;
  175259. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175260. wsptr = workspace;
  175261. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175262. /* Due to quantization, we will usually find that many of the input
  175263. * coefficients are zero, especially the AC terms. We can exploit this
  175264. * by short-circuiting the IDCT calculation for any column in which all
  175265. * the AC terms are zero. In that case each output is equal to the
  175266. * DC coefficient (with scale factor as needed).
  175267. * With typical images and quantization tables, half or more of the
  175268. * column DCT calculations can be simplified this way.
  175269. */
  175270. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175271. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175272. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175273. inptr[DCTSIZE*7] == 0) {
  175274. /* AC terms all zero */
  175275. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175276. wsptr[DCTSIZE*0] = dcval;
  175277. wsptr[DCTSIZE*1] = dcval;
  175278. wsptr[DCTSIZE*2] = dcval;
  175279. wsptr[DCTSIZE*3] = dcval;
  175280. wsptr[DCTSIZE*4] = dcval;
  175281. wsptr[DCTSIZE*5] = dcval;
  175282. wsptr[DCTSIZE*6] = dcval;
  175283. wsptr[DCTSIZE*7] = dcval;
  175284. inptr++; /* advance pointers to next column */
  175285. quantptr++;
  175286. wsptr++;
  175287. continue;
  175288. }
  175289. /* Even part: reverse the even part of the forward DCT. */
  175290. /* The rotator is sqrt(2)*c(-6). */
  175291. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175292. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175293. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175294. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175295. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175296. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175297. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175298. tmp0 = (z2 + z3) << CONST_BITS;
  175299. tmp1 = (z2 - z3) << CONST_BITS;
  175300. tmp10 = tmp0 + tmp3;
  175301. tmp13 = tmp0 - tmp3;
  175302. tmp11 = tmp1 + tmp2;
  175303. tmp12 = tmp1 - tmp2;
  175304. /* Odd part per figure 8; the matrix is unitary and hence its
  175305. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175306. */
  175307. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175308. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175309. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175310. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175311. z1 = tmp0 + tmp3;
  175312. z2 = tmp1 + tmp2;
  175313. z3 = tmp0 + tmp2;
  175314. z4 = tmp1 + tmp3;
  175315. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175316. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175317. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175318. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175319. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175320. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175321. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175322. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175323. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175324. z3 += z5;
  175325. z4 += z5;
  175326. tmp0 += z1 + z3;
  175327. tmp1 += z2 + z4;
  175328. tmp2 += z2 + z3;
  175329. tmp3 += z1 + z4;
  175330. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175331. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175332. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175333. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175334. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175335. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175336. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175337. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175338. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175339. inptr++; /* advance pointers to next column */
  175340. quantptr++;
  175341. wsptr++;
  175342. }
  175343. /* Pass 2: process rows from work array, store into output array. */
  175344. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175345. /* and also undo the PASS1_BITS scaling. */
  175346. wsptr = workspace;
  175347. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175348. outptr = output_buf[ctr] + output_col;
  175349. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175350. * However, the column calculation has created many nonzero AC terms, so
  175351. * the simplification applies less often (typically 5% to 10% of the time).
  175352. * On machines with very fast multiplication, it's possible that the
  175353. * test takes more time than it's worth. In that case this section
  175354. * may be commented out.
  175355. */
  175356. #ifndef NO_ZERO_ROW_TEST
  175357. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175358. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175359. /* AC terms all zero */
  175360. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175361. & RANGE_MASK];
  175362. outptr[0] = dcval;
  175363. outptr[1] = dcval;
  175364. outptr[2] = dcval;
  175365. outptr[3] = dcval;
  175366. outptr[4] = dcval;
  175367. outptr[5] = dcval;
  175368. outptr[6] = dcval;
  175369. outptr[7] = dcval;
  175370. wsptr += DCTSIZE; /* advance pointer to next row */
  175371. continue;
  175372. }
  175373. #endif
  175374. /* Even part: reverse the even part of the forward DCT. */
  175375. /* The rotator is sqrt(2)*c(-6). */
  175376. z2 = (INT32) wsptr[2];
  175377. z3 = (INT32) wsptr[6];
  175378. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175379. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175380. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175381. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175382. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175383. tmp10 = tmp0 + tmp3;
  175384. tmp13 = tmp0 - tmp3;
  175385. tmp11 = tmp1 + tmp2;
  175386. tmp12 = tmp1 - tmp2;
  175387. /* Odd part per figure 8; the matrix is unitary and hence its
  175388. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175389. */
  175390. tmp0 = (INT32) wsptr[7];
  175391. tmp1 = (INT32) wsptr[5];
  175392. tmp2 = (INT32) wsptr[3];
  175393. tmp3 = (INT32) wsptr[1];
  175394. z1 = tmp0 + tmp3;
  175395. z2 = tmp1 + tmp2;
  175396. z3 = tmp0 + tmp2;
  175397. z4 = tmp1 + tmp3;
  175398. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175399. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175400. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175401. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175402. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175403. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175404. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175405. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175406. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175407. z3 += z5;
  175408. z4 += z5;
  175409. tmp0 += z1 + z3;
  175410. tmp1 += z2 + z4;
  175411. tmp2 += z2 + z3;
  175412. tmp3 += z1 + z4;
  175413. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175414. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175415. CONST_BITS+PASS1_BITS+3)
  175416. & RANGE_MASK];
  175417. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175418. CONST_BITS+PASS1_BITS+3)
  175419. & RANGE_MASK];
  175420. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175421. CONST_BITS+PASS1_BITS+3)
  175422. & RANGE_MASK];
  175423. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175424. CONST_BITS+PASS1_BITS+3)
  175425. & RANGE_MASK];
  175426. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175427. CONST_BITS+PASS1_BITS+3)
  175428. & RANGE_MASK];
  175429. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175430. CONST_BITS+PASS1_BITS+3)
  175431. & RANGE_MASK];
  175432. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175433. CONST_BITS+PASS1_BITS+3)
  175434. & RANGE_MASK];
  175435. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175436. CONST_BITS+PASS1_BITS+3)
  175437. & RANGE_MASK];
  175438. wsptr += DCTSIZE; /* advance pointer to next row */
  175439. }
  175440. }
  175441. #endif /* DCT_ISLOW_SUPPORTED */
  175442. /*** End of inlined file: jidctint.c ***/
  175443. /*** Start of inlined file: jidctred.c ***/
  175444. #define JPEG_INTERNALS
  175445. #ifdef IDCT_SCALING_SUPPORTED
  175446. /*
  175447. * This module is specialized to the case DCTSIZE = 8.
  175448. */
  175449. #if DCTSIZE != 8
  175450. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175451. #endif
  175452. /* Scaling is the same as in jidctint.c. */
  175453. #if BITS_IN_JSAMPLE == 8
  175454. #define CONST_BITS 13
  175455. #define PASS1_BITS 2
  175456. #else
  175457. #define CONST_BITS 13
  175458. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175459. #endif
  175460. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175461. * causing a lot of useless floating-point operations at run time.
  175462. * To get around this we use the following pre-calculated constants.
  175463. * If you change CONST_BITS you may want to add appropriate values.
  175464. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175465. */
  175466. #if CONST_BITS == 13
  175467. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175468. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175469. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175470. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175471. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175472. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175473. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175474. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175475. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175476. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175477. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175478. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175479. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175480. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175481. #else
  175482. #define FIX_0_211164243 FIX(0.211164243)
  175483. #define FIX_0_509795579 FIX(0.509795579)
  175484. #define FIX_0_601344887 FIX(0.601344887)
  175485. #define FIX_0_720959822 FIX(0.720959822)
  175486. #define FIX_0_765366865 FIX(0.765366865)
  175487. #define FIX_0_850430095 FIX(0.850430095)
  175488. #define FIX_0_899976223 FIX(0.899976223)
  175489. #define FIX_1_061594337 FIX(1.061594337)
  175490. #define FIX_1_272758580 FIX(1.272758580)
  175491. #define FIX_1_451774981 FIX(1.451774981)
  175492. #define FIX_1_847759065 FIX(1.847759065)
  175493. #define FIX_2_172734803 FIX(2.172734803)
  175494. #define FIX_2_562915447 FIX(2.562915447)
  175495. #define FIX_3_624509785 FIX(3.624509785)
  175496. #endif
  175497. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175498. * For 8-bit samples with the recommended scaling, all the variable
  175499. * and constant values involved are no more than 16 bits wide, so a
  175500. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175501. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175502. */
  175503. #if BITS_IN_JSAMPLE == 8
  175504. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175505. #else
  175506. #define MULTIPLY(var,const) ((var) * (const))
  175507. #endif
  175508. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175509. * entry; produce an int result. In this module, both inputs and result
  175510. * are 16 bits or less, so either int or short multiply will work.
  175511. */
  175512. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175513. /*
  175514. * Perform dequantization and inverse DCT on one block of coefficients,
  175515. * producing a reduced-size 4x4 output block.
  175516. */
  175517. GLOBAL(void)
  175518. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175519. JCOEFPTR coef_block,
  175520. JSAMPARRAY output_buf, JDIMENSION output_col)
  175521. {
  175522. INT32 tmp0, tmp2, tmp10, tmp12;
  175523. INT32 z1, z2, z3, z4;
  175524. JCOEFPTR inptr;
  175525. ISLOW_MULT_TYPE * quantptr;
  175526. int * wsptr;
  175527. JSAMPROW outptr;
  175528. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175529. int ctr;
  175530. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175531. SHIFT_TEMPS
  175532. /* Pass 1: process columns from input, store into work array. */
  175533. inptr = coef_block;
  175534. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175535. wsptr = workspace;
  175536. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175537. /* Don't bother to process column 4, because second pass won't use it */
  175538. if (ctr == DCTSIZE-4)
  175539. continue;
  175540. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175541. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175542. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175543. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175544. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175545. wsptr[DCTSIZE*0] = dcval;
  175546. wsptr[DCTSIZE*1] = dcval;
  175547. wsptr[DCTSIZE*2] = dcval;
  175548. wsptr[DCTSIZE*3] = dcval;
  175549. continue;
  175550. }
  175551. /* Even part */
  175552. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175553. tmp0 <<= (CONST_BITS+1);
  175554. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175555. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175556. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175557. tmp10 = tmp0 + tmp2;
  175558. tmp12 = tmp0 - tmp2;
  175559. /* Odd part */
  175560. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175561. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175562. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175563. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175564. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175565. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175566. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175567. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175568. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175569. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175570. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175571. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175572. /* Final output stage */
  175573. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175574. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175575. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175576. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175577. }
  175578. /* Pass 2: process 4 rows from work array, store into output array. */
  175579. wsptr = workspace;
  175580. for (ctr = 0; ctr < 4; ctr++) {
  175581. outptr = output_buf[ctr] + output_col;
  175582. /* It's not clear whether a zero row test is worthwhile here ... */
  175583. #ifndef NO_ZERO_ROW_TEST
  175584. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175585. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175586. /* AC terms all zero */
  175587. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175588. & RANGE_MASK];
  175589. outptr[0] = dcval;
  175590. outptr[1] = dcval;
  175591. outptr[2] = dcval;
  175592. outptr[3] = dcval;
  175593. wsptr += DCTSIZE; /* advance pointer to next row */
  175594. continue;
  175595. }
  175596. #endif
  175597. /* Even part */
  175598. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175599. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175600. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175601. tmp10 = tmp0 + tmp2;
  175602. tmp12 = tmp0 - tmp2;
  175603. /* Odd part */
  175604. z1 = (INT32) wsptr[7];
  175605. z2 = (INT32) wsptr[5];
  175606. z3 = (INT32) wsptr[3];
  175607. z4 = (INT32) wsptr[1];
  175608. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175609. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175610. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175611. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175612. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175613. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175614. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175615. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175616. /* Final output stage */
  175617. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175618. CONST_BITS+PASS1_BITS+3+1)
  175619. & RANGE_MASK];
  175620. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175621. CONST_BITS+PASS1_BITS+3+1)
  175622. & RANGE_MASK];
  175623. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175624. CONST_BITS+PASS1_BITS+3+1)
  175625. & RANGE_MASK];
  175626. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175627. CONST_BITS+PASS1_BITS+3+1)
  175628. & RANGE_MASK];
  175629. wsptr += DCTSIZE; /* advance pointer to next row */
  175630. }
  175631. }
  175632. /*
  175633. * Perform dequantization and inverse DCT on one block of coefficients,
  175634. * producing a reduced-size 2x2 output block.
  175635. */
  175636. GLOBAL(void)
  175637. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175638. JCOEFPTR coef_block,
  175639. JSAMPARRAY output_buf, JDIMENSION output_col)
  175640. {
  175641. INT32 tmp0, tmp10, z1;
  175642. JCOEFPTR inptr;
  175643. ISLOW_MULT_TYPE * quantptr;
  175644. int * wsptr;
  175645. JSAMPROW outptr;
  175646. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175647. int ctr;
  175648. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175649. SHIFT_TEMPS
  175650. /* Pass 1: process columns from input, store into work array. */
  175651. inptr = coef_block;
  175652. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175653. wsptr = workspace;
  175654. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175655. /* Don't bother to process columns 2,4,6 */
  175656. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175657. continue;
  175658. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175659. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175660. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175661. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175662. wsptr[DCTSIZE*0] = dcval;
  175663. wsptr[DCTSIZE*1] = dcval;
  175664. continue;
  175665. }
  175666. /* Even part */
  175667. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175668. tmp10 = z1 << (CONST_BITS+2);
  175669. /* Odd part */
  175670. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175671. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175672. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175673. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175674. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175675. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175676. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175677. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175678. /* Final output stage */
  175679. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175680. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175681. }
  175682. /* Pass 2: process 2 rows from work array, store into output array. */
  175683. wsptr = workspace;
  175684. for (ctr = 0; ctr < 2; ctr++) {
  175685. outptr = output_buf[ctr] + output_col;
  175686. /* It's not clear whether a zero row test is worthwhile here ... */
  175687. #ifndef NO_ZERO_ROW_TEST
  175688. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175689. /* AC terms all zero */
  175690. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175691. & RANGE_MASK];
  175692. outptr[0] = dcval;
  175693. outptr[1] = dcval;
  175694. wsptr += DCTSIZE; /* advance pointer to next row */
  175695. continue;
  175696. }
  175697. #endif
  175698. /* Even part */
  175699. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175700. /* Odd part */
  175701. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175702. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175703. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175704. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175705. /* Final output stage */
  175706. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175707. CONST_BITS+PASS1_BITS+3+2)
  175708. & RANGE_MASK];
  175709. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175710. CONST_BITS+PASS1_BITS+3+2)
  175711. & RANGE_MASK];
  175712. wsptr += DCTSIZE; /* advance pointer to next row */
  175713. }
  175714. }
  175715. /*
  175716. * Perform dequantization and inverse DCT on one block of coefficients,
  175717. * producing a reduced-size 1x1 output block.
  175718. */
  175719. GLOBAL(void)
  175720. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175721. JCOEFPTR coef_block,
  175722. JSAMPARRAY output_buf, JDIMENSION output_col)
  175723. {
  175724. int dcval;
  175725. ISLOW_MULT_TYPE * quantptr;
  175726. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175727. SHIFT_TEMPS
  175728. /* We hardly need an inverse DCT routine for this: just take the
  175729. * average pixel value, which is one-eighth of the DC coefficient.
  175730. */
  175731. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175732. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175733. dcval = (int) DESCALE((INT32) dcval, 3);
  175734. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175735. }
  175736. #endif /* IDCT_SCALING_SUPPORTED */
  175737. /*** End of inlined file: jidctred.c ***/
  175738. /*** Start of inlined file: jmemmgr.c ***/
  175739. #define JPEG_INTERNALS
  175740. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175741. /*** Start of inlined file: jmemsys.h ***/
  175742. #ifndef __jmemsys_h__
  175743. #define __jmemsys_h__
  175744. /* Short forms of external names for systems with brain-damaged linkers. */
  175745. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175746. #define jpeg_get_small jGetSmall
  175747. #define jpeg_free_small jFreeSmall
  175748. #define jpeg_get_large jGetLarge
  175749. #define jpeg_free_large jFreeLarge
  175750. #define jpeg_mem_available jMemAvail
  175751. #define jpeg_open_backing_store jOpenBackStore
  175752. #define jpeg_mem_init jMemInit
  175753. #define jpeg_mem_term jMemTerm
  175754. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175755. /*
  175756. * These two functions are used to allocate and release small chunks of
  175757. * memory. (Typically the total amount requested through jpeg_get_small is
  175758. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175759. * Behavior should be the same as for the standard library functions malloc
  175760. * and free; in particular, jpeg_get_small must return NULL on failure.
  175761. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175762. * size of the object being freed, just in case it's needed.
  175763. * On an 80x86 machine using small-data memory model, these manage near heap.
  175764. */
  175765. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175766. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175767. size_t sizeofobject));
  175768. /*
  175769. * These two functions are used to allocate and release large chunks of
  175770. * memory (up to the total free space designated by jpeg_mem_available).
  175771. * The interface is the same as above, except that on an 80x86 machine,
  175772. * far pointers are used. On most other machines these are identical to
  175773. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175774. * in case a different allocation strategy is desirable for large chunks.
  175775. */
  175776. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175777. size_t sizeofobject));
  175778. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175779. size_t sizeofobject));
  175780. /*
  175781. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175782. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175783. * matter, but that case should never come into play). This macro is needed
  175784. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175785. * On those machines, we expect that jconfig.h will provide a proper value.
  175786. * On machines with 32-bit flat address spaces, any large constant may be used.
  175787. *
  175788. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175789. * size_t and will be a multiple of sizeof(align_type).
  175790. */
  175791. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175792. #define MAX_ALLOC_CHUNK 1000000000L
  175793. #endif
  175794. /*
  175795. * This routine computes the total space still available for allocation by
  175796. * jpeg_get_large. If more space than this is needed, backing store will be
  175797. * used. NOTE: any memory already allocated must not be counted.
  175798. *
  175799. * There is a minimum space requirement, corresponding to the minimum
  175800. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175801. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175802. * all working storage in memory, is also passed in case it is useful.
  175803. * Finally, the total space already allocated is passed. If no better
  175804. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175805. * is often a suitable calculation.
  175806. *
  175807. * It is OK for jpeg_mem_available to underestimate the space available
  175808. * (that'll just lead to more backing-store access than is really necessary).
  175809. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175810. * a slop factor from the true available space. 5% should be enough.
  175811. *
  175812. * On machines with lots of virtual memory, any large constant may be returned.
  175813. * Conversely, zero may be returned to always use the minimum amount of memory.
  175814. */
  175815. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175816. long min_bytes_needed,
  175817. long max_bytes_needed,
  175818. long already_allocated));
  175819. /*
  175820. * This structure holds whatever state is needed to access a single
  175821. * backing-store object. The read/write/close method pointers are called
  175822. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175823. * are private to the system-dependent backing store routines.
  175824. */
  175825. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175826. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175827. typedef unsigned short XMSH; /* type of extended-memory handles */
  175828. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175829. typedef union {
  175830. short file_handle; /* DOS file handle if it's a temp file */
  175831. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175832. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175833. } handle_union;
  175834. #endif /* USE_MSDOS_MEMMGR */
  175835. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175836. #include <Files.h>
  175837. #endif /* USE_MAC_MEMMGR */
  175838. //typedef struct backing_store_struct * backing_store_ptr;
  175839. typedef struct backing_store_struct {
  175840. /* Methods for reading/writing/closing this backing-store object */
  175841. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175842. struct backing_store_struct *info,
  175843. void FAR * buffer_address,
  175844. long file_offset, long byte_count));
  175845. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175846. struct backing_store_struct *info,
  175847. void FAR * buffer_address,
  175848. long file_offset, long byte_count));
  175849. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175850. struct backing_store_struct *info));
  175851. /* Private fields for system-dependent backing-store management */
  175852. #ifdef USE_MSDOS_MEMMGR
  175853. /* For the MS-DOS manager (jmemdos.c), we need: */
  175854. handle_union handle; /* reference to backing-store storage object */
  175855. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175856. #else
  175857. #ifdef USE_MAC_MEMMGR
  175858. /* For the Mac manager (jmemmac.c), we need: */
  175859. short temp_file; /* file reference number to temp file */
  175860. FSSpec tempSpec; /* the FSSpec for the temp file */
  175861. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175862. #else
  175863. /* For a typical implementation with temp files, we need: */
  175864. FILE * temp_file; /* stdio reference to temp file */
  175865. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175866. #endif
  175867. #endif
  175868. } backing_store_info;
  175869. /*
  175870. * Initial opening of a backing-store object. This must fill in the
  175871. * read/write/close pointers in the object. The read/write routines
  175872. * may take an error exit if the specified maximum file size is exceeded.
  175873. * (If jpeg_mem_available always returns a large value, this routine can
  175874. * just take an error exit.)
  175875. */
  175876. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175877. struct backing_store_struct *info,
  175878. long total_bytes_needed));
  175879. /*
  175880. * These routines take care of any system-dependent initialization and
  175881. * cleanup required. jpeg_mem_init will be called before anything is
  175882. * allocated (and, therefore, nothing in cinfo is of use except the error
  175883. * manager pointer). It should return a suitable default value for
  175884. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175885. * application. (Note that max_memory_to_use is only important if
  175886. * jpeg_mem_available chooses to consult it ... no one else will.)
  175887. * jpeg_mem_term may assume that all requested memory has been freed and that
  175888. * all opened backing-store objects have been closed.
  175889. */
  175890. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175891. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175892. #endif
  175893. /*** End of inlined file: jmemsys.h ***/
  175894. /* import the system-dependent declarations */
  175895. #ifndef NO_GETENV
  175896. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175897. extern char * getenv JPP((const char * name));
  175898. #endif
  175899. #endif
  175900. /*
  175901. * Some important notes:
  175902. * The allocation routines provided here must never return NULL.
  175903. * They should exit to error_exit if unsuccessful.
  175904. *
  175905. * It's not a good idea to try to merge the sarray and barray routines,
  175906. * even though they are textually almost the same, because samples are
  175907. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175908. * in machines where byte pointers have a different representation from
  175909. * word pointers, the resulting machine code could not be the same.
  175910. */
  175911. /*
  175912. * Many machines require storage alignment: longs must start on 4-byte
  175913. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175914. * always returns pointers that are multiples of the worst-case alignment
  175915. * requirement, and we had better do so too.
  175916. * There isn't any really portable way to determine the worst-case alignment
  175917. * requirement. This module assumes that the alignment requirement is
  175918. * multiples of sizeof(ALIGN_TYPE).
  175919. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175920. * workstations (where doubles really do need 8-byte alignment) and will work
  175921. * fine on nearly everything. If your machine has lesser alignment needs,
  175922. * you can save a few bytes by making ALIGN_TYPE smaller.
  175923. * The only place I know of where this will NOT work is certain Macintosh
  175924. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175925. * Doing 10-byte alignment is counterproductive because longwords won't be
  175926. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175927. * such a compiler.
  175928. */
  175929. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175930. #define ALIGN_TYPE double
  175931. #endif
  175932. /*
  175933. * We allocate objects from "pools", where each pool is gotten with a single
  175934. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175935. * overhead within a pool, except for alignment padding. Each pool has a
  175936. * header with a link to the next pool of the same class.
  175937. * Small and large pool headers are identical except that the latter's
  175938. * link pointer must be FAR on 80x86 machines.
  175939. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175940. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175941. * of the alignment requirement of ALIGN_TYPE.
  175942. */
  175943. typedef union small_pool_struct * small_pool_ptr;
  175944. typedef union small_pool_struct {
  175945. struct {
  175946. small_pool_ptr next; /* next in list of pools */
  175947. size_t bytes_used; /* how many bytes already used within pool */
  175948. size_t bytes_left; /* bytes still available in this pool */
  175949. } hdr;
  175950. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175951. } small_pool_hdr;
  175952. typedef union large_pool_struct FAR * large_pool_ptr;
  175953. typedef union large_pool_struct {
  175954. struct {
  175955. large_pool_ptr next; /* next in list of pools */
  175956. size_t bytes_used; /* how many bytes already used within pool */
  175957. size_t bytes_left; /* bytes still available in this pool */
  175958. } hdr;
  175959. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175960. } large_pool_hdr;
  175961. /*
  175962. * Here is the full definition of a memory manager object.
  175963. */
  175964. typedef struct {
  175965. struct jpeg_memory_mgr pub; /* public fields */
  175966. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175967. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175968. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175969. /* Since we only have one lifetime class of virtual arrays, only one
  175970. * linked list is necessary (for each datatype). Note that the virtual
  175971. * array control blocks being linked together are actually stored somewhere
  175972. * in the small-pool list.
  175973. */
  175974. jvirt_sarray_ptr virt_sarray_list;
  175975. jvirt_barray_ptr virt_barray_list;
  175976. /* This counts total space obtained from jpeg_get_small/large */
  175977. long total_space_allocated;
  175978. /* alloc_sarray and alloc_barray set this value for use by virtual
  175979. * array routines.
  175980. */
  175981. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175982. } my_memory_mgr;
  175983. typedef my_memory_mgr * my_mem_ptr;
  175984. /*
  175985. * The control blocks for virtual arrays.
  175986. * Note that these blocks are allocated in the "small" pool area.
  175987. * System-dependent info for the associated backing store (if any) is hidden
  175988. * inside the backing_store_info struct.
  175989. */
  175990. struct jvirt_sarray_control {
  175991. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175992. JDIMENSION rows_in_array; /* total virtual array height */
  175993. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175994. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175995. JDIMENSION rows_in_mem; /* height of memory buffer */
  175996. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175997. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175998. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175999. boolean pre_zero; /* pre-zero mode requested? */
  176000. boolean dirty; /* do current buffer contents need written? */
  176001. boolean b_s_open; /* is backing-store data valid? */
  176002. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176003. backing_store_info b_s_info; /* System-dependent control info */
  176004. };
  176005. struct jvirt_barray_control {
  176006. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176007. JDIMENSION rows_in_array; /* total virtual array height */
  176008. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176009. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176010. JDIMENSION rows_in_mem; /* height of memory buffer */
  176011. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176012. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176013. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176014. boolean pre_zero; /* pre-zero mode requested? */
  176015. boolean dirty; /* do current buffer contents need written? */
  176016. boolean b_s_open; /* is backing-store data valid? */
  176017. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176018. backing_store_info b_s_info; /* System-dependent control info */
  176019. };
  176020. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176021. LOCAL(void)
  176022. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176023. {
  176024. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176025. small_pool_ptr shdr_ptr;
  176026. large_pool_ptr lhdr_ptr;
  176027. /* Since this is only a debugging stub, we can cheat a little by using
  176028. * fprintf directly rather than going through the trace message code.
  176029. * This is helpful because message parm array can't handle longs.
  176030. */
  176031. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176032. pool_id, mem->total_space_allocated);
  176033. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176034. lhdr_ptr = lhdr_ptr->hdr.next) {
  176035. fprintf(stderr, " Large chunk used %ld\n",
  176036. (long) lhdr_ptr->hdr.bytes_used);
  176037. }
  176038. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176039. shdr_ptr = shdr_ptr->hdr.next) {
  176040. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176041. (long) shdr_ptr->hdr.bytes_used,
  176042. (long) shdr_ptr->hdr.bytes_left);
  176043. }
  176044. }
  176045. #endif /* MEM_STATS */
  176046. LOCAL(void)
  176047. out_of_memory (j_common_ptr cinfo, int which)
  176048. /* Report an out-of-memory error and stop execution */
  176049. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176050. {
  176051. #ifdef MEM_STATS
  176052. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176053. #endif
  176054. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176055. }
  176056. /*
  176057. * Allocation of "small" objects.
  176058. *
  176059. * For these, we use pooled storage. When a new pool must be created,
  176060. * we try to get enough space for the current request plus a "slop" factor,
  176061. * where the slop will be the amount of leftover space in the new pool.
  176062. * The speed vs. space tradeoff is largely determined by the slop values.
  176063. * A different slop value is provided for each pool class (lifetime),
  176064. * and we also distinguish the first pool of a class from later ones.
  176065. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176066. * machines, but may be too small if longs are 64 bits or more.
  176067. */
  176068. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176069. {
  176070. 1600, /* first PERMANENT pool */
  176071. 16000 /* first IMAGE pool */
  176072. };
  176073. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176074. {
  176075. 0, /* additional PERMANENT pools */
  176076. 5000 /* additional IMAGE pools */
  176077. };
  176078. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176079. METHODDEF(void *)
  176080. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176081. /* Allocate a "small" object */
  176082. {
  176083. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176084. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176085. char * data_ptr;
  176086. size_t odd_bytes, min_request, slop;
  176087. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176088. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176089. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176090. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176091. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176092. if (odd_bytes > 0)
  176093. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176094. /* See if space is available in any existing pool */
  176095. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176096. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176097. prev_hdr_ptr = NULL;
  176098. hdr_ptr = mem->small_list[pool_id];
  176099. while (hdr_ptr != NULL) {
  176100. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176101. break; /* found pool with enough space */
  176102. prev_hdr_ptr = hdr_ptr;
  176103. hdr_ptr = hdr_ptr->hdr.next;
  176104. }
  176105. /* Time to make a new pool? */
  176106. if (hdr_ptr == NULL) {
  176107. /* min_request is what we need now, slop is what will be leftover */
  176108. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176109. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176110. slop = first_pool_slop[pool_id];
  176111. else
  176112. slop = extra_pool_slop[pool_id];
  176113. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176114. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176115. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176116. /* Try to get space, if fail reduce slop and try again */
  176117. for (;;) {
  176118. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176119. if (hdr_ptr != NULL)
  176120. break;
  176121. slop /= 2;
  176122. if (slop < MIN_SLOP) /* give up when it gets real small */
  176123. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176124. }
  176125. mem->total_space_allocated += min_request + slop;
  176126. /* Success, initialize the new pool header and add to end of list */
  176127. hdr_ptr->hdr.next = NULL;
  176128. hdr_ptr->hdr.bytes_used = 0;
  176129. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176130. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176131. mem->small_list[pool_id] = hdr_ptr;
  176132. else
  176133. prev_hdr_ptr->hdr.next = hdr_ptr;
  176134. }
  176135. /* OK, allocate the object from the current pool */
  176136. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176137. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176138. hdr_ptr->hdr.bytes_used += sizeofobject;
  176139. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176140. return (void *) data_ptr;
  176141. }
  176142. /*
  176143. * Allocation of "large" objects.
  176144. *
  176145. * The external semantics of these are the same as "small" objects,
  176146. * except that FAR pointers are used on 80x86. However the pool
  176147. * management heuristics are quite different. We assume that each
  176148. * request is large enough that it may as well be passed directly to
  176149. * jpeg_get_large; the pool management just links everything together
  176150. * so that we can free it all on demand.
  176151. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176152. * structures. The routines that create these structures (see below)
  176153. * deliberately bunch rows together to ensure a large request size.
  176154. */
  176155. METHODDEF(void FAR *)
  176156. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176157. /* Allocate a "large" object */
  176158. {
  176159. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176160. large_pool_ptr hdr_ptr;
  176161. size_t odd_bytes;
  176162. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176163. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176164. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176165. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176166. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176167. if (odd_bytes > 0)
  176168. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176169. /* Always make a new pool */
  176170. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176171. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176172. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176173. SIZEOF(large_pool_hdr));
  176174. if (hdr_ptr == NULL)
  176175. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176176. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176177. /* Success, initialize the new pool header and add to list */
  176178. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176179. /* We maintain space counts in each pool header for statistical purposes,
  176180. * even though they are not needed for allocation.
  176181. */
  176182. hdr_ptr->hdr.bytes_used = sizeofobject;
  176183. hdr_ptr->hdr.bytes_left = 0;
  176184. mem->large_list[pool_id] = hdr_ptr;
  176185. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176186. }
  176187. /*
  176188. * Creation of 2-D sample arrays.
  176189. * The pointers are in near heap, the samples themselves in FAR heap.
  176190. *
  176191. * To minimize allocation overhead and to allow I/O of large contiguous
  176192. * blocks, we allocate the sample rows in groups of as many rows as possible
  176193. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176194. * NB: the virtual array control routines, later in this file, know about
  176195. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176196. * object so that it can be saved away if this sarray is the workspace for
  176197. * a virtual array.
  176198. */
  176199. METHODDEF(JSAMPARRAY)
  176200. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176201. JDIMENSION samplesperrow, JDIMENSION numrows)
  176202. /* Allocate a 2-D sample array */
  176203. {
  176204. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176205. JSAMPARRAY result;
  176206. JSAMPROW workspace;
  176207. JDIMENSION rowsperchunk, currow, i;
  176208. long ltemp;
  176209. /* Calculate max # of rows allowed in one allocation chunk */
  176210. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176211. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176212. if (ltemp <= 0)
  176213. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176214. if (ltemp < (long) numrows)
  176215. rowsperchunk = (JDIMENSION) ltemp;
  176216. else
  176217. rowsperchunk = numrows;
  176218. mem->last_rowsperchunk = rowsperchunk;
  176219. /* Get space for row pointers (small object) */
  176220. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176221. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176222. /* Get the rows themselves (large objects) */
  176223. currow = 0;
  176224. while (currow < numrows) {
  176225. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176226. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176227. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176228. * SIZEOF(JSAMPLE)));
  176229. for (i = rowsperchunk; i > 0; i--) {
  176230. result[currow++] = workspace;
  176231. workspace += samplesperrow;
  176232. }
  176233. }
  176234. return result;
  176235. }
  176236. /*
  176237. * Creation of 2-D coefficient-block arrays.
  176238. * This is essentially the same as the code for sample arrays, above.
  176239. */
  176240. METHODDEF(JBLOCKARRAY)
  176241. alloc_barray (j_common_ptr cinfo, int pool_id,
  176242. JDIMENSION blocksperrow, JDIMENSION numrows)
  176243. /* Allocate a 2-D coefficient-block array */
  176244. {
  176245. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176246. JBLOCKARRAY result;
  176247. JBLOCKROW workspace;
  176248. JDIMENSION rowsperchunk, currow, i;
  176249. long ltemp;
  176250. /* Calculate max # of rows allowed in one allocation chunk */
  176251. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176252. ((long) blocksperrow * SIZEOF(JBLOCK));
  176253. if (ltemp <= 0)
  176254. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176255. if (ltemp < (long) numrows)
  176256. rowsperchunk = (JDIMENSION) ltemp;
  176257. else
  176258. rowsperchunk = numrows;
  176259. mem->last_rowsperchunk = rowsperchunk;
  176260. /* Get space for row pointers (small object) */
  176261. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176262. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176263. /* Get the rows themselves (large objects) */
  176264. currow = 0;
  176265. while (currow < numrows) {
  176266. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176267. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176268. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176269. * SIZEOF(JBLOCK)));
  176270. for (i = rowsperchunk; i > 0; i--) {
  176271. result[currow++] = workspace;
  176272. workspace += blocksperrow;
  176273. }
  176274. }
  176275. return result;
  176276. }
  176277. /*
  176278. * About virtual array management:
  176279. *
  176280. * The above "normal" array routines are only used to allocate strip buffers
  176281. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176282. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176283. * time, but the memory manager must save the whole array for repeated
  176284. * accesses. The intended implementation is that there is a strip buffer in
  176285. * memory (as high as is possible given the desired memory limit), plus a
  176286. * backing file that holds the rest of the array.
  176287. *
  176288. * The request_virt_array routines are told the total size of the image and
  176289. * the maximum number of rows that will be accessed at once. The in-memory
  176290. * buffer must be at least as large as the maxaccess value.
  176291. *
  176292. * The request routines create control blocks but not the in-memory buffers.
  176293. * That is postponed until realize_virt_arrays is called. At that time the
  176294. * total amount of space needed is known (approximately, anyway), so free
  176295. * memory can be divided up fairly.
  176296. *
  176297. * The access_virt_array routines are responsible for making a specific strip
  176298. * area accessible (after reading or writing the backing file, if necessary).
  176299. * Note that the access routines are told whether the caller intends to modify
  176300. * the accessed strip; during a read-only pass this saves having to rewrite
  176301. * data to disk. The access routines are also responsible for pre-zeroing
  176302. * any newly accessed rows, if pre-zeroing was requested.
  176303. *
  176304. * In current usage, the access requests are usually for nonoverlapping
  176305. * strips; that is, successive access start_row numbers differ by exactly
  176306. * num_rows = maxaccess. This means we can get good performance with simple
  176307. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176308. * of the access height; then there will never be accesses across bufferload
  176309. * boundaries. The code will still work with overlapping access requests,
  176310. * but it doesn't handle bufferload overlaps very efficiently.
  176311. */
  176312. METHODDEF(jvirt_sarray_ptr)
  176313. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176314. JDIMENSION samplesperrow, JDIMENSION numrows,
  176315. JDIMENSION maxaccess)
  176316. /* Request a virtual 2-D sample array */
  176317. {
  176318. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176319. jvirt_sarray_ptr result;
  176320. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176321. if (pool_id != JPOOL_IMAGE)
  176322. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176323. /* get control block */
  176324. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176325. SIZEOF(struct jvirt_sarray_control));
  176326. result->mem_buffer = NULL; /* marks array not yet realized */
  176327. result->rows_in_array = numrows;
  176328. result->samplesperrow = samplesperrow;
  176329. result->maxaccess = maxaccess;
  176330. result->pre_zero = pre_zero;
  176331. result->b_s_open = FALSE; /* no associated backing-store object */
  176332. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176333. mem->virt_sarray_list = result;
  176334. return result;
  176335. }
  176336. METHODDEF(jvirt_barray_ptr)
  176337. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176338. JDIMENSION blocksperrow, JDIMENSION numrows,
  176339. JDIMENSION maxaccess)
  176340. /* Request a virtual 2-D coefficient-block array */
  176341. {
  176342. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176343. jvirt_barray_ptr result;
  176344. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176345. if (pool_id != JPOOL_IMAGE)
  176346. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176347. /* get control block */
  176348. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176349. SIZEOF(struct jvirt_barray_control));
  176350. result->mem_buffer = NULL; /* marks array not yet realized */
  176351. result->rows_in_array = numrows;
  176352. result->blocksperrow = blocksperrow;
  176353. result->maxaccess = maxaccess;
  176354. result->pre_zero = pre_zero;
  176355. result->b_s_open = FALSE; /* no associated backing-store object */
  176356. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176357. mem->virt_barray_list = result;
  176358. return result;
  176359. }
  176360. METHODDEF(void)
  176361. realize_virt_arrays (j_common_ptr cinfo)
  176362. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176363. {
  176364. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176365. long space_per_minheight, maximum_space, avail_mem;
  176366. long minheights, max_minheights;
  176367. jvirt_sarray_ptr sptr;
  176368. jvirt_barray_ptr bptr;
  176369. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176370. * and the maximum space needed (full image height in each buffer).
  176371. * These may be of use to the system-dependent jpeg_mem_available routine.
  176372. */
  176373. space_per_minheight = 0;
  176374. maximum_space = 0;
  176375. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176376. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176377. space_per_minheight += (long) sptr->maxaccess *
  176378. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176379. maximum_space += (long) sptr->rows_in_array *
  176380. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176381. }
  176382. }
  176383. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176384. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176385. space_per_minheight += (long) bptr->maxaccess *
  176386. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176387. maximum_space += (long) bptr->rows_in_array *
  176388. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176389. }
  176390. }
  176391. if (space_per_minheight <= 0)
  176392. return; /* no unrealized arrays, no work */
  176393. /* Determine amount of memory to actually use; this is system-dependent. */
  176394. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176395. mem->total_space_allocated);
  176396. /* If the maximum space needed is available, make all the buffers full
  176397. * height; otherwise parcel it out with the same number of minheights
  176398. * in each buffer.
  176399. */
  176400. if (avail_mem >= maximum_space)
  176401. max_minheights = 1000000000L;
  176402. else {
  176403. max_minheights = avail_mem / space_per_minheight;
  176404. /* If there doesn't seem to be enough space, try to get the minimum
  176405. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176406. */
  176407. if (max_minheights <= 0)
  176408. max_minheights = 1;
  176409. }
  176410. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176411. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176412. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176413. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176414. if (minheights <= max_minheights) {
  176415. /* This buffer fits in memory */
  176416. sptr->rows_in_mem = sptr->rows_in_array;
  176417. } else {
  176418. /* It doesn't fit in memory, create backing store. */
  176419. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176420. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176421. (long) sptr->rows_in_array *
  176422. (long) sptr->samplesperrow *
  176423. (long) SIZEOF(JSAMPLE));
  176424. sptr->b_s_open = TRUE;
  176425. }
  176426. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176427. sptr->samplesperrow, sptr->rows_in_mem);
  176428. sptr->rowsperchunk = mem->last_rowsperchunk;
  176429. sptr->cur_start_row = 0;
  176430. sptr->first_undef_row = 0;
  176431. sptr->dirty = FALSE;
  176432. }
  176433. }
  176434. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176435. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176436. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176437. if (minheights <= max_minheights) {
  176438. /* This buffer fits in memory */
  176439. bptr->rows_in_mem = bptr->rows_in_array;
  176440. } else {
  176441. /* It doesn't fit in memory, create backing store. */
  176442. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176443. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176444. (long) bptr->rows_in_array *
  176445. (long) bptr->blocksperrow *
  176446. (long) SIZEOF(JBLOCK));
  176447. bptr->b_s_open = TRUE;
  176448. }
  176449. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176450. bptr->blocksperrow, bptr->rows_in_mem);
  176451. bptr->rowsperchunk = mem->last_rowsperchunk;
  176452. bptr->cur_start_row = 0;
  176453. bptr->first_undef_row = 0;
  176454. bptr->dirty = FALSE;
  176455. }
  176456. }
  176457. }
  176458. LOCAL(void)
  176459. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176460. /* Do backing store read or write of a virtual sample array */
  176461. {
  176462. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176463. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176464. file_offset = ptr->cur_start_row * bytesperrow;
  176465. /* Loop to read or write each allocation chunk in mem_buffer */
  176466. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176467. /* One chunk, but check for short chunk at end of buffer */
  176468. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176469. /* Transfer no more than is currently defined */
  176470. thisrow = (long) ptr->cur_start_row + i;
  176471. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176472. /* Transfer no more than fits in file */
  176473. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176474. if (rows <= 0) /* this chunk might be past end of file! */
  176475. break;
  176476. byte_count = rows * bytesperrow;
  176477. if (writing)
  176478. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176479. (void FAR *) ptr->mem_buffer[i],
  176480. file_offset, byte_count);
  176481. else
  176482. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176483. (void FAR *) ptr->mem_buffer[i],
  176484. file_offset, byte_count);
  176485. file_offset += byte_count;
  176486. }
  176487. }
  176488. LOCAL(void)
  176489. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176490. /* Do backing store read or write of a virtual coefficient-block array */
  176491. {
  176492. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176493. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176494. file_offset = ptr->cur_start_row * bytesperrow;
  176495. /* Loop to read or write each allocation chunk in mem_buffer */
  176496. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176497. /* One chunk, but check for short chunk at end of buffer */
  176498. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176499. /* Transfer no more than is currently defined */
  176500. thisrow = (long) ptr->cur_start_row + i;
  176501. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176502. /* Transfer no more than fits in file */
  176503. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176504. if (rows <= 0) /* this chunk might be past end of file! */
  176505. break;
  176506. byte_count = rows * bytesperrow;
  176507. if (writing)
  176508. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176509. (void FAR *) ptr->mem_buffer[i],
  176510. file_offset, byte_count);
  176511. else
  176512. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176513. (void FAR *) ptr->mem_buffer[i],
  176514. file_offset, byte_count);
  176515. file_offset += byte_count;
  176516. }
  176517. }
  176518. METHODDEF(JSAMPARRAY)
  176519. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176520. JDIMENSION start_row, JDIMENSION num_rows,
  176521. boolean writable)
  176522. /* Access the part of a virtual sample array starting at start_row */
  176523. /* and extending for num_rows rows. writable is true if */
  176524. /* caller intends to modify the accessed area. */
  176525. {
  176526. JDIMENSION end_row = start_row + num_rows;
  176527. JDIMENSION undef_row;
  176528. /* debugging check */
  176529. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176530. ptr->mem_buffer == NULL)
  176531. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176532. /* Make the desired part of the virtual array accessible */
  176533. if (start_row < ptr->cur_start_row ||
  176534. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176535. if (! ptr->b_s_open)
  176536. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176537. /* Flush old buffer contents if necessary */
  176538. if (ptr->dirty) {
  176539. do_sarray_io(cinfo, ptr, TRUE);
  176540. ptr->dirty = FALSE;
  176541. }
  176542. /* Decide what part of virtual array to access.
  176543. * Algorithm: if target address > current window, assume forward scan,
  176544. * load starting at target address. If target address < current window,
  176545. * assume backward scan, load so that target area is top of window.
  176546. * Note that when switching from forward write to forward read, will have
  176547. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176548. */
  176549. if (start_row > ptr->cur_start_row) {
  176550. ptr->cur_start_row = start_row;
  176551. } else {
  176552. /* use long arithmetic here to avoid overflow & unsigned problems */
  176553. long ltemp;
  176554. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176555. if (ltemp < 0)
  176556. ltemp = 0; /* don't fall off front end of file */
  176557. ptr->cur_start_row = (JDIMENSION) ltemp;
  176558. }
  176559. /* Read in the selected part of the array.
  176560. * During the initial write pass, we will do no actual read
  176561. * because the selected part is all undefined.
  176562. */
  176563. do_sarray_io(cinfo, ptr, FALSE);
  176564. }
  176565. /* Ensure the accessed part of the array is defined; prezero if needed.
  176566. * To improve locality of access, we only prezero the part of the array
  176567. * that the caller is about to access, not the entire in-memory array.
  176568. */
  176569. if (ptr->first_undef_row < end_row) {
  176570. if (ptr->first_undef_row < start_row) {
  176571. if (writable) /* writer skipped over a section of array */
  176572. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176573. undef_row = start_row; /* but reader is allowed to read ahead */
  176574. } else {
  176575. undef_row = ptr->first_undef_row;
  176576. }
  176577. if (writable)
  176578. ptr->first_undef_row = end_row;
  176579. if (ptr->pre_zero) {
  176580. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176581. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176582. end_row -= ptr->cur_start_row;
  176583. while (undef_row < end_row) {
  176584. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176585. undef_row++;
  176586. }
  176587. } else {
  176588. if (! writable) /* reader looking at undefined data */
  176589. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176590. }
  176591. }
  176592. /* Flag the buffer dirty if caller will write in it */
  176593. if (writable)
  176594. ptr->dirty = TRUE;
  176595. /* Return address of proper part of the buffer */
  176596. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176597. }
  176598. METHODDEF(JBLOCKARRAY)
  176599. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176600. JDIMENSION start_row, JDIMENSION num_rows,
  176601. boolean writable)
  176602. /* Access the part of a virtual block array starting at start_row */
  176603. /* and extending for num_rows rows. writable is true if */
  176604. /* caller intends to modify the accessed area. */
  176605. {
  176606. JDIMENSION end_row = start_row + num_rows;
  176607. JDIMENSION undef_row;
  176608. /* debugging check */
  176609. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176610. ptr->mem_buffer == NULL)
  176611. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176612. /* Make the desired part of the virtual array accessible */
  176613. if (start_row < ptr->cur_start_row ||
  176614. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176615. if (! ptr->b_s_open)
  176616. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176617. /* Flush old buffer contents if necessary */
  176618. if (ptr->dirty) {
  176619. do_barray_io(cinfo, ptr, TRUE);
  176620. ptr->dirty = FALSE;
  176621. }
  176622. /* Decide what part of virtual array to access.
  176623. * Algorithm: if target address > current window, assume forward scan,
  176624. * load starting at target address. If target address < current window,
  176625. * assume backward scan, load so that target area is top of window.
  176626. * Note that when switching from forward write to forward read, will have
  176627. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176628. */
  176629. if (start_row > ptr->cur_start_row) {
  176630. ptr->cur_start_row = start_row;
  176631. } else {
  176632. /* use long arithmetic here to avoid overflow & unsigned problems */
  176633. long ltemp;
  176634. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176635. if (ltemp < 0)
  176636. ltemp = 0; /* don't fall off front end of file */
  176637. ptr->cur_start_row = (JDIMENSION) ltemp;
  176638. }
  176639. /* Read in the selected part of the array.
  176640. * During the initial write pass, we will do no actual read
  176641. * because the selected part is all undefined.
  176642. */
  176643. do_barray_io(cinfo, ptr, FALSE);
  176644. }
  176645. /* Ensure the accessed part of the array is defined; prezero if needed.
  176646. * To improve locality of access, we only prezero the part of the array
  176647. * that the caller is about to access, not the entire in-memory array.
  176648. */
  176649. if (ptr->first_undef_row < end_row) {
  176650. if (ptr->first_undef_row < start_row) {
  176651. if (writable) /* writer skipped over a section of array */
  176652. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176653. undef_row = start_row; /* but reader is allowed to read ahead */
  176654. } else {
  176655. undef_row = ptr->first_undef_row;
  176656. }
  176657. if (writable)
  176658. ptr->first_undef_row = end_row;
  176659. if (ptr->pre_zero) {
  176660. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176661. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176662. end_row -= ptr->cur_start_row;
  176663. while (undef_row < end_row) {
  176664. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176665. undef_row++;
  176666. }
  176667. } else {
  176668. if (! writable) /* reader looking at undefined data */
  176669. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176670. }
  176671. }
  176672. /* Flag the buffer dirty if caller will write in it */
  176673. if (writable)
  176674. ptr->dirty = TRUE;
  176675. /* Return address of proper part of the buffer */
  176676. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176677. }
  176678. /*
  176679. * Release all objects belonging to a specified pool.
  176680. */
  176681. METHODDEF(void)
  176682. free_pool (j_common_ptr cinfo, int pool_id)
  176683. {
  176684. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176685. small_pool_ptr shdr_ptr;
  176686. large_pool_ptr lhdr_ptr;
  176687. size_t space_freed;
  176688. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176689. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176690. #ifdef MEM_STATS
  176691. if (cinfo->err->trace_level > 1)
  176692. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176693. #endif
  176694. /* If freeing IMAGE pool, close any virtual arrays first */
  176695. if (pool_id == JPOOL_IMAGE) {
  176696. jvirt_sarray_ptr sptr;
  176697. jvirt_barray_ptr bptr;
  176698. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176699. if (sptr->b_s_open) { /* there may be no backing store */
  176700. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176701. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176702. }
  176703. }
  176704. mem->virt_sarray_list = NULL;
  176705. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176706. if (bptr->b_s_open) { /* there may be no backing store */
  176707. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176708. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176709. }
  176710. }
  176711. mem->virt_barray_list = NULL;
  176712. }
  176713. /* Release large objects */
  176714. lhdr_ptr = mem->large_list[pool_id];
  176715. mem->large_list[pool_id] = NULL;
  176716. while (lhdr_ptr != NULL) {
  176717. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176718. space_freed = lhdr_ptr->hdr.bytes_used +
  176719. lhdr_ptr->hdr.bytes_left +
  176720. SIZEOF(large_pool_hdr);
  176721. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176722. mem->total_space_allocated -= space_freed;
  176723. lhdr_ptr = next_lhdr_ptr;
  176724. }
  176725. /* Release small objects */
  176726. shdr_ptr = mem->small_list[pool_id];
  176727. mem->small_list[pool_id] = NULL;
  176728. while (shdr_ptr != NULL) {
  176729. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176730. space_freed = shdr_ptr->hdr.bytes_used +
  176731. shdr_ptr->hdr.bytes_left +
  176732. SIZEOF(small_pool_hdr);
  176733. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176734. mem->total_space_allocated -= space_freed;
  176735. shdr_ptr = next_shdr_ptr;
  176736. }
  176737. }
  176738. /*
  176739. * Close up shop entirely.
  176740. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176741. */
  176742. METHODDEF(void)
  176743. self_destruct (j_common_ptr cinfo)
  176744. {
  176745. int pool;
  176746. /* Close all backing store, release all memory.
  176747. * Releasing pools in reverse order might help avoid fragmentation
  176748. * with some (brain-damaged) malloc libraries.
  176749. */
  176750. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176751. free_pool(cinfo, pool);
  176752. }
  176753. /* Release the memory manager control block too. */
  176754. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176755. cinfo->mem = NULL; /* ensures I will be called only once */
  176756. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176757. }
  176758. /*
  176759. * Memory manager initialization.
  176760. * When this is called, only the error manager pointer is valid in cinfo!
  176761. */
  176762. GLOBAL(void)
  176763. jinit_memory_mgr (j_common_ptr cinfo)
  176764. {
  176765. my_mem_ptr mem;
  176766. long max_to_use;
  176767. int pool;
  176768. size_t test_mac;
  176769. cinfo->mem = NULL; /* for safety if init fails */
  176770. /* Check for configuration errors.
  176771. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176772. * doesn't reflect any real hardware alignment requirement.
  176773. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176774. * in common if and only if X is a power of 2, ie has only one one-bit.
  176775. * Some compilers may give an "unreachable code" warning here; ignore it.
  176776. */
  176777. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176778. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176779. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176780. * a multiple of SIZEOF(ALIGN_TYPE).
  176781. * Again, an "unreachable code" warning may be ignored here.
  176782. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176783. */
  176784. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176785. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176786. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176787. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176788. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176789. /* Attempt to allocate memory manager's control block */
  176790. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176791. if (mem == NULL) {
  176792. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176793. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176794. }
  176795. /* OK, fill in the method pointers */
  176796. mem->pub.alloc_small = alloc_small;
  176797. mem->pub.alloc_large = alloc_large;
  176798. mem->pub.alloc_sarray = alloc_sarray;
  176799. mem->pub.alloc_barray = alloc_barray;
  176800. mem->pub.request_virt_sarray = request_virt_sarray;
  176801. mem->pub.request_virt_barray = request_virt_barray;
  176802. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176803. mem->pub.access_virt_sarray = access_virt_sarray;
  176804. mem->pub.access_virt_barray = access_virt_barray;
  176805. mem->pub.free_pool = free_pool;
  176806. mem->pub.self_destruct = self_destruct;
  176807. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176808. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176809. /* Initialize working state */
  176810. mem->pub.max_memory_to_use = max_to_use;
  176811. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176812. mem->small_list[pool] = NULL;
  176813. mem->large_list[pool] = NULL;
  176814. }
  176815. mem->virt_sarray_list = NULL;
  176816. mem->virt_barray_list = NULL;
  176817. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176818. /* Declare ourselves open for business */
  176819. cinfo->mem = & mem->pub;
  176820. /* Check for an environment variable JPEGMEM; if found, override the
  176821. * default max_memory setting from jpeg_mem_init. Note that the
  176822. * surrounding application may again override this value.
  176823. * If your system doesn't support getenv(), define NO_GETENV to disable
  176824. * this feature.
  176825. */
  176826. #ifndef NO_GETENV
  176827. { char * memenv;
  176828. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176829. char ch = 'x';
  176830. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176831. if (ch == 'm' || ch == 'M')
  176832. max_to_use *= 1000L;
  176833. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176834. }
  176835. }
  176836. }
  176837. #endif
  176838. }
  176839. /*** End of inlined file: jmemmgr.c ***/
  176840. /*** Start of inlined file: jmemnobs.c ***/
  176841. #define JPEG_INTERNALS
  176842. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176843. extern void * malloc JPP((size_t size));
  176844. extern void free JPP((void *ptr));
  176845. #endif
  176846. /*
  176847. * Memory allocation and freeing are controlled by the regular library
  176848. * routines malloc() and free().
  176849. */
  176850. GLOBAL(void *)
  176851. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176852. {
  176853. return (void *) malloc(sizeofobject);
  176854. }
  176855. GLOBAL(void)
  176856. jpeg_free_small (j_common_ptr , void * object, size_t)
  176857. {
  176858. free(object);
  176859. }
  176860. /*
  176861. * "Large" objects are treated the same as "small" ones.
  176862. * NB: although we include FAR keywords in the routine declarations,
  176863. * this file won't actually work in 80x86 small/medium model; at least,
  176864. * you probably won't be able to process useful-size images in only 64KB.
  176865. */
  176866. GLOBAL(void FAR *)
  176867. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176868. {
  176869. return (void FAR *) malloc(sizeofobject);
  176870. }
  176871. GLOBAL(void)
  176872. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176873. {
  176874. free(object);
  176875. }
  176876. /*
  176877. * This routine computes the total memory space available for allocation.
  176878. * Here we always say, "we got all you want bud!"
  176879. */
  176880. GLOBAL(long)
  176881. jpeg_mem_available (j_common_ptr, long,
  176882. long max_bytes_needed, long)
  176883. {
  176884. return max_bytes_needed;
  176885. }
  176886. /*
  176887. * Backing store (temporary file) management.
  176888. * Since jpeg_mem_available always promised the moon,
  176889. * this should never be called and we can just error out.
  176890. */
  176891. GLOBAL(void)
  176892. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176893. long )
  176894. {
  176895. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176896. }
  176897. /*
  176898. * These routines take care of any system-dependent initialization and
  176899. * cleanup required. Here, there isn't any.
  176900. */
  176901. GLOBAL(long)
  176902. jpeg_mem_init (j_common_ptr)
  176903. {
  176904. return 0; /* just set max_memory_to_use to 0 */
  176905. }
  176906. GLOBAL(void)
  176907. jpeg_mem_term (j_common_ptr)
  176908. {
  176909. /* no work */
  176910. }
  176911. /*** End of inlined file: jmemnobs.c ***/
  176912. /*** Start of inlined file: jquant1.c ***/
  176913. #define JPEG_INTERNALS
  176914. #ifdef QUANT_1PASS_SUPPORTED
  176915. /*
  176916. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176917. * high quality, colormapped output capability. A 2-pass quantizer usually
  176918. * gives better visual quality; however, for quantized grayscale output this
  176919. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176920. * quantizer, though you can turn it off if you really want to.
  176921. *
  176922. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176923. * image. We use a map consisting of all combinations of Ncolors[i] color
  176924. * values for the i'th component. The Ncolors[] values are chosen so that
  176925. * their product, the total number of colors, is no more than that requested.
  176926. * (In most cases, the product will be somewhat less.)
  176927. *
  176928. * Since the colormap is orthogonal, the representative value for each color
  176929. * component can be determined without considering the other components;
  176930. * then these indexes can be combined into a colormap index by a standard
  176931. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176932. * can be precalculated and stored in the lookup table colorindex[].
  176933. * colorindex[i][j] maps pixel value j in component i to the nearest
  176934. * representative value (grid plane) for that component; this index is
  176935. * multiplied by the array stride for component i, so that the
  176936. * index of the colormap entry closest to a given pixel value is just
  176937. * sum( colorindex[component-number][pixel-component-value] )
  176938. * Aside from being fast, this scheme allows for variable spacing between
  176939. * representative values with no additional lookup cost.
  176940. *
  176941. * If gamma correction has been applied in color conversion, it might be wise
  176942. * to adjust the color grid spacing so that the representative colors are
  176943. * equidistant in linear space. At this writing, gamma correction is not
  176944. * implemented by jdcolor, so nothing is done here.
  176945. */
  176946. /* Declarations for ordered dithering.
  176947. *
  176948. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176949. * dithering is described in many references, for instance Dale Schumacher's
  176950. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176951. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176952. * "dither" value to the input pixel and then round the result to the nearest
  176953. * output value. The dither value is equivalent to (0.5 - threshold) times
  176954. * the distance between output values. For ordered dithering, we assume that
  176955. * the output colors are equally spaced; if not, results will probably be
  176956. * worse, since the dither may be too much or too little at a given point.
  176957. *
  176958. * The normal calculation would be to form pixel value + dither, range-limit
  176959. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176960. * We can skip the separate range-limiting step by extending the colorindex
  176961. * table in both directions.
  176962. */
  176963. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176964. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176965. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176966. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176967. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176968. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176969. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176970. /* Bayer's order-4 dither array. Generated by the code given in
  176971. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176972. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176973. */
  176974. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176975. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176976. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176977. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176978. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176979. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176980. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176981. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176982. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176983. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176984. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176985. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176986. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176987. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176988. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176989. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176990. };
  176991. /* Declarations for Floyd-Steinberg dithering.
  176992. *
  176993. * Errors are accumulated into the array fserrors[], at a resolution of
  176994. * 1/16th of a pixel count. The error at a given pixel is propagated
  176995. * to its not-yet-processed neighbors using the standard F-S fractions,
  176996. * ... (here) 7/16
  176997. * 3/16 5/16 1/16
  176998. * We work left-to-right on even rows, right-to-left on odd rows.
  176999. *
  177000. * We can get away with a single array (holding one row's worth of errors)
  177001. * by using it to store the current row's errors at pixel columns not yet
  177002. * processed, but the next row's errors at columns already processed. We
  177003. * need only a few extra variables to hold the errors immediately around the
  177004. * current column. (If we are lucky, those variables are in registers, but
  177005. * even if not, they're probably cheaper to access than array elements are.)
  177006. *
  177007. * The fserrors[] array is indexed [component#][position].
  177008. * We provide (#columns + 2) entries per component; the extra entry at each
  177009. * end saves us from special-casing the first and last pixels.
  177010. *
  177011. * Note: on a wide image, we might not have enough room in a PC's near data
  177012. * segment to hold the error array; so it is allocated with alloc_large.
  177013. */
  177014. #if BITS_IN_JSAMPLE == 8
  177015. typedef INT16 FSERROR; /* 16 bits should be enough */
  177016. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177017. #else
  177018. typedef INT32 FSERROR; /* may need more than 16 bits */
  177019. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177020. #endif
  177021. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177022. /* Private subobject */
  177023. #define MAX_Q_COMPS 4 /* max components I can handle */
  177024. typedef struct {
  177025. struct jpeg_color_quantizer pub; /* public fields */
  177026. /* Initially allocated colormap is saved here */
  177027. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177028. int sv_actual; /* number of entries in use */
  177029. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177030. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177031. * premultiplied as described above. Since colormap indexes must fit into
  177032. * JSAMPLEs, the entries of this array will too.
  177033. */
  177034. boolean is_padded; /* is the colorindex padded for odither? */
  177035. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177036. /* Variables for ordered dithering */
  177037. int row_index; /* cur row's vertical index in dither matrix */
  177038. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177039. /* Variables for Floyd-Steinberg dithering */
  177040. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177041. boolean on_odd_row; /* flag to remember which row we are on */
  177042. } my_cquantizer;
  177043. typedef my_cquantizer * my_cquantize_ptr;
  177044. /*
  177045. * Policy-making subroutines for create_colormap and create_colorindex.
  177046. * These routines determine the colormap to be used. The rest of the module
  177047. * only assumes that the colormap is orthogonal.
  177048. *
  177049. * * select_ncolors decides how to divvy up the available colors
  177050. * among the components.
  177051. * * output_value defines the set of representative values for a component.
  177052. * * largest_input_value defines the mapping from input values to
  177053. * representative values for a component.
  177054. * Note that the latter two routines may impose different policies for
  177055. * different components, though this is not currently done.
  177056. */
  177057. LOCAL(int)
  177058. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177059. /* Determine allocation of desired colors to components, */
  177060. /* and fill in Ncolors[] array to indicate choice. */
  177061. /* Return value is total number of colors (product of Ncolors[] values). */
  177062. {
  177063. int nc = cinfo->out_color_components; /* number of color components */
  177064. int max_colors = cinfo->desired_number_of_colors;
  177065. int total_colors, iroot, i, j;
  177066. boolean changed;
  177067. long temp;
  177068. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177069. /* We can allocate at least the nc'th root of max_colors per component. */
  177070. /* Compute floor(nc'th root of max_colors). */
  177071. iroot = 1;
  177072. do {
  177073. iroot++;
  177074. temp = iroot; /* set temp = iroot ** nc */
  177075. for (i = 1; i < nc; i++)
  177076. temp *= iroot;
  177077. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177078. iroot--; /* now iroot = floor(root) */
  177079. /* Must have at least 2 color values per component */
  177080. if (iroot < 2)
  177081. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177082. /* Initialize to iroot color values for each component */
  177083. total_colors = 1;
  177084. for (i = 0; i < nc; i++) {
  177085. Ncolors[i] = iroot;
  177086. total_colors *= iroot;
  177087. }
  177088. /* We may be able to increment the count for one or more components without
  177089. * exceeding max_colors, though we know not all can be incremented.
  177090. * Sometimes, the first component can be incremented more than once!
  177091. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177092. * In RGB colorspace, try to increment G first, then R, then B.
  177093. */
  177094. do {
  177095. changed = FALSE;
  177096. for (i = 0; i < nc; i++) {
  177097. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177098. /* calculate new total_colors if Ncolors[j] is incremented */
  177099. temp = total_colors / Ncolors[j];
  177100. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177101. if (temp > (long) max_colors)
  177102. break; /* won't fit, done with this pass */
  177103. Ncolors[j]++; /* OK, apply the increment */
  177104. total_colors = (int) temp;
  177105. changed = TRUE;
  177106. }
  177107. } while (changed);
  177108. return total_colors;
  177109. }
  177110. LOCAL(int)
  177111. output_value (j_decompress_ptr, int, int j, int maxj)
  177112. /* Return j'th output value, where j will range from 0 to maxj */
  177113. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177114. {
  177115. /* We always provide values 0 and MAXJSAMPLE for each component;
  177116. * any additional values are equally spaced between these limits.
  177117. * (Forcing the upper and lower values to the limits ensures that
  177118. * dithering can't produce a color outside the selected gamut.)
  177119. */
  177120. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177121. }
  177122. LOCAL(int)
  177123. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177124. /* Return largest input value that should map to j'th output value */
  177125. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177126. {
  177127. /* Breakpoints are halfway between values returned by output_value */
  177128. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177129. }
  177130. /*
  177131. * Create the colormap.
  177132. */
  177133. LOCAL(void)
  177134. create_colormap (j_decompress_ptr cinfo)
  177135. {
  177136. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177137. JSAMPARRAY colormap; /* Created colormap */
  177138. int total_colors; /* Number of distinct output colors */
  177139. int i,j,k, nci, blksize, blkdist, ptr, val;
  177140. /* Select number of colors for each component */
  177141. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177142. /* Report selected color counts */
  177143. if (cinfo->out_color_components == 3)
  177144. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177145. total_colors, cquantize->Ncolors[0],
  177146. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177147. else
  177148. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177149. /* Allocate and fill in the colormap. */
  177150. /* The colors are ordered in the map in standard row-major order, */
  177151. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177152. colormap = (*cinfo->mem->alloc_sarray)
  177153. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177154. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177155. /* blksize is number of adjacent repeated entries for a component */
  177156. /* blkdist is distance between groups of identical entries for a component */
  177157. blkdist = total_colors;
  177158. for (i = 0; i < cinfo->out_color_components; i++) {
  177159. /* fill in colormap entries for i'th color component */
  177160. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177161. blksize = blkdist / nci;
  177162. for (j = 0; j < nci; j++) {
  177163. /* Compute j'th output value (out of nci) for component */
  177164. val = output_value(cinfo, i, j, nci-1);
  177165. /* Fill in all colormap entries that have this value of this component */
  177166. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177167. /* fill in blksize entries beginning at ptr */
  177168. for (k = 0; k < blksize; k++)
  177169. colormap[i][ptr+k] = (JSAMPLE) val;
  177170. }
  177171. }
  177172. blkdist = blksize; /* blksize of this color is blkdist of next */
  177173. }
  177174. /* Save the colormap in private storage,
  177175. * where it will survive color quantization mode changes.
  177176. */
  177177. cquantize->sv_colormap = colormap;
  177178. cquantize->sv_actual = total_colors;
  177179. }
  177180. /*
  177181. * Create the color index table.
  177182. */
  177183. LOCAL(void)
  177184. create_colorindex (j_decompress_ptr cinfo)
  177185. {
  177186. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177187. JSAMPROW indexptr;
  177188. int i,j,k, nci, blksize, val, pad;
  177189. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177190. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177191. * This is not necessary in the other dithering modes. However, we
  177192. * flag whether it was done in case user changes dithering mode.
  177193. */
  177194. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177195. pad = MAXJSAMPLE*2;
  177196. cquantize->is_padded = TRUE;
  177197. } else {
  177198. pad = 0;
  177199. cquantize->is_padded = FALSE;
  177200. }
  177201. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177202. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177203. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177204. (JDIMENSION) cinfo->out_color_components);
  177205. /* blksize is number of adjacent repeated entries for a component */
  177206. blksize = cquantize->sv_actual;
  177207. for (i = 0; i < cinfo->out_color_components; i++) {
  177208. /* fill in colorindex entries for i'th color component */
  177209. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177210. blksize = blksize / nci;
  177211. /* adjust colorindex pointers to provide padding at negative indexes. */
  177212. if (pad)
  177213. cquantize->colorindex[i] += MAXJSAMPLE;
  177214. /* in loop, val = index of current output value, */
  177215. /* and k = largest j that maps to current val */
  177216. indexptr = cquantize->colorindex[i];
  177217. val = 0;
  177218. k = largest_input_value(cinfo, i, 0, nci-1);
  177219. for (j = 0; j <= MAXJSAMPLE; j++) {
  177220. while (j > k) /* advance val if past boundary */
  177221. k = largest_input_value(cinfo, i, ++val, nci-1);
  177222. /* premultiply so that no multiplication needed in main processing */
  177223. indexptr[j] = (JSAMPLE) (val * blksize);
  177224. }
  177225. /* Pad at both ends if necessary */
  177226. if (pad)
  177227. for (j = 1; j <= MAXJSAMPLE; j++) {
  177228. indexptr[-j] = indexptr[0];
  177229. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177230. }
  177231. }
  177232. }
  177233. /*
  177234. * Create an ordered-dither array for a component having ncolors
  177235. * distinct output values.
  177236. */
  177237. LOCAL(ODITHER_MATRIX_PTR)
  177238. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177239. {
  177240. ODITHER_MATRIX_PTR odither;
  177241. int j,k;
  177242. INT32 num,den;
  177243. odither = (ODITHER_MATRIX_PTR)
  177244. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177245. SIZEOF(ODITHER_MATRIX));
  177246. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177247. * Hence the dither value for the matrix cell with fill order f
  177248. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177249. * On 16-bit-int machine, be careful to avoid overflow.
  177250. */
  177251. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177252. for (j = 0; j < ODITHER_SIZE; j++) {
  177253. for (k = 0; k < ODITHER_SIZE; k++) {
  177254. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177255. * MAXJSAMPLE;
  177256. /* Ensure round towards zero despite C's lack of consistency
  177257. * about rounding negative values in integer division...
  177258. */
  177259. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177260. }
  177261. }
  177262. return odither;
  177263. }
  177264. /*
  177265. * Create the ordered-dither tables.
  177266. * Components having the same number of representative colors may
  177267. * share a dither table.
  177268. */
  177269. LOCAL(void)
  177270. create_odither_tables (j_decompress_ptr cinfo)
  177271. {
  177272. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177273. ODITHER_MATRIX_PTR odither;
  177274. int i, j, nci;
  177275. for (i = 0; i < cinfo->out_color_components; i++) {
  177276. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177277. odither = NULL; /* search for matching prior component */
  177278. for (j = 0; j < i; j++) {
  177279. if (nci == cquantize->Ncolors[j]) {
  177280. odither = cquantize->odither[j];
  177281. break;
  177282. }
  177283. }
  177284. if (odither == NULL) /* need a new table? */
  177285. odither = make_odither_array(cinfo, nci);
  177286. cquantize->odither[i] = odither;
  177287. }
  177288. }
  177289. /*
  177290. * Map some rows of pixels to the output colormapped representation.
  177291. */
  177292. METHODDEF(void)
  177293. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177294. JSAMPARRAY output_buf, int num_rows)
  177295. /* General case, no dithering */
  177296. {
  177297. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177298. JSAMPARRAY colorindex = cquantize->colorindex;
  177299. register int pixcode, ci;
  177300. register JSAMPROW ptrin, ptrout;
  177301. int row;
  177302. JDIMENSION col;
  177303. JDIMENSION width = cinfo->output_width;
  177304. register int nc = cinfo->out_color_components;
  177305. for (row = 0; row < num_rows; row++) {
  177306. ptrin = input_buf[row];
  177307. ptrout = output_buf[row];
  177308. for (col = width; col > 0; col--) {
  177309. pixcode = 0;
  177310. for (ci = 0; ci < nc; ci++) {
  177311. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177312. }
  177313. *ptrout++ = (JSAMPLE) pixcode;
  177314. }
  177315. }
  177316. }
  177317. METHODDEF(void)
  177318. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177319. JSAMPARRAY output_buf, int num_rows)
  177320. /* Fast path for out_color_components==3, no dithering */
  177321. {
  177322. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177323. register int pixcode;
  177324. register JSAMPROW ptrin, ptrout;
  177325. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177326. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177327. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177328. int row;
  177329. JDIMENSION col;
  177330. JDIMENSION width = cinfo->output_width;
  177331. for (row = 0; row < num_rows; row++) {
  177332. ptrin = input_buf[row];
  177333. ptrout = output_buf[row];
  177334. for (col = width; col > 0; col--) {
  177335. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177336. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177337. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177338. *ptrout++ = (JSAMPLE) pixcode;
  177339. }
  177340. }
  177341. }
  177342. METHODDEF(void)
  177343. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177344. JSAMPARRAY output_buf, int num_rows)
  177345. /* General case, with ordered dithering */
  177346. {
  177347. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177348. register JSAMPROW input_ptr;
  177349. register JSAMPROW output_ptr;
  177350. JSAMPROW colorindex_ci;
  177351. int * dither; /* points to active row of dither matrix */
  177352. int row_index, col_index; /* current indexes into dither matrix */
  177353. int nc = cinfo->out_color_components;
  177354. int ci;
  177355. int row;
  177356. JDIMENSION col;
  177357. JDIMENSION width = cinfo->output_width;
  177358. for (row = 0; row < num_rows; row++) {
  177359. /* Initialize output values to 0 so can process components separately */
  177360. jzero_far((void FAR *) output_buf[row],
  177361. (size_t) (width * SIZEOF(JSAMPLE)));
  177362. row_index = cquantize->row_index;
  177363. for (ci = 0; ci < nc; ci++) {
  177364. input_ptr = input_buf[row] + ci;
  177365. output_ptr = output_buf[row];
  177366. colorindex_ci = cquantize->colorindex[ci];
  177367. dither = cquantize->odither[ci][row_index];
  177368. col_index = 0;
  177369. for (col = width; col > 0; col--) {
  177370. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177371. * select output value, accumulate into output code for this pixel.
  177372. * Range-limiting need not be done explicitly, as we have extended
  177373. * the colorindex table to produce the right answers for out-of-range
  177374. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177375. * required amount of padding.
  177376. */
  177377. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177378. input_ptr += nc;
  177379. output_ptr++;
  177380. col_index = (col_index + 1) & ODITHER_MASK;
  177381. }
  177382. }
  177383. /* Advance row index for next row */
  177384. row_index = (row_index + 1) & ODITHER_MASK;
  177385. cquantize->row_index = row_index;
  177386. }
  177387. }
  177388. METHODDEF(void)
  177389. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177390. JSAMPARRAY output_buf, int num_rows)
  177391. /* Fast path for out_color_components==3, with ordered dithering */
  177392. {
  177393. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177394. register int pixcode;
  177395. register JSAMPROW input_ptr;
  177396. register JSAMPROW output_ptr;
  177397. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177398. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177399. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177400. int * dither0; /* points to active row of dither matrix */
  177401. int * dither1;
  177402. int * dither2;
  177403. int row_index, col_index; /* current indexes into dither matrix */
  177404. int row;
  177405. JDIMENSION col;
  177406. JDIMENSION width = cinfo->output_width;
  177407. for (row = 0; row < num_rows; row++) {
  177408. row_index = cquantize->row_index;
  177409. input_ptr = input_buf[row];
  177410. output_ptr = output_buf[row];
  177411. dither0 = cquantize->odither[0][row_index];
  177412. dither1 = cquantize->odither[1][row_index];
  177413. dither2 = cquantize->odither[2][row_index];
  177414. col_index = 0;
  177415. for (col = width; col > 0; col--) {
  177416. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177417. dither0[col_index]]);
  177418. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177419. dither1[col_index]]);
  177420. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177421. dither2[col_index]]);
  177422. *output_ptr++ = (JSAMPLE) pixcode;
  177423. col_index = (col_index + 1) & ODITHER_MASK;
  177424. }
  177425. row_index = (row_index + 1) & ODITHER_MASK;
  177426. cquantize->row_index = row_index;
  177427. }
  177428. }
  177429. METHODDEF(void)
  177430. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177431. JSAMPARRAY output_buf, int num_rows)
  177432. /* General case, with Floyd-Steinberg dithering */
  177433. {
  177434. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177435. register LOCFSERROR cur; /* current error or pixel value */
  177436. LOCFSERROR belowerr; /* error for pixel below cur */
  177437. LOCFSERROR bpreverr; /* error for below/prev col */
  177438. LOCFSERROR bnexterr; /* error for below/next col */
  177439. LOCFSERROR delta;
  177440. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177441. register JSAMPROW input_ptr;
  177442. register JSAMPROW output_ptr;
  177443. JSAMPROW colorindex_ci;
  177444. JSAMPROW colormap_ci;
  177445. int pixcode;
  177446. int nc = cinfo->out_color_components;
  177447. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177448. int dirnc; /* dir * nc */
  177449. int ci;
  177450. int row;
  177451. JDIMENSION col;
  177452. JDIMENSION width = cinfo->output_width;
  177453. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177454. SHIFT_TEMPS
  177455. for (row = 0; row < num_rows; row++) {
  177456. /* Initialize output values to 0 so can process components separately */
  177457. jzero_far((void FAR *) output_buf[row],
  177458. (size_t) (width * SIZEOF(JSAMPLE)));
  177459. for (ci = 0; ci < nc; ci++) {
  177460. input_ptr = input_buf[row] + ci;
  177461. output_ptr = output_buf[row];
  177462. if (cquantize->on_odd_row) {
  177463. /* work right to left in this row */
  177464. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177465. output_ptr += width-1;
  177466. dir = -1;
  177467. dirnc = -nc;
  177468. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177469. } else {
  177470. /* work left to right in this row */
  177471. dir = 1;
  177472. dirnc = nc;
  177473. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177474. }
  177475. colorindex_ci = cquantize->colorindex[ci];
  177476. colormap_ci = cquantize->sv_colormap[ci];
  177477. /* Preset error values: no error propagated to first pixel from left */
  177478. cur = 0;
  177479. /* and no error propagated to row below yet */
  177480. belowerr = bpreverr = 0;
  177481. for (col = width; col > 0; col--) {
  177482. /* cur holds the error propagated from the previous pixel on the
  177483. * current line. Add the error propagated from the previous line
  177484. * to form the complete error correction term for this pixel, and
  177485. * round the error term (which is expressed * 16) to an integer.
  177486. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177487. * for either sign of the error value.
  177488. * Note: errorptr points to *previous* column's array entry.
  177489. */
  177490. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177491. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177492. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177493. * of the range_limit array.
  177494. */
  177495. cur += GETJSAMPLE(*input_ptr);
  177496. cur = GETJSAMPLE(range_limit[cur]);
  177497. /* Select output value, accumulate into output code for this pixel */
  177498. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177499. *output_ptr += (JSAMPLE) pixcode;
  177500. /* Compute actual representation error at this pixel */
  177501. /* Note: we can do this even though we don't have the final */
  177502. /* pixel code, because the colormap is orthogonal. */
  177503. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177504. /* Compute error fractions to be propagated to adjacent pixels.
  177505. * Add these into the running sums, and simultaneously shift the
  177506. * next-line error sums left by 1 column.
  177507. */
  177508. bnexterr = cur;
  177509. delta = cur * 2;
  177510. cur += delta; /* form error * 3 */
  177511. errorptr[0] = (FSERROR) (bpreverr + cur);
  177512. cur += delta; /* form error * 5 */
  177513. bpreverr = belowerr + cur;
  177514. belowerr = bnexterr;
  177515. cur += delta; /* form error * 7 */
  177516. /* At this point cur contains the 7/16 error value to be propagated
  177517. * to the next pixel on the current line, and all the errors for the
  177518. * next line have been shifted over. We are therefore ready to move on.
  177519. */
  177520. input_ptr += dirnc; /* advance input ptr to next column */
  177521. output_ptr += dir; /* advance output ptr to next column */
  177522. errorptr += dir; /* advance errorptr to current column */
  177523. }
  177524. /* Post-loop cleanup: we must unload the final error value into the
  177525. * final fserrors[] entry. Note we need not unload belowerr because
  177526. * it is for the dummy column before or after the actual array.
  177527. */
  177528. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177529. }
  177530. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177531. }
  177532. }
  177533. /*
  177534. * Allocate workspace for Floyd-Steinberg errors.
  177535. */
  177536. LOCAL(void)
  177537. alloc_fs_workspace (j_decompress_ptr cinfo)
  177538. {
  177539. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177540. size_t arraysize;
  177541. int i;
  177542. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177543. for (i = 0; i < cinfo->out_color_components; i++) {
  177544. cquantize->fserrors[i] = (FSERRPTR)
  177545. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177546. }
  177547. }
  177548. /*
  177549. * Initialize for one-pass color quantization.
  177550. */
  177551. METHODDEF(void)
  177552. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177553. {
  177554. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177555. size_t arraysize;
  177556. int i;
  177557. /* Install my colormap. */
  177558. cinfo->colormap = cquantize->sv_colormap;
  177559. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177560. /* Initialize for desired dithering mode. */
  177561. switch (cinfo->dither_mode) {
  177562. case JDITHER_NONE:
  177563. if (cinfo->out_color_components == 3)
  177564. cquantize->pub.color_quantize = color_quantize3;
  177565. else
  177566. cquantize->pub.color_quantize = color_quantize;
  177567. break;
  177568. case JDITHER_ORDERED:
  177569. if (cinfo->out_color_components == 3)
  177570. cquantize->pub.color_quantize = quantize3_ord_dither;
  177571. else
  177572. cquantize->pub.color_quantize = quantize_ord_dither;
  177573. cquantize->row_index = 0; /* initialize state for ordered dither */
  177574. /* If user changed to ordered dither from another mode,
  177575. * we must recreate the color index table with padding.
  177576. * This will cost extra space, but probably isn't very likely.
  177577. */
  177578. if (! cquantize->is_padded)
  177579. create_colorindex(cinfo);
  177580. /* Create ordered-dither tables if we didn't already. */
  177581. if (cquantize->odither[0] == NULL)
  177582. create_odither_tables(cinfo);
  177583. break;
  177584. case JDITHER_FS:
  177585. cquantize->pub.color_quantize = quantize_fs_dither;
  177586. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177587. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177588. if (cquantize->fserrors[0] == NULL)
  177589. alloc_fs_workspace(cinfo);
  177590. /* Initialize the propagated errors to zero. */
  177591. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177592. for (i = 0; i < cinfo->out_color_components; i++)
  177593. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177594. break;
  177595. default:
  177596. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177597. break;
  177598. }
  177599. }
  177600. /*
  177601. * Finish up at the end of the pass.
  177602. */
  177603. METHODDEF(void)
  177604. finish_pass_1_quant (j_decompress_ptr)
  177605. {
  177606. /* no work in 1-pass case */
  177607. }
  177608. /*
  177609. * Switch to a new external colormap between output passes.
  177610. * Shouldn't get to this module!
  177611. */
  177612. METHODDEF(void)
  177613. new_color_map_1_quant (j_decompress_ptr cinfo)
  177614. {
  177615. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177616. }
  177617. /*
  177618. * Module initialization routine for 1-pass color quantization.
  177619. */
  177620. GLOBAL(void)
  177621. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177622. {
  177623. my_cquantize_ptr cquantize;
  177624. cquantize = (my_cquantize_ptr)
  177625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177626. SIZEOF(my_cquantizer));
  177627. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177628. cquantize->pub.start_pass = start_pass_1_quant;
  177629. cquantize->pub.finish_pass = finish_pass_1_quant;
  177630. cquantize->pub.new_color_map = new_color_map_1_quant;
  177631. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177632. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177633. /* Make sure my internal arrays won't overflow */
  177634. if (cinfo->out_color_components > MAX_Q_COMPS)
  177635. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177636. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177637. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177638. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177639. /* Create the colormap and color index table. */
  177640. create_colormap(cinfo);
  177641. create_colorindex(cinfo);
  177642. /* Allocate Floyd-Steinberg workspace now if requested.
  177643. * We do this now since it is FAR storage and may affect the memory
  177644. * manager's space calculations. If the user changes to FS dither
  177645. * mode in a later pass, we will allocate the space then, and will
  177646. * possibly overrun the max_memory_to_use setting.
  177647. */
  177648. if (cinfo->dither_mode == JDITHER_FS)
  177649. alloc_fs_workspace(cinfo);
  177650. }
  177651. #endif /* QUANT_1PASS_SUPPORTED */
  177652. /*** End of inlined file: jquant1.c ***/
  177653. /*** Start of inlined file: jquant2.c ***/
  177654. #define JPEG_INTERNALS
  177655. #ifdef QUANT_2PASS_SUPPORTED
  177656. /*
  177657. * This module implements the well-known Heckbert paradigm for color
  177658. * quantization. Most of the ideas used here can be traced back to
  177659. * Heckbert's seminal paper
  177660. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177661. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177662. *
  177663. * In the first pass over the image, we accumulate a histogram showing the
  177664. * usage count of each possible color. To keep the histogram to a reasonable
  177665. * size, we reduce the precision of the input; typical practice is to retain
  177666. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177667. * in the same histogram cell.
  177668. *
  177669. * Next, the color-selection step begins with a box representing the whole
  177670. * color space, and repeatedly splits the "largest" remaining box until we
  177671. * have as many boxes as desired colors. Then the mean color in each
  177672. * remaining box becomes one of the possible output colors.
  177673. *
  177674. * The second pass over the image maps each input pixel to the closest output
  177675. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177676. * This mapping is logically trivial, but making it go fast enough requires
  177677. * considerable care.
  177678. *
  177679. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177680. * the "largest" box and deciding where to cut it. The particular policies
  177681. * used here have proved out well in experimental comparisons, but better ones
  177682. * may yet be found.
  177683. *
  177684. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177685. * space, processing the raw upsampled data without a color conversion step.
  177686. * This allowed the color conversion math to be done only once per colormap
  177687. * entry, not once per pixel. However, that optimization precluded other
  177688. * useful optimizations (such as merging color conversion with upsampling)
  177689. * and it also interfered with desired capabilities such as quantizing to an
  177690. * externally-supplied colormap. We have therefore abandoned that approach.
  177691. * The present code works in the post-conversion color space, typically RGB.
  177692. *
  177693. * To improve the visual quality of the results, we actually work in scaled
  177694. * RGB space, giving G distances more weight than R, and R in turn more than
  177695. * B. To do everything in integer math, we must use integer scale factors.
  177696. * The 2/3/1 scale factors used here correspond loosely to the relative
  177697. * weights of the colors in the NTSC grayscale equation.
  177698. * If you want to use this code to quantize a non-RGB color space, you'll
  177699. * probably need to change these scale factors.
  177700. */
  177701. #define R_SCALE 2 /* scale R distances by this much */
  177702. #define G_SCALE 3 /* scale G distances by this much */
  177703. #define B_SCALE 1 /* and B by this much */
  177704. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177705. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177706. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177707. * you'll get compile errors until you extend this logic. In that case
  177708. * you'll probably want to tweak the histogram sizes too.
  177709. */
  177710. #if RGB_RED == 0
  177711. #define C0_SCALE R_SCALE
  177712. #endif
  177713. #if RGB_BLUE == 0
  177714. #define C0_SCALE B_SCALE
  177715. #endif
  177716. #if RGB_GREEN == 1
  177717. #define C1_SCALE G_SCALE
  177718. #endif
  177719. #if RGB_RED == 2
  177720. #define C2_SCALE R_SCALE
  177721. #endif
  177722. #if RGB_BLUE == 2
  177723. #define C2_SCALE B_SCALE
  177724. #endif
  177725. /*
  177726. * First we have the histogram data structure and routines for creating it.
  177727. *
  177728. * The number of bits of precision can be adjusted by changing these symbols.
  177729. * We recommend keeping 6 bits for G and 5 each for R and B.
  177730. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177731. * better results; if you are short of memory, 5 bits all around will save
  177732. * some space but degrade the results.
  177733. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177734. * (preferably unsigned long) for each cell. In practice this is overkill;
  177735. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177736. * and clamping those that do overflow to the maximum value will give close-
  177737. * enough results. This reduces the recommended histogram size from 256Kb
  177738. * to 128Kb, which is a useful savings on PC-class machines.
  177739. * (In the second pass the histogram space is re-used for pixel mapping data;
  177740. * in that capacity, each cell must be able to store zero to the number of
  177741. * desired colors. 16 bits/cell is plenty for that too.)
  177742. * Since the JPEG code is intended to run in small memory model on 80x86
  177743. * machines, we can't just allocate the histogram in one chunk. Instead
  177744. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177745. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177746. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177747. * on 80x86 machines, the pointer row is in near memory but the actual
  177748. * arrays are in far memory (same arrangement as we use for image arrays).
  177749. */
  177750. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177751. /* These will do the right thing for either R,G,B or B,G,R color order,
  177752. * but you may not like the results for other color orders.
  177753. */
  177754. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177755. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177756. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177757. /* Number of elements along histogram axes. */
  177758. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177759. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177760. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177761. /* These are the amounts to shift an input value to get a histogram index. */
  177762. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177763. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177764. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177765. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177766. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177767. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177768. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177769. typedef hist2d * hist3d; /* type for top-level pointer */
  177770. /* Declarations for Floyd-Steinberg dithering.
  177771. *
  177772. * Errors are accumulated into the array fserrors[], at a resolution of
  177773. * 1/16th of a pixel count. The error at a given pixel is propagated
  177774. * to its not-yet-processed neighbors using the standard F-S fractions,
  177775. * ... (here) 7/16
  177776. * 3/16 5/16 1/16
  177777. * We work left-to-right on even rows, right-to-left on odd rows.
  177778. *
  177779. * We can get away with a single array (holding one row's worth of errors)
  177780. * by using it to store the current row's errors at pixel columns not yet
  177781. * processed, but the next row's errors at columns already processed. We
  177782. * need only a few extra variables to hold the errors immediately around the
  177783. * current column. (If we are lucky, those variables are in registers, but
  177784. * even if not, they're probably cheaper to access than array elements are.)
  177785. *
  177786. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177787. * each end saves us from special-casing the first and last pixels.
  177788. * Each entry is three values long, one value for each color component.
  177789. *
  177790. * Note: on a wide image, we might not have enough room in a PC's near data
  177791. * segment to hold the error array; so it is allocated with alloc_large.
  177792. */
  177793. #if BITS_IN_JSAMPLE == 8
  177794. typedef INT16 FSERROR; /* 16 bits should be enough */
  177795. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177796. #else
  177797. typedef INT32 FSERROR; /* may need more than 16 bits */
  177798. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177799. #endif
  177800. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177801. /* Private subobject */
  177802. typedef struct {
  177803. struct jpeg_color_quantizer pub; /* public fields */
  177804. /* Space for the eventually created colormap is stashed here */
  177805. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177806. int desired; /* desired # of colors = size of colormap */
  177807. /* Variables for accumulating image statistics */
  177808. hist3d histogram; /* pointer to the histogram */
  177809. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177810. /* Variables for Floyd-Steinberg dithering */
  177811. FSERRPTR fserrors; /* accumulated errors */
  177812. boolean on_odd_row; /* flag to remember which row we are on */
  177813. int * error_limiter; /* table for clamping the applied error */
  177814. } my_cquantizer2;
  177815. typedef my_cquantizer2 * my_cquantize_ptr2;
  177816. /*
  177817. * Prescan some rows of pixels.
  177818. * In this module the prescan simply updates the histogram, which has been
  177819. * initialized to zeroes by start_pass.
  177820. * An output_buf parameter is required by the method signature, but no data
  177821. * is actually output (in fact the buffer controller is probably passing a
  177822. * NULL pointer).
  177823. */
  177824. METHODDEF(void)
  177825. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177826. JSAMPARRAY, int num_rows)
  177827. {
  177828. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177829. register JSAMPROW ptr;
  177830. register histptr histp;
  177831. register hist3d histogram = cquantize->histogram;
  177832. int row;
  177833. JDIMENSION col;
  177834. JDIMENSION width = cinfo->output_width;
  177835. for (row = 0; row < num_rows; row++) {
  177836. ptr = input_buf[row];
  177837. for (col = width; col > 0; col--) {
  177838. /* get pixel value and index into the histogram */
  177839. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177840. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177841. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177842. /* increment, check for overflow and undo increment if so. */
  177843. if (++(*histp) <= 0)
  177844. (*histp)--;
  177845. ptr += 3;
  177846. }
  177847. }
  177848. }
  177849. /*
  177850. * Next we have the really interesting routines: selection of a colormap
  177851. * given the completed histogram.
  177852. * These routines work with a list of "boxes", each representing a rectangular
  177853. * subset of the input color space (to histogram precision).
  177854. */
  177855. typedef struct {
  177856. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177857. int c0min, c0max;
  177858. int c1min, c1max;
  177859. int c2min, c2max;
  177860. /* The volume (actually 2-norm) of the box */
  177861. INT32 volume;
  177862. /* The number of nonzero histogram cells within this box */
  177863. long colorcount;
  177864. } box;
  177865. typedef box * boxptr;
  177866. LOCAL(boxptr)
  177867. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177868. /* Find the splittable box with the largest color population */
  177869. /* Returns NULL if no splittable boxes remain */
  177870. {
  177871. register boxptr boxp;
  177872. register int i;
  177873. register long maxc = 0;
  177874. boxptr which = NULL;
  177875. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177876. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177877. which = boxp;
  177878. maxc = boxp->colorcount;
  177879. }
  177880. }
  177881. return which;
  177882. }
  177883. LOCAL(boxptr)
  177884. find_biggest_volume (boxptr boxlist, int numboxes)
  177885. /* Find the splittable box with the largest (scaled) volume */
  177886. /* Returns NULL if no splittable boxes remain */
  177887. {
  177888. register boxptr boxp;
  177889. register int i;
  177890. register INT32 maxv = 0;
  177891. boxptr which = NULL;
  177892. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177893. if (boxp->volume > maxv) {
  177894. which = boxp;
  177895. maxv = boxp->volume;
  177896. }
  177897. }
  177898. return which;
  177899. }
  177900. LOCAL(void)
  177901. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177902. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177903. /* and recompute its volume and population */
  177904. {
  177905. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177906. hist3d histogram = cquantize->histogram;
  177907. histptr histp;
  177908. int c0,c1,c2;
  177909. int c0min,c0max,c1min,c1max,c2min,c2max;
  177910. INT32 dist0,dist1,dist2;
  177911. long ccount;
  177912. c0min = boxp->c0min; c0max = boxp->c0max;
  177913. c1min = boxp->c1min; c1max = boxp->c1max;
  177914. c2min = boxp->c2min; c2max = boxp->c2max;
  177915. if (c0max > c0min)
  177916. for (c0 = c0min; c0 <= c0max; c0++)
  177917. for (c1 = c1min; c1 <= c1max; c1++) {
  177918. histp = & histogram[c0][c1][c2min];
  177919. for (c2 = c2min; c2 <= c2max; c2++)
  177920. if (*histp++ != 0) {
  177921. boxp->c0min = c0min = c0;
  177922. goto have_c0min;
  177923. }
  177924. }
  177925. have_c0min:
  177926. if (c0max > c0min)
  177927. for (c0 = c0max; c0 >= c0min; c0--)
  177928. for (c1 = c1min; c1 <= c1max; c1++) {
  177929. histp = & histogram[c0][c1][c2min];
  177930. for (c2 = c2min; c2 <= c2max; c2++)
  177931. if (*histp++ != 0) {
  177932. boxp->c0max = c0max = c0;
  177933. goto have_c0max;
  177934. }
  177935. }
  177936. have_c0max:
  177937. if (c1max > c1min)
  177938. for (c1 = c1min; c1 <= c1max; c1++)
  177939. for (c0 = c0min; c0 <= c0max; c0++) {
  177940. histp = & histogram[c0][c1][c2min];
  177941. for (c2 = c2min; c2 <= c2max; c2++)
  177942. if (*histp++ != 0) {
  177943. boxp->c1min = c1min = c1;
  177944. goto have_c1min;
  177945. }
  177946. }
  177947. have_c1min:
  177948. if (c1max > c1min)
  177949. for (c1 = c1max; c1 >= c1min; c1--)
  177950. for (c0 = c0min; c0 <= c0max; c0++) {
  177951. histp = & histogram[c0][c1][c2min];
  177952. for (c2 = c2min; c2 <= c2max; c2++)
  177953. if (*histp++ != 0) {
  177954. boxp->c1max = c1max = c1;
  177955. goto have_c1max;
  177956. }
  177957. }
  177958. have_c1max:
  177959. if (c2max > c2min)
  177960. for (c2 = c2min; c2 <= c2max; c2++)
  177961. for (c0 = c0min; c0 <= c0max; c0++) {
  177962. histp = & histogram[c0][c1min][c2];
  177963. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177964. if (*histp != 0) {
  177965. boxp->c2min = c2min = c2;
  177966. goto have_c2min;
  177967. }
  177968. }
  177969. have_c2min:
  177970. if (c2max > c2min)
  177971. for (c2 = c2max; c2 >= c2min; c2--)
  177972. for (c0 = c0min; c0 <= c0max; c0++) {
  177973. histp = & histogram[c0][c1min][c2];
  177974. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177975. if (*histp != 0) {
  177976. boxp->c2max = c2max = c2;
  177977. goto have_c2max;
  177978. }
  177979. }
  177980. have_c2max:
  177981. /* Update box volume.
  177982. * We use 2-norm rather than real volume here; this biases the method
  177983. * against making long narrow boxes, and it has the side benefit that
  177984. * a box is splittable iff norm > 0.
  177985. * Since the differences are expressed in histogram-cell units,
  177986. * we have to shift back to JSAMPLE units to get consistent distances;
  177987. * after which, we scale according to the selected distance scale factors.
  177988. */
  177989. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177990. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177991. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177992. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177993. /* Now scan remaining volume of box and compute population */
  177994. ccount = 0;
  177995. for (c0 = c0min; c0 <= c0max; c0++)
  177996. for (c1 = c1min; c1 <= c1max; c1++) {
  177997. histp = & histogram[c0][c1][c2min];
  177998. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177999. if (*histp != 0) {
  178000. ccount++;
  178001. }
  178002. }
  178003. boxp->colorcount = ccount;
  178004. }
  178005. LOCAL(int)
  178006. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178007. int desired_colors)
  178008. /* Repeatedly select and split the largest box until we have enough boxes */
  178009. {
  178010. int n,lb;
  178011. int c0,c1,c2,cmax;
  178012. register boxptr b1,b2;
  178013. while (numboxes < desired_colors) {
  178014. /* Select box to split.
  178015. * Current algorithm: by population for first half, then by volume.
  178016. */
  178017. if (numboxes*2 <= desired_colors) {
  178018. b1 = find_biggest_color_pop(boxlist, numboxes);
  178019. } else {
  178020. b1 = find_biggest_volume(boxlist, numboxes);
  178021. }
  178022. if (b1 == NULL) /* no splittable boxes left! */
  178023. break;
  178024. b2 = &boxlist[numboxes]; /* where new box will go */
  178025. /* Copy the color bounds to the new box. */
  178026. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178027. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178028. /* Choose which axis to split the box on.
  178029. * Current algorithm: longest scaled axis.
  178030. * See notes in update_box about scaling distances.
  178031. */
  178032. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178033. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178034. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178035. /* We want to break any ties in favor of green, then red, blue last.
  178036. * This code does the right thing for R,G,B or B,G,R color orders only.
  178037. */
  178038. #if RGB_RED == 0
  178039. cmax = c1; n = 1;
  178040. if (c0 > cmax) { cmax = c0; n = 0; }
  178041. if (c2 > cmax) { n = 2; }
  178042. #else
  178043. cmax = c1; n = 1;
  178044. if (c2 > cmax) { cmax = c2; n = 2; }
  178045. if (c0 > cmax) { n = 0; }
  178046. #endif
  178047. /* Choose split point along selected axis, and update box bounds.
  178048. * Current algorithm: split at halfway point.
  178049. * (Since the box has been shrunk to minimum volume,
  178050. * any split will produce two nonempty subboxes.)
  178051. * Note that lb value is max for lower box, so must be < old max.
  178052. */
  178053. switch (n) {
  178054. case 0:
  178055. lb = (b1->c0max + b1->c0min) / 2;
  178056. b1->c0max = lb;
  178057. b2->c0min = lb+1;
  178058. break;
  178059. case 1:
  178060. lb = (b1->c1max + b1->c1min) / 2;
  178061. b1->c1max = lb;
  178062. b2->c1min = lb+1;
  178063. break;
  178064. case 2:
  178065. lb = (b1->c2max + b1->c2min) / 2;
  178066. b1->c2max = lb;
  178067. b2->c2min = lb+1;
  178068. break;
  178069. }
  178070. /* Update stats for boxes */
  178071. update_box(cinfo, b1);
  178072. update_box(cinfo, b2);
  178073. numboxes++;
  178074. }
  178075. return numboxes;
  178076. }
  178077. LOCAL(void)
  178078. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178079. /* Compute representative color for a box, put it in colormap[icolor] */
  178080. {
  178081. /* Current algorithm: mean weighted by pixels (not colors) */
  178082. /* Note it is important to get the rounding correct! */
  178083. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178084. hist3d histogram = cquantize->histogram;
  178085. histptr histp;
  178086. int c0,c1,c2;
  178087. int c0min,c0max,c1min,c1max,c2min,c2max;
  178088. long count;
  178089. long total = 0;
  178090. long c0total = 0;
  178091. long c1total = 0;
  178092. long c2total = 0;
  178093. c0min = boxp->c0min; c0max = boxp->c0max;
  178094. c1min = boxp->c1min; c1max = boxp->c1max;
  178095. c2min = boxp->c2min; c2max = boxp->c2max;
  178096. for (c0 = c0min; c0 <= c0max; c0++)
  178097. for (c1 = c1min; c1 <= c1max; c1++) {
  178098. histp = & histogram[c0][c1][c2min];
  178099. for (c2 = c2min; c2 <= c2max; c2++) {
  178100. if ((count = *histp++) != 0) {
  178101. total += count;
  178102. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178103. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178104. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178105. }
  178106. }
  178107. }
  178108. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178109. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178110. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178111. }
  178112. LOCAL(void)
  178113. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178114. /* Master routine for color selection */
  178115. {
  178116. boxptr boxlist;
  178117. int numboxes;
  178118. int i;
  178119. /* Allocate workspace for box list */
  178120. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178121. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178122. /* Initialize one box containing whole space */
  178123. numboxes = 1;
  178124. boxlist[0].c0min = 0;
  178125. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178126. boxlist[0].c1min = 0;
  178127. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178128. boxlist[0].c2min = 0;
  178129. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178130. /* Shrink it to actually-used volume and set its statistics */
  178131. update_box(cinfo, & boxlist[0]);
  178132. /* Perform median-cut to produce final box list */
  178133. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178134. /* Compute the representative color for each box, fill colormap */
  178135. for (i = 0; i < numboxes; i++)
  178136. compute_color(cinfo, & boxlist[i], i);
  178137. cinfo->actual_number_of_colors = numboxes;
  178138. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178139. }
  178140. /*
  178141. * These routines are concerned with the time-critical task of mapping input
  178142. * colors to the nearest color in the selected colormap.
  178143. *
  178144. * We re-use the histogram space as an "inverse color map", essentially a
  178145. * cache for the results of nearest-color searches. All colors within a
  178146. * histogram cell will be mapped to the same colormap entry, namely the one
  178147. * closest to the cell's center. This may not be quite the closest entry to
  178148. * the actual input color, but it's almost as good. A zero in the cache
  178149. * indicates we haven't found the nearest color for that cell yet; the array
  178150. * is cleared to zeroes before starting the mapping pass. When we find the
  178151. * nearest color for a cell, its colormap index plus one is recorded in the
  178152. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178153. * when they need to use an unfilled entry in the cache.
  178154. *
  178155. * Our method of efficiently finding nearest colors is based on the "locally
  178156. * sorted search" idea described by Heckbert and on the incremental distance
  178157. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178158. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178159. * the distances from a given colormap entry to each cell of the histogram can
  178160. * be computed quickly using an incremental method: the differences between
  178161. * distances to adjacent cells themselves differ by a constant. This allows a
  178162. * fairly fast implementation of the "brute force" approach of computing the
  178163. * distance from every colormap entry to every histogram cell. Unfortunately,
  178164. * it needs a work array to hold the best-distance-so-far for each histogram
  178165. * cell (because the inner loop has to be over cells, not colormap entries).
  178166. * The work array elements have to be INT32s, so the work array would need
  178167. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178168. *
  178169. * To get around these problems, we apply Thomas' method to compute the
  178170. * nearest colors for only the cells within a small subbox of the histogram.
  178171. * The work array need be only as big as the subbox, so the memory usage
  178172. * problem is solved. Furthermore, we need not fill subboxes that are never
  178173. * referenced in pass2; many images use only part of the color gamut, so a
  178174. * fair amount of work is saved. An additional advantage of this
  178175. * approach is that we can apply Heckbert's locality criterion to quickly
  178176. * eliminate colormap entries that are far away from the subbox; typically
  178177. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178178. * and we need not compute their distances to individual cells in the subbox.
  178179. * The speed of this approach is heavily influenced by the subbox size: too
  178180. * small means too much overhead, too big loses because Heckbert's criterion
  178181. * can't eliminate as many colormap entries. Empirically the best subbox
  178182. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178183. *
  178184. * Thomas' article also describes a refined method which is asymptotically
  178185. * faster than the brute-force method, but it is also far more complex and
  178186. * cannot efficiently be applied to small subboxes. It is therefore not
  178187. * useful for programs intended to be portable to DOS machines. On machines
  178188. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178189. * refined method might be faster than the present code --- but then again,
  178190. * it might not be any faster, and it's certainly more complicated.
  178191. */
  178192. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178193. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178194. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178195. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178196. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178197. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178198. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178199. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178200. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178201. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178202. /*
  178203. * The next three routines implement inverse colormap filling. They could
  178204. * all be folded into one big routine, but splitting them up this way saves
  178205. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178206. * and may allow some compilers to produce better code by registerizing more
  178207. * inner-loop variables.
  178208. */
  178209. LOCAL(int)
  178210. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178211. JSAMPLE colorlist[])
  178212. /* Locate the colormap entries close enough to an update box to be candidates
  178213. * for the nearest entry to some cell(s) in the update box. The update box
  178214. * is specified by the center coordinates of its first cell. The number of
  178215. * candidate colormap entries is returned, and their colormap indexes are
  178216. * placed in colorlist[].
  178217. * This routine uses Heckbert's "locally sorted search" criterion to select
  178218. * the colors that need further consideration.
  178219. */
  178220. {
  178221. int numcolors = cinfo->actual_number_of_colors;
  178222. int maxc0, maxc1, maxc2;
  178223. int centerc0, centerc1, centerc2;
  178224. int i, x, ncolors;
  178225. INT32 minmaxdist, min_dist, max_dist, tdist;
  178226. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178227. /* Compute true coordinates of update box's upper corner and center.
  178228. * Actually we compute the coordinates of the center of the upper-corner
  178229. * histogram cell, which are the upper bounds of the volume we care about.
  178230. * Note that since ">>" rounds down, the "center" values may be closer to
  178231. * min than to max; hence comparisons to them must be "<=", not "<".
  178232. */
  178233. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178234. centerc0 = (minc0 + maxc0) >> 1;
  178235. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178236. centerc1 = (minc1 + maxc1) >> 1;
  178237. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178238. centerc2 = (minc2 + maxc2) >> 1;
  178239. /* For each color in colormap, find:
  178240. * 1. its minimum squared-distance to any point in the update box
  178241. * (zero if color is within update box);
  178242. * 2. its maximum squared-distance to any point in the update box.
  178243. * Both of these can be found by considering only the corners of the box.
  178244. * We save the minimum distance for each color in mindist[];
  178245. * only the smallest maximum distance is of interest.
  178246. */
  178247. minmaxdist = 0x7FFFFFFFL;
  178248. for (i = 0; i < numcolors; i++) {
  178249. /* We compute the squared-c0-distance term, then add in the other two. */
  178250. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178251. if (x < minc0) {
  178252. tdist = (x - minc0) * C0_SCALE;
  178253. min_dist = tdist*tdist;
  178254. tdist = (x - maxc0) * C0_SCALE;
  178255. max_dist = tdist*tdist;
  178256. } else if (x > maxc0) {
  178257. tdist = (x - maxc0) * C0_SCALE;
  178258. min_dist = tdist*tdist;
  178259. tdist = (x - minc0) * C0_SCALE;
  178260. max_dist = tdist*tdist;
  178261. } else {
  178262. /* within cell range so no contribution to min_dist */
  178263. min_dist = 0;
  178264. if (x <= centerc0) {
  178265. tdist = (x - maxc0) * C0_SCALE;
  178266. max_dist = tdist*tdist;
  178267. } else {
  178268. tdist = (x - minc0) * C0_SCALE;
  178269. max_dist = tdist*tdist;
  178270. }
  178271. }
  178272. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178273. if (x < minc1) {
  178274. tdist = (x - minc1) * C1_SCALE;
  178275. min_dist += tdist*tdist;
  178276. tdist = (x - maxc1) * C1_SCALE;
  178277. max_dist += tdist*tdist;
  178278. } else if (x > maxc1) {
  178279. tdist = (x - maxc1) * C1_SCALE;
  178280. min_dist += tdist*tdist;
  178281. tdist = (x - minc1) * C1_SCALE;
  178282. max_dist += tdist*tdist;
  178283. } else {
  178284. /* within cell range so no contribution to min_dist */
  178285. if (x <= centerc1) {
  178286. tdist = (x - maxc1) * C1_SCALE;
  178287. max_dist += tdist*tdist;
  178288. } else {
  178289. tdist = (x - minc1) * C1_SCALE;
  178290. max_dist += tdist*tdist;
  178291. }
  178292. }
  178293. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178294. if (x < minc2) {
  178295. tdist = (x - minc2) * C2_SCALE;
  178296. min_dist += tdist*tdist;
  178297. tdist = (x - maxc2) * C2_SCALE;
  178298. max_dist += tdist*tdist;
  178299. } else if (x > maxc2) {
  178300. tdist = (x - maxc2) * C2_SCALE;
  178301. min_dist += tdist*tdist;
  178302. tdist = (x - minc2) * C2_SCALE;
  178303. max_dist += tdist*tdist;
  178304. } else {
  178305. /* within cell range so no contribution to min_dist */
  178306. if (x <= centerc2) {
  178307. tdist = (x - maxc2) * C2_SCALE;
  178308. max_dist += tdist*tdist;
  178309. } else {
  178310. tdist = (x - minc2) * C2_SCALE;
  178311. max_dist += tdist*tdist;
  178312. }
  178313. }
  178314. mindist[i] = min_dist; /* save away the results */
  178315. if (max_dist < minmaxdist)
  178316. minmaxdist = max_dist;
  178317. }
  178318. /* Now we know that no cell in the update box is more than minmaxdist
  178319. * away from some colormap entry. Therefore, only colors that are
  178320. * within minmaxdist of some part of the box need be considered.
  178321. */
  178322. ncolors = 0;
  178323. for (i = 0; i < numcolors; i++) {
  178324. if (mindist[i] <= minmaxdist)
  178325. colorlist[ncolors++] = (JSAMPLE) i;
  178326. }
  178327. return ncolors;
  178328. }
  178329. LOCAL(void)
  178330. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178331. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178332. /* Find the closest colormap entry for each cell in the update box,
  178333. * given the list of candidate colors prepared by find_nearby_colors.
  178334. * Return the indexes of the closest entries in the bestcolor[] array.
  178335. * This routine uses Thomas' incremental distance calculation method to
  178336. * find the distance from a colormap entry to successive cells in the box.
  178337. */
  178338. {
  178339. int ic0, ic1, ic2;
  178340. int i, icolor;
  178341. register INT32 * bptr; /* pointer into bestdist[] array */
  178342. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178343. INT32 dist0, dist1; /* initial distance values */
  178344. register INT32 dist2; /* current distance in inner loop */
  178345. INT32 xx0, xx1; /* distance increments */
  178346. register INT32 xx2;
  178347. INT32 inc0, inc1, inc2; /* initial values for increments */
  178348. /* This array holds the distance to the nearest-so-far color for each cell */
  178349. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178350. /* Initialize best-distance for each cell of the update box */
  178351. bptr = bestdist;
  178352. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178353. *bptr++ = 0x7FFFFFFFL;
  178354. /* For each color selected by find_nearby_colors,
  178355. * compute its distance to the center of each cell in the box.
  178356. * If that's less than best-so-far, update best distance and color number.
  178357. */
  178358. /* Nominal steps between cell centers ("x" in Thomas article) */
  178359. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178360. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178361. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178362. for (i = 0; i < numcolors; i++) {
  178363. icolor = GETJSAMPLE(colorlist[i]);
  178364. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178365. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178366. dist0 = inc0*inc0;
  178367. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178368. dist0 += inc1*inc1;
  178369. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178370. dist0 += inc2*inc2;
  178371. /* Form the initial difference increments */
  178372. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178373. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178374. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178375. /* Now loop over all cells in box, updating distance per Thomas method */
  178376. bptr = bestdist;
  178377. cptr = bestcolor;
  178378. xx0 = inc0;
  178379. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178380. dist1 = dist0;
  178381. xx1 = inc1;
  178382. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178383. dist2 = dist1;
  178384. xx2 = inc2;
  178385. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178386. if (dist2 < *bptr) {
  178387. *bptr = dist2;
  178388. *cptr = (JSAMPLE) icolor;
  178389. }
  178390. dist2 += xx2;
  178391. xx2 += 2 * STEP_C2 * STEP_C2;
  178392. bptr++;
  178393. cptr++;
  178394. }
  178395. dist1 += xx1;
  178396. xx1 += 2 * STEP_C1 * STEP_C1;
  178397. }
  178398. dist0 += xx0;
  178399. xx0 += 2 * STEP_C0 * STEP_C0;
  178400. }
  178401. }
  178402. }
  178403. LOCAL(void)
  178404. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178405. /* Fill the inverse-colormap entries in the update box that contains */
  178406. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178407. /* we can fill as many others as we wish.) */
  178408. {
  178409. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178410. hist3d histogram = cquantize->histogram;
  178411. int minc0, minc1, minc2; /* lower left corner of update box */
  178412. int ic0, ic1, ic2;
  178413. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178414. register histptr cachep; /* pointer into main cache array */
  178415. /* This array lists the candidate colormap indexes. */
  178416. JSAMPLE colorlist[MAXNUMCOLORS];
  178417. int numcolors; /* number of candidate colors */
  178418. /* This array holds the actually closest colormap index for each cell. */
  178419. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178420. /* Convert cell coordinates to update box ID */
  178421. c0 >>= BOX_C0_LOG;
  178422. c1 >>= BOX_C1_LOG;
  178423. c2 >>= BOX_C2_LOG;
  178424. /* Compute true coordinates of update box's origin corner.
  178425. * Actually we compute the coordinates of the center of the corner
  178426. * histogram cell, which are the lower bounds of the volume we care about.
  178427. */
  178428. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178429. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178430. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178431. /* Determine which colormap entries are close enough to be candidates
  178432. * for the nearest entry to some cell in the update box.
  178433. */
  178434. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178435. /* Determine the actually nearest colors. */
  178436. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178437. bestcolor);
  178438. /* Save the best color numbers (plus 1) in the main cache array */
  178439. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178440. c1 <<= BOX_C1_LOG;
  178441. c2 <<= BOX_C2_LOG;
  178442. cptr = bestcolor;
  178443. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178444. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178445. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178446. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178447. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178448. }
  178449. }
  178450. }
  178451. }
  178452. /*
  178453. * Map some rows of pixels to the output colormapped representation.
  178454. */
  178455. METHODDEF(void)
  178456. pass2_no_dither (j_decompress_ptr cinfo,
  178457. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178458. /* This version performs no dithering */
  178459. {
  178460. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178461. hist3d histogram = cquantize->histogram;
  178462. register JSAMPROW inptr, outptr;
  178463. register histptr cachep;
  178464. register int c0, c1, c2;
  178465. int row;
  178466. JDIMENSION col;
  178467. JDIMENSION width = cinfo->output_width;
  178468. for (row = 0; row < num_rows; row++) {
  178469. inptr = input_buf[row];
  178470. outptr = output_buf[row];
  178471. for (col = width; col > 0; col--) {
  178472. /* get pixel value and index into the cache */
  178473. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178474. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178475. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178476. cachep = & histogram[c0][c1][c2];
  178477. /* If we have not seen this color before, find nearest colormap entry */
  178478. /* and update the cache */
  178479. if (*cachep == 0)
  178480. fill_inverse_cmap(cinfo, c0,c1,c2);
  178481. /* Now emit the colormap index for this cell */
  178482. *outptr++ = (JSAMPLE) (*cachep - 1);
  178483. }
  178484. }
  178485. }
  178486. METHODDEF(void)
  178487. pass2_fs_dither (j_decompress_ptr cinfo,
  178488. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178489. /* This version performs Floyd-Steinberg dithering */
  178490. {
  178491. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178492. hist3d histogram = cquantize->histogram;
  178493. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178494. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178495. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178496. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178497. JSAMPROW inptr; /* => current input pixel */
  178498. JSAMPROW outptr; /* => current output pixel */
  178499. histptr cachep;
  178500. int dir; /* +1 or -1 depending on direction */
  178501. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178502. int row;
  178503. JDIMENSION col;
  178504. JDIMENSION width = cinfo->output_width;
  178505. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178506. int *error_limit = cquantize->error_limiter;
  178507. JSAMPROW colormap0 = cinfo->colormap[0];
  178508. JSAMPROW colormap1 = cinfo->colormap[1];
  178509. JSAMPROW colormap2 = cinfo->colormap[2];
  178510. SHIFT_TEMPS
  178511. for (row = 0; row < num_rows; row++) {
  178512. inptr = input_buf[row];
  178513. outptr = output_buf[row];
  178514. if (cquantize->on_odd_row) {
  178515. /* work right to left in this row */
  178516. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178517. outptr += width-1;
  178518. dir = -1;
  178519. dir3 = -3;
  178520. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178521. cquantize->on_odd_row = FALSE; /* flip for next time */
  178522. } else {
  178523. /* work left to right in this row */
  178524. dir = 1;
  178525. dir3 = 3;
  178526. errorptr = cquantize->fserrors; /* => entry before first real column */
  178527. cquantize->on_odd_row = TRUE; /* flip for next time */
  178528. }
  178529. /* Preset error values: no error propagated to first pixel from left */
  178530. cur0 = cur1 = cur2 = 0;
  178531. /* and no error propagated to row below yet */
  178532. belowerr0 = belowerr1 = belowerr2 = 0;
  178533. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178534. for (col = width; col > 0; col--) {
  178535. /* curN holds the error propagated from the previous pixel on the
  178536. * current line. Add the error propagated from the previous line
  178537. * to form the complete error correction term for this pixel, and
  178538. * round the error term (which is expressed * 16) to an integer.
  178539. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178540. * for either sign of the error value.
  178541. * Note: errorptr points to *previous* column's array entry.
  178542. */
  178543. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178544. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178545. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178546. /* Limit the error using transfer function set by init_error_limit.
  178547. * See comments with init_error_limit for rationale.
  178548. */
  178549. cur0 = error_limit[cur0];
  178550. cur1 = error_limit[cur1];
  178551. cur2 = error_limit[cur2];
  178552. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178553. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178554. * this sets the required size of the range_limit array.
  178555. */
  178556. cur0 += GETJSAMPLE(inptr[0]);
  178557. cur1 += GETJSAMPLE(inptr[1]);
  178558. cur2 += GETJSAMPLE(inptr[2]);
  178559. cur0 = GETJSAMPLE(range_limit[cur0]);
  178560. cur1 = GETJSAMPLE(range_limit[cur1]);
  178561. cur2 = GETJSAMPLE(range_limit[cur2]);
  178562. /* Index into the cache with adjusted pixel value */
  178563. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178564. /* If we have not seen this color before, find nearest colormap */
  178565. /* entry and update the cache */
  178566. if (*cachep == 0)
  178567. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178568. /* Now emit the colormap index for this cell */
  178569. { register int pixcode = *cachep - 1;
  178570. *outptr = (JSAMPLE) pixcode;
  178571. /* Compute representation error for this pixel */
  178572. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178573. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178574. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178575. }
  178576. /* Compute error fractions to be propagated to adjacent pixels.
  178577. * Add these into the running sums, and simultaneously shift the
  178578. * next-line error sums left by 1 column.
  178579. */
  178580. { register LOCFSERROR bnexterr, delta;
  178581. bnexterr = cur0; /* Process component 0 */
  178582. delta = cur0 * 2;
  178583. cur0 += delta; /* form error * 3 */
  178584. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178585. cur0 += delta; /* form error * 5 */
  178586. bpreverr0 = belowerr0 + cur0;
  178587. belowerr0 = bnexterr;
  178588. cur0 += delta; /* form error * 7 */
  178589. bnexterr = cur1; /* Process component 1 */
  178590. delta = cur1 * 2;
  178591. cur1 += delta; /* form error * 3 */
  178592. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178593. cur1 += delta; /* form error * 5 */
  178594. bpreverr1 = belowerr1 + cur1;
  178595. belowerr1 = bnexterr;
  178596. cur1 += delta; /* form error * 7 */
  178597. bnexterr = cur2; /* Process component 2 */
  178598. delta = cur2 * 2;
  178599. cur2 += delta; /* form error * 3 */
  178600. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178601. cur2 += delta; /* form error * 5 */
  178602. bpreverr2 = belowerr2 + cur2;
  178603. belowerr2 = bnexterr;
  178604. cur2 += delta; /* form error * 7 */
  178605. }
  178606. /* At this point curN contains the 7/16 error value to be propagated
  178607. * to the next pixel on the current line, and all the errors for the
  178608. * next line have been shifted over. We are therefore ready to move on.
  178609. */
  178610. inptr += dir3; /* Advance pixel pointers to next column */
  178611. outptr += dir;
  178612. errorptr += dir3; /* advance errorptr to current column */
  178613. }
  178614. /* Post-loop cleanup: we must unload the final error values into the
  178615. * final fserrors[] entry. Note we need not unload belowerrN because
  178616. * it is for the dummy column before or after the actual array.
  178617. */
  178618. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178619. errorptr[1] = (FSERROR) bpreverr1;
  178620. errorptr[2] = (FSERROR) bpreverr2;
  178621. }
  178622. }
  178623. /*
  178624. * Initialize the error-limiting transfer function (lookup table).
  178625. * The raw F-S error computation can potentially compute error values of up to
  178626. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178627. * much less, otherwise obviously wrong pixels will be created. (Typical
  178628. * effects include weird fringes at color-area boundaries, isolated bright
  178629. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178630. * is to ensure that the "corners" of the color cube are allocated as output
  178631. * colors; then repeated errors in the same direction cannot cause cascading
  178632. * error buildup. However, that only prevents the error from getting
  178633. * completely out of hand; Aaron Giles reports that error limiting improves
  178634. * the results even with corner colors allocated.
  178635. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178636. * well, but the smoother transfer function used below is even better. Thanks
  178637. * to Aaron Giles for this idea.
  178638. */
  178639. LOCAL(void)
  178640. init_error_limit (j_decompress_ptr cinfo)
  178641. /* Allocate and fill in the error_limiter table */
  178642. {
  178643. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178644. int * table;
  178645. int in, out;
  178646. table = (int *) (*cinfo->mem->alloc_small)
  178647. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178648. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178649. cquantize->error_limiter = table;
  178650. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178651. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178652. out = 0;
  178653. for (in = 0; in < STEPSIZE; in++, out++) {
  178654. table[in] = out; table[-in] = -out;
  178655. }
  178656. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178657. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178658. table[in] = out; table[-in] = -out;
  178659. }
  178660. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178661. for (; in <= MAXJSAMPLE; in++) {
  178662. table[in] = out; table[-in] = -out;
  178663. }
  178664. #undef STEPSIZE
  178665. }
  178666. /*
  178667. * Finish up at the end of each pass.
  178668. */
  178669. METHODDEF(void)
  178670. finish_pass1 (j_decompress_ptr cinfo)
  178671. {
  178672. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178673. /* Select the representative colors and fill in cinfo->colormap */
  178674. cinfo->colormap = cquantize->sv_colormap;
  178675. select_colors(cinfo, cquantize->desired);
  178676. /* Force next pass to zero the color index table */
  178677. cquantize->needs_zeroed = TRUE;
  178678. }
  178679. METHODDEF(void)
  178680. finish_pass2 (j_decompress_ptr)
  178681. {
  178682. /* no work */
  178683. }
  178684. /*
  178685. * Initialize for each processing pass.
  178686. */
  178687. METHODDEF(void)
  178688. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178689. {
  178690. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178691. hist3d histogram = cquantize->histogram;
  178692. int i;
  178693. /* Only F-S dithering or no dithering is supported. */
  178694. /* If user asks for ordered dither, give him F-S. */
  178695. if (cinfo->dither_mode != JDITHER_NONE)
  178696. cinfo->dither_mode = JDITHER_FS;
  178697. if (is_pre_scan) {
  178698. /* Set up method pointers */
  178699. cquantize->pub.color_quantize = prescan_quantize;
  178700. cquantize->pub.finish_pass = finish_pass1;
  178701. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178702. } else {
  178703. /* Set up method pointers */
  178704. if (cinfo->dither_mode == JDITHER_FS)
  178705. cquantize->pub.color_quantize = pass2_fs_dither;
  178706. else
  178707. cquantize->pub.color_quantize = pass2_no_dither;
  178708. cquantize->pub.finish_pass = finish_pass2;
  178709. /* Make sure color count is acceptable */
  178710. i = cinfo->actual_number_of_colors;
  178711. if (i < 1)
  178712. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178713. if (i > MAXNUMCOLORS)
  178714. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178715. if (cinfo->dither_mode == JDITHER_FS) {
  178716. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178717. (3 * SIZEOF(FSERROR)));
  178718. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178719. if (cquantize->fserrors == NULL)
  178720. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178721. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178722. /* Initialize the propagated errors to zero. */
  178723. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178724. /* Make the error-limit table if we didn't already. */
  178725. if (cquantize->error_limiter == NULL)
  178726. init_error_limit(cinfo);
  178727. cquantize->on_odd_row = FALSE;
  178728. }
  178729. }
  178730. /* Zero the histogram or inverse color map, if necessary */
  178731. if (cquantize->needs_zeroed) {
  178732. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178733. jzero_far((void FAR *) histogram[i],
  178734. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178735. }
  178736. cquantize->needs_zeroed = FALSE;
  178737. }
  178738. }
  178739. /*
  178740. * Switch to a new external colormap between output passes.
  178741. */
  178742. METHODDEF(void)
  178743. new_color_map_2_quant (j_decompress_ptr cinfo)
  178744. {
  178745. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178746. /* Reset the inverse color map */
  178747. cquantize->needs_zeroed = TRUE;
  178748. }
  178749. /*
  178750. * Module initialization routine for 2-pass color quantization.
  178751. */
  178752. GLOBAL(void)
  178753. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178754. {
  178755. my_cquantize_ptr2 cquantize;
  178756. int i;
  178757. cquantize = (my_cquantize_ptr2)
  178758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178759. SIZEOF(my_cquantizer2));
  178760. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178761. cquantize->pub.start_pass = start_pass_2_quant;
  178762. cquantize->pub.new_color_map = new_color_map_2_quant;
  178763. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178764. cquantize->error_limiter = NULL;
  178765. /* Make sure jdmaster didn't give me a case I can't handle */
  178766. if (cinfo->out_color_components != 3)
  178767. ERREXIT(cinfo, JERR_NOTIMPL);
  178768. /* Allocate the histogram/inverse colormap storage */
  178769. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178770. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178771. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178772. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178773. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178774. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178775. }
  178776. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178777. /* Allocate storage for the completed colormap, if required.
  178778. * We do this now since it is FAR storage and may affect
  178779. * the memory manager's space calculations.
  178780. */
  178781. if (cinfo->enable_2pass_quant) {
  178782. /* Make sure color count is acceptable */
  178783. int desired = cinfo->desired_number_of_colors;
  178784. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178785. if (desired < 8)
  178786. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178787. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178788. if (desired > MAXNUMCOLORS)
  178789. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178790. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178791. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178792. cquantize->desired = desired;
  178793. } else
  178794. cquantize->sv_colormap = NULL;
  178795. /* Only F-S dithering or no dithering is supported. */
  178796. /* If user asks for ordered dither, give him F-S. */
  178797. if (cinfo->dither_mode != JDITHER_NONE)
  178798. cinfo->dither_mode = JDITHER_FS;
  178799. /* Allocate Floyd-Steinberg workspace if necessary.
  178800. * This isn't really needed until pass 2, but again it is FAR storage.
  178801. * Although we will cope with a later change in dither_mode,
  178802. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178803. */
  178804. if (cinfo->dither_mode == JDITHER_FS) {
  178805. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178806. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178807. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178808. /* Might as well create the error-limiting table too. */
  178809. init_error_limit(cinfo);
  178810. }
  178811. }
  178812. #endif /* QUANT_2PASS_SUPPORTED */
  178813. /*** End of inlined file: jquant2.c ***/
  178814. /*** Start of inlined file: jutils.c ***/
  178815. #define JPEG_INTERNALS
  178816. /*
  178817. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178818. * of a DCT block read in natural order (left to right, top to bottom).
  178819. */
  178820. #if 0 /* This table is not actually needed in v6a */
  178821. const int jpeg_zigzag_order[DCTSIZE2] = {
  178822. 0, 1, 5, 6, 14, 15, 27, 28,
  178823. 2, 4, 7, 13, 16, 26, 29, 42,
  178824. 3, 8, 12, 17, 25, 30, 41, 43,
  178825. 9, 11, 18, 24, 31, 40, 44, 53,
  178826. 10, 19, 23, 32, 39, 45, 52, 54,
  178827. 20, 22, 33, 38, 46, 51, 55, 60,
  178828. 21, 34, 37, 47, 50, 56, 59, 61,
  178829. 35, 36, 48, 49, 57, 58, 62, 63
  178830. };
  178831. #endif
  178832. /*
  178833. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178834. * of zigzag order.
  178835. *
  178836. * When reading corrupted data, the Huffman decoders could attempt
  178837. * to reference an entry beyond the end of this array (if the decoded
  178838. * zero run length reaches past the end of the block). To prevent
  178839. * wild stores without adding an inner-loop test, we put some extra
  178840. * "63"s after the real entries. This will cause the extra coefficient
  178841. * to be stored in location 63 of the block, not somewhere random.
  178842. * The worst case would be a run-length of 15, which means we need 16
  178843. * fake entries.
  178844. */
  178845. const int jpeg_natural_order[DCTSIZE2+16] = {
  178846. 0, 1, 8, 16, 9, 2, 3, 10,
  178847. 17, 24, 32, 25, 18, 11, 4, 5,
  178848. 12, 19, 26, 33, 40, 48, 41, 34,
  178849. 27, 20, 13, 6, 7, 14, 21, 28,
  178850. 35, 42, 49, 56, 57, 50, 43, 36,
  178851. 29, 22, 15, 23, 30, 37, 44, 51,
  178852. 58, 59, 52, 45, 38, 31, 39, 46,
  178853. 53, 60, 61, 54, 47, 55, 62, 63,
  178854. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178855. 63, 63, 63, 63, 63, 63, 63, 63
  178856. };
  178857. /*
  178858. * Arithmetic utilities
  178859. */
  178860. GLOBAL(long)
  178861. jdiv_round_up (long a, long b)
  178862. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178863. /* Assumes a >= 0, b > 0 */
  178864. {
  178865. return (a + b - 1L) / b;
  178866. }
  178867. GLOBAL(long)
  178868. jround_up (long a, long b)
  178869. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178870. /* Assumes a >= 0, b > 0 */
  178871. {
  178872. a += b - 1L;
  178873. return a - (a % b);
  178874. }
  178875. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178876. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178877. * are FAR and we're assuming a small-pointer memory model. However, some
  178878. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178879. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178880. * Otherwise, the routines below do it the hard way. (The performance cost
  178881. * is not all that great, because these routines aren't very heavily used.)
  178882. */
  178883. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178884. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178885. #define FMEMZERO(target,size) MEMZERO(target,size)
  178886. #else /* 80x86 case, define if we can */
  178887. #ifdef USE_FMEM
  178888. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178889. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178890. #endif
  178891. #endif
  178892. GLOBAL(void)
  178893. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178894. JSAMPARRAY output_array, int dest_row,
  178895. int num_rows, JDIMENSION num_cols)
  178896. /* Copy some rows of samples from one place to another.
  178897. * num_rows rows are copied from input_array[source_row++]
  178898. * to output_array[dest_row++]; these areas may overlap for duplication.
  178899. * The source and destination arrays must be at least as wide as num_cols.
  178900. */
  178901. {
  178902. register JSAMPROW inptr, outptr;
  178903. #ifdef FMEMCOPY
  178904. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178905. #else
  178906. register JDIMENSION count;
  178907. #endif
  178908. register int row;
  178909. input_array += source_row;
  178910. output_array += dest_row;
  178911. for (row = num_rows; row > 0; row--) {
  178912. inptr = *input_array++;
  178913. outptr = *output_array++;
  178914. #ifdef FMEMCOPY
  178915. FMEMCOPY(outptr, inptr, count);
  178916. #else
  178917. for (count = num_cols; count > 0; count--)
  178918. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178919. #endif
  178920. }
  178921. }
  178922. GLOBAL(void)
  178923. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178924. JDIMENSION num_blocks)
  178925. /* Copy a row of coefficient blocks from one place to another. */
  178926. {
  178927. #ifdef FMEMCOPY
  178928. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178929. #else
  178930. register JCOEFPTR inptr, outptr;
  178931. register long count;
  178932. inptr = (JCOEFPTR) input_row;
  178933. outptr = (JCOEFPTR) output_row;
  178934. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178935. *outptr++ = *inptr++;
  178936. }
  178937. #endif
  178938. }
  178939. GLOBAL(void)
  178940. jzero_far (void FAR * target, size_t bytestozero)
  178941. /* Zero out a chunk of FAR memory. */
  178942. /* This might be sample-array data, block-array data, or alloc_large data. */
  178943. {
  178944. #ifdef FMEMZERO
  178945. FMEMZERO(target, bytestozero);
  178946. #else
  178947. register char FAR * ptr = (char FAR *) target;
  178948. register size_t count;
  178949. for (count = bytestozero; count > 0; count--) {
  178950. *ptr++ = 0;
  178951. }
  178952. #endif
  178953. }
  178954. /*** End of inlined file: jutils.c ***/
  178955. /*** Start of inlined file: transupp.c ***/
  178956. /* Although this file really shouldn't have access to the library internals,
  178957. * it's helpful to let it call jround_up() and jcopy_block_row().
  178958. */
  178959. #define JPEG_INTERNALS
  178960. /*** Start of inlined file: transupp.h ***/
  178961. /* If you happen not to want the image transform support, disable it here */
  178962. #ifndef TRANSFORMS_SUPPORTED
  178963. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178964. #endif
  178965. /* Short forms of external names for systems with brain-damaged linkers. */
  178966. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178967. #define jtransform_request_workspace jTrRequest
  178968. #define jtransform_adjust_parameters jTrAdjust
  178969. #define jtransform_execute_transformation jTrExec
  178970. #define jcopy_markers_setup jCMrkSetup
  178971. #define jcopy_markers_execute jCMrkExec
  178972. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178973. /*
  178974. * Codes for supported types of image transformations.
  178975. */
  178976. typedef enum {
  178977. JXFORM_NONE, /* no transformation */
  178978. JXFORM_FLIP_H, /* horizontal flip */
  178979. JXFORM_FLIP_V, /* vertical flip */
  178980. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178981. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178982. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178983. JXFORM_ROT_180, /* 180-degree rotation */
  178984. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178985. } JXFORM_CODE;
  178986. /*
  178987. * Although rotating and flipping data expressed as DCT coefficients is not
  178988. * hard, there is an asymmetry in the JPEG format specification for images
  178989. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178990. * image edges are padded out to the next iMCU boundary with junk data; but
  178991. * no padding is possible at the top and left edges. If we were to flip
  178992. * the whole image including the pad data, then pad garbage would become
  178993. * visible at the top and/or left, and real pixels would disappear into the
  178994. * pad margins --- perhaps permanently, since encoders & decoders may not
  178995. * bother to preserve DCT blocks that appear to be completely outside the
  178996. * nominal image area. So, we have to exclude any partial iMCUs from the
  178997. * basic transformation.
  178998. *
  178999. * Transpose is the only transformation that can handle partial iMCUs at the
  179000. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179001. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179002. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179003. * The other transforms are defined as combinations of these basic transforms
  179004. * and process edge blocks in a way that preserves the equivalence.
  179005. *
  179006. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179007. * this is not strictly lossless, but it usually gives the best-looking
  179008. * result for odd-size images. Note that when this option is active,
  179009. * the expected mathematical equivalences between the transforms may not hold.
  179010. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179011. * followed by -rot 180 -trim trims both edges.)
  179012. *
  179013. * We also offer a "force to grayscale" option, which simply discards the
  179014. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179015. * the luminance channel is preserved exactly. It's not the same kind of
  179016. * thing as the rotate/flip transformations, but it's convenient to handle it
  179017. * as part of this package, mainly because the transformation routines have to
  179018. * be aware of the option to know how many components to work on.
  179019. */
  179020. typedef struct {
  179021. /* Options: set by caller */
  179022. JXFORM_CODE transform; /* image transform operator */
  179023. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179024. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179025. /* Internal workspace: caller should not touch these */
  179026. int num_components; /* # of components in workspace */
  179027. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179028. } jpeg_transform_info;
  179029. #if TRANSFORMS_SUPPORTED
  179030. /* Request any required workspace */
  179031. EXTERN(void) jtransform_request_workspace
  179032. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179033. /* Adjust output image parameters */
  179034. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179035. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179036. jvirt_barray_ptr *src_coef_arrays,
  179037. jpeg_transform_info *info));
  179038. /* Execute the actual transformation, if any */
  179039. EXTERN(void) jtransform_execute_transformation
  179040. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179041. jvirt_barray_ptr *src_coef_arrays,
  179042. jpeg_transform_info *info));
  179043. #endif /* TRANSFORMS_SUPPORTED */
  179044. /*
  179045. * Support for copying optional markers from source to destination file.
  179046. */
  179047. typedef enum {
  179048. JCOPYOPT_NONE, /* copy no optional markers */
  179049. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179050. JCOPYOPT_ALL /* copy all optional markers */
  179051. } JCOPY_OPTION;
  179052. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179053. /* Setup decompression object to save desired markers in memory */
  179054. EXTERN(void) jcopy_markers_setup
  179055. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179056. /* Copy markers saved in the given source object to the destination object */
  179057. EXTERN(void) jcopy_markers_execute
  179058. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179059. JCOPY_OPTION option));
  179060. /*** End of inlined file: transupp.h ***/
  179061. /* My own external interface */
  179062. #if TRANSFORMS_SUPPORTED
  179063. /*
  179064. * Lossless image transformation routines. These routines work on DCT
  179065. * coefficient arrays and thus do not require any lossy decompression
  179066. * or recompression of the image.
  179067. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179068. *
  179069. * Horizontal flipping is done in-place, using a single top-to-bottom
  179070. * pass through the virtual source array. It will thus be much the
  179071. * fastest option for images larger than main memory.
  179072. *
  179073. * The other routines require a set of destination virtual arrays, so they
  179074. * need twice as much memory as jpegtran normally does. The destination
  179075. * arrays are always written in normal scan order (top to bottom) because
  179076. * the virtual array manager expects this. The source arrays will be scanned
  179077. * in the corresponding order, which means multiple passes through the source
  179078. * arrays for most of the transforms. That could result in much thrashing
  179079. * if the image is larger than main memory.
  179080. *
  179081. * Some notes about the operating environment of the individual transform
  179082. * routines:
  179083. * 1. Both the source and destination virtual arrays are allocated from the
  179084. * source JPEG object, and therefore should be manipulated by calling the
  179085. * source's memory manager.
  179086. * 2. The destination's component count should be used. It may be smaller
  179087. * than the source's when forcing to grayscale.
  179088. * 3. Likewise the destination's sampling factors should be used. When
  179089. * forcing to grayscale the destination's sampling factors will be all 1,
  179090. * and we may as well take that as the effective iMCU size.
  179091. * 4. When "trim" is in effect, the destination's dimensions will be the
  179092. * trimmed values but the source's will be untrimmed.
  179093. * 5. All the routines assume that the source and destination buffers are
  179094. * padded out to a full iMCU boundary. This is true, although for the
  179095. * source buffer it is an undocumented property of jdcoefct.c.
  179096. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179097. * dimensions and ignore the source's.
  179098. */
  179099. LOCAL(void)
  179100. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179101. jvirt_barray_ptr *src_coef_arrays)
  179102. /* Horizontal flip; done in-place, so no separate dest array is required */
  179103. {
  179104. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179105. int ci, k, offset_y;
  179106. JBLOCKARRAY buffer;
  179107. JCOEFPTR ptr1, ptr2;
  179108. JCOEF temp1, temp2;
  179109. jpeg_component_info *compptr;
  179110. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179111. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179112. * mirroring by changing the signs of odd-numbered columns.
  179113. * Partial iMCUs at the right edge are left untouched.
  179114. */
  179115. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179116. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179117. compptr = dstinfo->comp_info + ci;
  179118. comp_width = MCU_cols * compptr->h_samp_factor;
  179119. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179120. blk_y += compptr->v_samp_factor) {
  179121. buffer = (*srcinfo->mem->access_virt_barray)
  179122. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179123. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179124. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179125. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179126. ptr1 = buffer[offset_y][blk_x];
  179127. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179128. /* this unrolled loop doesn't need to know which row it's on... */
  179129. for (k = 0; k < DCTSIZE2; k += 2) {
  179130. temp1 = *ptr1; /* swap even column */
  179131. temp2 = *ptr2;
  179132. *ptr1++ = temp2;
  179133. *ptr2++ = temp1;
  179134. temp1 = *ptr1; /* swap odd column with sign change */
  179135. temp2 = *ptr2;
  179136. *ptr1++ = -temp2;
  179137. *ptr2++ = -temp1;
  179138. }
  179139. }
  179140. }
  179141. }
  179142. }
  179143. }
  179144. LOCAL(void)
  179145. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179146. jvirt_barray_ptr *src_coef_arrays,
  179147. jvirt_barray_ptr *dst_coef_arrays)
  179148. /* Vertical flip */
  179149. {
  179150. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179151. int ci, i, j, offset_y;
  179152. JBLOCKARRAY src_buffer, dst_buffer;
  179153. JBLOCKROW src_row_ptr, dst_row_ptr;
  179154. JCOEFPTR src_ptr, dst_ptr;
  179155. jpeg_component_info *compptr;
  179156. /* We output into a separate array because we can't touch different
  179157. * rows of the source virtual array simultaneously. Otherwise, this
  179158. * is a pretty straightforward analog of horizontal flip.
  179159. * Within a DCT block, vertical mirroring is done by changing the signs
  179160. * of odd-numbered rows.
  179161. * Partial iMCUs at the bottom edge are copied verbatim.
  179162. */
  179163. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179164. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179165. compptr = dstinfo->comp_info + ci;
  179166. comp_height = MCU_rows * compptr->v_samp_factor;
  179167. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179168. dst_blk_y += compptr->v_samp_factor) {
  179169. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179170. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179171. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179172. if (dst_blk_y < comp_height) {
  179173. /* Row is within the mirrorable area. */
  179174. src_buffer = (*srcinfo->mem->access_virt_barray)
  179175. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179176. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179177. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179178. } else {
  179179. /* Bottom-edge blocks will be copied verbatim. */
  179180. src_buffer = (*srcinfo->mem->access_virt_barray)
  179181. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179182. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179183. }
  179184. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179185. if (dst_blk_y < comp_height) {
  179186. /* Row is within the mirrorable area. */
  179187. dst_row_ptr = dst_buffer[offset_y];
  179188. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179189. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179190. dst_blk_x++) {
  179191. dst_ptr = dst_row_ptr[dst_blk_x];
  179192. src_ptr = src_row_ptr[dst_blk_x];
  179193. for (i = 0; i < DCTSIZE; i += 2) {
  179194. /* copy even row */
  179195. for (j = 0; j < DCTSIZE; j++)
  179196. *dst_ptr++ = *src_ptr++;
  179197. /* copy odd row with sign change */
  179198. for (j = 0; j < DCTSIZE; j++)
  179199. *dst_ptr++ = - *src_ptr++;
  179200. }
  179201. }
  179202. } else {
  179203. /* Just copy row verbatim. */
  179204. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179205. compptr->width_in_blocks);
  179206. }
  179207. }
  179208. }
  179209. }
  179210. }
  179211. LOCAL(void)
  179212. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179213. jvirt_barray_ptr *src_coef_arrays,
  179214. jvirt_barray_ptr *dst_coef_arrays)
  179215. /* Transpose source into destination */
  179216. {
  179217. JDIMENSION dst_blk_x, dst_blk_y;
  179218. int ci, i, j, offset_x, offset_y;
  179219. JBLOCKARRAY src_buffer, dst_buffer;
  179220. JCOEFPTR src_ptr, dst_ptr;
  179221. jpeg_component_info *compptr;
  179222. /* Transposing pixels within a block just requires transposing the
  179223. * DCT coefficients.
  179224. * Partial iMCUs at the edges require no special treatment; we simply
  179225. * process all the available DCT blocks for every component.
  179226. */
  179227. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179228. compptr = dstinfo->comp_info + ci;
  179229. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179230. dst_blk_y += compptr->v_samp_factor) {
  179231. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179232. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179233. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179234. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179235. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179236. dst_blk_x += compptr->h_samp_factor) {
  179237. src_buffer = (*srcinfo->mem->access_virt_barray)
  179238. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179239. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179240. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179241. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179242. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179243. for (i = 0; i < DCTSIZE; i++)
  179244. for (j = 0; j < DCTSIZE; j++)
  179245. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179246. }
  179247. }
  179248. }
  179249. }
  179250. }
  179251. }
  179252. LOCAL(void)
  179253. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179254. jvirt_barray_ptr *src_coef_arrays,
  179255. jvirt_barray_ptr *dst_coef_arrays)
  179256. /* 90 degree rotation is equivalent to
  179257. * 1. Transposing the image;
  179258. * 2. Horizontal mirroring.
  179259. * These two steps are merged into a single processing routine.
  179260. */
  179261. {
  179262. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179263. int ci, i, j, offset_x, offset_y;
  179264. JBLOCKARRAY src_buffer, dst_buffer;
  179265. JCOEFPTR src_ptr, dst_ptr;
  179266. jpeg_component_info *compptr;
  179267. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179268. * at the (output) right edge properly. They just get transposed and
  179269. * not mirrored.
  179270. */
  179271. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179272. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179273. compptr = dstinfo->comp_info + ci;
  179274. comp_width = MCU_cols * compptr->h_samp_factor;
  179275. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179276. dst_blk_y += compptr->v_samp_factor) {
  179277. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179278. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179279. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179280. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179281. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179282. dst_blk_x += compptr->h_samp_factor) {
  179283. src_buffer = (*srcinfo->mem->access_virt_barray)
  179284. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179285. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179286. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179287. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179288. if (dst_blk_x < comp_width) {
  179289. /* Block is within the mirrorable area. */
  179290. dst_ptr = dst_buffer[offset_y]
  179291. [comp_width - dst_blk_x - offset_x - 1];
  179292. for (i = 0; i < DCTSIZE; i++) {
  179293. for (j = 0; j < DCTSIZE; j++)
  179294. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179295. i++;
  179296. for (j = 0; j < DCTSIZE; j++)
  179297. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179298. }
  179299. } else {
  179300. /* Edge blocks are transposed but not mirrored. */
  179301. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179302. for (i = 0; i < DCTSIZE; i++)
  179303. for (j = 0; j < DCTSIZE; j++)
  179304. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179305. }
  179306. }
  179307. }
  179308. }
  179309. }
  179310. }
  179311. }
  179312. LOCAL(void)
  179313. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179314. jvirt_barray_ptr *src_coef_arrays,
  179315. jvirt_barray_ptr *dst_coef_arrays)
  179316. /* 270 degree rotation is equivalent to
  179317. * 1. Horizontal mirroring;
  179318. * 2. Transposing the image.
  179319. * These two steps are merged into a single processing routine.
  179320. */
  179321. {
  179322. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179323. int ci, i, j, offset_x, offset_y;
  179324. JBLOCKARRAY src_buffer, dst_buffer;
  179325. JCOEFPTR src_ptr, dst_ptr;
  179326. jpeg_component_info *compptr;
  179327. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179328. * at the (output) bottom edge properly. They just get transposed and
  179329. * not mirrored.
  179330. */
  179331. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179332. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179333. compptr = dstinfo->comp_info + ci;
  179334. comp_height = MCU_rows * compptr->v_samp_factor;
  179335. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179336. dst_blk_y += compptr->v_samp_factor) {
  179337. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179338. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179339. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179340. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179341. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179342. dst_blk_x += compptr->h_samp_factor) {
  179343. src_buffer = (*srcinfo->mem->access_virt_barray)
  179344. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179345. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179346. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179347. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179348. if (dst_blk_y < comp_height) {
  179349. /* Block is within the mirrorable area. */
  179350. src_ptr = src_buffer[offset_x]
  179351. [comp_height - dst_blk_y - offset_y - 1];
  179352. for (i = 0; i < DCTSIZE; i++) {
  179353. for (j = 0; j < DCTSIZE; j++) {
  179354. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179355. j++;
  179356. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179357. }
  179358. }
  179359. } else {
  179360. /* Edge blocks are transposed but not mirrored. */
  179361. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179362. for (i = 0; i < DCTSIZE; i++)
  179363. for (j = 0; j < DCTSIZE; j++)
  179364. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179365. }
  179366. }
  179367. }
  179368. }
  179369. }
  179370. }
  179371. }
  179372. LOCAL(void)
  179373. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179374. jvirt_barray_ptr *src_coef_arrays,
  179375. jvirt_barray_ptr *dst_coef_arrays)
  179376. /* 180 degree rotation is equivalent to
  179377. * 1. Vertical mirroring;
  179378. * 2. Horizontal mirroring.
  179379. * These two steps are merged into a single processing routine.
  179380. */
  179381. {
  179382. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179383. int ci, i, j, offset_y;
  179384. JBLOCKARRAY src_buffer, dst_buffer;
  179385. JBLOCKROW src_row_ptr, dst_row_ptr;
  179386. JCOEFPTR src_ptr, dst_ptr;
  179387. jpeg_component_info *compptr;
  179388. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179389. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179390. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179391. compptr = dstinfo->comp_info + ci;
  179392. comp_width = MCU_cols * compptr->h_samp_factor;
  179393. comp_height = MCU_rows * compptr->v_samp_factor;
  179394. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179395. dst_blk_y += compptr->v_samp_factor) {
  179396. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179397. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179398. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179399. if (dst_blk_y < comp_height) {
  179400. /* Row is within the vertically mirrorable area. */
  179401. src_buffer = (*srcinfo->mem->access_virt_barray)
  179402. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179403. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179404. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179405. } else {
  179406. /* Bottom-edge rows are only mirrored horizontally. */
  179407. src_buffer = (*srcinfo->mem->access_virt_barray)
  179408. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179409. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179410. }
  179411. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179412. if (dst_blk_y < comp_height) {
  179413. /* Row is within the mirrorable area. */
  179414. dst_row_ptr = dst_buffer[offset_y];
  179415. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179416. /* Process the blocks that can be mirrored both ways. */
  179417. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179418. dst_ptr = dst_row_ptr[dst_blk_x];
  179419. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179420. for (i = 0; i < DCTSIZE; i += 2) {
  179421. /* For even row, negate every odd column. */
  179422. for (j = 0; j < DCTSIZE; j += 2) {
  179423. *dst_ptr++ = *src_ptr++;
  179424. *dst_ptr++ = - *src_ptr++;
  179425. }
  179426. /* For odd row, negate every even column. */
  179427. for (j = 0; j < DCTSIZE; j += 2) {
  179428. *dst_ptr++ = - *src_ptr++;
  179429. *dst_ptr++ = *src_ptr++;
  179430. }
  179431. }
  179432. }
  179433. /* Any remaining right-edge blocks are only mirrored vertically. */
  179434. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179435. dst_ptr = dst_row_ptr[dst_blk_x];
  179436. src_ptr = src_row_ptr[dst_blk_x];
  179437. for (i = 0; i < DCTSIZE; i += 2) {
  179438. for (j = 0; j < DCTSIZE; j++)
  179439. *dst_ptr++ = *src_ptr++;
  179440. for (j = 0; j < DCTSIZE; j++)
  179441. *dst_ptr++ = - *src_ptr++;
  179442. }
  179443. }
  179444. } else {
  179445. /* Remaining rows are just mirrored horizontally. */
  179446. dst_row_ptr = dst_buffer[offset_y];
  179447. src_row_ptr = src_buffer[offset_y];
  179448. /* Process the blocks that can be mirrored. */
  179449. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179450. dst_ptr = dst_row_ptr[dst_blk_x];
  179451. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179452. for (i = 0; i < DCTSIZE2; i += 2) {
  179453. *dst_ptr++ = *src_ptr++;
  179454. *dst_ptr++ = - *src_ptr++;
  179455. }
  179456. }
  179457. /* Any remaining right-edge blocks are only copied. */
  179458. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179459. dst_ptr = dst_row_ptr[dst_blk_x];
  179460. src_ptr = src_row_ptr[dst_blk_x];
  179461. for (i = 0; i < DCTSIZE2; i++)
  179462. *dst_ptr++ = *src_ptr++;
  179463. }
  179464. }
  179465. }
  179466. }
  179467. }
  179468. }
  179469. LOCAL(void)
  179470. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179471. jvirt_barray_ptr *src_coef_arrays,
  179472. jvirt_barray_ptr *dst_coef_arrays)
  179473. /* Transverse transpose is equivalent to
  179474. * 1. 180 degree rotation;
  179475. * 2. Transposition;
  179476. * or
  179477. * 1. Horizontal mirroring;
  179478. * 2. Transposition;
  179479. * 3. Horizontal mirroring.
  179480. * These steps are merged into a single processing routine.
  179481. */
  179482. {
  179483. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179484. int ci, i, j, offset_x, offset_y;
  179485. JBLOCKARRAY src_buffer, dst_buffer;
  179486. JCOEFPTR src_ptr, dst_ptr;
  179487. jpeg_component_info *compptr;
  179488. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179489. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179490. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179491. compptr = dstinfo->comp_info + ci;
  179492. comp_width = MCU_cols * compptr->h_samp_factor;
  179493. comp_height = MCU_rows * compptr->v_samp_factor;
  179494. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179495. dst_blk_y += compptr->v_samp_factor) {
  179496. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179497. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179498. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179499. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179500. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179501. dst_blk_x += compptr->h_samp_factor) {
  179502. src_buffer = (*srcinfo->mem->access_virt_barray)
  179503. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179504. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179505. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179506. if (dst_blk_y < comp_height) {
  179507. src_ptr = src_buffer[offset_x]
  179508. [comp_height - dst_blk_y - offset_y - 1];
  179509. if (dst_blk_x < comp_width) {
  179510. /* Block is within the mirrorable area. */
  179511. dst_ptr = dst_buffer[offset_y]
  179512. [comp_width - dst_blk_x - offset_x - 1];
  179513. for (i = 0; i < DCTSIZE; i++) {
  179514. for (j = 0; j < DCTSIZE; j++) {
  179515. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179516. j++;
  179517. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179518. }
  179519. i++;
  179520. for (j = 0; j < DCTSIZE; j++) {
  179521. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179522. j++;
  179523. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179524. }
  179525. }
  179526. } else {
  179527. /* Right-edge blocks are mirrored in y only */
  179528. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179529. for (i = 0; i < DCTSIZE; i++) {
  179530. for (j = 0; j < DCTSIZE; j++) {
  179531. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179532. j++;
  179533. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179534. }
  179535. }
  179536. }
  179537. } else {
  179538. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179539. if (dst_blk_x < comp_width) {
  179540. /* Bottom-edge blocks are mirrored in x only */
  179541. dst_ptr = dst_buffer[offset_y]
  179542. [comp_width - dst_blk_x - offset_x - 1];
  179543. for (i = 0; i < DCTSIZE; i++) {
  179544. for (j = 0; j < DCTSIZE; j++)
  179545. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179546. i++;
  179547. for (j = 0; j < DCTSIZE; j++)
  179548. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179549. }
  179550. } else {
  179551. /* At lower right corner, just transpose, no mirroring */
  179552. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179553. for (i = 0; i < DCTSIZE; i++)
  179554. for (j = 0; j < DCTSIZE; j++)
  179555. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179556. }
  179557. }
  179558. }
  179559. }
  179560. }
  179561. }
  179562. }
  179563. }
  179564. /* Request any required workspace.
  179565. *
  179566. * We allocate the workspace virtual arrays from the source decompression
  179567. * object, so that all the arrays (both the original data and the workspace)
  179568. * will be taken into account while making memory management decisions.
  179569. * Hence, this routine must be called after jpeg_read_header (which reads
  179570. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179571. * the source's virtual arrays).
  179572. */
  179573. GLOBAL(void)
  179574. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179575. jpeg_transform_info *info)
  179576. {
  179577. jvirt_barray_ptr *coef_arrays = NULL;
  179578. jpeg_component_info *compptr;
  179579. int ci;
  179580. if (info->force_grayscale &&
  179581. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179582. srcinfo->num_components == 3) {
  179583. /* We'll only process the first component */
  179584. info->num_components = 1;
  179585. } else {
  179586. /* Process all the components */
  179587. info->num_components = srcinfo->num_components;
  179588. }
  179589. switch (info->transform) {
  179590. case JXFORM_NONE:
  179591. case JXFORM_FLIP_H:
  179592. /* Don't need a workspace array */
  179593. break;
  179594. case JXFORM_FLIP_V:
  179595. case JXFORM_ROT_180:
  179596. /* Need workspace arrays having same dimensions as source image.
  179597. * Note that we allocate arrays padded out to the next iMCU boundary,
  179598. * so that transform routines need not worry about missing edge blocks.
  179599. */
  179600. coef_arrays = (jvirt_barray_ptr *)
  179601. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179602. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179603. for (ci = 0; ci < info->num_components; ci++) {
  179604. compptr = srcinfo->comp_info + ci;
  179605. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179606. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179607. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179608. (long) compptr->h_samp_factor),
  179609. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179610. (long) compptr->v_samp_factor),
  179611. (JDIMENSION) compptr->v_samp_factor);
  179612. }
  179613. break;
  179614. case JXFORM_TRANSPOSE:
  179615. case JXFORM_TRANSVERSE:
  179616. case JXFORM_ROT_90:
  179617. case JXFORM_ROT_270:
  179618. /* Need workspace arrays having transposed dimensions.
  179619. * Note that we allocate arrays padded out to the next iMCU boundary,
  179620. * so that transform routines need not worry about missing edge blocks.
  179621. */
  179622. coef_arrays = (jvirt_barray_ptr *)
  179623. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179624. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179625. for (ci = 0; ci < info->num_components; ci++) {
  179626. compptr = srcinfo->comp_info + ci;
  179627. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179628. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179629. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179630. (long) compptr->v_samp_factor),
  179631. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179632. (long) compptr->h_samp_factor),
  179633. (JDIMENSION) compptr->h_samp_factor);
  179634. }
  179635. break;
  179636. }
  179637. info->workspace_coef_arrays = coef_arrays;
  179638. }
  179639. /* Transpose destination image parameters */
  179640. LOCAL(void)
  179641. transpose_critical_parameters (j_compress_ptr dstinfo)
  179642. {
  179643. int tblno, i, j, ci, itemp;
  179644. jpeg_component_info *compptr;
  179645. JQUANT_TBL *qtblptr;
  179646. JDIMENSION dtemp;
  179647. UINT16 qtemp;
  179648. /* Transpose basic image dimensions */
  179649. dtemp = dstinfo->image_width;
  179650. dstinfo->image_width = dstinfo->image_height;
  179651. dstinfo->image_height = dtemp;
  179652. /* Transpose sampling factors */
  179653. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179654. compptr = dstinfo->comp_info + ci;
  179655. itemp = compptr->h_samp_factor;
  179656. compptr->h_samp_factor = compptr->v_samp_factor;
  179657. compptr->v_samp_factor = itemp;
  179658. }
  179659. /* Transpose quantization tables */
  179660. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179661. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179662. if (qtblptr != NULL) {
  179663. for (i = 0; i < DCTSIZE; i++) {
  179664. for (j = 0; j < i; j++) {
  179665. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179666. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179667. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179668. }
  179669. }
  179670. }
  179671. }
  179672. }
  179673. /* Trim off any partial iMCUs on the indicated destination edge */
  179674. LOCAL(void)
  179675. trim_right_edge (j_compress_ptr dstinfo)
  179676. {
  179677. int ci, max_h_samp_factor;
  179678. JDIMENSION MCU_cols;
  179679. /* We have to compute max_h_samp_factor ourselves,
  179680. * because it hasn't been set yet in the destination
  179681. * (and we don't want to use the source's value).
  179682. */
  179683. max_h_samp_factor = 1;
  179684. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179685. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179686. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179687. }
  179688. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179689. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179690. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179691. }
  179692. LOCAL(void)
  179693. trim_bottom_edge (j_compress_ptr dstinfo)
  179694. {
  179695. int ci, max_v_samp_factor;
  179696. JDIMENSION MCU_rows;
  179697. /* We have to compute max_v_samp_factor ourselves,
  179698. * because it hasn't been set yet in the destination
  179699. * (and we don't want to use the source's value).
  179700. */
  179701. max_v_samp_factor = 1;
  179702. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179703. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179704. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179705. }
  179706. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179707. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179708. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179709. }
  179710. /* Adjust output image parameters as needed.
  179711. *
  179712. * This must be called after jpeg_copy_critical_parameters()
  179713. * and before jpeg_write_coefficients().
  179714. *
  179715. * The return value is the set of virtual coefficient arrays to be written
  179716. * (either the ones allocated by jtransform_request_workspace, or the
  179717. * original source data arrays). The caller will need to pass this value
  179718. * to jpeg_write_coefficients().
  179719. */
  179720. GLOBAL(jvirt_barray_ptr *)
  179721. jtransform_adjust_parameters (j_decompress_ptr,
  179722. j_compress_ptr dstinfo,
  179723. jvirt_barray_ptr *src_coef_arrays,
  179724. jpeg_transform_info *info)
  179725. {
  179726. /* If force-to-grayscale is requested, adjust destination parameters */
  179727. if (info->force_grayscale) {
  179728. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179729. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179730. * will get set to 1, which typically won't match the source.
  179731. * In fact we do this even if the source is already grayscale; that
  179732. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179733. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179734. */
  179735. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179736. dstinfo->num_components == 3) ||
  179737. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179738. dstinfo->num_components == 1)) {
  179739. /* We have to preserve the source's quantization table number. */
  179740. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179741. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179742. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179743. } else {
  179744. /* Sorry, can't do it */
  179745. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179746. }
  179747. }
  179748. /* Correct the destination's image dimensions etc if necessary */
  179749. switch (info->transform) {
  179750. case JXFORM_NONE:
  179751. /* Nothing to do */
  179752. break;
  179753. case JXFORM_FLIP_H:
  179754. if (info->trim)
  179755. trim_right_edge(dstinfo);
  179756. break;
  179757. case JXFORM_FLIP_V:
  179758. if (info->trim)
  179759. trim_bottom_edge(dstinfo);
  179760. break;
  179761. case JXFORM_TRANSPOSE:
  179762. transpose_critical_parameters(dstinfo);
  179763. /* transpose does NOT have to trim anything */
  179764. break;
  179765. case JXFORM_TRANSVERSE:
  179766. transpose_critical_parameters(dstinfo);
  179767. if (info->trim) {
  179768. trim_right_edge(dstinfo);
  179769. trim_bottom_edge(dstinfo);
  179770. }
  179771. break;
  179772. case JXFORM_ROT_90:
  179773. transpose_critical_parameters(dstinfo);
  179774. if (info->trim)
  179775. trim_right_edge(dstinfo);
  179776. break;
  179777. case JXFORM_ROT_180:
  179778. if (info->trim) {
  179779. trim_right_edge(dstinfo);
  179780. trim_bottom_edge(dstinfo);
  179781. }
  179782. break;
  179783. case JXFORM_ROT_270:
  179784. transpose_critical_parameters(dstinfo);
  179785. if (info->trim)
  179786. trim_bottom_edge(dstinfo);
  179787. break;
  179788. }
  179789. /* Return the appropriate output data set */
  179790. if (info->workspace_coef_arrays != NULL)
  179791. return info->workspace_coef_arrays;
  179792. return src_coef_arrays;
  179793. }
  179794. /* Execute the actual transformation, if any.
  179795. *
  179796. * This must be called *after* jpeg_write_coefficients, because it depends
  179797. * on jpeg_write_coefficients to have computed subsidiary values such as
  179798. * the per-component width and height fields in the destination object.
  179799. *
  179800. * Note that some transformations will modify the source data arrays!
  179801. */
  179802. GLOBAL(void)
  179803. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179804. j_compress_ptr dstinfo,
  179805. jvirt_barray_ptr *src_coef_arrays,
  179806. jpeg_transform_info *info)
  179807. {
  179808. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179809. switch (info->transform) {
  179810. case JXFORM_NONE:
  179811. break;
  179812. case JXFORM_FLIP_H:
  179813. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179814. break;
  179815. case JXFORM_FLIP_V:
  179816. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179817. break;
  179818. case JXFORM_TRANSPOSE:
  179819. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179820. break;
  179821. case JXFORM_TRANSVERSE:
  179822. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179823. break;
  179824. case JXFORM_ROT_90:
  179825. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179826. break;
  179827. case JXFORM_ROT_180:
  179828. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179829. break;
  179830. case JXFORM_ROT_270:
  179831. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179832. break;
  179833. }
  179834. }
  179835. #endif /* TRANSFORMS_SUPPORTED */
  179836. /* Setup decompression object to save desired markers in memory.
  179837. * This must be called before jpeg_read_header() to have the desired effect.
  179838. */
  179839. GLOBAL(void)
  179840. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179841. {
  179842. #ifdef SAVE_MARKERS_SUPPORTED
  179843. int m;
  179844. /* Save comments except under NONE option */
  179845. if (option != JCOPYOPT_NONE) {
  179846. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179847. }
  179848. /* Save all types of APPn markers iff ALL option */
  179849. if (option == JCOPYOPT_ALL) {
  179850. for (m = 0; m < 16; m++)
  179851. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179852. }
  179853. #endif /* SAVE_MARKERS_SUPPORTED */
  179854. }
  179855. /* Copy markers saved in the given source object to the destination object.
  179856. * This should be called just after jpeg_start_compress() or
  179857. * jpeg_write_coefficients().
  179858. * Note that those routines will have written the SOI, and also the
  179859. * JFIF APP0 or Adobe APP14 markers if selected.
  179860. */
  179861. GLOBAL(void)
  179862. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179863. JCOPY_OPTION)
  179864. {
  179865. jpeg_saved_marker_ptr marker;
  179866. /* In the current implementation, we don't actually need to examine the
  179867. * option flag here; we just copy everything that got saved.
  179868. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179869. * if the encoder library already wrote one.
  179870. */
  179871. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179872. if (dstinfo->write_JFIF_header &&
  179873. marker->marker == JPEG_APP0 &&
  179874. marker->data_length >= 5 &&
  179875. GETJOCTET(marker->data[0]) == 0x4A &&
  179876. GETJOCTET(marker->data[1]) == 0x46 &&
  179877. GETJOCTET(marker->data[2]) == 0x49 &&
  179878. GETJOCTET(marker->data[3]) == 0x46 &&
  179879. GETJOCTET(marker->data[4]) == 0)
  179880. continue; /* reject duplicate JFIF */
  179881. if (dstinfo->write_Adobe_marker &&
  179882. marker->marker == JPEG_APP0+14 &&
  179883. marker->data_length >= 5 &&
  179884. GETJOCTET(marker->data[0]) == 0x41 &&
  179885. GETJOCTET(marker->data[1]) == 0x64 &&
  179886. GETJOCTET(marker->data[2]) == 0x6F &&
  179887. GETJOCTET(marker->data[3]) == 0x62 &&
  179888. GETJOCTET(marker->data[4]) == 0x65)
  179889. continue; /* reject duplicate Adobe */
  179890. #ifdef NEED_FAR_POINTERS
  179891. /* We could use jpeg_write_marker if the data weren't FAR... */
  179892. {
  179893. unsigned int i;
  179894. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179895. for (i = 0; i < marker->data_length; i++)
  179896. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179897. }
  179898. #else
  179899. jpeg_write_marker(dstinfo, marker->marker,
  179900. marker->data, marker->data_length);
  179901. #endif
  179902. }
  179903. }
  179904. /*** End of inlined file: transupp.c ***/
  179905. #else
  179906. #define JPEG_INTERNALS
  179907. #undef FAR
  179908. #include <jpeglib.h>
  179909. #endif
  179910. }
  179911. #undef max
  179912. #undef min
  179913. #if JUCE_MSVC
  179914. #pragma warning (pop)
  179915. #endif
  179916. BEGIN_JUCE_NAMESPACE
  179917. namespace JPEGHelpers
  179918. {
  179919. using namespace jpeglibNamespace;
  179920. #if ! JUCE_MSVC
  179921. using jpeglibNamespace::boolean;
  179922. #endif
  179923. struct JPEGDecodingFailure {};
  179924. void fatalErrorHandler (j_common_ptr)
  179925. {
  179926. throw JPEGDecodingFailure();
  179927. }
  179928. void silentErrorCallback1 (j_common_ptr) {}
  179929. void silentErrorCallback2 (j_common_ptr, int) {}
  179930. void silentErrorCallback3 (j_common_ptr, char*) {}
  179931. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179932. {
  179933. zerostruct (err);
  179934. err.error_exit = fatalErrorHandler;
  179935. err.emit_message = silentErrorCallback2;
  179936. err.output_message = silentErrorCallback1;
  179937. err.format_message = silentErrorCallback3;
  179938. err.reset_error_mgr = silentErrorCallback1;
  179939. }
  179940. void dummyCallback1 (j_decompress_ptr)
  179941. {
  179942. }
  179943. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179944. {
  179945. decompStruct->src->next_input_byte += num;
  179946. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179947. decompStruct->src->bytes_in_buffer -= num;
  179948. }
  179949. boolean jpegFill (j_decompress_ptr)
  179950. {
  179951. return 0;
  179952. }
  179953. const int jpegBufferSize = 512;
  179954. struct JuceJpegDest : public jpeg_destination_mgr
  179955. {
  179956. OutputStream* output;
  179957. char* buffer;
  179958. };
  179959. void jpegWriteInit (j_compress_ptr)
  179960. {
  179961. }
  179962. void jpegWriteTerminate (j_compress_ptr cinfo)
  179963. {
  179964. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179965. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179966. dest->output->write (dest->buffer, (int) numToWrite);
  179967. }
  179968. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179969. {
  179970. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179971. const int numToWrite = jpegBufferSize;
  179972. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179973. dest->free_in_buffer = jpegBufferSize;
  179974. return dest->output->write (dest->buffer, numToWrite);
  179975. }
  179976. }
  179977. JPEGImageFormat::JPEGImageFormat()
  179978. : quality (-1.0f)
  179979. {
  179980. }
  179981. JPEGImageFormat::~JPEGImageFormat() {}
  179982. void JPEGImageFormat::setQuality (const float newQuality)
  179983. {
  179984. quality = newQuality;
  179985. }
  179986. const String JPEGImageFormat::getFormatName()
  179987. {
  179988. return "JPEG";
  179989. }
  179990. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179991. {
  179992. const int bytesNeeded = 10;
  179993. uint8 header [bytesNeeded];
  179994. if (in.read (header, bytesNeeded) == bytesNeeded)
  179995. {
  179996. return header[0] == 0xff
  179997. && header[1] == 0xd8
  179998. && header[2] == 0xff
  179999. && (header[3] == 0xe0 || header[3] == 0xe1);
  180000. }
  180001. return false;
  180002. }
  180003. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180004. const Image juce_loadWithCoreImage (InputStream& input);
  180005. #endif
  180006. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180007. {
  180008. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180009. return juce_loadWithCoreImage (in);
  180010. #else
  180011. using namespace jpeglibNamespace;
  180012. using namespace JPEGHelpers;
  180013. MemoryOutputStream mb;
  180014. mb.writeFromInputStream (in, -1);
  180015. Image image;
  180016. if (mb.getDataSize() > 16)
  180017. {
  180018. struct jpeg_decompress_struct jpegDecompStruct;
  180019. struct jpeg_error_mgr jerr;
  180020. setupSilentErrorHandler (jerr);
  180021. jpegDecompStruct.err = &jerr;
  180022. jpeg_create_decompress (&jpegDecompStruct);
  180023. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180024. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180025. jpegDecompStruct.src->init_source = dummyCallback1;
  180026. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180027. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180028. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180029. jpegDecompStruct.src->term_source = dummyCallback1;
  180030. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180031. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180032. try
  180033. {
  180034. jpeg_read_header (&jpegDecompStruct, TRUE);
  180035. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180036. const int width = jpegDecompStruct.output_width;
  180037. const int height = jpegDecompStruct.output_height;
  180038. jpegDecompStruct.out_color_space = JCS_RGB;
  180039. JSAMPARRAY buffer
  180040. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180041. JPOOL_IMAGE,
  180042. width * 3, 1);
  180043. if (jpeg_start_decompress (&jpegDecompStruct))
  180044. {
  180045. image = Image (Image::RGB, width, height, false);
  180046. image.getProperties()->set ("originalImageHadAlpha", false);
  180047. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180048. const Image::BitmapData destData (image, true);
  180049. for (int y = 0; y < height; ++y)
  180050. {
  180051. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180052. const uint8* src = *buffer;
  180053. uint8* dest = destData.getLinePointer (y);
  180054. if (hasAlphaChan)
  180055. {
  180056. for (int i = width; --i >= 0;)
  180057. {
  180058. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180059. ((PixelARGB*) dest)->premultiply();
  180060. dest += destData.pixelStride;
  180061. src += 3;
  180062. }
  180063. }
  180064. else
  180065. {
  180066. for (int i = width; --i >= 0;)
  180067. {
  180068. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180069. dest += destData.pixelStride;
  180070. src += 3;
  180071. }
  180072. }
  180073. }
  180074. jpeg_finish_decompress (&jpegDecompStruct);
  180075. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180076. }
  180077. jpeg_destroy_decompress (&jpegDecompStruct);
  180078. }
  180079. catch (...)
  180080. {}
  180081. }
  180082. return image;
  180083. #endif
  180084. }
  180085. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180086. {
  180087. using namespace jpeglibNamespace;
  180088. using namespace JPEGHelpers;
  180089. if (image.hasAlphaChannel())
  180090. {
  180091. // this method could fill the background in white and still save the image..
  180092. jassertfalse;
  180093. return true;
  180094. }
  180095. struct jpeg_compress_struct jpegCompStruct;
  180096. struct jpeg_error_mgr jerr;
  180097. setupSilentErrorHandler (jerr);
  180098. jpegCompStruct.err = &jerr;
  180099. jpeg_create_compress (&jpegCompStruct);
  180100. JuceJpegDest dest;
  180101. jpegCompStruct.dest = &dest;
  180102. dest.output = &out;
  180103. HeapBlock <char> tempBuffer (jpegBufferSize);
  180104. dest.buffer = tempBuffer;
  180105. dest.next_output_byte = (JOCTET*) dest.buffer;
  180106. dest.free_in_buffer = jpegBufferSize;
  180107. dest.init_destination = jpegWriteInit;
  180108. dest.empty_output_buffer = jpegWriteFlush;
  180109. dest.term_destination = jpegWriteTerminate;
  180110. jpegCompStruct.image_width = image.getWidth();
  180111. jpegCompStruct.image_height = image.getHeight();
  180112. jpegCompStruct.input_components = 3;
  180113. jpegCompStruct.in_color_space = JCS_RGB;
  180114. jpegCompStruct.write_JFIF_header = 1;
  180115. jpegCompStruct.X_density = 72;
  180116. jpegCompStruct.Y_density = 72;
  180117. jpeg_set_defaults (&jpegCompStruct);
  180118. jpegCompStruct.dct_method = JDCT_FLOAT;
  180119. jpegCompStruct.optimize_coding = 1;
  180120. //jpegCompStruct.smoothing_factor = 10;
  180121. if (quality < 0.0f)
  180122. quality = 0.85f;
  180123. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180124. jpeg_start_compress (&jpegCompStruct, TRUE);
  180125. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180126. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180127. JPOOL_IMAGE, strideBytes, 1);
  180128. const Image::BitmapData srcData (image, false);
  180129. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180130. {
  180131. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180132. uint8* dst = *buffer;
  180133. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180134. {
  180135. *dst++ = ((const PixelRGB*) src)->getRed();
  180136. *dst++ = ((const PixelRGB*) src)->getGreen();
  180137. *dst++ = ((const PixelRGB*) src)->getBlue();
  180138. src += srcData.pixelStride;
  180139. }
  180140. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180141. }
  180142. jpeg_finish_compress (&jpegCompStruct);
  180143. jpeg_destroy_compress (&jpegCompStruct);
  180144. out.flush();
  180145. return true;
  180146. }
  180147. END_JUCE_NAMESPACE
  180148. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180149. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180150. #if JUCE_MSVC
  180151. #pragma warning (push)
  180152. #pragma warning (disable: 4390 4611)
  180153. #endif
  180154. namespace zlibNamespace
  180155. {
  180156. #if JUCE_INCLUDE_ZLIB_CODE
  180157. #undef OS_CODE
  180158. #undef fdopen
  180159. #undef OS_CODE
  180160. #else
  180161. #include <zlib.h>
  180162. #endif
  180163. }
  180164. namespace pnglibNamespace
  180165. {
  180166. using namespace zlibNamespace;
  180167. #if JUCE_INCLUDE_PNGLIB_CODE
  180168. #if _MSC_VER != 1310
  180169. using ::calloc; // (causes conflict in VS.NET 2003)
  180170. using ::malloc;
  180171. using ::free;
  180172. #endif
  180173. using ::abs;
  180174. #define PNG_INTERNAL
  180175. #define NO_DUMMY_DECL
  180176. #define PNG_SETJMP_NOT_SUPPORTED
  180177. /*** Start of inlined file: png.h ***/
  180178. /* png.h - header file for PNG reference library
  180179. *
  180180. * libpng version 1.2.21 - October 4, 2007
  180181. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180182. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180183. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180184. *
  180185. * Authors and maintainers:
  180186. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180187. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180188. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180189. * See also "Contributing Authors", below.
  180190. *
  180191. * Note about libpng version numbers:
  180192. *
  180193. * Due to various miscommunications, unforeseen code incompatibilities
  180194. * and occasional factors outside the authors' control, version numbering
  180195. * on the library has not always been consistent and straightforward.
  180196. * The following table summarizes matters since version 0.89c, which was
  180197. * the first widely used release:
  180198. *
  180199. * source png.h png.h shared-lib
  180200. * version string int version
  180201. * ------- ------ ----- ----------
  180202. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180203. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180204. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180205. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180206. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180207. * 0.97c 0.97 97 2.0.97
  180208. * 0.98 0.98 98 2.0.98
  180209. * 0.99 0.99 98 2.0.99
  180210. * 0.99a-m 0.99 99 2.0.99
  180211. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180212. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180213. * 1.0.1 png.h string is 10001 2.1.0
  180214. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180215. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180216. * 1.0.2a-b 10003 version, except as noted.
  180217. * 1.0.3 10003
  180218. * 1.0.3a-d 10004
  180219. * 1.0.4 10004
  180220. * 1.0.4a-f 10005
  180221. * 1.0.5 (+ 2 patches) 10005
  180222. * 1.0.5a-d 10006
  180223. * 1.0.5e-r 10100 (not source compatible)
  180224. * 1.0.5s-v 10006 (not binary compatible)
  180225. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180226. * 1.0.6d-f 10007 (still binary incompatible)
  180227. * 1.0.6g 10007
  180228. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180229. * 1.0.6i 10007 10.6i
  180230. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180231. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180232. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180233. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180234. * 1.0.7 1 10007 (still compatible)
  180235. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180236. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180237. * 1.0.8 1 10008 2.1.0.8
  180238. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180239. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180240. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180241. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180242. * 1.0.9 1 10009 2.1.0.9
  180243. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180244. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180245. * 1.0.10 1 10010 2.1.0.10
  180246. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180247. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180248. * 1.0.11 1 10011 2.1.0.11
  180249. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180250. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180251. * 1.0.12 2 10012 2.1.0.12
  180252. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180253. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180254. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180255. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180256. * 1.2.0 3 10200 3.1.2.0
  180257. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180258. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180259. * 1.2.1 3 10201 3.1.2.1
  180260. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180261. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180262. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180263. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180264. * 1.0.13 10 10013 10.so.0.1.0.13
  180265. * 1.2.2 12 10202 12.so.0.1.2.2
  180266. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180267. * 1.2.3 12 10203 12.so.0.1.2.3
  180268. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180269. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180270. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180271. * 1.0.14 10 10014 10.so.0.1.0.14
  180272. * 1.2.4 13 10204 12.so.0.1.2.4
  180273. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180274. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180275. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180276. * 1.0.15 10 10015 10.so.0.1.0.15
  180277. * 1.2.5 13 10205 12.so.0.1.2.5
  180278. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180279. * 1.0.16 10 10016 10.so.0.1.0.16
  180280. * 1.2.6 13 10206 12.so.0.1.2.6
  180281. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180282. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180283. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180284. * 1.0.17 10 10017 10.so.0.1.0.17
  180285. * 1.2.7 13 10207 12.so.0.1.2.7
  180286. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180287. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180288. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180289. * 1.0.18 10 10018 10.so.0.1.0.18
  180290. * 1.2.8 13 10208 12.so.0.1.2.8
  180291. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180292. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180293. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180294. * 1.2.9 13 10209 12.so.0.9[.0]
  180295. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180296. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180297. * 1.2.10 13 10210 12.so.0.10[.0]
  180298. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180299. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180300. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180301. * 1.0.19 10 10019 10.so.0.19[.0]
  180302. * 1.2.11 13 10211 12.so.0.11[.0]
  180303. * 1.0.20 10 10020 10.so.0.20[.0]
  180304. * 1.2.12 13 10212 12.so.0.12[.0]
  180305. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180306. * 1.0.21 10 10021 10.so.0.21[.0]
  180307. * 1.2.13 13 10213 12.so.0.13[.0]
  180308. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180309. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180310. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180311. * 1.0.22 10 10022 10.so.0.22[.0]
  180312. * 1.2.14 13 10214 12.so.0.14[.0]
  180313. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180314. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180315. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180316. * 1.0.23 10 10023 10.so.0.23[.0]
  180317. * 1.2.15 13 10215 12.so.0.15[.0]
  180318. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180319. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180320. * 1.0.24 10 10024 10.so.0.24[.0]
  180321. * 1.2.16 13 10216 12.so.0.16[.0]
  180322. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180323. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180324. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180325. * 1.0.25 10 10025 10.so.0.25[.0]
  180326. * 1.2.17 13 10217 12.so.0.17[.0]
  180327. * 1.0.26 10 10026 10.so.0.26[.0]
  180328. * 1.2.18 13 10218 12.so.0.18[.0]
  180329. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180330. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180331. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180332. * 1.0.27 10 10027 10.so.0.27[.0]
  180333. * 1.2.19 13 10219 12.so.0.19[.0]
  180334. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180335. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180336. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180337. * 1.0.28 10 10028 10.so.0.28[.0]
  180338. * 1.2.20 13 10220 12.so.0.20[.0]
  180339. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180340. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180341. * 1.0.29 10 10029 10.so.0.29[.0]
  180342. * 1.2.21 13 10221 12.so.0.21[.0]
  180343. *
  180344. * Henceforth the source version will match the shared-library major
  180345. * and minor numbers; the shared-library major version number will be
  180346. * used for changes in backward compatibility, as it is intended. The
  180347. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180348. * for applications, is an unsigned integer of the form xyyzz corresponding
  180349. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180350. * were given the previous public release number plus a letter, until
  180351. * version 1.0.6j; from then on they were given the upcoming public
  180352. * release number plus "betaNN" or "rcN".
  180353. *
  180354. * Binary incompatibility exists only when applications make direct access
  180355. * to the info_ptr or png_ptr members through png.h, and the compiled
  180356. * application is loaded with a different version of the library.
  180357. *
  180358. * DLLNUM will change each time there are forward or backward changes
  180359. * in binary compatibility (e.g., when a new feature is added).
  180360. *
  180361. * See libpng.txt or libpng.3 for more information. The PNG specification
  180362. * is available as a W3C Recommendation and as an ISO Specification,
  180363. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180364. */
  180365. /*
  180366. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180367. *
  180368. * If you modify libpng you may insert additional notices immediately following
  180369. * this sentence.
  180370. *
  180371. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180372. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180373. * distributed according to the same disclaimer and license as libpng-1.2.5
  180374. * with the following individual added to the list of Contributing Authors:
  180375. *
  180376. * Cosmin Truta
  180377. *
  180378. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180379. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180380. * distributed according to the same disclaimer and license as libpng-1.0.6
  180381. * with the following individuals added to the list of Contributing Authors:
  180382. *
  180383. * Simon-Pierre Cadieux
  180384. * Eric S. Raymond
  180385. * Gilles Vollant
  180386. *
  180387. * and with the following additions to the disclaimer:
  180388. *
  180389. * There is no warranty against interference with your enjoyment of the
  180390. * library or against infringement. There is no warranty that our
  180391. * efforts or the library will fulfill any of your particular purposes
  180392. * or needs. This library is provided with all faults, and the entire
  180393. * risk of satisfactory quality, performance, accuracy, and effort is with
  180394. * the user.
  180395. *
  180396. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180397. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180398. * distributed according to the same disclaimer and license as libpng-0.96,
  180399. * with the following individuals added to the list of Contributing Authors:
  180400. *
  180401. * Tom Lane
  180402. * Glenn Randers-Pehrson
  180403. * Willem van Schaik
  180404. *
  180405. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180406. * Copyright (c) 1996, 1997 Andreas Dilger
  180407. * Distributed according to the same disclaimer and license as libpng-0.88,
  180408. * with the following individuals added to the list of Contributing Authors:
  180409. *
  180410. * John Bowler
  180411. * Kevin Bracey
  180412. * Sam Bushell
  180413. * Magnus Holmgren
  180414. * Greg Roelofs
  180415. * Tom Tanner
  180416. *
  180417. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180418. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180419. *
  180420. * For the purposes of this copyright and license, "Contributing Authors"
  180421. * is defined as the following set of individuals:
  180422. *
  180423. * Andreas Dilger
  180424. * Dave Martindale
  180425. * Guy Eric Schalnat
  180426. * Paul Schmidt
  180427. * Tim Wegner
  180428. *
  180429. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180430. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180431. * including, without limitation, the warranties of merchantability and of
  180432. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180433. * assume no liability for direct, indirect, incidental, special, exemplary,
  180434. * or consequential damages, which may result from the use of the PNG
  180435. * Reference Library, even if advised of the possibility of such damage.
  180436. *
  180437. * Permission is hereby granted to use, copy, modify, and distribute this
  180438. * source code, or portions hereof, for any purpose, without fee, subject
  180439. * to the following restrictions:
  180440. *
  180441. * 1. The origin of this source code must not be misrepresented.
  180442. *
  180443. * 2. Altered versions must be plainly marked as such and
  180444. * must not be misrepresented as being the original source.
  180445. *
  180446. * 3. This Copyright notice may not be removed or altered from
  180447. * any source or altered source distribution.
  180448. *
  180449. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180450. * fee, and encourage the use of this source code as a component to
  180451. * supporting the PNG file format in commercial products. If you use this
  180452. * source code in a product, acknowledgment is not required but would be
  180453. * appreciated.
  180454. */
  180455. /*
  180456. * A "png_get_copyright" function is available, for convenient use in "about"
  180457. * boxes and the like:
  180458. *
  180459. * printf("%s",png_get_copyright(NULL));
  180460. *
  180461. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180462. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180463. */
  180464. /*
  180465. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180466. * certification mark of the Open Source Initiative.
  180467. */
  180468. /*
  180469. * The contributing authors would like to thank all those who helped
  180470. * with testing, bug fixes, and patience. This wouldn't have been
  180471. * possible without all of you.
  180472. *
  180473. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180474. */
  180475. /*
  180476. * Y2K compliance in libpng:
  180477. * =========================
  180478. *
  180479. * October 4, 2007
  180480. *
  180481. * Since the PNG Development group is an ad-hoc body, we can't make
  180482. * an official declaration.
  180483. *
  180484. * This is your unofficial assurance that libpng from version 0.71 and
  180485. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180486. * versions were also Y2K compliant.
  180487. *
  180488. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180489. * that will hold years up to 65535. The other two hold the date in text
  180490. * format, and will hold years up to 9999.
  180491. *
  180492. * The integer is
  180493. * "png_uint_16 year" in png_time_struct.
  180494. *
  180495. * The strings are
  180496. * "png_charp time_buffer" in png_struct and
  180497. * "near_time_buffer", which is a local character string in png.c.
  180498. *
  180499. * There are seven time-related functions:
  180500. * png.c: png_convert_to_rfc_1123() in png.c
  180501. * (formerly png_convert_to_rfc_1152() in error)
  180502. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180503. * png_convert_from_time_t() in pngwrite.c
  180504. * png_get_tIME() in pngget.c
  180505. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180506. * png_set_tIME() in pngset.c
  180507. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180508. *
  180509. * All handle dates properly in a Y2K environment. The
  180510. * png_convert_from_time_t() function calls gmtime() to convert from system
  180511. * clock time, which returns (year - 1900), which we properly convert to
  180512. * the full 4-digit year. There is a possibility that applications using
  180513. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180514. * function, or that they are incorrectly passing only a 2-digit year
  180515. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180516. * but this is not under our control. The libpng documentation has always
  180517. * stated that it works with 4-digit years, and the APIs have been
  180518. * documented as such.
  180519. *
  180520. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180521. * integer to hold the year, and can hold years as large as 65535.
  180522. *
  180523. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180524. * no date-related code.
  180525. *
  180526. * Glenn Randers-Pehrson
  180527. * libpng maintainer
  180528. * PNG Development Group
  180529. */
  180530. #ifndef PNG_H
  180531. #define PNG_H
  180532. /* This is not the place to learn how to use libpng. The file libpng.txt
  180533. * describes how to use libpng, and the file example.c summarizes it
  180534. * with some code on which to build. This file is useful for looking
  180535. * at the actual function definitions and structure components.
  180536. */
  180537. /* Version information for png.h - this should match the version in png.c */
  180538. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180539. #define PNG_HEADER_VERSION_STRING \
  180540. " libpng version 1.2.21 - October 4, 2007\n"
  180541. #define PNG_LIBPNG_VER_SONUM 0
  180542. #define PNG_LIBPNG_VER_DLLNUM 13
  180543. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180544. #define PNG_LIBPNG_VER_MAJOR 1
  180545. #define PNG_LIBPNG_VER_MINOR 2
  180546. #define PNG_LIBPNG_VER_RELEASE 21
  180547. /* This should match the numeric part of the final component of
  180548. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180549. #define PNG_LIBPNG_VER_BUILD 0
  180550. /* Release Status */
  180551. #define PNG_LIBPNG_BUILD_ALPHA 1
  180552. #define PNG_LIBPNG_BUILD_BETA 2
  180553. #define PNG_LIBPNG_BUILD_RC 3
  180554. #define PNG_LIBPNG_BUILD_STABLE 4
  180555. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180556. /* Release-Specific Flags */
  180557. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180558. PNG_LIBPNG_BUILD_STABLE only */
  180559. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180560. PNG_LIBPNG_BUILD_SPECIAL */
  180561. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180562. PNG_LIBPNG_BUILD_PRIVATE */
  180563. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180564. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180565. * We must not include leading zeros.
  180566. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180567. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180568. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180569. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180570. #ifndef PNG_VERSION_INFO_ONLY
  180571. /* include the compression library's header */
  180572. #endif
  180573. /* include all user configurable info, including optional assembler routines */
  180574. /*** Start of inlined file: pngconf.h ***/
  180575. /* pngconf.h - machine configurable file for libpng
  180576. *
  180577. * libpng version 1.2.21 - October 4, 2007
  180578. * For conditions of distribution and use, see copyright notice in png.h
  180579. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180580. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180581. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180582. */
  180583. /* Any machine specific code is near the front of this file, so if you
  180584. * are configuring libpng for a machine, you may want to read the section
  180585. * starting here down to where it starts to typedef png_color, png_text,
  180586. * and png_info.
  180587. */
  180588. #ifndef PNGCONF_H
  180589. #define PNGCONF_H
  180590. #define PNG_1_2_X
  180591. // These are some Juce config settings that should remove any unnecessary code bloat..
  180592. #define PNG_NO_STDIO 1
  180593. #define PNG_DEBUG 0
  180594. #define PNG_NO_WARNINGS 1
  180595. #define PNG_NO_ERROR_TEXT 1
  180596. #define PNG_NO_ERROR_NUMBERS 1
  180597. #define PNG_NO_USER_MEM 1
  180598. #define PNG_NO_READ_iCCP 1
  180599. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180600. #define PNG_NO_READ_USER_CHUNKS 1
  180601. #define PNG_NO_READ_iTXt 1
  180602. #define PNG_NO_READ_sCAL 1
  180603. #define PNG_NO_READ_sPLT 1
  180604. #define png_error(a, b) png_err(a)
  180605. #define png_warning(a, b)
  180606. #define png_chunk_error(a, b) png_err(a)
  180607. #define png_chunk_warning(a, b)
  180608. /*
  180609. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180610. * includes the resource compiler for Windows DLL configurations.
  180611. */
  180612. #ifdef PNG_USER_CONFIG
  180613. # ifndef PNG_USER_PRIVATEBUILD
  180614. # define PNG_USER_PRIVATEBUILD
  180615. # endif
  180616. #include "pngusr.h"
  180617. #endif
  180618. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180619. #ifdef PNG_CONFIGURE_LIBPNG
  180620. #ifdef HAVE_CONFIG_H
  180621. #include "config.h"
  180622. #endif
  180623. #endif
  180624. /*
  180625. * Added at libpng-1.2.8
  180626. *
  180627. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180628. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180629. * the DLL was built>
  180630. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180631. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180632. * distinguish your DLL from those of the official release. These
  180633. * correspond to the trailing letters that come after the version
  180634. * number and must match your private DLL name>
  180635. * e.g. // private DLL "libpng13gx.dll"
  180636. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180637. *
  180638. * The following macros are also at your disposal if you want to complete the
  180639. * DLL VERSIONINFO structure.
  180640. * - PNG_USER_VERSIONINFO_COMMENTS
  180641. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180642. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180643. */
  180644. #ifdef __STDC__
  180645. #ifdef SPECIALBUILD
  180646. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180647. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180648. #endif
  180649. #ifdef PRIVATEBUILD
  180650. # pragma message("PRIVATEBUILD is deprecated.\
  180651. Use PNG_USER_PRIVATEBUILD instead.")
  180652. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180653. #endif
  180654. #endif /* __STDC__ */
  180655. #ifndef PNG_VERSION_INFO_ONLY
  180656. /* End of material added to libpng-1.2.8 */
  180657. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180658. Restored at libpng-1.2.21 */
  180659. # define PNG_WARN_UNINITIALIZED_ROW 1
  180660. /* End of material added at libpng-1.2.19/1.2.21 */
  180661. /* This is the size of the compression buffer, and thus the size of
  180662. * an IDAT chunk. Make this whatever size you feel is best for your
  180663. * machine. One of these will be allocated per png_struct. When this
  180664. * is full, it writes the data to the disk, and does some other
  180665. * calculations. Making this an extremely small size will slow
  180666. * the library down, but you may want to experiment to determine
  180667. * where it becomes significant, if you are concerned with memory
  180668. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180669. * this describes the size of the buffer available to read the data in.
  180670. * Unless this gets smaller than the size of a row (compressed),
  180671. * it should not make much difference how big this is.
  180672. */
  180673. #ifndef PNG_ZBUF_SIZE
  180674. # define PNG_ZBUF_SIZE 8192
  180675. #endif
  180676. /* Enable if you want a write-only libpng */
  180677. #ifndef PNG_NO_READ_SUPPORTED
  180678. # define PNG_READ_SUPPORTED
  180679. #endif
  180680. /* Enable if you want a read-only libpng */
  180681. #ifndef PNG_NO_WRITE_SUPPORTED
  180682. # define PNG_WRITE_SUPPORTED
  180683. #endif
  180684. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180685. support PNGs that are embedded in MNG datastreams */
  180686. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180687. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180688. # define PNG_MNG_FEATURES_SUPPORTED
  180689. # endif
  180690. #endif
  180691. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180692. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180693. # define PNG_FLOATING_POINT_SUPPORTED
  180694. # endif
  180695. #endif
  180696. /* If you are running on a machine where you cannot allocate more
  180697. * than 64K of memory at once, uncomment this. While libpng will not
  180698. * normally need that much memory in a chunk (unless you load up a very
  180699. * large file), zlib needs to know how big of a chunk it can use, and
  180700. * libpng thus makes sure to check any memory allocation to verify it
  180701. * will fit into memory.
  180702. #define PNG_MAX_MALLOC_64K
  180703. */
  180704. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180705. # define PNG_MAX_MALLOC_64K
  180706. #endif
  180707. /* Special munging to support doing things the 'cygwin' way:
  180708. * 'Normal' png-on-win32 defines/defaults:
  180709. * PNG_BUILD_DLL -- building dll
  180710. * PNG_USE_DLL -- building an application, linking to dll
  180711. * (no define) -- building static library, or building an
  180712. * application and linking to the static lib
  180713. * 'Cygwin' defines/defaults:
  180714. * PNG_BUILD_DLL -- (ignored) building the dll
  180715. * (no define) -- (ignored) building an application, linking to the dll
  180716. * PNG_STATIC -- (ignored) building the static lib, or building an
  180717. * application that links to the static lib.
  180718. * ALL_STATIC -- (ignored) building various static libs, or building an
  180719. * application that links to the static libs.
  180720. * Thus,
  180721. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180722. * this bit of #ifdefs will define the 'correct' config variables based on
  180723. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180724. * unnecessary.
  180725. *
  180726. * Also, the precedence order is:
  180727. * ALL_STATIC (since we can't #undef something outside our namespace)
  180728. * PNG_BUILD_DLL
  180729. * PNG_STATIC
  180730. * (nothing) == PNG_USE_DLL
  180731. *
  180732. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180733. * of auto-import in binutils, we no longer need to worry about
  180734. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180735. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180736. * to __declspec() stuff. However, we DO need to worry about
  180737. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180738. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180739. */
  180740. #if defined(__CYGWIN__)
  180741. # if defined(ALL_STATIC)
  180742. # if defined(PNG_BUILD_DLL)
  180743. # undef PNG_BUILD_DLL
  180744. # endif
  180745. # if defined(PNG_USE_DLL)
  180746. # undef PNG_USE_DLL
  180747. # endif
  180748. # if defined(PNG_DLL)
  180749. # undef PNG_DLL
  180750. # endif
  180751. # if !defined(PNG_STATIC)
  180752. # define PNG_STATIC
  180753. # endif
  180754. # else
  180755. # if defined (PNG_BUILD_DLL)
  180756. # if defined(PNG_STATIC)
  180757. # undef PNG_STATIC
  180758. # endif
  180759. # if defined(PNG_USE_DLL)
  180760. # undef PNG_USE_DLL
  180761. # endif
  180762. # if !defined(PNG_DLL)
  180763. # define PNG_DLL
  180764. # endif
  180765. # else
  180766. # if defined(PNG_STATIC)
  180767. # if defined(PNG_USE_DLL)
  180768. # undef PNG_USE_DLL
  180769. # endif
  180770. # if defined(PNG_DLL)
  180771. # undef PNG_DLL
  180772. # endif
  180773. # else
  180774. # if !defined(PNG_USE_DLL)
  180775. # define PNG_USE_DLL
  180776. # endif
  180777. # if !defined(PNG_DLL)
  180778. # define PNG_DLL
  180779. # endif
  180780. # endif
  180781. # endif
  180782. # endif
  180783. #endif
  180784. /* This protects us against compilers that run on a windowing system
  180785. * and thus don't have or would rather us not use the stdio types:
  180786. * stdin, stdout, and stderr. The only one currently used is stderr
  180787. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180788. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180789. * will also prevent these, plus will prevent the entire set of stdio
  180790. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180791. * unless (PNG_DEBUG > 0) has been #defined.
  180792. *
  180793. * #define PNG_NO_CONSOLE_IO
  180794. * #define PNG_NO_STDIO
  180795. */
  180796. #if defined(_WIN32_WCE)
  180797. # include <windows.h>
  180798. /* Console I/O functions are not supported on WindowsCE */
  180799. # define PNG_NO_CONSOLE_IO
  180800. # ifdef PNG_DEBUG
  180801. # undef PNG_DEBUG
  180802. # endif
  180803. #endif
  180804. #ifdef PNG_BUILD_DLL
  180805. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180806. # ifndef PNG_NO_CONSOLE_IO
  180807. # define PNG_NO_CONSOLE_IO
  180808. # endif
  180809. # endif
  180810. #endif
  180811. # ifdef PNG_NO_STDIO
  180812. # ifndef PNG_NO_CONSOLE_IO
  180813. # define PNG_NO_CONSOLE_IO
  180814. # endif
  180815. # ifdef PNG_DEBUG
  180816. # if (PNG_DEBUG > 0)
  180817. # include <stdio.h>
  180818. # endif
  180819. # endif
  180820. # else
  180821. # if !defined(_WIN32_WCE)
  180822. /* "stdio.h" functions are not supported on WindowsCE */
  180823. # include <stdio.h>
  180824. # endif
  180825. # endif
  180826. /* This macro protects us against machines that don't have function
  180827. * prototypes (ie K&R style headers). If your compiler does not handle
  180828. * function prototypes, define this macro and use the included ansi2knr.
  180829. * I've always been able to use _NO_PROTO as the indicator, but you may
  180830. * need to drag the empty declaration out in front of here, or change the
  180831. * ifdef to suit your own needs.
  180832. */
  180833. #ifndef PNGARG
  180834. #ifdef OF /* zlib prototype munger */
  180835. # define PNGARG(arglist) OF(arglist)
  180836. #else
  180837. #ifdef _NO_PROTO
  180838. # define PNGARG(arglist) ()
  180839. # ifndef PNG_TYPECAST_NULL
  180840. # define PNG_TYPECAST_NULL
  180841. # endif
  180842. #else
  180843. # define PNGARG(arglist) arglist
  180844. #endif /* _NO_PROTO */
  180845. #endif /* OF */
  180846. #endif /* PNGARG */
  180847. /* Try to determine if we are compiling on a Mac. Note that testing for
  180848. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180849. * on non-Mac platforms.
  180850. */
  180851. #ifndef MACOS
  180852. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180853. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180854. # define MACOS
  180855. # endif
  180856. #endif
  180857. /* enough people need this for various reasons to include it here */
  180858. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180859. # include <sys/types.h>
  180860. #endif
  180861. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180862. # define PNG_SETJMP_SUPPORTED
  180863. #endif
  180864. #ifdef PNG_SETJMP_SUPPORTED
  180865. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180866. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180867. */
  180868. # ifdef __linux__
  180869. # ifdef _BSD_SOURCE
  180870. # define PNG_SAVE_BSD_SOURCE
  180871. # undef _BSD_SOURCE
  180872. # endif
  180873. # ifdef _SETJMP_H
  180874. /* If you encounter a compiler error here, see the explanation
  180875. * near the end of INSTALL.
  180876. */
  180877. __png.h__ already includes setjmp.h;
  180878. __dont__ include it again.;
  180879. # endif
  180880. # endif /* __linux__ */
  180881. /* include setjmp.h for error handling */
  180882. # include <setjmp.h>
  180883. # ifdef __linux__
  180884. # ifdef PNG_SAVE_BSD_SOURCE
  180885. # define _BSD_SOURCE
  180886. # undef PNG_SAVE_BSD_SOURCE
  180887. # endif
  180888. # endif /* __linux__ */
  180889. #endif /* PNG_SETJMP_SUPPORTED */
  180890. #ifdef BSD
  180891. #if ! JUCE_MAC
  180892. # include <strings.h>
  180893. #endif
  180894. #else
  180895. # include <string.h>
  180896. #endif
  180897. /* Other defines for things like memory and the like can go here. */
  180898. #ifdef PNG_INTERNAL
  180899. #include <stdlib.h>
  180900. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180901. * aren't usually used outside the library (as far as I know), so it is
  180902. * debatable if they should be exported at all. In the future, when it is
  180903. * possible to have run-time registry of chunk-handling functions, some of
  180904. * these will be made available again.
  180905. #define PNG_EXTERN extern
  180906. */
  180907. #define PNG_EXTERN
  180908. /* Other defines specific to compilers can go here. Try to keep
  180909. * them inside an appropriate ifdef/endif pair for portability.
  180910. */
  180911. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180912. # if defined(MACOS)
  180913. /* We need to check that <math.h> hasn't already been included earlier
  180914. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180915. * <fp.h> if possible.
  180916. */
  180917. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180918. # include <fp.h>
  180919. # endif
  180920. # else
  180921. # include <math.h>
  180922. # endif
  180923. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180924. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180925. * MATH=68881
  180926. */
  180927. # include <m68881.h>
  180928. # endif
  180929. #endif
  180930. /* Codewarrior on NT has linking problems without this. */
  180931. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180932. # define PNG_ALWAYS_EXTERN
  180933. #endif
  180934. /* This provides the non-ANSI (far) memory allocation routines. */
  180935. #if defined(__TURBOC__) && defined(__MSDOS__)
  180936. # include <mem.h>
  180937. # include <alloc.h>
  180938. #endif
  180939. /* I have no idea why is this necessary... */
  180940. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180941. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180942. # include <malloc.h>
  180943. #endif
  180944. /* This controls how fine the dithering gets. As this allocates
  180945. * a largish chunk of memory (32K), those who are not as concerned
  180946. * with dithering quality can decrease some or all of these.
  180947. */
  180948. #ifndef PNG_DITHER_RED_BITS
  180949. # define PNG_DITHER_RED_BITS 5
  180950. #endif
  180951. #ifndef PNG_DITHER_GREEN_BITS
  180952. # define PNG_DITHER_GREEN_BITS 5
  180953. #endif
  180954. #ifndef PNG_DITHER_BLUE_BITS
  180955. # define PNG_DITHER_BLUE_BITS 5
  180956. #endif
  180957. /* This controls how fine the gamma correction becomes when you
  180958. * are only interested in 8 bits anyway. Increasing this value
  180959. * results in more memory being used, and more pow() functions
  180960. * being called to fill in the gamma tables. Don't set this value
  180961. * less then 8, and even that may not work (I haven't tested it).
  180962. */
  180963. #ifndef PNG_MAX_GAMMA_8
  180964. # define PNG_MAX_GAMMA_8 11
  180965. #endif
  180966. /* This controls how much a difference in gamma we can tolerate before
  180967. * we actually start doing gamma conversion.
  180968. */
  180969. #ifndef PNG_GAMMA_THRESHOLD
  180970. # define PNG_GAMMA_THRESHOLD 0.05
  180971. #endif
  180972. #endif /* PNG_INTERNAL */
  180973. /* The following uses const char * instead of char * for error
  180974. * and warning message functions, so some compilers won't complain.
  180975. * If you do not want to use const, define PNG_NO_CONST here.
  180976. */
  180977. #ifndef PNG_NO_CONST
  180978. # define PNG_CONST const
  180979. #else
  180980. # define PNG_CONST
  180981. #endif
  180982. /* The following defines give you the ability to remove code from the
  180983. * library that you will not be using. I wish I could figure out how to
  180984. * automate this, but I can't do that without making it seriously hard
  180985. * on the users. So if you are not using an ability, change the #define
  180986. * to and #undef, and that part of the library will not be compiled. If
  180987. * your linker can't find a function, you may want to make sure the
  180988. * ability is defined here. Some of these depend upon some others being
  180989. * defined. I haven't figured out all the interactions here, so you may
  180990. * have to experiment awhile to get everything to compile. If you are
  180991. * creating or using a shared library, you probably shouldn't touch this,
  180992. * as it will affect the size of the structures, and this will cause bad
  180993. * things to happen if the library and/or application ever change.
  180994. */
  180995. /* Any features you will not be using can be undef'ed here */
  180996. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180997. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180998. * on the compile line, then pick and choose which ones to define without
  180999. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181000. * if you only want to have a png-compliant reader/writer but don't need
  181001. * any of the extra transformations. This saves about 80 kbytes in a
  181002. * typical installation of the library. (PNG_NO_* form added in version
  181003. * 1.0.1c, for consistency)
  181004. */
  181005. /* The size of the png_text structure changed in libpng-1.0.6 when
  181006. * iTXt support was added. iTXt support was turned off by default through
  181007. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181008. * instead of calling png_set_text() and letting libpng malloc it. It
  181009. * was turned on by default in libpng-1.3.0.
  181010. */
  181011. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181012. # ifndef PNG_NO_iTXt_SUPPORTED
  181013. # define PNG_NO_iTXt_SUPPORTED
  181014. # endif
  181015. # ifndef PNG_NO_READ_iTXt
  181016. # define PNG_NO_READ_iTXt
  181017. # endif
  181018. # ifndef PNG_NO_WRITE_iTXt
  181019. # define PNG_NO_WRITE_iTXt
  181020. # endif
  181021. #endif
  181022. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181023. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181024. # define PNG_READ_iTXt
  181025. # endif
  181026. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181027. # define PNG_WRITE_iTXt
  181028. # endif
  181029. #endif
  181030. /* The following support, added after version 1.0.0, can be turned off here en
  181031. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181032. * with old applications that require the length of png_struct and png_info
  181033. * to remain unchanged.
  181034. */
  181035. #ifdef PNG_LEGACY_SUPPORTED
  181036. # define PNG_NO_FREE_ME
  181037. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181038. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181039. # define PNG_NO_READ_USER_CHUNKS
  181040. # define PNG_NO_READ_iCCP
  181041. # define PNG_NO_WRITE_iCCP
  181042. # define PNG_NO_READ_iTXt
  181043. # define PNG_NO_WRITE_iTXt
  181044. # define PNG_NO_READ_sCAL
  181045. # define PNG_NO_WRITE_sCAL
  181046. # define PNG_NO_READ_sPLT
  181047. # define PNG_NO_WRITE_sPLT
  181048. # define PNG_NO_INFO_IMAGE
  181049. # define PNG_NO_READ_RGB_TO_GRAY
  181050. # define PNG_NO_READ_USER_TRANSFORM
  181051. # define PNG_NO_WRITE_USER_TRANSFORM
  181052. # define PNG_NO_USER_MEM
  181053. # define PNG_NO_READ_EMPTY_PLTE
  181054. # define PNG_NO_MNG_FEATURES
  181055. # define PNG_NO_FIXED_POINT_SUPPORTED
  181056. #endif
  181057. /* Ignore attempt to turn off both floating and fixed point support */
  181058. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181059. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181060. # define PNG_FIXED_POINT_SUPPORTED
  181061. #endif
  181062. #ifndef PNG_NO_FREE_ME
  181063. # define PNG_FREE_ME_SUPPORTED
  181064. #endif
  181065. #if defined(PNG_READ_SUPPORTED)
  181066. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181067. !defined(PNG_NO_READ_TRANSFORMS)
  181068. # define PNG_READ_TRANSFORMS_SUPPORTED
  181069. #endif
  181070. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181071. # ifndef PNG_NO_READ_EXPAND
  181072. # define PNG_READ_EXPAND_SUPPORTED
  181073. # endif
  181074. # ifndef PNG_NO_READ_SHIFT
  181075. # define PNG_READ_SHIFT_SUPPORTED
  181076. # endif
  181077. # ifndef PNG_NO_READ_PACK
  181078. # define PNG_READ_PACK_SUPPORTED
  181079. # endif
  181080. # ifndef PNG_NO_READ_BGR
  181081. # define PNG_READ_BGR_SUPPORTED
  181082. # endif
  181083. # ifndef PNG_NO_READ_SWAP
  181084. # define PNG_READ_SWAP_SUPPORTED
  181085. # endif
  181086. # ifndef PNG_NO_READ_PACKSWAP
  181087. # define PNG_READ_PACKSWAP_SUPPORTED
  181088. # endif
  181089. # ifndef PNG_NO_READ_INVERT
  181090. # define PNG_READ_INVERT_SUPPORTED
  181091. # endif
  181092. # ifndef PNG_NO_READ_DITHER
  181093. # define PNG_READ_DITHER_SUPPORTED
  181094. # endif
  181095. # ifndef PNG_NO_READ_BACKGROUND
  181096. # define PNG_READ_BACKGROUND_SUPPORTED
  181097. # endif
  181098. # ifndef PNG_NO_READ_16_TO_8
  181099. # define PNG_READ_16_TO_8_SUPPORTED
  181100. # endif
  181101. # ifndef PNG_NO_READ_FILLER
  181102. # define PNG_READ_FILLER_SUPPORTED
  181103. # endif
  181104. # ifndef PNG_NO_READ_GAMMA
  181105. # define PNG_READ_GAMMA_SUPPORTED
  181106. # endif
  181107. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181108. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181109. # endif
  181110. # ifndef PNG_NO_READ_SWAP_ALPHA
  181111. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181112. # endif
  181113. # ifndef PNG_NO_READ_INVERT_ALPHA
  181114. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181115. # endif
  181116. # ifndef PNG_NO_READ_STRIP_ALPHA
  181117. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181118. # endif
  181119. # ifndef PNG_NO_READ_USER_TRANSFORM
  181120. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181121. # endif
  181122. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181123. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181124. # endif
  181125. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181126. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181127. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181128. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181129. #endif /* about interlacing capability! You'll */
  181130. /* still have interlacing unless you change the following line: */
  181131. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181132. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181133. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181134. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181135. # endif
  181136. #endif
  181137. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181138. /* Deprecated, will be removed from version 2.0.0.
  181139. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181140. #ifndef PNG_NO_READ_EMPTY_PLTE
  181141. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181142. #endif
  181143. #endif
  181144. #endif /* PNG_READ_SUPPORTED */
  181145. #if defined(PNG_WRITE_SUPPORTED)
  181146. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181147. !defined(PNG_NO_WRITE_TRANSFORMS)
  181148. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181149. #endif
  181150. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181151. # ifndef PNG_NO_WRITE_SHIFT
  181152. # define PNG_WRITE_SHIFT_SUPPORTED
  181153. # endif
  181154. # ifndef PNG_NO_WRITE_PACK
  181155. # define PNG_WRITE_PACK_SUPPORTED
  181156. # endif
  181157. # ifndef PNG_NO_WRITE_BGR
  181158. # define PNG_WRITE_BGR_SUPPORTED
  181159. # endif
  181160. # ifndef PNG_NO_WRITE_SWAP
  181161. # define PNG_WRITE_SWAP_SUPPORTED
  181162. # endif
  181163. # ifndef PNG_NO_WRITE_PACKSWAP
  181164. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181165. # endif
  181166. # ifndef PNG_NO_WRITE_INVERT
  181167. # define PNG_WRITE_INVERT_SUPPORTED
  181168. # endif
  181169. # ifndef PNG_NO_WRITE_FILLER
  181170. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181171. # endif
  181172. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181173. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181174. # endif
  181175. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181176. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181177. # endif
  181178. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181179. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181180. # endif
  181181. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181182. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181183. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181184. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181185. encoders, but can cause trouble
  181186. if left undefined */
  181187. #endif
  181188. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181189. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181190. defined(PNG_FLOATING_POINT_SUPPORTED)
  181191. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181192. #endif
  181193. #ifndef PNG_NO_WRITE_FLUSH
  181194. # define PNG_WRITE_FLUSH_SUPPORTED
  181195. #endif
  181196. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181197. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181198. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181199. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181200. #endif
  181201. #endif
  181202. #endif /* PNG_WRITE_SUPPORTED */
  181203. #ifndef PNG_1_0_X
  181204. # ifndef PNG_NO_ERROR_NUMBERS
  181205. # define PNG_ERROR_NUMBERS_SUPPORTED
  181206. # endif
  181207. #endif /* PNG_1_0_X */
  181208. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181209. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181210. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181211. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181212. # endif
  181213. #endif
  181214. #ifndef PNG_NO_STDIO
  181215. # define PNG_TIME_RFC1123_SUPPORTED
  181216. #endif
  181217. /* This adds extra functions in pngget.c for accessing data from the
  181218. * info pointer (added in version 0.99)
  181219. * png_get_image_width()
  181220. * png_get_image_height()
  181221. * png_get_bit_depth()
  181222. * png_get_color_type()
  181223. * png_get_compression_type()
  181224. * png_get_filter_type()
  181225. * png_get_interlace_type()
  181226. * png_get_pixel_aspect_ratio()
  181227. * png_get_pixels_per_meter()
  181228. * png_get_x_offset_pixels()
  181229. * png_get_y_offset_pixels()
  181230. * png_get_x_offset_microns()
  181231. * png_get_y_offset_microns()
  181232. */
  181233. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181234. # define PNG_EASY_ACCESS_SUPPORTED
  181235. #endif
  181236. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181237. * and removed from version 1.2.20. The following will be removed
  181238. * from libpng-1.4.0
  181239. */
  181240. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181241. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181242. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181243. # endif
  181244. #endif
  181245. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181246. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181247. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181248. # endif
  181249. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181250. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181251. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181252. # define PNG_NO_MMX_CODE
  181253. # endif
  181254. # endif
  181255. # if defined(__APPLE__)
  181256. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181257. # define PNG_NO_MMX_CODE
  181258. # endif
  181259. # endif
  181260. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181261. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181262. # define PNG_NO_MMX_CODE
  181263. # endif
  181264. # endif
  181265. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181266. # define PNG_MMX_CODE_SUPPORTED
  181267. # endif
  181268. #endif
  181269. /* end of obsolete code to be removed from libpng-1.4.0 */
  181270. #if !defined(PNG_1_0_X)
  181271. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181272. # define PNG_USER_MEM_SUPPORTED
  181273. #endif
  181274. #endif /* PNG_1_0_X */
  181275. /* Added at libpng-1.2.6 */
  181276. #if !defined(PNG_1_0_X)
  181277. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181278. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181279. # define PNG_SET_USER_LIMITS_SUPPORTED
  181280. #endif
  181281. #endif
  181282. #endif /* PNG_1_0_X */
  181283. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181284. * how large, set these limits to 0x7fffffffL
  181285. */
  181286. #ifndef PNG_USER_WIDTH_MAX
  181287. # define PNG_USER_WIDTH_MAX 1000000L
  181288. #endif
  181289. #ifndef PNG_USER_HEIGHT_MAX
  181290. # define PNG_USER_HEIGHT_MAX 1000000L
  181291. #endif
  181292. /* These are currently experimental features, define them if you want */
  181293. /* very little testing */
  181294. /*
  181295. #ifdef PNG_READ_SUPPORTED
  181296. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181297. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181298. # endif
  181299. #endif
  181300. */
  181301. /* This is only for PowerPC big-endian and 680x0 systems */
  181302. /* some testing */
  181303. /*
  181304. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181305. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181306. #endif
  181307. */
  181308. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181309. /*
  181310. #define PNG_NO_POINTER_INDEXING
  181311. */
  181312. /* These functions are turned off by default, as they will be phased out. */
  181313. /*
  181314. #define PNG_USELESS_TESTS_SUPPORTED
  181315. #define PNG_CORRECT_PALETTE_SUPPORTED
  181316. */
  181317. /* Any chunks you are not interested in, you can undef here. The
  181318. * ones that allocate memory may be expecially important (hIST,
  181319. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181320. * a bit smaller.
  181321. */
  181322. #if defined(PNG_READ_SUPPORTED) && \
  181323. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181324. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181325. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181326. #endif
  181327. #if defined(PNG_WRITE_SUPPORTED) && \
  181328. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181329. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181330. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181331. #endif
  181332. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181333. #ifdef PNG_NO_READ_TEXT
  181334. # define PNG_NO_READ_iTXt
  181335. # define PNG_NO_READ_tEXt
  181336. # define PNG_NO_READ_zTXt
  181337. #endif
  181338. #ifndef PNG_NO_READ_bKGD
  181339. # define PNG_READ_bKGD_SUPPORTED
  181340. # define PNG_bKGD_SUPPORTED
  181341. #endif
  181342. #ifndef PNG_NO_READ_cHRM
  181343. # define PNG_READ_cHRM_SUPPORTED
  181344. # define PNG_cHRM_SUPPORTED
  181345. #endif
  181346. #ifndef PNG_NO_READ_gAMA
  181347. # define PNG_READ_gAMA_SUPPORTED
  181348. # define PNG_gAMA_SUPPORTED
  181349. #endif
  181350. #ifndef PNG_NO_READ_hIST
  181351. # define PNG_READ_hIST_SUPPORTED
  181352. # define PNG_hIST_SUPPORTED
  181353. #endif
  181354. #ifndef PNG_NO_READ_iCCP
  181355. # define PNG_READ_iCCP_SUPPORTED
  181356. # define PNG_iCCP_SUPPORTED
  181357. #endif
  181358. #ifndef PNG_NO_READ_iTXt
  181359. # ifndef PNG_READ_iTXt_SUPPORTED
  181360. # define PNG_READ_iTXt_SUPPORTED
  181361. # endif
  181362. # ifndef PNG_iTXt_SUPPORTED
  181363. # define PNG_iTXt_SUPPORTED
  181364. # endif
  181365. #endif
  181366. #ifndef PNG_NO_READ_oFFs
  181367. # define PNG_READ_oFFs_SUPPORTED
  181368. # define PNG_oFFs_SUPPORTED
  181369. #endif
  181370. #ifndef PNG_NO_READ_pCAL
  181371. # define PNG_READ_pCAL_SUPPORTED
  181372. # define PNG_pCAL_SUPPORTED
  181373. #endif
  181374. #ifndef PNG_NO_READ_sCAL
  181375. # define PNG_READ_sCAL_SUPPORTED
  181376. # define PNG_sCAL_SUPPORTED
  181377. #endif
  181378. #ifndef PNG_NO_READ_pHYs
  181379. # define PNG_READ_pHYs_SUPPORTED
  181380. # define PNG_pHYs_SUPPORTED
  181381. #endif
  181382. #ifndef PNG_NO_READ_sBIT
  181383. # define PNG_READ_sBIT_SUPPORTED
  181384. # define PNG_sBIT_SUPPORTED
  181385. #endif
  181386. #ifndef PNG_NO_READ_sPLT
  181387. # define PNG_READ_sPLT_SUPPORTED
  181388. # define PNG_sPLT_SUPPORTED
  181389. #endif
  181390. #ifndef PNG_NO_READ_sRGB
  181391. # define PNG_READ_sRGB_SUPPORTED
  181392. # define PNG_sRGB_SUPPORTED
  181393. #endif
  181394. #ifndef PNG_NO_READ_tEXt
  181395. # define PNG_READ_tEXt_SUPPORTED
  181396. # define PNG_tEXt_SUPPORTED
  181397. #endif
  181398. #ifndef PNG_NO_READ_tIME
  181399. # define PNG_READ_tIME_SUPPORTED
  181400. # define PNG_tIME_SUPPORTED
  181401. #endif
  181402. #ifndef PNG_NO_READ_tRNS
  181403. # define PNG_READ_tRNS_SUPPORTED
  181404. # define PNG_tRNS_SUPPORTED
  181405. #endif
  181406. #ifndef PNG_NO_READ_zTXt
  181407. # define PNG_READ_zTXt_SUPPORTED
  181408. # define PNG_zTXt_SUPPORTED
  181409. #endif
  181410. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181411. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181412. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181413. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181414. # endif
  181415. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181416. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181417. # endif
  181418. #endif
  181419. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181420. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181421. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181422. # define PNG_USER_CHUNKS_SUPPORTED
  181423. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181424. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181425. # endif
  181426. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181427. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181428. # endif
  181429. #endif
  181430. #ifndef PNG_NO_READ_OPT_PLTE
  181431. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181432. #endif /* optional PLTE chunk in RGB and RGBA images */
  181433. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181434. defined(PNG_READ_zTXt_SUPPORTED)
  181435. # define PNG_READ_TEXT_SUPPORTED
  181436. # define PNG_TEXT_SUPPORTED
  181437. #endif
  181438. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181439. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181440. #ifdef PNG_NO_WRITE_TEXT
  181441. # define PNG_NO_WRITE_iTXt
  181442. # define PNG_NO_WRITE_tEXt
  181443. # define PNG_NO_WRITE_zTXt
  181444. #endif
  181445. #ifndef PNG_NO_WRITE_bKGD
  181446. # define PNG_WRITE_bKGD_SUPPORTED
  181447. # ifndef PNG_bKGD_SUPPORTED
  181448. # define PNG_bKGD_SUPPORTED
  181449. # endif
  181450. #endif
  181451. #ifndef PNG_NO_WRITE_cHRM
  181452. # define PNG_WRITE_cHRM_SUPPORTED
  181453. # ifndef PNG_cHRM_SUPPORTED
  181454. # define PNG_cHRM_SUPPORTED
  181455. # endif
  181456. #endif
  181457. #ifndef PNG_NO_WRITE_gAMA
  181458. # define PNG_WRITE_gAMA_SUPPORTED
  181459. # ifndef PNG_gAMA_SUPPORTED
  181460. # define PNG_gAMA_SUPPORTED
  181461. # endif
  181462. #endif
  181463. #ifndef PNG_NO_WRITE_hIST
  181464. # define PNG_WRITE_hIST_SUPPORTED
  181465. # ifndef PNG_hIST_SUPPORTED
  181466. # define PNG_hIST_SUPPORTED
  181467. # endif
  181468. #endif
  181469. #ifndef PNG_NO_WRITE_iCCP
  181470. # define PNG_WRITE_iCCP_SUPPORTED
  181471. # ifndef PNG_iCCP_SUPPORTED
  181472. # define PNG_iCCP_SUPPORTED
  181473. # endif
  181474. #endif
  181475. #ifndef PNG_NO_WRITE_iTXt
  181476. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181477. # define PNG_WRITE_iTXt_SUPPORTED
  181478. # endif
  181479. # ifndef PNG_iTXt_SUPPORTED
  181480. # define PNG_iTXt_SUPPORTED
  181481. # endif
  181482. #endif
  181483. #ifndef PNG_NO_WRITE_oFFs
  181484. # define PNG_WRITE_oFFs_SUPPORTED
  181485. # ifndef PNG_oFFs_SUPPORTED
  181486. # define PNG_oFFs_SUPPORTED
  181487. # endif
  181488. #endif
  181489. #ifndef PNG_NO_WRITE_pCAL
  181490. # define PNG_WRITE_pCAL_SUPPORTED
  181491. # ifndef PNG_pCAL_SUPPORTED
  181492. # define PNG_pCAL_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #ifndef PNG_NO_WRITE_sCAL
  181496. # define PNG_WRITE_sCAL_SUPPORTED
  181497. # ifndef PNG_sCAL_SUPPORTED
  181498. # define PNG_sCAL_SUPPORTED
  181499. # endif
  181500. #endif
  181501. #ifndef PNG_NO_WRITE_pHYs
  181502. # define PNG_WRITE_pHYs_SUPPORTED
  181503. # ifndef PNG_pHYs_SUPPORTED
  181504. # define PNG_pHYs_SUPPORTED
  181505. # endif
  181506. #endif
  181507. #ifndef PNG_NO_WRITE_sBIT
  181508. # define PNG_WRITE_sBIT_SUPPORTED
  181509. # ifndef PNG_sBIT_SUPPORTED
  181510. # define PNG_sBIT_SUPPORTED
  181511. # endif
  181512. #endif
  181513. #ifndef PNG_NO_WRITE_sPLT
  181514. # define PNG_WRITE_sPLT_SUPPORTED
  181515. # ifndef PNG_sPLT_SUPPORTED
  181516. # define PNG_sPLT_SUPPORTED
  181517. # endif
  181518. #endif
  181519. #ifndef PNG_NO_WRITE_sRGB
  181520. # define PNG_WRITE_sRGB_SUPPORTED
  181521. # ifndef PNG_sRGB_SUPPORTED
  181522. # define PNG_sRGB_SUPPORTED
  181523. # endif
  181524. #endif
  181525. #ifndef PNG_NO_WRITE_tEXt
  181526. # define PNG_WRITE_tEXt_SUPPORTED
  181527. # ifndef PNG_tEXt_SUPPORTED
  181528. # define PNG_tEXt_SUPPORTED
  181529. # endif
  181530. #endif
  181531. #ifndef PNG_NO_WRITE_tIME
  181532. # define PNG_WRITE_tIME_SUPPORTED
  181533. # ifndef PNG_tIME_SUPPORTED
  181534. # define PNG_tIME_SUPPORTED
  181535. # endif
  181536. #endif
  181537. #ifndef PNG_NO_WRITE_tRNS
  181538. # define PNG_WRITE_tRNS_SUPPORTED
  181539. # ifndef PNG_tRNS_SUPPORTED
  181540. # define PNG_tRNS_SUPPORTED
  181541. # endif
  181542. #endif
  181543. #ifndef PNG_NO_WRITE_zTXt
  181544. # define PNG_WRITE_zTXt_SUPPORTED
  181545. # ifndef PNG_zTXt_SUPPORTED
  181546. # define PNG_zTXt_SUPPORTED
  181547. # endif
  181548. #endif
  181549. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181550. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181551. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181552. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181553. # endif
  181554. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181555. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181556. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181557. # endif
  181558. # endif
  181559. #endif
  181560. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181561. defined(PNG_WRITE_zTXt_SUPPORTED)
  181562. # define PNG_WRITE_TEXT_SUPPORTED
  181563. # ifndef PNG_TEXT_SUPPORTED
  181564. # define PNG_TEXT_SUPPORTED
  181565. # endif
  181566. #endif
  181567. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181568. /* Turn this off to disable png_read_png() and
  181569. * png_write_png() and leave the row_pointers member
  181570. * out of the info structure.
  181571. */
  181572. #ifndef PNG_NO_INFO_IMAGE
  181573. # define PNG_INFO_IMAGE_SUPPORTED
  181574. #endif
  181575. /* need the time information for reading tIME chunks */
  181576. #if defined(PNG_tIME_SUPPORTED)
  181577. # if !defined(_WIN32_WCE)
  181578. /* "time.h" functions are not supported on WindowsCE */
  181579. # include <time.h>
  181580. # endif
  181581. #endif
  181582. /* Some typedefs to get us started. These should be safe on most of the
  181583. * common platforms. The typedefs should be at least as large as the
  181584. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181585. * don't have to be exactly that size. Some compilers dislike passing
  181586. * unsigned shorts as function parameters, so you may be better off using
  181587. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181588. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181589. */
  181590. typedef unsigned long png_uint_32;
  181591. typedef long png_int_32;
  181592. typedef unsigned short png_uint_16;
  181593. typedef short png_int_16;
  181594. typedef unsigned char png_byte;
  181595. /* This is usually size_t. It is typedef'ed just in case you need it to
  181596. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181597. #ifdef PNG_SIZE_T
  181598. typedef PNG_SIZE_T png_size_t;
  181599. # define png_sizeof(x) png_convert_size(sizeof (x))
  181600. #else
  181601. typedef size_t png_size_t;
  181602. # define png_sizeof(x) sizeof (x)
  181603. #endif
  181604. /* The following is needed for medium model support. It cannot be in the
  181605. * PNG_INTERNAL section. Needs modification for other compilers besides
  181606. * MSC. Model independent support declares all arrays and pointers to be
  181607. * large using the far keyword. The zlib version used must also support
  181608. * model independent data. As of version zlib 1.0.4, the necessary changes
  181609. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181610. * changes that are needed. (Tim Wegner)
  181611. */
  181612. /* Separate compiler dependencies (problem here is that zlib.h always
  181613. defines FAR. (SJT) */
  181614. #ifdef __BORLANDC__
  181615. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181616. # define LDATA 1
  181617. # else
  181618. # define LDATA 0
  181619. # endif
  181620. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181621. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181622. # define PNG_MAX_MALLOC_64K
  181623. # if (LDATA != 1)
  181624. # ifndef FAR
  181625. # define FAR __far
  181626. # endif
  181627. # define USE_FAR_KEYWORD
  181628. # endif /* LDATA != 1 */
  181629. /* Possibly useful for moving data out of default segment.
  181630. * Uncomment it if you want. Could also define FARDATA as
  181631. * const if your compiler supports it. (SJT)
  181632. # define FARDATA FAR
  181633. */
  181634. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181635. #endif /* __BORLANDC__ */
  181636. /* Suggest testing for specific compiler first before testing for
  181637. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181638. * making reliance oncertain keywords suspect. (SJT)
  181639. */
  181640. /* MSC Medium model */
  181641. #if defined(FAR)
  181642. # if defined(M_I86MM)
  181643. # define USE_FAR_KEYWORD
  181644. # define FARDATA FAR
  181645. # include <dos.h>
  181646. # endif
  181647. #endif
  181648. /* SJT: default case */
  181649. #ifndef FAR
  181650. # define FAR
  181651. #endif
  181652. /* At this point FAR is always defined */
  181653. #ifndef FARDATA
  181654. # define FARDATA
  181655. #endif
  181656. /* Typedef for floating-point numbers that are converted
  181657. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181658. typedef png_int_32 png_fixed_point;
  181659. /* Add typedefs for pointers */
  181660. typedef void FAR * png_voidp;
  181661. typedef png_byte FAR * png_bytep;
  181662. typedef png_uint_32 FAR * png_uint_32p;
  181663. typedef png_int_32 FAR * png_int_32p;
  181664. typedef png_uint_16 FAR * png_uint_16p;
  181665. typedef png_int_16 FAR * png_int_16p;
  181666. typedef PNG_CONST char FAR * png_const_charp;
  181667. typedef char FAR * png_charp;
  181668. typedef png_fixed_point FAR * png_fixed_point_p;
  181669. #ifndef PNG_NO_STDIO
  181670. #if defined(_WIN32_WCE)
  181671. typedef HANDLE png_FILE_p;
  181672. #else
  181673. typedef FILE * png_FILE_p;
  181674. #endif
  181675. #endif
  181676. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181677. typedef double FAR * png_doublep;
  181678. #endif
  181679. /* Pointers to pointers; i.e. arrays */
  181680. typedef png_byte FAR * FAR * png_bytepp;
  181681. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181682. typedef png_int_32 FAR * FAR * png_int_32pp;
  181683. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181684. typedef png_int_16 FAR * FAR * png_int_16pp;
  181685. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181686. typedef char FAR * FAR * png_charpp;
  181687. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181688. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181689. typedef double FAR * FAR * png_doublepp;
  181690. #endif
  181691. /* Pointers to pointers to pointers; i.e., pointer to array */
  181692. typedef char FAR * FAR * FAR * png_charppp;
  181693. #if 0
  181694. /* SPC - Is this stuff deprecated? */
  181695. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181696. /* libpng typedefs for types in zlib. If zlib changes
  181697. * or another compression library is used, then change these.
  181698. * Eliminates need to change all the source files.
  181699. */
  181700. typedef charf * png_zcharp;
  181701. typedef charf * FAR * png_zcharpp;
  181702. typedef z_stream FAR * png_zstreamp;
  181703. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181704. /*
  181705. * Define PNG_BUILD_DLL if the module being built is a Windows
  181706. * LIBPNG DLL.
  181707. *
  181708. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181709. * It is equivalent to Microsoft predefined macro _DLL that is
  181710. * automatically defined when you compile using the share
  181711. * version of the CRT (C Run-Time library)
  181712. *
  181713. * The cygwin mods make this behavior a little different:
  181714. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181715. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181716. * -or- if you are building an application that you want to link to the
  181717. * static library.
  181718. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181719. * the other flags is defined.
  181720. */
  181721. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181722. # define PNG_DLL
  181723. #endif
  181724. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181725. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181726. * command-line override
  181727. */
  181728. #if defined(__CYGWIN__)
  181729. # if !defined(PNG_STATIC)
  181730. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181731. # undef PNG_USE_GLOBAL_ARRAYS
  181732. # endif
  181733. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181734. # define PNG_USE_LOCAL_ARRAYS
  181735. # endif
  181736. # else
  181737. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181738. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181739. # undef PNG_USE_GLOBAL_ARRAYS
  181740. # endif
  181741. # endif
  181742. # endif
  181743. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181744. # define PNG_USE_LOCAL_ARRAYS
  181745. # endif
  181746. #endif
  181747. /* Do not use global arrays (helps with building DLL's)
  181748. * They are no longer used in libpng itself, since version 1.0.5c,
  181749. * but might be required for some pre-1.0.5c applications.
  181750. */
  181751. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181752. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181753. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181754. # define PNG_USE_LOCAL_ARRAYS
  181755. # else
  181756. # define PNG_USE_GLOBAL_ARRAYS
  181757. # endif
  181758. #endif
  181759. #if defined(__CYGWIN__)
  181760. # undef PNGAPI
  181761. # define PNGAPI __cdecl
  181762. # undef PNG_IMPEXP
  181763. # define PNG_IMPEXP
  181764. #endif
  181765. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181766. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181767. * Don't ignore those warnings; you must also reset the default calling
  181768. * convention in your compiler to match your PNGAPI, and you must build
  181769. * zlib and your applications the same way you build libpng.
  181770. */
  181771. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181772. # ifndef PNG_NO_MODULEDEF
  181773. # define PNG_NO_MODULEDEF
  181774. # endif
  181775. #endif
  181776. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181777. # define PNG_IMPEXP
  181778. #endif
  181779. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181780. (( defined(_Windows) || defined(_WINDOWS) || \
  181781. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181782. # ifndef PNGAPI
  181783. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181784. # define PNGAPI __cdecl
  181785. # else
  181786. # define PNGAPI _cdecl
  181787. # endif
  181788. # endif
  181789. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181790. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181791. # define PNG_IMPEXP
  181792. # endif
  181793. # if !defined(PNG_IMPEXP)
  181794. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181795. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181796. /* Borland/Microsoft */
  181797. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181798. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181799. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181800. # else
  181801. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181802. # if defined(PNG_BUILD_DLL)
  181803. # define PNG_IMPEXP __export
  181804. # else
  181805. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181806. VC++ */
  181807. # endif /* Exists in Borland C++ for
  181808. C++ classes (== huge) */
  181809. # endif
  181810. # endif
  181811. # if !defined(PNG_IMPEXP)
  181812. # if defined(PNG_BUILD_DLL)
  181813. # define PNG_IMPEXP __declspec(dllexport)
  181814. # else
  181815. # define PNG_IMPEXP __declspec(dllimport)
  181816. # endif
  181817. # endif
  181818. # endif /* PNG_IMPEXP */
  181819. #else /* !(DLL || non-cygwin WINDOWS) */
  181820. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181821. # ifndef PNGAPI
  181822. # define PNGAPI _System
  181823. # endif
  181824. # else
  181825. # if 0 /* ... other platforms, with other meanings */
  181826. # endif
  181827. # endif
  181828. #endif
  181829. #ifndef PNGAPI
  181830. # define PNGAPI
  181831. #endif
  181832. #ifndef PNG_IMPEXP
  181833. # define PNG_IMPEXP
  181834. #endif
  181835. #ifdef PNG_BUILDSYMS
  181836. # ifndef PNG_EXPORT
  181837. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181838. # endif
  181839. # ifdef PNG_USE_GLOBAL_ARRAYS
  181840. # ifndef PNG_EXPORT_VAR
  181841. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181842. # endif
  181843. # endif
  181844. #endif
  181845. #ifndef PNG_EXPORT
  181846. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181847. #endif
  181848. #ifdef PNG_USE_GLOBAL_ARRAYS
  181849. # ifndef PNG_EXPORT_VAR
  181850. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181851. # endif
  181852. #endif
  181853. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181854. * functions that are passed far data must be model independent.
  181855. */
  181856. #ifndef PNG_ABORT
  181857. # define PNG_ABORT() abort()
  181858. #endif
  181859. #ifdef PNG_SETJMP_SUPPORTED
  181860. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181861. #else
  181862. # define png_jmpbuf(png_ptr) \
  181863. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181864. #endif
  181865. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181866. /* use this to make far-to-near assignments */
  181867. # define CHECK 1
  181868. # define NOCHECK 0
  181869. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181870. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181871. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181872. # define png_strcpy _fstrcpy
  181873. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181874. # define png_strlen _fstrlen
  181875. # define png_memcmp _fmemcmp /* SJT: added */
  181876. # define png_memcpy _fmemcpy
  181877. # define png_memset _fmemset
  181878. #else /* use the usual functions */
  181879. # define CVT_PTR(ptr) (ptr)
  181880. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181881. # ifndef PNG_NO_SNPRINTF
  181882. # ifdef _MSC_VER
  181883. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181884. # define png_snprintf2 _snprintf
  181885. # define png_snprintf6 _snprintf
  181886. # else
  181887. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181888. # define png_snprintf2 snprintf
  181889. # define png_snprintf6 snprintf
  181890. # endif
  181891. # else
  181892. /* You don't have or don't want to use snprintf(). Caution: Using
  181893. * sprintf instead of snprintf exposes your application to accidental
  181894. * or malevolent buffer overflows. If you don't have snprintf()
  181895. * as a general rule you should provide one (you can get one from
  181896. * Portable OpenSSH). */
  181897. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181898. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181899. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181900. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181901. # endif
  181902. # define png_strcpy strcpy
  181903. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181904. # define png_strlen strlen
  181905. # define png_memcmp memcmp /* SJT: added */
  181906. # define png_memcpy memcpy
  181907. # define png_memset memset
  181908. #endif
  181909. /* End of memory model independent support */
  181910. /* Just a little check that someone hasn't tried to define something
  181911. * contradictory.
  181912. */
  181913. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181914. # undef PNG_ZBUF_SIZE
  181915. # define PNG_ZBUF_SIZE 65536L
  181916. #endif
  181917. /* Added at libpng-1.2.8 */
  181918. #endif /* PNG_VERSION_INFO_ONLY */
  181919. #endif /* PNGCONF_H */
  181920. /*** End of inlined file: pngconf.h ***/
  181921. #ifdef _MSC_VER
  181922. #pragma warning (disable: 4996 4100)
  181923. #endif
  181924. /*
  181925. * Added at libpng-1.2.8 */
  181926. /* Ref MSDN: Private as priority over Special
  181927. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181928. * procedures. If this value is given, the StringFileInfo block must
  181929. * contain a PrivateBuild string.
  181930. *
  181931. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181932. * standard release procedures but is a variation of the standard
  181933. * file of the same version number. If this value is given, the
  181934. * StringFileInfo block must contain a SpecialBuild string.
  181935. */
  181936. #if defined(PNG_USER_PRIVATEBUILD)
  181937. # define PNG_LIBPNG_BUILD_TYPE \
  181938. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181939. #else
  181940. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181941. # define PNG_LIBPNG_BUILD_TYPE \
  181942. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181943. # else
  181944. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181945. # endif
  181946. #endif
  181947. #ifndef PNG_VERSION_INFO_ONLY
  181948. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181949. #ifdef __cplusplus
  181950. //extern "C" {
  181951. #endif /* __cplusplus */
  181952. /* This file is arranged in several sections. The first section contains
  181953. * structure and type definitions. The second section contains the external
  181954. * library functions, while the third has the internal library functions,
  181955. * which applications aren't expected to use directly.
  181956. */
  181957. #ifndef PNG_NO_TYPECAST_NULL
  181958. #define int_p_NULL (int *)NULL
  181959. #define png_bytep_NULL (png_bytep)NULL
  181960. #define png_bytepp_NULL (png_bytepp)NULL
  181961. #define png_doublep_NULL (png_doublep)NULL
  181962. #define png_error_ptr_NULL (png_error_ptr)NULL
  181963. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181964. #define png_free_ptr_NULL (png_free_ptr)NULL
  181965. #define png_infopp_NULL (png_infopp)NULL
  181966. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181967. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181968. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181969. #define png_structp_NULL (png_structp)NULL
  181970. #define png_uint_16p_NULL (png_uint_16p)NULL
  181971. #define png_voidp_NULL (png_voidp)NULL
  181972. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181973. #else
  181974. #define int_p_NULL NULL
  181975. #define png_bytep_NULL NULL
  181976. #define png_bytepp_NULL NULL
  181977. #define png_doublep_NULL NULL
  181978. #define png_error_ptr_NULL NULL
  181979. #define png_flush_ptr_NULL NULL
  181980. #define png_free_ptr_NULL NULL
  181981. #define png_infopp_NULL NULL
  181982. #define png_malloc_ptr_NULL NULL
  181983. #define png_read_status_ptr_NULL NULL
  181984. #define png_rw_ptr_NULL NULL
  181985. #define png_structp_NULL NULL
  181986. #define png_uint_16p_NULL NULL
  181987. #define png_voidp_NULL NULL
  181988. #define png_write_status_ptr_NULL NULL
  181989. #endif
  181990. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181991. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181992. /* Version information for C files, stored in png.c. This had better match
  181993. * the version above.
  181994. */
  181995. #ifdef PNG_USE_GLOBAL_ARRAYS
  181996. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181997. /* need room for 99.99.99beta99z */
  181998. #else
  181999. #define png_libpng_ver png_get_header_ver(NULL)
  182000. #endif
  182001. #ifdef PNG_USE_GLOBAL_ARRAYS
  182002. /* This was removed in version 1.0.5c */
  182003. /* Structures to facilitate easy interlacing. See png.c for more details */
  182004. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182005. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182006. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182007. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182008. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182009. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182010. /* This isn't currently used. If you need it, see png.c for more details.
  182011. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182012. */
  182013. #endif
  182014. #endif /* PNG_NO_EXTERN */
  182015. /* Three color definitions. The order of the red, green, and blue, (and the
  182016. * exact size) is not important, although the size of the fields need to
  182017. * be png_byte or png_uint_16 (as defined below).
  182018. */
  182019. typedef struct png_color_struct
  182020. {
  182021. png_byte red;
  182022. png_byte green;
  182023. png_byte blue;
  182024. } png_color;
  182025. typedef png_color FAR * png_colorp;
  182026. typedef png_color FAR * FAR * png_colorpp;
  182027. typedef struct png_color_16_struct
  182028. {
  182029. png_byte index; /* used for palette files */
  182030. png_uint_16 red; /* for use in red green blue files */
  182031. png_uint_16 green;
  182032. png_uint_16 blue;
  182033. png_uint_16 gray; /* for use in grayscale files */
  182034. } png_color_16;
  182035. typedef png_color_16 FAR * png_color_16p;
  182036. typedef png_color_16 FAR * FAR * png_color_16pp;
  182037. typedef struct png_color_8_struct
  182038. {
  182039. png_byte red; /* for use in red green blue files */
  182040. png_byte green;
  182041. png_byte blue;
  182042. png_byte gray; /* for use in grayscale files */
  182043. png_byte alpha; /* for alpha channel files */
  182044. } png_color_8;
  182045. typedef png_color_8 FAR * png_color_8p;
  182046. typedef png_color_8 FAR * FAR * png_color_8pp;
  182047. /*
  182048. * The following two structures are used for the in-core representation
  182049. * of sPLT chunks.
  182050. */
  182051. typedef struct png_sPLT_entry_struct
  182052. {
  182053. png_uint_16 red;
  182054. png_uint_16 green;
  182055. png_uint_16 blue;
  182056. png_uint_16 alpha;
  182057. png_uint_16 frequency;
  182058. } png_sPLT_entry;
  182059. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182060. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182061. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182062. * occupy the LSB of their respective members, and the MSB of each member
  182063. * is zero-filled. The frequency member always occupies the full 16 bits.
  182064. */
  182065. typedef struct png_sPLT_struct
  182066. {
  182067. png_charp name; /* palette name */
  182068. png_byte depth; /* depth of palette samples */
  182069. png_sPLT_entryp entries; /* palette entries */
  182070. png_int_32 nentries; /* number of palette entries */
  182071. } png_sPLT_t;
  182072. typedef png_sPLT_t FAR * png_sPLT_tp;
  182073. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182074. #ifdef PNG_TEXT_SUPPORTED
  182075. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182076. * and whether that contents is compressed or not. The "key" field
  182077. * points to a regular zero-terminated C string. The "text", "lang", and
  182078. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182079. * However, the * structure returned by png_get_text() will always contain
  182080. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182081. * so they can be safely used in printf() and other string-handling functions.
  182082. */
  182083. typedef struct png_text_struct
  182084. {
  182085. int compression; /* compression value:
  182086. -1: tEXt, none
  182087. 0: zTXt, deflate
  182088. 1: iTXt, none
  182089. 2: iTXt, deflate */
  182090. png_charp key; /* keyword, 1-79 character description of "text" */
  182091. png_charp text; /* comment, may be an empty string (ie "")
  182092. or a NULL pointer */
  182093. png_size_t text_length; /* length of the text string */
  182094. #ifdef PNG_iTXt_SUPPORTED
  182095. png_size_t itxt_length; /* length of the itxt string */
  182096. png_charp lang; /* language code, 0-79 characters
  182097. or a NULL pointer */
  182098. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182099. chars or a NULL pointer */
  182100. #endif
  182101. } png_text;
  182102. typedef png_text FAR * png_textp;
  182103. typedef png_text FAR * FAR * png_textpp;
  182104. #endif
  182105. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182106. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182107. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182108. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182109. #define PNG_TEXT_COMPRESSION_NONE -1
  182110. #define PNG_TEXT_COMPRESSION_zTXt 0
  182111. #define PNG_ITXT_COMPRESSION_NONE 1
  182112. #define PNG_ITXT_COMPRESSION_zTXt 2
  182113. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182114. /* png_time is a way to hold the time in an machine independent way.
  182115. * Two conversions are provided, both from time_t and struct tm. There
  182116. * is no portable way to convert to either of these structures, as far
  182117. * as I know. If you know of a portable way, send it to me. As a side
  182118. * note - PNG has always been Year 2000 compliant!
  182119. */
  182120. typedef struct png_time_struct
  182121. {
  182122. png_uint_16 year; /* full year, as in, 1995 */
  182123. png_byte month; /* month of year, 1 - 12 */
  182124. png_byte day; /* day of month, 1 - 31 */
  182125. png_byte hour; /* hour of day, 0 - 23 */
  182126. png_byte minute; /* minute of hour, 0 - 59 */
  182127. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182128. } png_time;
  182129. typedef png_time FAR * png_timep;
  182130. typedef png_time FAR * FAR * png_timepp;
  182131. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182132. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182133. * no specific support. The idea is that we can use this to queue
  182134. * up private chunks for output even though the library doesn't actually
  182135. * know about their semantics.
  182136. */
  182137. typedef struct png_unknown_chunk_t
  182138. {
  182139. png_byte name[5];
  182140. png_byte *data;
  182141. png_size_t size;
  182142. /* libpng-using applications should NOT directly modify this byte. */
  182143. png_byte location; /* mode of operation at read time */
  182144. }
  182145. png_unknown_chunk;
  182146. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182147. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182148. #endif
  182149. /* png_info is a structure that holds the information in a PNG file so
  182150. * that the application can find out the characteristics of the image.
  182151. * If you are reading the file, this structure will tell you what is
  182152. * in the PNG file. If you are writing the file, fill in the information
  182153. * you want to put into the PNG file, then call png_write_info().
  182154. * The names chosen should be very close to the PNG specification, so
  182155. * consult that document for information about the meaning of each field.
  182156. *
  182157. * With libpng < 0.95, it was only possible to directly set and read the
  182158. * the values in the png_info_struct, which meant that the contents and
  182159. * order of the values had to remain fixed. With libpng 0.95 and later,
  182160. * however, there are now functions that abstract the contents of
  182161. * png_info_struct from the application, so this makes it easier to use
  182162. * libpng with dynamic libraries, and even makes it possible to use
  182163. * libraries that don't have all of the libpng ancillary chunk-handing
  182164. * functionality.
  182165. *
  182166. * In any case, the order of the parameters in png_info_struct should NOT
  182167. * be changed for as long as possible to keep compatibility with applications
  182168. * that use the old direct-access method with png_info_struct.
  182169. *
  182170. * The following members may have allocated storage attached that should be
  182171. * cleaned up before the structure is discarded: palette, trans, text,
  182172. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182173. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182174. * are automatically freed when the info structure is deallocated, if they were
  182175. * allocated internally by libpng. This behavior can be changed by means
  182176. * of the png_data_freer() function.
  182177. *
  182178. * More allocation details: all the chunk-reading functions that
  182179. * change these members go through the corresponding png_set_*
  182180. * functions. A function to clear these members is available: see
  182181. * png_free_data(). The png_set_* functions do not depend on being
  182182. * able to point info structure members to any of the storage they are
  182183. * passed (they make their own copies), EXCEPT that the png_set_text
  182184. * functions use the same storage passed to them in the text_ptr or
  182185. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182186. * functions do not make their own copies.
  182187. */
  182188. typedef struct png_info_struct
  182189. {
  182190. /* the following are necessary for every PNG file */
  182191. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182192. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182193. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182194. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182195. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182196. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182197. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182198. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182199. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182200. /* The following three should have been named *_method not *_type */
  182201. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182202. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182203. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182204. /* The following is informational only on read, and not used on writes. */
  182205. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182206. png_byte pixel_depth; /* number of bits per pixel */
  182207. png_byte spare_byte; /* to align the data, and for future use */
  182208. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182209. /* The rest of the data is optional. If you are reading, check the
  182210. * valid field to see if the information in these are valid. If you
  182211. * are writing, set the valid field to those chunks you want written,
  182212. * and initialize the appropriate fields below.
  182213. */
  182214. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182215. /* The gAMA chunk describes the gamma characteristics of the system
  182216. * on which the image was created, normally in the range [1.0, 2.5].
  182217. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182218. */
  182219. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182220. #endif
  182221. #if defined(PNG_sRGB_SUPPORTED)
  182222. /* GR-P, 0.96a */
  182223. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182224. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182225. #endif
  182226. #if defined(PNG_TEXT_SUPPORTED)
  182227. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182228. * uncompressed, compressed, and optionally compressed forms, respectively.
  182229. * The data in "text" is an array of pointers to uncompressed,
  182230. * null-terminated C strings. Each chunk has a keyword that describes the
  182231. * textual data contained in that chunk. Keywords are not required to be
  182232. * unique, and the text string may be empty. Any number of text chunks may
  182233. * be in an image.
  182234. */
  182235. int num_text; /* number of comments read/to write */
  182236. int max_text; /* current size of text array */
  182237. png_textp text; /* array of comments read/to write */
  182238. #endif /* PNG_TEXT_SUPPORTED */
  182239. #if defined(PNG_tIME_SUPPORTED)
  182240. /* The tIME chunk holds the last time the displayed image data was
  182241. * modified. See the png_time struct for the contents of this struct.
  182242. */
  182243. png_time mod_time;
  182244. #endif
  182245. #if defined(PNG_sBIT_SUPPORTED)
  182246. /* The sBIT chunk specifies the number of significant high-order bits
  182247. * in the pixel data. Values are in the range [1, bit_depth], and are
  182248. * only specified for the channels in the pixel data. The contents of
  182249. * the low-order bits is not specified. Data is valid if
  182250. * (valid & PNG_INFO_sBIT) is non-zero.
  182251. */
  182252. png_color_8 sig_bit; /* significant bits in color channels */
  182253. #endif
  182254. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182255. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182256. /* The tRNS chunk supplies transparency data for paletted images and
  182257. * other image types that don't need a full alpha channel. There are
  182258. * "num_trans" transparency values for a paletted image, stored in the
  182259. * same order as the palette colors, starting from index 0. Values
  182260. * for the data are in the range [0, 255], ranging from fully transparent
  182261. * to fully opaque, respectively. For non-paletted images, there is a
  182262. * single color specified that should be treated as fully transparent.
  182263. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182264. */
  182265. png_bytep trans; /* transparent values for paletted image */
  182266. png_color_16 trans_values; /* transparent color for non-palette image */
  182267. #endif
  182268. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182269. /* The bKGD chunk gives the suggested image background color if the
  182270. * display program does not have its own background color and the image
  182271. * is needs to composited onto a background before display. The colors
  182272. * in "background" are normally in the same color space/depth as the
  182273. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182274. */
  182275. png_color_16 background;
  182276. #endif
  182277. #if defined(PNG_oFFs_SUPPORTED)
  182278. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182279. * and downwards from the top-left corner of the display, page, or other
  182280. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182281. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182282. */
  182283. png_int_32 x_offset; /* x offset on page */
  182284. png_int_32 y_offset; /* y offset on page */
  182285. png_byte offset_unit_type; /* offset units type */
  182286. #endif
  182287. #if defined(PNG_pHYs_SUPPORTED)
  182288. /* The pHYs chunk gives the physical pixel density of the image for
  182289. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182290. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182291. */
  182292. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182293. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182294. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182295. #endif
  182296. #if defined(PNG_hIST_SUPPORTED)
  182297. /* The hIST chunk contains the relative frequency or importance of the
  182298. * various palette entries, so that a viewer can intelligently select a
  182299. * reduced-color palette, if required. Data is an array of "num_palette"
  182300. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182301. * is non-zero.
  182302. */
  182303. png_uint_16p hist;
  182304. #endif
  182305. #ifdef PNG_cHRM_SUPPORTED
  182306. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182307. * on which the PNG was created. This data allows the viewer to do gamut
  182308. * mapping of the input image to ensure that the viewer sees the same
  182309. * colors in the image as the creator. Values are in the range
  182310. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182311. */
  182312. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182313. float x_white;
  182314. float y_white;
  182315. float x_red;
  182316. float y_red;
  182317. float x_green;
  182318. float y_green;
  182319. float x_blue;
  182320. float y_blue;
  182321. #endif
  182322. #endif
  182323. #if defined(PNG_pCAL_SUPPORTED)
  182324. /* The pCAL chunk describes a transformation between the stored pixel
  182325. * values and original physical data values used to create the image.
  182326. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182327. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182328. * (possibly non-linear) transformation function given by "pcal_type"
  182329. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182330. * defines below, and the PNG-Group's PNG extensions document for a
  182331. * complete description of the transformations and how they should be
  182332. * implemented, and for a description of the ASCII parameter strings.
  182333. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182334. */
  182335. png_charp pcal_purpose; /* pCAL chunk description string */
  182336. png_int_32 pcal_X0; /* minimum value */
  182337. png_int_32 pcal_X1; /* maximum value */
  182338. png_charp pcal_units; /* Latin-1 string giving physical units */
  182339. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182340. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182341. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182342. #endif
  182343. /* New members added in libpng-1.0.6 */
  182344. #ifdef PNG_FREE_ME_SUPPORTED
  182345. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182346. #endif
  182347. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182348. /* storage for unknown chunks that the library doesn't recognize. */
  182349. png_unknown_chunkp unknown_chunks;
  182350. png_size_t unknown_chunks_num;
  182351. #endif
  182352. #if defined(PNG_iCCP_SUPPORTED)
  182353. /* iCCP chunk data. */
  182354. png_charp iccp_name; /* profile name */
  182355. png_charp iccp_profile; /* International Color Consortium profile data */
  182356. /* Note to maintainer: should be png_bytep */
  182357. png_uint_32 iccp_proflen; /* ICC profile data length */
  182358. png_byte iccp_compression; /* Always zero */
  182359. #endif
  182360. #if defined(PNG_sPLT_SUPPORTED)
  182361. /* data on sPLT chunks (there may be more than one). */
  182362. png_sPLT_tp splt_palettes;
  182363. png_uint_32 splt_palettes_num;
  182364. #endif
  182365. #if defined(PNG_sCAL_SUPPORTED)
  182366. /* The sCAL chunk describes the actual physical dimensions of the
  182367. * subject matter of the graphic. The chunk contains a unit specification
  182368. * a byte value, and two ASCII strings representing floating-point
  182369. * values. The values are width and height corresponsing to one pixel
  182370. * in the image. This external representation is converted to double
  182371. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182372. */
  182373. png_byte scal_unit; /* unit of physical scale */
  182374. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182375. double scal_pixel_width; /* width of one pixel */
  182376. double scal_pixel_height; /* height of one pixel */
  182377. #endif
  182378. #ifdef PNG_FIXED_POINT_SUPPORTED
  182379. png_charp scal_s_width; /* string containing height */
  182380. png_charp scal_s_height; /* string containing width */
  182381. #endif
  182382. #endif
  182383. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182384. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182385. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182386. png_bytepp row_pointers; /* the image bits */
  182387. #endif
  182388. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182389. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182390. #endif
  182391. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182392. png_fixed_point int_x_white;
  182393. png_fixed_point int_y_white;
  182394. png_fixed_point int_x_red;
  182395. png_fixed_point int_y_red;
  182396. png_fixed_point int_x_green;
  182397. png_fixed_point int_y_green;
  182398. png_fixed_point int_x_blue;
  182399. png_fixed_point int_y_blue;
  182400. #endif
  182401. } png_info;
  182402. typedef png_info FAR * png_infop;
  182403. typedef png_info FAR * FAR * png_infopp;
  182404. /* Maximum positive integer used in PNG is (2^31)-1 */
  182405. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182406. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182407. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182408. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182409. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182410. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182411. #endif
  182412. /* These describe the color_type field in png_info. */
  182413. /* color type masks */
  182414. #define PNG_COLOR_MASK_PALETTE 1
  182415. #define PNG_COLOR_MASK_COLOR 2
  182416. #define PNG_COLOR_MASK_ALPHA 4
  182417. /* color types. Note that not all combinations are legal */
  182418. #define PNG_COLOR_TYPE_GRAY 0
  182419. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182420. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182421. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182422. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182423. /* aliases */
  182424. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182425. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182426. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182427. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182428. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182429. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182430. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182431. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182432. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182433. /* These are for the interlacing type. These values should NOT be changed. */
  182434. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182435. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182436. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182437. /* These are for the oFFs chunk. These values should NOT be changed. */
  182438. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182439. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182440. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182441. /* These are for the pCAL chunk. These values should NOT be changed. */
  182442. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182443. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182444. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182445. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182446. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182447. /* These are for the sCAL chunk. These values should NOT be changed. */
  182448. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182449. #define PNG_SCALE_METER 1 /* meters per pixel */
  182450. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182451. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182452. /* These are for the pHYs chunk. These values should NOT be changed. */
  182453. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182454. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182455. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182456. /* These are for the sRGB chunk. These values should NOT be changed. */
  182457. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182458. #define PNG_sRGB_INTENT_RELATIVE 1
  182459. #define PNG_sRGB_INTENT_SATURATION 2
  182460. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182461. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182462. /* This is for text chunks */
  182463. #define PNG_KEYWORD_MAX_LENGTH 79
  182464. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182465. #define PNG_MAX_PALETTE_LENGTH 256
  182466. /* These determine if an ancillary chunk's data has been successfully read
  182467. * from the PNG header, or if the application has filled in the corresponding
  182468. * data in the info_struct to be written into the output file. The values
  182469. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182470. */
  182471. #define PNG_INFO_gAMA 0x0001
  182472. #define PNG_INFO_sBIT 0x0002
  182473. #define PNG_INFO_cHRM 0x0004
  182474. #define PNG_INFO_PLTE 0x0008
  182475. #define PNG_INFO_tRNS 0x0010
  182476. #define PNG_INFO_bKGD 0x0020
  182477. #define PNG_INFO_hIST 0x0040
  182478. #define PNG_INFO_pHYs 0x0080
  182479. #define PNG_INFO_oFFs 0x0100
  182480. #define PNG_INFO_tIME 0x0200
  182481. #define PNG_INFO_pCAL 0x0400
  182482. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182483. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182484. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182485. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182486. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182487. /* This is used for the transformation routines, as some of them
  182488. * change these values for the row. It also should enable using
  182489. * the routines for other purposes.
  182490. */
  182491. typedef struct png_row_info_struct
  182492. {
  182493. png_uint_32 width; /* width of row */
  182494. png_uint_32 rowbytes; /* number of bytes in row */
  182495. png_byte color_type; /* color type of row */
  182496. png_byte bit_depth; /* bit depth of row */
  182497. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182498. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182499. } png_row_info;
  182500. typedef png_row_info FAR * png_row_infop;
  182501. typedef png_row_info FAR * FAR * png_row_infopp;
  182502. /* These are the function types for the I/O functions and for the functions
  182503. * that allow the user to override the default I/O functions with his or her
  182504. * own. The png_error_ptr type should match that of user-supplied warning
  182505. * and error functions, while the png_rw_ptr type should match that of the
  182506. * user read/write data functions.
  182507. */
  182508. typedef struct png_struct_def png_struct;
  182509. typedef png_struct FAR * png_structp;
  182510. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182511. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182512. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182513. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182514. int));
  182515. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182516. int));
  182517. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182518. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182519. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182520. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182521. png_uint_32, int));
  182522. #endif
  182523. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182524. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182525. defined(PNG_LEGACY_SUPPORTED)
  182526. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182527. png_row_infop, png_bytep));
  182528. #endif
  182529. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182530. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182531. #endif
  182532. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182533. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182534. #endif
  182535. /* Transform masks for the high-level interface */
  182536. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182537. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182538. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182539. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182540. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182541. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182542. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182543. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182544. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182545. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182546. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182547. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182548. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182549. /* Flags for MNG supported features */
  182550. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182551. #define PNG_FLAG_MNG_FILTER_64 0x04
  182552. #define PNG_ALL_MNG_FEATURES 0x05
  182553. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182554. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182555. /* The structure that holds the information to read and write PNG files.
  182556. * The only people who need to care about what is inside of this are the
  182557. * people who will be modifying the library for their own special needs.
  182558. * It should NOT be accessed directly by an application, except to store
  182559. * the jmp_buf.
  182560. */
  182561. struct png_struct_def
  182562. {
  182563. #ifdef PNG_SETJMP_SUPPORTED
  182564. jmp_buf jmpbuf; /* used in png_error */
  182565. #endif
  182566. png_error_ptr error_fn; /* function for printing errors and aborting */
  182567. png_error_ptr warning_fn; /* function for printing warnings */
  182568. png_voidp error_ptr; /* user supplied struct for error functions */
  182569. png_rw_ptr write_data_fn; /* function for writing output data */
  182570. png_rw_ptr read_data_fn; /* function for reading input data */
  182571. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182572. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182573. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182574. #endif
  182575. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182576. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182577. #endif
  182578. /* These were added in libpng-1.0.2 */
  182579. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182580. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182581. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182582. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182583. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182584. png_byte user_transform_channels; /* channels in user transformed pixels */
  182585. #endif
  182586. #endif
  182587. png_uint_32 mode; /* tells us where we are in the PNG file */
  182588. png_uint_32 flags; /* flags indicating various things to libpng */
  182589. png_uint_32 transformations; /* which transformations to perform */
  182590. z_stream zstream; /* pointer to decompression structure (below) */
  182591. png_bytep zbuf; /* buffer for zlib */
  182592. png_size_t zbuf_size; /* size of zbuf */
  182593. int zlib_level; /* holds zlib compression level */
  182594. int zlib_method; /* holds zlib compression method */
  182595. int zlib_window_bits; /* holds zlib compression window bits */
  182596. int zlib_mem_level; /* holds zlib compression memory level */
  182597. int zlib_strategy; /* holds zlib compression strategy */
  182598. png_uint_32 width; /* width of image in pixels */
  182599. png_uint_32 height; /* height of image in pixels */
  182600. png_uint_32 num_rows; /* number of rows in current pass */
  182601. png_uint_32 usr_width; /* width of row at start of write */
  182602. png_uint_32 rowbytes; /* size of row in bytes */
  182603. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182604. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182605. png_uint_32 row_number; /* current row in interlace pass */
  182606. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182607. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182608. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182609. png_bytep up_row; /* buffer to save "up" row when filtering */
  182610. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182611. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182612. png_row_info row_info; /* used for transformation routines */
  182613. png_uint_32 idat_size; /* current IDAT size for read */
  182614. png_uint_32 crc; /* current chunk CRC value */
  182615. png_colorp palette; /* palette from the input file */
  182616. png_uint_16 num_palette; /* number of color entries in palette */
  182617. png_uint_16 num_trans; /* number of transparency values */
  182618. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182619. png_byte compression; /* file compression type (always 0) */
  182620. png_byte filter; /* file filter type (always 0) */
  182621. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182622. png_byte pass; /* current interlace pass (0 - 6) */
  182623. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182624. png_byte color_type; /* color type of file */
  182625. png_byte bit_depth; /* bit depth of file */
  182626. png_byte usr_bit_depth; /* bit depth of users row */
  182627. png_byte pixel_depth; /* number of bits per pixel */
  182628. png_byte channels; /* number of channels in file */
  182629. png_byte usr_channels; /* channels at start of write */
  182630. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182631. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182632. #ifdef PNG_LEGACY_SUPPORTED
  182633. png_byte filler; /* filler byte for pixel expansion */
  182634. #else
  182635. png_uint_16 filler; /* filler bytes for pixel expansion */
  182636. #endif
  182637. #endif
  182638. #if defined(PNG_bKGD_SUPPORTED)
  182639. png_byte background_gamma_type;
  182640. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182641. float background_gamma;
  182642. # endif
  182643. png_color_16 background; /* background color in screen gamma space */
  182644. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182645. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182646. #endif
  182647. #endif /* PNG_bKGD_SUPPORTED */
  182648. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182649. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182650. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182651. png_uint_32 flush_rows; /* number of rows written since last flush */
  182652. #endif
  182653. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182654. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182656. float gamma; /* file gamma value */
  182657. float screen_gamma; /* screen gamma value (display_exponent) */
  182658. #endif
  182659. #endif
  182660. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182661. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182662. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182663. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182664. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182665. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182666. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182667. #endif
  182668. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182669. png_color_8 sig_bit; /* significant bits in each available channel */
  182670. #endif
  182671. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182672. png_color_8 shift; /* shift for significant bit tranformation */
  182673. #endif
  182674. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182675. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182676. png_bytep trans; /* transparency values for paletted files */
  182677. png_color_16 trans_values; /* transparency values for non-paletted files */
  182678. #endif
  182679. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182680. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182681. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182682. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182683. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182684. png_progressive_end_ptr end_fn; /* called after image is complete */
  182685. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182686. png_bytep save_buffer; /* buffer for previously read data */
  182687. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182688. png_bytep current_buffer; /* buffer for recently used data */
  182689. png_uint_32 push_length; /* size of current input chunk */
  182690. png_uint_32 skip_length; /* bytes to skip in input data */
  182691. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182692. png_size_t save_buffer_max; /* total size of save_buffer */
  182693. png_size_t buffer_size; /* total amount of available input data */
  182694. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182695. int process_mode; /* what push library is currently doing */
  182696. int cur_palette; /* current push library palette index */
  182697. # if defined(PNG_TEXT_SUPPORTED)
  182698. png_size_t current_text_size; /* current size of text input data */
  182699. png_size_t current_text_left; /* how much text left to read in input */
  182700. png_charp current_text; /* current text chunk buffer */
  182701. png_charp current_text_ptr; /* current location in current_text */
  182702. # endif /* PNG_TEXT_SUPPORTED */
  182703. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182704. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182705. /* for the Borland special 64K segment handler */
  182706. png_bytepp offset_table_ptr;
  182707. png_bytep offset_table;
  182708. png_uint_16 offset_table_number;
  182709. png_uint_16 offset_table_count;
  182710. png_uint_16 offset_table_count_free;
  182711. #endif
  182712. #if defined(PNG_READ_DITHER_SUPPORTED)
  182713. png_bytep palette_lookup; /* lookup table for dithering */
  182714. png_bytep dither_index; /* index translation for palette files */
  182715. #endif
  182716. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182717. png_uint_16p hist; /* histogram */
  182718. #endif
  182719. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182720. png_byte heuristic_method; /* heuristic for row filter selection */
  182721. png_byte num_prev_filters; /* number of weights for previous rows */
  182722. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182723. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182724. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182725. png_uint_16p filter_costs; /* relative filter calculation cost */
  182726. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182727. #endif
  182728. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182729. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182730. #endif
  182731. /* New members added in libpng-1.0.6 */
  182732. #ifdef PNG_FREE_ME_SUPPORTED
  182733. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182734. #endif
  182735. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182736. png_voidp user_chunk_ptr;
  182737. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182738. #endif
  182739. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182740. int num_chunk_list;
  182741. png_bytep chunk_list;
  182742. #endif
  182743. /* New members added in libpng-1.0.3 */
  182744. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182745. png_byte rgb_to_gray_status;
  182746. /* These were changed from png_byte in libpng-1.0.6 */
  182747. png_uint_16 rgb_to_gray_red_coeff;
  182748. png_uint_16 rgb_to_gray_green_coeff;
  182749. png_uint_16 rgb_to_gray_blue_coeff;
  182750. #endif
  182751. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182752. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182753. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182754. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182755. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182756. #ifdef PNG_1_0_X
  182757. png_byte mng_features_permitted;
  182758. #else
  182759. png_uint_32 mng_features_permitted;
  182760. #endif /* PNG_1_0_X */
  182761. #endif
  182762. /* New member added in libpng-1.0.7 */
  182763. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182764. png_fixed_point int_gamma;
  182765. #endif
  182766. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182767. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182768. png_byte filter_type;
  182769. #endif
  182770. #if defined(PNG_1_0_X)
  182771. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182772. png_uint_32 row_buf_size;
  182773. #endif
  182774. /* New members added in libpng-1.2.0 */
  182775. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182776. # if !defined(PNG_1_0_X)
  182777. # if defined(PNG_MMX_CODE_SUPPORTED)
  182778. png_byte mmx_bitdepth_threshold;
  182779. png_uint_32 mmx_rowbytes_threshold;
  182780. # endif
  182781. png_uint_32 asm_flags;
  182782. # endif
  182783. #endif
  182784. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182785. #ifdef PNG_USER_MEM_SUPPORTED
  182786. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182787. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182788. png_free_ptr free_fn; /* function for freeing memory */
  182789. #endif
  182790. /* New member added in libpng-1.0.13 and 1.2.0 */
  182791. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182792. #if defined(PNG_READ_DITHER_SUPPORTED)
  182793. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182794. png_bytep dither_sort; /* working sort array */
  182795. png_bytep index_to_palette; /* where the original index currently is */
  182796. /* in the palette */
  182797. png_bytep palette_to_index; /* which original index points to this */
  182798. /* palette color */
  182799. #endif
  182800. /* New members added in libpng-1.0.16 and 1.2.6 */
  182801. png_byte compression_type;
  182802. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182803. png_uint_32 user_width_max;
  182804. png_uint_32 user_height_max;
  182805. #endif
  182806. /* New member added in libpng-1.0.25 and 1.2.17 */
  182807. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182808. /* storage for unknown chunk that the library doesn't recognize. */
  182809. png_unknown_chunk unknown_chunk;
  182810. #endif
  182811. };
  182812. /* This triggers a compiler error in png.c, if png.c and png.h
  182813. * do not agree upon the version number.
  182814. */
  182815. typedef png_structp version_1_2_21;
  182816. typedef png_struct FAR * FAR * png_structpp;
  182817. /* Here are the function definitions most commonly used. This is not
  182818. * the place to find out how to use libpng. See libpng.txt for the
  182819. * full explanation, see example.c for the summary. This just provides
  182820. * a simple one line description of the use of each function.
  182821. */
  182822. /* Returns the version number of the library */
  182823. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182824. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182825. * Handling more than 8 bytes from the beginning of the file is an error.
  182826. */
  182827. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182828. int num_bytes));
  182829. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182830. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182831. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182832. * start > 7 will always fail (ie return non-zero).
  182833. */
  182834. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182835. png_size_t num_to_check));
  182836. /* Simple signature checking function. This is the same as calling
  182837. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182838. */
  182839. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182840. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182841. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182842. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182843. png_error_ptr error_fn, png_error_ptr warn_fn));
  182844. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182845. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182846. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182847. png_error_ptr error_fn, png_error_ptr warn_fn));
  182848. #ifdef PNG_WRITE_SUPPORTED
  182849. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182850. PNGARG((png_structp png_ptr));
  182851. #endif
  182852. #ifdef PNG_WRITE_SUPPORTED
  182853. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182854. PNGARG((png_structp png_ptr, png_uint_32 size));
  182855. #endif
  182856. /* Reset the compression stream */
  182857. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182858. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182859. #ifdef PNG_USER_MEM_SUPPORTED
  182860. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182861. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182862. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182863. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182864. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182865. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182866. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182867. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182868. #endif
  182869. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182870. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182871. png_bytep chunk_name, png_bytep data, png_size_t length));
  182872. /* Write the start of a PNG chunk - length and chunk name. */
  182873. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182874. png_bytep chunk_name, png_uint_32 length));
  182875. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182876. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182877. png_bytep data, png_size_t length));
  182878. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182879. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182880. /* Allocate and initialize the info structure */
  182881. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182882. PNGARG((png_structp png_ptr));
  182883. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182884. /* Initialize the info structure (old interface - DEPRECATED) */
  182885. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182886. #undef png_info_init
  182887. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182888. png_sizeof(png_info));
  182889. #endif
  182890. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182891. png_size_t png_info_struct_size));
  182892. /* Writes all the PNG information before the image. */
  182893. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182894. png_infop info_ptr));
  182895. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182896. png_infop info_ptr));
  182897. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182898. /* read the information before the actual image data. */
  182899. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182900. png_infop info_ptr));
  182901. #endif
  182902. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182903. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182904. PNGARG((png_structp png_ptr, png_timep ptime));
  182905. #endif
  182906. #if !defined(_WIN32_WCE)
  182907. /* "time.h" functions are not supported on WindowsCE */
  182908. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182909. /* convert from a struct tm to png_time */
  182910. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182911. struct tm FAR * ttime));
  182912. /* convert from time_t to png_time. Uses gmtime() */
  182913. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182914. time_t ttime));
  182915. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182916. #endif /* _WIN32_WCE */
  182917. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182918. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182919. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182920. #if !defined(PNG_1_0_X)
  182921. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182922. png_ptr));
  182923. #endif
  182924. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182925. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182926. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182927. /* Deprecated */
  182928. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182929. #endif
  182930. #endif
  182931. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182932. /* Use blue, green, red order for pixels. */
  182933. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182934. #endif
  182935. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182936. /* Expand the grayscale to 24-bit RGB if necessary. */
  182937. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182938. #endif
  182939. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182940. /* Reduce RGB to grayscale. */
  182941. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182942. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182943. int error_action, double red, double green ));
  182944. #endif
  182945. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182946. int error_action, png_fixed_point red, png_fixed_point green ));
  182947. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182948. png_ptr));
  182949. #endif
  182950. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182951. png_colorp palette));
  182952. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182953. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182954. #endif
  182955. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182956. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182957. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182958. #endif
  182959. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182960. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182961. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182962. #endif
  182963. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182964. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182965. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182966. png_uint_32 filler, int flags));
  182967. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182968. #define PNG_FILLER_BEFORE 0
  182969. #define PNG_FILLER_AFTER 1
  182970. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182971. #if !defined(PNG_1_0_X)
  182972. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182973. png_uint_32 filler, int flags));
  182974. #endif
  182975. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182976. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182977. /* Swap bytes in 16-bit depth files. */
  182978. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182979. #endif
  182980. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182981. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182982. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182983. #endif
  182984. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182985. /* Swap packing order of pixels in bytes. */
  182986. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182987. #endif
  182988. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182989. /* Converts files to legal bit depths. */
  182990. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182991. png_color_8p true_bits));
  182992. #endif
  182993. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182994. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182995. /* Have the code handle the interlacing. Returns the number of passes. */
  182996. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182997. #endif
  182998. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182999. /* Invert monochrome files */
  183000. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183001. #endif
  183002. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183003. /* Handle alpha and tRNS by replacing with a background color. */
  183004. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183005. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183006. png_color_16p background_color, int background_gamma_code,
  183007. int need_expand, double background_gamma));
  183008. #endif
  183009. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183010. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183011. #define PNG_BACKGROUND_GAMMA_FILE 2
  183012. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183013. #endif
  183014. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183015. /* strip the second byte of information from a 16-bit depth file. */
  183016. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183017. #endif
  183018. #if defined(PNG_READ_DITHER_SUPPORTED)
  183019. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183020. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183021. png_colorp palette, int num_palette, int maximum_colors,
  183022. png_uint_16p histogram, int full_dither));
  183023. #endif
  183024. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183025. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183026. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183027. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183028. double screen_gamma, double default_file_gamma));
  183029. #endif
  183030. #endif
  183031. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183032. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183033. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183034. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183035. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183036. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183037. int empty_plte_permitted));
  183038. #endif
  183039. #endif
  183040. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183041. /* Set how many lines between output flushes - 0 for no flushing */
  183042. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183043. /* Flush the current PNG output buffer */
  183044. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183045. #endif
  183046. /* optional update palette with requested transformations */
  183047. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183048. /* optional call to update the users info structure */
  183049. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183050. png_infop info_ptr));
  183051. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183052. /* read one or more rows of image data. */
  183053. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183054. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183055. #endif
  183056. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183057. /* read a row of data. */
  183058. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183059. png_bytep row,
  183060. png_bytep display_row));
  183061. #endif
  183062. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183063. /* read the whole image into memory at once. */
  183064. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183065. png_bytepp image));
  183066. #endif
  183067. /* write a row of image data */
  183068. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183069. png_bytep row));
  183070. /* write a few rows of image data */
  183071. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183072. png_bytepp row, png_uint_32 num_rows));
  183073. /* write the image data */
  183074. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183075. png_bytepp image));
  183076. /* writes the end of the PNG file. */
  183077. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183078. png_infop info_ptr));
  183079. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183080. /* read the end of the PNG file. */
  183081. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183082. png_infop info_ptr));
  183083. #endif
  183084. /* free any memory associated with the png_info_struct */
  183085. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183086. png_infopp info_ptr_ptr));
  183087. /* free any memory associated with the png_struct and the png_info_structs */
  183088. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183089. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183090. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183091. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183092. png_infop end_info_ptr));
  183093. /* free any memory associated with the png_struct and the png_info_structs */
  183094. extern PNG_EXPORT(void,png_destroy_write_struct)
  183095. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183096. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183097. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183098. /* set the libpng method of handling chunk CRC errors */
  183099. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183100. int crit_action, int ancil_action));
  183101. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183102. * ancillary and critical chunks, and whether to use the data contained
  183103. * therein. Note that it is impossible to "discard" data in a critical
  183104. * chunk. For versions prior to 0.90, the action was always error/quit,
  183105. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183106. * chunks is warn/discard. These values should NOT be changed.
  183107. *
  183108. * value action:critical action:ancillary
  183109. */
  183110. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183111. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183112. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183113. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183114. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183115. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183116. /* These functions give the user control over the scan-line filtering in
  183117. * libpng and the compression methods used by zlib. These functions are
  183118. * mainly useful for testing, as the defaults should work with most users.
  183119. * Those users who are tight on memory or want faster performance at the
  183120. * expense of compression can modify them. See the compression library
  183121. * header file (zlib.h) for an explination of the compression functions.
  183122. */
  183123. /* set the filtering method(s) used by libpng. Currently, the only valid
  183124. * value for "method" is 0.
  183125. */
  183126. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183127. int filters));
  183128. /* Flags for png_set_filter() to say which filters to use. The flags
  183129. * are chosen so that they don't conflict with real filter types
  183130. * below, in case they are supplied instead of the #defined constants.
  183131. * These values should NOT be changed.
  183132. */
  183133. #define PNG_NO_FILTERS 0x00
  183134. #define PNG_FILTER_NONE 0x08
  183135. #define PNG_FILTER_SUB 0x10
  183136. #define PNG_FILTER_UP 0x20
  183137. #define PNG_FILTER_AVG 0x40
  183138. #define PNG_FILTER_PAETH 0x80
  183139. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183140. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183141. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183142. * These defines should NOT be changed.
  183143. */
  183144. #define PNG_FILTER_VALUE_NONE 0
  183145. #define PNG_FILTER_VALUE_SUB 1
  183146. #define PNG_FILTER_VALUE_UP 2
  183147. #define PNG_FILTER_VALUE_AVG 3
  183148. #define PNG_FILTER_VALUE_PAETH 4
  183149. #define PNG_FILTER_VALUE_LAST 5
  183150. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183151. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183152. * defines, either the default (minimum-sum-of-absolute-differences), or
  183153. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183154. *
  183155. * Weights are factors >= 1.0, indicating how important it is to keep the
  183156. * filter type consistent between rows. Larger numbers mean the current
  183157. * filter is that many times as likely to be the same as the "num_weights"
  183158. * previous filters. This is cumulative for each previous row with a weight.
  183159. * There needs to be "num_weights" values in "filter_weights", or it can be
  183160. * NULL if the weights aren't being specified. Weights have no influence on
  183161. * the selection of the first row filter. Well chosen weights can (in theory)
  183162. * improve the compression for a given image.
  183163. *
  183164. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183165. * filter type. Higher costs indicate more decoding expense, and are
  183166. * therefore less likely to be selected over a filter with lower computational
  183167. * costs. There needs to be a value in "filter_costs" for each valid filter
  183168. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183169. * setting the costs. Costs try to improve the speed of decompression without
  183170. * unduly increasing the compressed image size.
  183171. *
  183172. * A negative weight or cost indicates the default value is to be used, and
  183173. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183174. * The default values for both weights and costs are currently 1.0, but may
  183175. * change if good general weighting/cost heuristics can be found. If both
  183176. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183177. * to the UNWEIGHTED method, but with added encoding time/computation.
  183178. */
  183179. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183180. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183181. int heuristic_method, int num_weights, png_doublep filter_weights,
  183182. png_doublep filter_costs));
  183183. #endif
  183184. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183185. /* Heuristic used for row filter selection. These defines should NOT be
  183186. * changed.
  183187. */
  183188. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183189. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183190. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183191. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183192. /* Set the library compression level. Currently, valid values range from
  183193. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183194. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183195. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183196. * for PNG images, and do considerably fewer caclulations. In the future,
  183197. * these values may not correspond directly to the zlib compression levels.
  183198. */
  183199. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183200. int level));
  183201. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183202. PNGARG((png_structp png_ptr, int mem_level));
  183203. extern PNG_EXPORT(void,png_set_compression_strategy)
  183204. PNGARG((png_structp png_ptr, int strategy));
  183205. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183206. PNGARG((png_structp png_ptr, int window_bits));
  183207. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183208. int method));
  183209. /* These next functions are called for input/output, memory, and error
  183210. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183211. * and call standard C I/O routines such as fread(), fwrite(), and
  183212. * fprintf(). These functions can be made to use other I/O routines
  183213. * at run time for those applications that need to handle I/O in a
  183214. * different manner by calling png_set_???_fn(). See libpng.txt for
  183215. * more information.
  183216. */
  183217. #if !defined(PNG_NO_STDIO)
  183218. /* Initialize the input/output for the PNG file to the default functions. */
  183219. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183220. #endif
  183221. /* Replace the (error and abort), and warning functions with user
  183222. * supplied functions. If no messages are to be printed you must still
  183223. * write and use replacement functions. The replacement error_fn should
  183224. * still do a longjmp to the last setjmp location if you are using this
  183225. * method of error handling. If error_fn or warning_fn is NULL, the
  183226. * default function will be used.
  183227. */
  183228. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183229. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183230. /* Return the user pointer associated with the error functions */
  183231. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183232. /* Replace the default data output functions with a user supplied one(s).
  183233. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183234. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183235. * output_flush_fn will be ignored (and thus can be NULL).
  183236. */
  183237. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183238. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183239. /* Replace the default data input function with a user supplied one. */
  183240. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183241. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183242. /* Return the user pointer associated with the I/O functions */
  183243. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183244. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183245. png_read_status_ptr read_row_fn));
  183246. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183247. png_write_status_ptr write_row_fn));
  183248. #ifdef PNG_USER_MEM_SUPPORTED
  183249. /* Replace the default memory allocation functions with user supplied one(s). */
  183250. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183251. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183252. /* Return the user pointer associated with the memory functions */
  183253. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183254. #endif
  183255. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183256. defined(PNG_LEGACY_SUPPORTED)
  183257. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183258. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183259. #endif
  183260. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183261. defined(PNG_LEGACY_SUPPORTED)
  183262. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183263. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183264. #endif
  183265. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183266. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183267. defined(PNG_LEGACY_SUPPORTED)
  183268. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183269. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183270. int user_transform_channels));
  183271. /* Return the user pointer associated with the user transform functions */
  183272. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183273. PNGARG((png_structp png_ptr));
  183274. #endif
  183275. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183276. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183277. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183278. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183279. png_ptr));
  183280. #endif
  183281. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183282. /* Sets the function callbacks for the push reader, and a pointer to a
  183283. * user-defined structure available to the callback functions.
  183284. */
  183285. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183286. png_voidp progressive_ptr,
  183287. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183288. png_progressive_end_ptr end_fn));
  183289. /* returns the user pointer associated with the push read functions */
  183290. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183291. PNGARG((png_structp png_ptr));
  183292. /* function to be called when data becomes available */
  183293. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183294. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183295. /* function that combines rows. Not very much different than the
  183296. * png_combine_row() call. Is this even used?????
  183297. */
  183298. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183299. png_bytep old_row, png_bytep new_row));
  183300. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183301. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183302. png_uint_32 size));
  183303. #if defined(PNG_1_0_X)
  183304. # define png_malloc_warn png_malloc
  183305. #else
  183306. /* Added at libpng version 1.2.4 */
  183307. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183308. png_uint_32 size));
  183309. #endif
  183310. /* frees a pointer allocated by png_malloc() */
  183311. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183312. #if defined(PNG_1_0_X)
  183313. /* Function to allocate memory for zlib. */
  183314. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183315. uInt size));
  183316. /* Function to free memory for zlib */
  183317. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183318. #endif
  183319. /* Free data that was allocated internally */
  183320. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183321. png_infop info_ptr, png_uint_32 free_me, int num));
  183322. #ifdef PNG_FREE_ME_SUPPORTED
  183323. /* Reassign responsibility for freeing existing data, whether allocated
  183324. * by libpng or by the application */
  183325. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183326. png_infop info_ptr, int freer, png_uint_32 mask));
  183327. #endif
  183328. /* assignments for png_data_freer */
  183329. #define PNG_DESTROY_WILL_FREE_DATA 1
  183330. #define PNG_SET_WILL_FREE_DATA 1
  183331. #define PNG_USER_WILL_FREE_DATA 2
  183332. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183333. #define PNG_FREE_HIST 0x0008
  183334. #define PNG_FREE_ICCP 0x0010
  183335. #define PNG_FREE_SPLT 0x0020
  183336. #define PNG_FREE_ROWS 0x0040
  183337. #define PNG_FREE_PCAL 0x0080
  183338. #define PNG_FREE_SCAL 0x0100
  183339. #define PNG_FREE_UNKN 0x0200
  183340. #define PNG_FREE_LIST 0x0400
  183341. #define PNG_FREE_PLTE 0x1000
  183342. #define PNG_FREE_TRNS 0x2000
  183343. #define PNG_FREE_TEXT 0x4000
  183344. #define PNG_FREE_ALL 0x7fff
  183345. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183346. #ifdef PNG_USER_MEM_SUPPORTED
  183347. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183348. png_uint_32 size));
  183349. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183350. png_voidp ptr));
  183351. #endif
  183352. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183353. png_voidp s1, png_voidp s2, png_uint_32 size));
  183354. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183355. png_voidp s1, int value, png_uint_32 size));
  183356. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183357. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183358. int check));
  183359. #endif /* USE_FAR_KEYWORD */
  183360. #ifndef PNG_NO_ERROR_TEXT
  183361. /* Fatal error in PNG image of libpng - can't continue */
  183362. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183363. png_const_charp error_message));
  183364. /* The same, but the chunk name is prepended to the error string. */
  183365. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183366. png_const_charp error_message));
  183367. #else
  183368. /* Fatal error in PNG image of libpng - can't continue */
  183369. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183370. #endif
  183371. #ifndef PNG_NO_WARNINGS
  183372. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183373. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183374. png_const_charp warning_message));
  183375. #ifdef PNG_READ_SUPPORTED
  183376. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183377. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183378. png_const_charp warning_message));
  183379. #endif /* PNG_READ_SUPPORTED */
  183380. #endif /* PNG_NO_WARNINGS */
  183381. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183382. * Similarly, the png_get_<chunk> calls are used to read values from the
  183383. * png_info_struct, either storing the parameters in the passed variables, or
  183384. * setting pointers into the png_info_struct where the data is stored. The
  183385. * png_get_<chunk> functions return a non-zero value if the data was available
  183386. * in info_ptr, or return zero and do not change any of the parameters if the
  183387. * data was not available.
  183388. *
  183389. * These functions should be used instead of directly accessing png_info
  183390. * to avoid problems with future changes in the size and internal layout of
  183391. * png_info_struct.
  183392. */
  183393. /* Returns "flag" if chunk data is valid in info_ptr. */
  183394. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183395. png_infop info_ptr, png_uint_32 flag));
  183396. /* Returns number of bytes needed to hold a transformed row. */
  183397. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183398. png_infop info_ptr));
  183399. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183400. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183401. returned from png_read_png(). */
  183402. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183403. png_infop info_ptr));
  183404. /* Set row_pointers, which is an array of pointers to scanlines for use
  183405. by png_write_png(). */
  183406. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183407. png_infop info_ptr, png_bytepp row_pointers));
  183408. #endif
  183409. /* Returns number of color channels in image. */
  183410. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183411. png_infop info_ptr));
  183412. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183413. /* Returns image width in pixels. */
  183414. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183415. png_ptr, png_infop info_ptr));
  183416. /* Returns image height in pixels. */
  183417. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183418. png_ptr, png_infop info_ptr));
  183419. /* Returns image bit_depth. */
  183420. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183421. png_ptr, png_infop info_ptr));
  183422. /* Returns image color_type. */
  183423. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183424. png_ptr, png_infop info_ptr));
  183425. /* Returns image filter_type. */
  183426. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183427. png_ptr, png_infop info_ptr));
  183428. /* Returns image interlace_type. */
  183429. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183430. png_ptr, png_infop info_ptr));
  183431. /* Returns image compression_type. */
  183432. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183433. png_ptr, png_infop info_ptr));
  183434. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183435. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183436. png_ptr, png_infop info_ptr));
  183437. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183438. png_ptr, png_infop info_ptr));
  183439. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183440. png_ptr, png_infop info_ptr));
  183441. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183442. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183443. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183444. png_ptr, png_infop info_ptr));
  183445. #endif
  183446. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183447. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183448. png_ptr, png_infop info_ptr));
  183449. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183450. png_ptr, png_infop info_ptr));
  183451. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183452. png_ptr, png_infop info_ptr));
  183453. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183454. png_ptr, png_infop info_ptr));
  183455. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183456. /* Returns pointer to signature string read from PNG header */
  183457. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183458. png_infop info_ptr));
  183459. #if defined(PNG_bKGD_SUPPORTED)
  183460. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183461. png_infop info_ptr, png_color_16p *background));
  183462. #endif
  183463. #if defined(PNG_bKGD_SUPPORTED)
  183464. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183465. png_infop info_ptr, png_color_16p background));
  183466. #endif
  183467. #if defined(PNG_cHRM_SUPPORTED)
  183468. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183469. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183470. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183471. double *red_y, double *green_x, double *green_y, double *blue_x,
  183472. double *blue_y));
  183473. #endif
  183474. #ifdef PNG_FIXED_POINT_SUPPORTED
  183475. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183476. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183477. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183478. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183479. *int_blue_x, png_fixed_point *int_blue_y));
  183480. #endif
  183481. #endif
  183482. #if defined(PNG_cHRM_SUPPORTED)
  183483. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183484. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183485. png_infop info_ptr, double white_x, double white_y, double red_x,
  183486. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183487. #endif
  183488. #ifdef PNG_FIXED_POINT_SUPPORTED
  183489. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183490. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183491. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183492. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183493. png_fixed_point int_blue_y));
  183494. #endif
  183495. #endif
  183496. #if defined(PNG_gAMA_SUPPORTED)
  183497. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183498. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183499. png_infop info_ptr, double *file_gamma));
  183500. #endif
  183501. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183502. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183503. #endif
  183504. #if defined(PNG_gAMA_SUPPORTED)
  183505. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183506. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183507. png_infop info_ptr, double file_gamma));
  183508. #endif
  183509. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183510. png_infop info_ptr, png_fixed_point int_file_gamma));
  183511. #endif
  183512. #if defined(PNG_hIST_SUPPORTED)
  183513. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183514. png_infop info_ptr, png_uint_16p *hist));
  183515. #endif
  183516. #if defined(PNG_hIST_SUPPORTED)
  183517. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183518. png_infop info_ptr, png_uint_16p hist));
  183519. #endif
  183520. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183521. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183522. int *bit_depth, int *color_type, int *interlace_method,
  183523. int *compression_method, int *filter_method));
  183524. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183525. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183526. int color_type, int interlace_method, int compression_method,
  183527. int filter_method));
  183528. #if defined(PNG_oFFs_SUPPORTED)
  183529. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183530. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183531. int *unit_type));
  183532. #endif
  183533. #if defined(PNG_oFFs_SUPPORTED)
  183534. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183535. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183536. int unit_type));
  183537. #endif
  183538. #if defined(PNG_pCAL_SUPPORTED)
  183539. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183540. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183541. int *type, int *nparams, png_charp *units, png_charpp *params));
  183542. #endif
  183543. #if defined(PNG_pCAL_SUPPORTED)
  183544. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183545. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183546. int type, int nparams, png_charp units, png_charpp params));
  183547. #endif
  183548. #if defined(PNG_pHYs_SUPPORTED)
  183549. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183550. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183551. #endif
  183552. #if defined(PNG_pHYs_SUPPORTED)
  183553. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183554. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183555. #endif
  183556. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183557. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183558. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183559. png_infop info_ptr, png_colorp palette, int num_palette));
  183560. #if defined(PNG_sBIT_SUPPORTED)
  183561. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183562. png_infop info_ptr, png_color_8p *sig_bit));
  183563. #endif
  183564. #if defined(PNG_sBIT_SUPPORTED)
  183565. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183566. png_infop info_ptr, png_color_8p sig_bit));
  183567. #endif
  183568. #if defined(PNG_sRGB_SUPPORTED)
  183569. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183570. png_infop info_ptr, int *intent));
  183571. #endif
  183572. #if defined(PNG_sRGB_SUPPORTED)
  183573. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183574. png_infop info_ptr, int intent));
  183575. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr, int intent));
  183577. #endif
  183578. #if defined(PNG_iCCP_SUPPORTED)
  183579. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183580. png_infop info_ptr, png_charpp name, int *compression_type,
  183581. png_charpp profile, png_uint_32 *proflen));
  183582. /* Note to maintainer: profile should be png_bytepp */
  183583. #endif
  183584. #if defined(PNG_iCCP_SUPPORTED)
  183585. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183586. png_infop info_ptr, png_charp name, int compression_type,
  183587. png_charp profile, png_uint_32 proflen));
  183588. /* Note to maintainer: profile should be png_bytep */
  183589. #endif
  183590. #if defined(PNG_sPLT_SUPPORTED)
  183591. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183592. png_infop info_ptr, png_sPLT_tpp entries));
  183593. #endif
  183594. #if defined(PNG_sPLT_SUPPORTED)
  183595. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183596. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183597. #endif
  183598. #if defined(PNG_TEXT_SUPPORTED)
  183599. /* png_get_text also returns the number of text chunks in *num_text */
  183600. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183601. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183602. #endif
  183603. /*
  183604. * Note while png_set_text() will accept a structure whose text,
  183605. * language, and translated keywords are NULL pointers, the structure
  183606. * returned by png_get_text will always contain regular
  183607. * zero-terminated C strings. They might be empty strings but
  183608. * they will never be NULL pointers.
  183609. */
  183610. #if defined(PNG_TEXT_SUPPORTED)
  183611. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183612. png_infop info_ptr, png_textp text_ptr, int num_text));
  183613. #endif
  183614. #if defined(PNG_tIME_SUPPORTED)
  183615. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183616. png_infop info_ptr, png_timep *mod_time));
  183617. #endif
  183618. #if defined(PNG_tIME_SUPPORTED)
  183619. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183620. png_infop info_ptr, png_timep mod_time));
  183621. #endif
  183622. #if defined(PNG_tRNS_SUPPORTED)
  183623. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183624. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183625. png_color_16p *trans_values));
  183626. #endif
  183627. #if defined(PNG_tRNS_SUPPORTED)
  183628. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183629. png_infop info_ptr, png_bytep trans, int num_trans,
  183630. png_color_16p trans_values));
  183631. #endif
  183632. #if defined(PNG_tRNS_SUPPORTED)
  183633. #endif
  183634. #if defined(PNG_sCAL_SUPPORTED)
  183635. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183636. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183637. png_infop info_ptr, int *unit, double *width, double *height));
  183638. #else
  183639. #ifdef PNG_FIXED_POINT_SUPPORTED
  183640. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183641. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183642. #endif
  183643. #endif
  183644. #endif /* PNG_sCAL_SUPPORTED */
  183645. #if defined(PNG_sCAL_SUPPORTED)
  183646. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183647. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr, int unit, double width, double height));
  183649. #else
  183650. #ifdef PNG_FIXED_POINT_SUPPORTED
  183651. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183652. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183653. #endif
  183654. #endif
  183655. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183656. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183657. /* provide a list of chunks and how they are to be handled, if the built-in
  183658. handling or default unknown chunk handling is not desired. Any chunks not
  183659. listed will be handled in the default manner. The IHDR and IEND chunks
  183660. must not be listed.
  183661. keep = 0: follow default behaviour
  183662. = 1: do not keep
  183663. = 2: keep only if safe-to-copy
  183664. = 3: keep even if unsafe-to-copy
  183665. */
  183666. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183667. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183668. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183669. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183670. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183671. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183672. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183673. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183674. #endif
  183675. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183676. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183677. chunk_name));
  183678. #endif
  183679. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183680. If you need to turn it off for a chunk that your application has freed,
  183681. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183682. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183683. png_infop info_ptr, int mask));
  183684. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183685. /* The "params" pointer is currently not used and is for future expansion. */
  183686. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183687. png_infop info_ptr,
  183688. int transforms,
  183689. png_voidp params));
  183690. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183691. png_infop info_ptr,
  183692. int transforms,
  183693. png_voidp params));
  183694. #endif
  183695. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183696. * numbers for PNG_DEBUG mean more debugging information. This has
  183697. * only been added since version 0.95 so it is not implemented throughout
  183698. * libpng yet, but more support will be added as needed.
  183699. */
  183700. #ifdef PNG_DEBUG
  183701. #if (PNG_DEBUG > 0)
  183702. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183703. #include <crtdbg.h>
  183704. #if (PNG_DEBUG > 1)
  183705. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183706. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183707. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183708. #endif
  183709. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183710. #ifndef PNG_DEBUG_FILE
  183711. #define PNG_DEBUG_FILE stderr
  183712. #endif /* PNG_DEBUG_FILE */
  183713. #if (PNG_DEBUG > 1)
  183714. #define png_debug(l,m) \
  183715. { \
  183716. int num_tabs=l; \
  183717. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183718. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183719. }
  183720. #define png_debug1(l,m,p1) \
  183721. { \
  183722. int num_tabs=l; \
  183723. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183724. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183725. }
  183726. #define png_debug2(l,m,p1,p2) \
  183727. { \
  183728. int num_tabs=l; \
  183729. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183730. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183731. }
  183732. #endif /* (PNG_DEBUG > 1) */
  183733. #endif /* _MSC_VER */
  183734. #endif /* (PNG_DEBUG > 0) */
  183735. #endif /* PNG_DEBUG */
  183736. #ifndef png_debug
  183737. #define png_debug(l, m)
  183738. #endif
  183739. #ifndef png_debug1
  183740. #define png_debug1(l, m, p1)
  183741. #endif
  183742. #ifndef png_debug2
  183743. #define png_debug2(l, m, p1, p2)
  183744. #endif
  183745. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183746. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183747. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183748. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183749. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183750. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183751. png_ptr, png_uint_32 mng_features_permitted));
  183752. #endif
  183753. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183754. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183755. #define PNG_HANDLE_CHUNK_NEVER 1
  183756. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183757. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183758. /* Added to version 1.2.0 */
  183759. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183760. #if defined(PNG_MMX_CODE_SUPPORTED)
  183761. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183762. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183763. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183764. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183765. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183766. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183767. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183768. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183769. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183770. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183771. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183772. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183773. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183774. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183775. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183776. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183777. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183778. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183779. | PNG_MMX_READ_FLAGS \
  183780. | PNG_MMX_WRITE_FLAGS )
  183781. #define PNG_SELECT_READ 1
  183782. #define PNG_SELECT_WRITE 2
  183783. #endif /* PNG_MMX_CODE_SUPPORTED */
  183784. #if !defined(PNG_1_0_X)
  183785. /* pngget.c */
  183786. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183787. PNGARG((int flag_select, int *compilerID));
  183788. /* pngget.c */
  183789. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183790. PNGARG((int flag_select));
  183791. /* pngget.c */
  183792. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183793. PNGARG((png_structp png_ptr));
  183794. /* pngget.c */
  183795. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183796. PNGARG((png_structp png_ptr));
  183797. /* pngget.c */
  183798. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183799. PNGARG((png_structp png_ptr));
  183800. /* pngset.c */
  183801. extern PNG_EXPORT(void,png_set_asm_flags)
  183802. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183803. /* pngset.c */
  183804. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183805. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183806. png_uint_32 mmx_rowbytes_threshold));
  183807. #endif /* PNG_1_0_X */
  183808. #if !defined(PNG_1_0_X)
  183809. /* png.c, pnggccrd.c, or pngvcrd.c */
  183810. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183811. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183812. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183813. * messages before passing them to the error or warning handler. */
  183814. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183815. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183816. png_ptr, png_uint_32 strip_mode));
  183817. #endif
  183818. #endif /* PNG_1_0_X */
  183819. /* Added at libpng-1.2.6 */
  183820. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183821. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183822. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183823. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183824. png_ptr));
  183825. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183826. png_ptr));
  183827. #endif
  183828. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183829. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183830. /* With these routines we avoid an integer divide, which will be slower on
  183831. * most machines. However, it does take more operations than the corresponding
  183832. * divide method, so it may be slower on a few RISC systems. There are two
  183833. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183834. *
  183835. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183836. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183837. * standard method.
  183838. *
  183839. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183840. */
  183841. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183842. # define png_composite(composite, fg, alpha, bg) \
  183843. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183844. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183845. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183846. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183847. # define png_composite_16(composite, fg, alpha, bg) \
  183848. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183849. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183850. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183851. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183852. #else /* standard method using integer division */
  183853. # define png_composite(composite, fg, alpha, bg) \
  183854. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183855. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183856. (png_uint_16)127) / 255)
  183857. # define png_composite_16(composite, fg, alpha, bg) \
  183858. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183859. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183860. (png_uint_32)32767) / (png_uint_32)65535L)
  183861. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183862. /* Inline macros to do direct reads of bytes from the input buffer. These
  183863. * require that you are using an architecture that uses PNG byte ordering
  183864. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183865. * in big-endian mode and 680x0 are the only ones that will support this.
  183866. * The x86 line of processors definitely do not. The png_get_int_32()
  183867. * routine also assumes we are using two's complement format for negative
  183868. * values, which is almost certainly true.
  183869. */
  183870. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183871. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183872. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183873. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183874. #else
  183875. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183876. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183877. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183878. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183879. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183880. PNGARG((png_structp png_ptr, png_bytep buf));
  183881. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183882. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183883. */
  183884. extern PNG_EXPORT(void,png_save_uint_32)
  183885. PNGARG((png_bytep buf, png_uint_32 i));
  183886. extern PNG_EXPORT(void,png_save_int_32)
  183887. PNGARG((png_bytep buf, png_int_32 i));
  183888. /* Place a 16-bit number into a buffer in PNG byte order.
  183889. * The parameter is declared unsigned int, not png_uint_16,
  183890. * just to avoid potential problems on pre-ANSI C compilers.
  183891. */
  183892. extern PNG_EXPORT(void,png_save_uint_16)
  183893. PNGARG((png_bytep buf, unsigned int i));
  183894. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183895. /* ************************************************************************* */
  183896. /* These next functions are used internally in the code. They generally
  183897. * shouldn't be used unless you are writing code to add or replace some
  183898. * functionality in libpng. More information about most functions can
  183899. * be found in the files where the functions are located.
  183900. */
  183901. /* Various modes of operation, that are visible to applications because
  183902. * they are used for unknown chunk location.
  183903. */
  183904. #define PNG_HAVE_IHDR 0x01
  183905. #define PNG_HAVE_PLTE 0x02
  183906. #define PNG_HAVE_IDAT 0x04
  183907. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183908. #define PNG_HAVE_IEND 0x10
  183909. #if defined(PNG_INTERNAL)
  183910. /* More modes of operation. Note that after an init, mode is set to
  183911. * zero automatically when the structure is created.
  183912. */
  183913. #define PNG_HAVE_gAMA 0x20
  183914. #define PNG_HAVE_cHRM 0x40
  183915. #define PNG_HAVE_sRGB 0x80
  183916. #define PNG_HAVE_CHUNK_HEADER 0x100
  183917. #define PNG_WROTE_tIME 0x200
  183918. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183919. #define PNG_BACKGROUND_IS_GRAY 0x800
  183920. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183921. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183922. /* flags for the transformations the PNG library does on the image data */
  183923. #define PNG_BGR 0x0001
  183924. #define PNG_INTERLACE 0x0002
  183925. #define PNG_PACK 0x0004
  183926. #define PNG_SHIFT 0x0008
  183927. #define PNG_SWAP_BYTES 0x0010
  183928. #define PNG_INVERT_MONO 0x0020
  183929. #define PNG_DITHER 0x0040
  183930. #define PNG_BACKGROUND 0x0080
  183931. #define PNG_BACKGROUND_EXPAND 0x0100
  183932. /* 0x0200 unused */
  183933. #define PNG_16_TO_8 0x0400
  183934. #define PNG_RGBA 0x0800
  183935. #define PNG_EXPAND 0x1000
  183936. #define PNG_GAMMA 0x2000
  183937. #define PNG_GRAY_TO_RGB 0x4000
  183938. #define PNG_FILLER 0x8000L
  183939. #define PNG_PACKSWAP 0x10000L
  183940. #define PNG_SWAP_ALPHA 0x20000L
  183941. #define PNG_STRIP_ALPHA 0x40000L
  183942. #define PNG_INVERT_ALPHA 0x80000L
  183943. #define PNG_USER_TRANSFORM 0x100000L
  183944. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183945. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183946. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183947. /* 0x800000L Unused */
  183948. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183949. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183950. /* 0x4000000L unused */
  183951. /* 0x8000000L unused */
  183952. /* 0x10000000L unused */
  183953. /* 0x20000000L unused */
  183954. /* 0x40000000L unused */
  183955. /* flags for png_create_struct */
  183956. #define PNG_STRUCT_PNG 0x0001
  183957. #define PNG_STRUCT_INFO 0x0002
  183958. /* Scaling factor for filter heuristic weighting calculations */
  183959. #define PNG_WEIGHT_SHIFT 8
  183960. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183961. #define PNG_COST_SHIFT 3
  183962. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183963. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183964. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183965. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183966. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183967. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183968. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183969. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183970. #define PNG_FLAG_ROW_INIT 0x0040
  183971. #define PNG_FLAG_FILLER_AFTER 0x0080
  183972. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183973. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183974. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183975. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183976. #define PNG_FLAG_FREE_PLTE 0x1000
  183977. #define PNG_FLAG_FREE_TRNS 0x2000
  183978. #define PNG_FLAG_FREE_HIST 0x4000
  183979. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183980. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183981. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183982. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183983. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183984. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183985. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183986. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183987. /* 0x800000L unused */
  183988. /* 0x1000000L unused */
  183989. /* 0x2000000L unused */
  183990. /* 0x4000000L unused */
  183991. /* 0x8000000L unused */
  183992. /* 0x10000000L unused */
  183993. /* 0x20000000L unused */
  183994. /* 0x40000000L unused */
  183995. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183996. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183997. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183998. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183999. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184000. PNG_FLAG_CRC_CRITICAL_MASK)
  184001. /* save typing and make code easier to understand */
  184002. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184003. abs((int)((c1).green) - (int)((c2).green)) + \
  184004. abs((int)((c1).blue) - (int)((c2).blue)))
  184005. /* Added to libpng-1.2.6 JB */
  184006. #define PNG_ROWBYTES(pixel_bits, width) \
  184007. ((pixel_bits) >= 8 ? \
  184008. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184009. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184010. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184011. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184012. "ideal" and "delta" should be constants, normally simple
  184013. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184014. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184015. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184016. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184017. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184018. /* place to hold the signature string for a PNG file. */
  184019. #ifdef PNG_USE_GLOBAL_ARRAYS
  184020. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184021. #else
  184022. #endif
  184023. #endif /* PNG_NO_EXTERN */
  184024. /* Constant strings for known chunk types. If you need to add a chunk,
  184025. * define the name here, and add an invocation of the macro in png.c and
  184026. * wherever it's needed.
  184027. */
  184028. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184029. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184030. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184031. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184032. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184033. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184034. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184035. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184036. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184037. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184038. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184039. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184040. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184041. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184042. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184043. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184044. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184045. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184046. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184047. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184048. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184049. #ifdef PNG_USE_GLOBAL_ARRAYS
  184050. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184051. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184052. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184053. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184054. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184055. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184056. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184057. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184058. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184059. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184060. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184061. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184062. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184063. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184064. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184065. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184066. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184067. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184068. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184069. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184070. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184071. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184072. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184073. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184074. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184075. */
  184076. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184077. #undef png_read_init
  184078. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184079. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184080. #endif
  184081. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184082. png_const_charp user_png_ver, png_size_t png_struct_size));
  184083. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184084. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184085. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184086. png_info_size));
  184087. #endif
  184088. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184089. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184090. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184091. */
  184092. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184093. #undef png_write_init
  184094. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184095. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184096. #endif
  184097. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184098. png_const_charp user_png_ver, png_size_t png_struct_size));
  184099. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184100. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184101. png_info_size));
  184102. /* Allocate memory for an internal libpng struct */
  184103. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184104. /* Free memory from internal libpng struct */
  184105. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184106. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184107. malloc_fn, png_voidp mem_ptr));
  184108. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184109. png_free_ptr free_fn, png_voidp mem_ptr));
  184110. /* Free any memory that info_ptr points to and reset struct. */
  184111. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184112. png_infop info_ptr));
  184113. #ifndef PNG_1_0_X
  184114. /* Function to allocate memory for zlib. */
  184115. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184116. /* Function to free memory for zlib */
  184117. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184118. #ifdef PNG_SIZE_T
  184119. /* Function to convert a sizeof an item to png_sizeof item */
  184120. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184121. #endif
  184122. /* Next four functions are used internally as callbacks. PNGAPI is required
  184123. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184124. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184125. png_bytep data, png_size_t length));
  184126. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184127. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184128. png_bytep buffer, png_size_t length));
  184129. #endif
  184130. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184131. png_bytep data, png_size_t length));
  184132. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184133. #if !defined(PNG_NO_STDIO)
  184134. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184135. #endif
  184136. #endif
  184137. #else /* PNG_1_0_X */
  184138. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184139. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184140. png_bytep buffer, png_size_t length));
  184141. #endif
  184142. #endif /* PNG_1_0_X */
  184143. /* Reset the CRC variable */
  184144. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184145. /* Write the "data" buffer to whatever output you are using. */
  184146. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184147. png_size_t length));
  184148. /* Read data from whatever input you are using into the "data" buffer */
  184149. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184150. png_size_t length));
  184151. /* Read bytes into buf, and update png_ptr->crc */
  184152. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184153. png_size_t length));
  184154. /* Decompress data in a chunk that uses compression */
  184155. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184156. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184157. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184158. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184159. png_size_t prefix_length, png_size_t *data_length));
  184160. #endif
  184161. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184162. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184163. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184164. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184165. /* Calculate the CRC over a section of data. Note that we are only
  184166. * passing a maximum of 64K on systems that have this as a memory limit,
  184167. * since this is the maximum buffer size we can specify.
  184168. */
  184169. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184170. png_size_t length));
  184171. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184172. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184173. #endif
  184174. /* simple function to write the signature */
  184175. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184176. /* write various chunks */
  184177. /* Write the IHDR chunk, and update the png_struct with the necessary
  184178. * information.
  184179. */
  184180. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184181. png_uint_32 height,
  184182. int bit_depth, int color_type, int compression_method, int filter_method,
  184183. int interlace_method));
  184184. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184185. png_uint_32 num_pal));
  184186. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184187. png_size_t length));
  184188. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184189. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184190. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184191. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184192. #endif
  184193. #ifdef PNG_FIXED_POINT_SUPPORTED
  184194. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184195. file_gamma));
  184196. #endif
  184197. #endif
  184198. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184199. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184200. int color_type));
  184201. #endif
  184202. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184203. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184204. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184205. double white_x, double white_y,
  184206. double red_x, double red_y, double green_x, double green_y,
  184207. double blue_x, double blue_y));
  184208. #endif
  184209. #ifdef PNG_FIXED_POINT_SUPPORTED
  184210. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184211. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184212. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184213. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184214. png_fixed_point int_blue_y));
  184215. #endif
  184216. #endif
  184217. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184218. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184219. int intent));
  184220. #endif
  184221. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184222. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184223. png_charp name, int compression_type,
  184224. png_charp profile, int proflen));
  184225. /* Note to maintainer: profile should be png_bytep */
  184226. #endif
  184227. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184228. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184229. png_sPLT_tp palette));
  184230. #endif
  184231. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184232. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184233. png_color_16p values, int number, int color_type));
  184234. #endif
  184235. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184236. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184237. png_color_16p values, int color_type));
  184238. #endif
  184239. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184240. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184241. int num_hist));
  184242. #endif
  184243. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184244. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184245. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184246. png_charp key, png_charpp new_key));
  184247. #endif
  184248. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184249. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184250. png_charp text, png_size_t text_len));
  184251. #endif
  184252. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184253. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184254. png_charp text, png_size_t text_len, int compression));
  184255. #endif
  184256. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184257. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184258. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184259. png_charp text));
  184260. #endif
  184261. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184262. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184263. png_infop info_ptr, png_textp text_ptr, int num_text));
  184264. #endif
  184265. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184266. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184267. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184268. #endif
  184269. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184270. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184271. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184272. png_charp units, png_charpp params));
  184273. #endif
  184274. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184275. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184276. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184277. int unit_type));
  184278. #endif
  184279. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184280. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184281. png_timep mod_time));
  184282. #endif
  184283. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184284. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184285. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184286. int unit, double width, double height));
  184287. #else
  184288. #ifdef PNG_FIXED_POINT_SUPPORTED
  184289. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184290. int unit, png_charp width, png_charp height));
  184291. #endif
  184292. #endif
  184293. #endif
  184294. /* Called when finished processing a row of data */
  184295. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184296. /* Internal use only. Called before first row of data */
  184297. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184298. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184299. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184300. #endif
  184301. /* combine a row of data, dealing with alpha, etc. if requested */
  184302. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184303. int mask));
  184304. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184305. /* expand an interlaced row */
  184306. /* OLD pre-1.0.9 interface:
  184307. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184308. png_bytep row, int pass, png_uint_32 transformations));
  184309. */
  184310. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184311. #endif
  184312. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184313. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184314. /* grab pixels out of a row for an interlaced pass */
  184315. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184316. png_bytep row, int pass));
  184317. #endif
  184318. /* unfilter a row */
  184319. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184320. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184321. /* Choose the best filter to use and filter the row data */
  184322. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184323. png_row_infop row_info));
  184324. /* Write out the filtered row. */
  184325. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184326. png_bytep filtered_row));
  184327. /* finish a row while reading, dealing with interlacing passes, etc. */
  184328. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184329. /* initialize the row buffers, etc. */
  184330. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184331. /* optional call to update the users info structure */
  184332. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184333. png_infop info_ptr));
  184334. /* these are the functions that do the transformations */
  184335. #if defined(PNG_READ_FILLER_SUPPORTED)
  184336. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184337. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184338. #endif
  184339. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184340. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184341. png_bytep row));
  184342. #endif
  184343. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184344. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184345. png_bytep row));
  184346. #endif
  184347. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184348. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184349. png_bytep row));
  184350. #endif
  184351. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184352. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184353. png_bytep row));
  184354. #endif
  184355. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184356. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184357. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184358. png_bytep row, png_uint_32 flags));
  184359. #endif
  184360. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184361. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184362. #endif
  184363. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184364. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184365. #endif
  184366. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184367. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184368. row_info, png_bytep row));
  184369. #endif
  184370. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184371. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184372. png_bytep row));
  184373. #endif
  184374. #if defined(PNG_READ_PACK_SUPPORTED)
  184375. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184376. #endif
  184377. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184378. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184379. png_color_8p sig_bits));
  184380. #endif
  184381. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184382. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184383. #endif
  184384. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184385. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184386. #endif
  184387. #if defined(PNG_READ_DITHER_SUPPORTED)
  184388. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184389. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184390. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184391. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184392. png_colorp palette, int num_palette));
  184393. # endif
  184394. #endif
  184395. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184396. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184397. #endif
  184398. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184399. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184400. png_bytep row, png_uint_32 bit_depth));
  184401. #endif
  184402. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184403. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184404. png_color_8p bit_depth));
  184405. #endif
  184406. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184407. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184408. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184409. png_color_16p trans_values, png_color_16p background,
  184410. png_color_16p background_1,
  184411. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184412. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184413. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184414. #else
  184415. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184416. png_color_16p trans_values, png_color_16p background));
  184417. #endif
  184418. #endif
  184419. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184420. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184421. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184422. int gamma_shift));
  184423. #endif
  184424. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184425. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184426. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184427. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184428. png_bytep row, png_color_16p trans_value));
  184429. #endif
  184430. /* The following decodes the appropriate chunks, and does error correction,
  184431. * then calls the appropriate callback for the chunk if it is valid.
  184432. */
  184433. /* decode the IHDR chunk */
  184434. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184435. png_uint_32 length));
  184436. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184437. png_uint_32 length));
  184438. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184439. png_uint_32 length));
  184440. #if defined(PNG_READ_bKGD_SUPPORTED)
  184441. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184442. png_uint_32 length));
  184443. #endif
  184444. #if defined(PNG_READ_cHRM_SUPPORTED)
  184445. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184446. png_uint_32 length));
  184447. #endif
  184448. #if defined(PNG_READ_gAMA_SUPPORTED)
  184449. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184450. png_uint_32 length));
  184451. #endif
  184452. #if defined(PNG_READ_hIST_SUPPORTED)
  184453. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184454. png_uint_32 length));
  184455. #endif
  184456. #if defined(PNG_READ_iCCP_SUPPORTED)
  184457. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184458. png_uint_32 length));
  184459. #endif /* PNG_READ_iCCP_SUPPORTED */
  184460. #if defined(PNG_READ_iTXt_SUPPORTED)
  184461. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184462. png_uint_32 length));
  184463. #endif
  184464. #if defined(PNG_READ_oFFs_SUPPORTED)
  184465. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184466. png_uint_32 length));
  184467. #endif
  184468. #if defined(PNG_READ_pCAL_SUPPORTED)
  184469. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184470. png_uint_32 length));
  184471. #endif
  184472. #if defined(PNG_READ_pHYs_SUPPORTED)
  184473. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184474. png_uint_32 length));
  184475. #endif
  184476. #if defined(PNG_READ_sBIT_SUPPORTED)
  184477. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184478. png_uint_32 length));
  184479. #endif
  184480. #if defined(PNG_READ_sCAL_SUPPORTED)
  184481. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184482. png_uint_32 length));
  184483. #endif
  184484. #if defined(PNG_READ_sPLT_SUPPORTED)
  184485. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184486. png_uint_32 length));
  184487. #endif /* PNG_READ_sPLT_SUPPORTED */
  184488. #if defined(PNG_READ_sRGB_SUPPORTED)
  184489. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184490. png_uint_32 length));
  184491. #endif
  184492. #if defined(PNG_READ_tEXt_SUPPORTED)
  184493. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184494. png_uint_32 length));
  184495. #endif
  184496. #if defined(PNG_READ_tIME_SUPPORTED)
  184497. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184498. png_uint_32 length));
  184499. #endif
  184500. #if defined(PNG_READ_tRNS_SUPPORTED)
  184501. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184502. png_uint_32 length));
  184503. #endif
  184504. #if defined(PNG_READ_zTXt_SUPPORTED)
  184505. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184506. png_uint_32 length));
  184507. #endif
  184508. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184509. png_infop info_ptr, png_uint_32 length));
  184510. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184511. png_bytep chunk_name));
  184512. /* handle the transformations for reading and writing */
  184513. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184514. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184515. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184516. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184517. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184518. png_infop info_ptr));
  184519. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184520. png_infop info_ptr));
  184521. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184522. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184523. png_uint_32 length));
  184524. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184525. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184526. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184527. png_bytep buffer, png_size_t buffer_length));
  184528. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184529. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184530. png_bytep buffer, png_size_t buffer_length));
  184531. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184532. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184533. png_infop info_ptr, png_uint_32 length));
  184534. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184535. png_infop info_ptr));
  184536. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184537. png_infop info_ptr));
  184538. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184539. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184540. png_infop info_ptr));
  184541. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184542. png_infop info_ptr));
  184543. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184544. #if defined(PNG_READ_tEXt_SUPPORTED)
  184545. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184546. png_infop info_ptr, png_uint_32 length));
  184547. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184548. png_infop info_ptr));
  184549. #endif
  184550. #if defined(PNG_READ_zTXt_SUPPORTED)
  184551. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184552. png_infop info_ptr, png_uint_32 length));
  184553. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184554. png_infop info_ptr));
  184555. #endif
  184556. #if defined(PNG_READ_iTXt_SUPPORTED)
  184557. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184558. png_infop info_ptr, png_uint_32 length));
  184559. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184560. png_infop info_ptr));
  184561. #endif
  184562. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184563. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184564. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184565. png_bytep row));
  184566. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184567. png_bytep row));
  184568. #endif
  184569. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184570. #if defined(PNG_MMX_CODE_SUPPORTED)
  184571. /* png.c */ /* PRIVATE */
  184572. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184573. #endif
  184574. #endif
  184575. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184576. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184577. png_infop info_ptr));
  184578. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184579. png_infop info_ptr));
  184580. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184581. png_infop info_ptr));
  184582. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184583. png_infop info_ptr));
  184584. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184585. png_infop info_ptr));
  184586. #if defined(PNG_pHYs_SUPPORTED)
  184587. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184588. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184589. #endif /* PNG_pHYs_SUPPORTED */
  184590. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184591. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184592. #endif /* PNG_INTERNAL */
  184593. #ifdef __cplusplus
  184594. //}
  184595. #endif
  184596. #endif /* PNG_VERSION_INFO_ONLY */
  184597. /* do not put anything past this line */
  184598. #endif /* PNG_H */
  184599. /*** End of inlined file: png.h ***/
  184600. #define PNG_NO_EXTERN
  184601. /*** Start of inlined file: png.c ***/
  184602. /* png.c - location for general purpose libpng functions
  184603. *
  184604. * Last changed in libpng 1.2.21 [October 4, 2007]
  184605. * For conditions of distribution and use, see copyright notice in png.h
  184606. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184607. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184608. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184609. */
  184610. #define PNG_INTERNAL
  184611. #define PNG_NO_EXTERN
  184612. /* Generate a compiler error if there is an old png.h in the search path. */
  184613. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184614. /* Version information for C files. This had better match the version
  184615. * string defined in png.h. */
  184616. #ifdef PNG_USE_GLOBAL_ARRAYS
  184617. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184618. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184619. #ifdef PNG_READ_SUPPORTED
  184620. /* png_sig was changed to a function in version 1.0.5c */
  184621. /* Place to hold the signature string for a PNG file. */
  184622. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184623. #endif /* PNG_READ_SUPPORTED */
  184624. /* Invoke global declarations for constant strings for known chunk types */
  184625. PNG_IHDR;
  184626. PNG_IDAT;
  184627. PNG_IEND;
  184628. PNG_PLTE;
  184629. PNG_bKGD;
  184630. PNG_cHRM;
  184631. PNG_gAMA;
  184632. PNG_hIST;
  184633. PNG_iCCP;
  184634. PNG_iTXt;
  184635. PNG_oFFs;
  184636. PNG_pCAL;
  184637. PNG_sCAL;
  184638. PNG_pHYs;
  184639. PNG_sBIT;
  184640. PNG_sPLT;
  184641. PNG_sRGB;
  184642. PNG_tEXt;
  184643. PNG_tIME;
  184644. PNG_tRNS;
  184645. PNG_zTXt;
  184646. #ifdef PNG_READ_SUPPORTED
  184647. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184648. /* start of interlace block */
  184649. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184650. /* offset to next interlace block */
  184651. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184652. /* start of interlace block in the y direction */
  184653. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184654. /* offset to next interlace block in the y direction */
  184655. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184656. /* Height of interlace block. This is not currently used - if you need
  184657. * it, uncomment it here and in png.h
  184658. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184659. */
  184660. /* Mask to determine which pixels are valid in a pass */
  184661. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184662. /* Mask to determine which pixels to overwrite while displaying */
  184663. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184664. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184665. #endif /* PNG_READ_SUPPORTED */
  184666. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184667. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184668. * of the PNG file signature. If the PNG data is embedded into another
  184669. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184670. * or write any of the magic bytes before it starts on the IHDR.
  184671. */
  184672. #ifdef PNG_READ_SUPPORTED
  184673. void PNGAPI
  184674. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184675. {
  184676. if(png_ptr == NULL) return;
  184677. png_debug(1, "in png_set_sig_bytes\n");
  184678. if (num_bytes > 8)
  184679. png_error(png_ptr, "Too many bytes for PNG signature.");
  184680. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184681. }
  184682. /* Checks whether the supplied bytes match the PNG signature. We allow
  184683. * checking less than the full 8-byte signature so that those apps that
  184684. * already read the first few bytes of a file to determine the file type
  184685. * can simply check the remaining bytes for extra assurance. Returns
  184686. * an integer less than, equal to, or greater than zero if sig is found,
  184687. * respectively, to be less than, to match, or be greater than the correct
  184688. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184689. */
  184690. int PNGAPI
  184691. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184692. {
  184693. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184694. if (num_to_check > 8)
  184695. num_to_check = 8;
  184696. else if (num_to_check < 1)
  184697. return (-1);
  184698. if (start > 7)
  184699. return (-1);
  184700. if (start + num_to_check > 8)
  184701. num_to_check = 8 - start;
  184702. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184703. }
  184704. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184705. /* (Obsolete) function to check signature bytes. It does not allow one
  184706. * to check a partial signature. This function might be removed in the
  184707. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184708. */
  184709. int PNGAPI
  184710. png_check_sig(png_bytep sig, int num)
  184711. {
  184712. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184713. }
  184714. #endif
  184715. #endif /* PNG_READ_SUPPORTED */
  184716. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184717. /* Function to allocate memory for zlib and clear it to 0. */
  184718. #ifdef PNG_1_0_X
  184719. voidpf PNGAPI
  184720. #else
  184721. voidpf /* private */
  184722. #endif
  184723. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184724. {
  184725. png_voidp ptr;
  184726. png_structp p=(png_structp)png_ptr;
  184727. png_uint_32 save_flags=p->flags;
  184728. png_uint_32 num_bytes;
  184729. if(png_ptr == NULL) return (NULL);
  184730. if (items > PNG_UINT_32_MAX/size)
  184731. {
  184732. png_warning (p, "Potential overflow in png_zalloc()");
  184733. return (NULL);
  184734. }
  184735. num_bytes = (png_uint_32)items * size;
  184736. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184737. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184738. p->flags=save_flags;
  184739. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184740. if (ptr == NULL)
  184741. return ((voidpf)ptr);
  184742. if (num_bytes > (png_uint_32)0x8000L)
  184743. {
  184744. png_memset(ptr, 0, (png_size_t)0x8000L);
  184745. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184746. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184747. }
  184748. else
  184749. {
  184750. png_memset(ptr, 0, (png_size_t)num_bytes);
  184751. }
  184752. #endif
  184753. return ((voidpf)ptr);
  184754. }
  184755. /* function to free memory for zlib */
  184756. #ifdef PNG_1_0_X
  184757. void PNGAPI
  184758. #else
  184759. void /* private */
  184760. #endif
  184761. png_zfree(voidpf png_ptr, voidpf ptr)
  184762. {
  184763. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184764. }
  184765. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184766. * in case CRC is > 32 bits to leave the top bits 0.
  184767. */
  184768. void /* PRIVATE */
  184769. png_reset_crc(png_structp png_ptr)
  184770. {
  184771. png_ptr->crc = crc32(0, Z_NULL, 0);
  184772. }
  184773. /* Calculate the CRC over a section of data. We can only pass as
  184774. * much data to this routine as the largest single buffer size. We
  184775. * also check that this data will actually be used before going to the
  184776. * trouble of calculating it.
  184777. */
  184778. void /* PRIVATE */
  184779. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184780. {
  184781. int need_crc = 1;
  184782. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184783. {
  184784. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184785. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184786. need_crc = 0;
  184787. }
  184788. else /* critical */
  184789. {
  184790. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184791. need_crc = 0;
  184792. }
  184793. if (need_crc)
  184794. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184795. }
  184796. /* Allocate the memory for an info_struct for the application. We don't
  184797. * really need the png_ptr, but it could potentially be useful in the
  184798. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184799. * and png_info_init() so that applications that want to use a shared
  184800. * libpng don't have to be recompiled if png_info changes size.
  184801. */
  184802. png_infop PNGAPI
  184803. png_create_info_struct(png_structp png_ptr)
  184804. {
  184805. png_infop info_ptr;
  184806. png_debug(1, "in png_create_info_struct\n");
  184807. if(png_ptr == NULL) return (NULL);
  184808. #ifdef PNG_USER_MEM_SUPPORTED
  184809. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184810. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184811. #else
  184812. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184813. #endif
  184814. if (info_ptr != NULL)
  184815. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184816. return (info_ptr);
  184817. }
  184818. /* This function frees the memory associated with a single info struct.
  184819. * Normally, one would use either png_destroy_read_struct() or
  184820. * png_destroy_write_struct() to free an info struct, but this may be
  184821. * useful for some applications.
  184822. */
  184823. void PNGAPI
  184824. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184825. {
  184826. png_infop info_ptr = NULL;
  184827. if(png_ptr == NULL) return;
  184828. png_debug(1, "in png_destroy_info_struct\n");
  184829. if (info_ptr_ptr != NULL)
  184830. info_ptr = *info_ptr_ptr;
  184831. if (info_ptr != NULL)
  184832. {
  184833. png_info_destroy(png_ptr, info_ptr);
  184834. #ifdef PNG_USER_MEM_SUPPORTED
  184835. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184836. png_ptr->mem_ptr);
  184837. #else
  184838. png_destroy_struct((png_voidp)info_ptr);
  184839. #endif
  184840. *info_ptr_ptr = NULL;
  184841. }
  184842. }
  184843. /* Initialize the info structure. This is now an internal function (0.89)
  184844. * and applications using it are urged to use png_create_info_struct()
  184845. * instead.
  184846. */
  184847. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184848. #undef png_info_init
  184849. void PNGAPI
  184850. png_info_init(png_infop info_ptr)
  184851. {
  184852. /* We only come here via pre-1.0.12-compiled applications */
  184853. png_info_init_3(&info_ptr, 0);
  184854. }
  184855. #endif
  184856. void PNGAPI
  184857. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184858. {
  184859. png_infop info_ptr = *ptr_ptr;
  184860. if(info_ptr == NULL) return;
  184861. png_debug(1, "in png_info_init_3\n");
  184862. if(png_sizeof(png_info) > png_info_struct_size)
  184863. {
  184864. png_destroy_struct(info_ptr);
  184865. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184866. *ptr_ptr = info_ptr;
  184867. }
  184868. /* set everything to 0 */
  184869. png_memset(info_ptr, 0, png_sizeof (png_info));
  184870. }
  184871. #ifdef PNG_FREE_ME_SUPPORTED
  184872. void PNGAPI
  184873. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184874. int freer, png_uint_32 mask)
  184875. {
  184876. png_debug(1, "in png_data_freer\n");
  184877. if (png_ptr == NULL || info_ptr == NULL)
  184878. return;
  184879. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184880. info_ptr->free_me |= mask;
  184881. else if(freer == PNG_USER_WILL_FREE_DATA)
  184882. info_ptr->free_me &= ~mask;
  184883. else
  184884. png_warning(png_ptr,
  184885. "Unknown freer parameter in png_data_freer.");
  184886. }
  184887. #endif
  184888. void PNGAPI
  184889. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184890. int num)
  184891. {
  184892. png_debug(1, "in png_free_data\n");
  184893. if (png_ptr == NULL || info_ptr == NULL)
  184894. return;
  184895. #if defined(PNG_TEXT_SUPPORTED)
  184896. /* free text item num or (if num == -1) all text items */
  184897. #ifdef PNG_FREE_ME_SUPPORTED
  184898. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184899. #else
  184900. if (mask & PNG_FREE_TEXT)
  184901. #endif
  184902. {
  184903. if (num != -1)
  184904. {
  184905. if (info_ptr->text && info_ptr->text[num].key)
  184906. {
  184907. png_free(png_ptr, info_ptr->text[num].key);
  184908. info_ptr->text[num].key = NULL;
  184909. }
  184910. }
  184911. else
  184912. {
  184913. int i;
  184914. for (i = 0; i < info_ptr->num_text; i++)
  184915. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184916. png_free(png_ptr, info_ptr->text);
  184917. info_ptr->text = NULL;
  184918. info_ptr->num_text=0;
  184919. }
  184920. }
  184921. #endif
  184922. #if defined(PNG_tRNS_SUPPORTED)
  184923. /* free any tRNS entry */
  184924. #ifdef PNG_FREE_ME_SUPPORTED
  184925. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184926. #else
  184927. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184928. #endif
  184929. {
  184930. png_free(png_ptr, info_ptr->trans);
  184931. info_ptr->valid &= ~PNG_INFO_tRNS;
  184932. #ifndef PNG_FREE_ME_SUPPORTED
  184933. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184934. #endif
  184935. info_ptr->trans = NULL;
  184936. }
  184937. #endif
  184938. #if defined(PNG_sCAL_SUPPORTED)
  184939. /* free any sCAL entry */
  184940. #ifdef PNG_FREE_ME_SUPPORTED
  184941. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184942. #else
  184943. if (mask & PNG_FREE_SCAL)
  184944. #endif
  184945. {
  184946. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184947. png_free(png_ptr, info_ptr->scal_s_width);
  184948. png_free(png_ptr, info_ptr->scal_s_height);
  184949. info_ptr->scal_s_width = NULL;
  184950. info_ptr->scal_s_height = NULL;
  184951. #endif
  184952. info_ptr->valid &= ~PNG_INFO_sCAL;
  184953. }
  184954. #endif
  184955. #if defined(PNG_pCAL_SUPPORTED)
  184956. /* free any pCAL entry */
  184957. #ifdef PNG_FREE_ME_SUPPORTED
  184958. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184959. #else
  184960. if (mask & PNG_FREE_PCAL)
  184961. #endif
  184962. {
  184963. png_free(png_ptr, info_ptr->pcal_purpose);
  184964. png_free(png_ptr, info_ptr->pcal_units);
  184965. info_ptr->pcal_purpose = NULL;
  184966. info_ptr->pcal_units = NULL;
  184967. if (info_ptr->pcal_params != NULL)
  184968. {
  184969. int i;
  184970. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184971. {
  184972. png_free(png_ptr, info_ptr->pcal_params[i]);
  184973. info_ptr->pcal_params[i]=NULL;
  184974. }
  184975. png_free(png_ptr, info_ptr->pcal_params);
  184976. info_ptr->pcal_params = NULL;
  184977. }
  184978. info_ptr->valid &= ~PNG_INFO_pCAL;
  184979. }
  184980. #endif
  184981. #if defined(PNG_iCCP_SUPPORTED)
  184982. /* free any iCCP entry */
  184983. #ifdef PNG_FREE_ME_SUPPORTED
  184984. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184985. #else
  184986. if (mask & PNG_FREE_ICCP)
  184987. #endif
  184988. {
  184989. png_free(png_ptr, info_ptr->iccp_name);
  184990. png_free(png_ptr, info_ptr->iccp_profile);
  184991. info_ptr->iccp_name = NULL;
  184992. info_ptr->iccp_profile = NULL;
  184993. info_ptr->valid &= ~PNG_INFO_iCCP;
  184994. }
  184995. #endif
  184996. #if defined(PNG_sPLT_SUPPORTED)
  184997. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184998. #ifdef PNG_FREE_ME_SUPPORTED
  184999. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185000. #else
  185001. if (mask & PNG_FREE_SPLT)
  185002. #endif
  185003. {
  185004. if (num != -1)
  185005. {
  185006. if(info_ptr->splt_palettes)
  185007. {
  185008. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185009. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185010. info_ptr->splt_palettes[num].name = NULL;
  185011. info_ptr->splt_palettes[num].entries = NULL;
  185012. }
  185013. }
  185014. else
  185015. {
  185016. if(info_ptr->splt_palettes_num)
  185017. {
  185018. int i;
  185019. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185020. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185021. png_free(png_ptr, info_ptr->splt_palettes);
  185022. info_ptr->splt_palettes = NULL;
  185023. info_ptr->splt_palettes_num = 0;
  185024. }
  185025. info_ptr->valid &= ~PNG_INFO_sPLT;
  185026. }
  185027. }
  185028. #endif
  185029. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185030. if(png_ptr->unknown_chunk.data)
  185031. {
  185032. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185033. png_ptr->unknown_chunk.data = NULL;
  185034. }
  185035. #ifdef PNG_FREE_ME_SUPPORTED
  185036. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185037. #else
  185038. if (mask & PNG_FREE_UNKN)
  185039. #endif
  185040. {
  185041. if (num != -1)
  185042. {
  185043. if(info_ptr->unknown_chunks)
  185044. {
  185045. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185046. info_ptr->unknown_chunks[num].data = NULL;
  185047. }
  185048. }
  185049. else
  185050. {
  185051. int i;
  185052. if(info_ptr->unknown_chunks_num)
  185053. {
  185054. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185055. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185056. png_free(png_ptr, info_ptr->unknown_chunks);
  185057. info_ptr->unknown_chunks = NULL;
  185058. info_ptr->unknown_chunks_num = 0;
  185059. }
  185060. }
  185061. }
  185062. #endif
  185063. #if defined(PNG_hIST_SUPPORTED)
  185064. /* free any hIST entry */
  185065. #ifdef PNG_FREE_ME_SUPPORTED
  185066. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185067. #else
  185068. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185069. #endif
  185070. {
  185071. png_free(png_ptr, info_ptr->hist);
  185072. info_ptr->hist = NULL;
  185073. info_ptr->valid &= ~PNG_INFO_hIST;
  185074. #ifndef PNG_FREE_ME_SUPPORTED
  185075. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185076. #endif
  185077. }
  185078. #endif
  185079. /* free any PLTE entry that was internally allocated */
  185080. #ifdef PNG_FREE_ME_SUPPORTED
  185081. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185082. #else
  185083. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185084. #endif
  185085. {
  185086. png_zfree(png_ptr, info_ptr->palette);
  185087. info_ptr->palette = NULL;
  185088. info_ptr->valid &= ~PNG_INFO_PLTE;
  185089. #ifndef PNG_FREE_ME_SUPPORTED
  185090. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185091. #endif
  185092. info_ptr->num_palette = 0;
  185093. }
  185094. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185095. /* free any image bits attached to the info structure */
  185096. #ifdef PNG_FREE_ME_SUPPORTED
  185097. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185098. #else
  185099. if (mask & PNG_FREE_ROWS)
  185100. #endif
  185101. {
  185102. if(info_ptr->row_pointers)
  185103. {
  185104. int row;
  185105. for (row = 0; row < (int)info_ptr->height; row++)
  185106. {
  185107. png_free(png_ptr, info_ptr->row_pointers[row]);
  185108. info_ptr->row_pointers[row]=NULL;
  185109. }
  185110. png_free(png_ptr, info_ptr->row_pointers);
  185111. info_ptr->row_pointers=NULL;
  185112. }
  185113. info_ptr->valid &= ~PNG_INFO_IDAT;
  185114. }
  185115. #endif
  185116. #ifdef PNG_FREE_ME_SUPPORTED
  185117. if(num == -1)
  185118. info_ptr->free_me &= ~mask;
  185119. else
  185120. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185121. #endif
  185122. }
  185123. /* This is an internal routine to free any memory that the info struct is
  185124. * pointing to before re-using it or freeing the struct itself. Recall
  185125. * that png_free() checks for NULL pointers for us.
  185126. */
  185127. void /* PRIVATE */
  185128. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185129. {
  185130. png_debug(1, "in png_info_destroy\n");
  185131. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185132. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185133. if (png_ptr->num_chunk_list)
  185134. {
  185135. png_free(png_ptr, png_ptr->chunk_list);
  185136. png_ptr->chunk_list=NULL;
  185137. png_ptr->num_chunk_list=0;
  185138. }
  185139. #endif
  185140. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185141. }
  185142. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185143. /* This function returns a pointer to the io_ptr associated with the user
  185144. * functions. The application should free any memory associated with this
  185145. * pointer before png_write_destroy() or png_read_destroy() are called.
  185146. */
  185147. png_voidp PNGAPI
  185148. png_get_io_ptr(png_structp png_ptr)
  185149. {
  185150. if(png_ptr == NULL) return (NULL);
  185151. return (png_ptr->io_ptr);
  185152. }
  185153. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185154. #if !defined(PNG_NO_STDIO)
  185155. /* Initialize the default input/output functions for the PNG file. If you
  185156. * use your own read or write routines, you can call either png_set_read_fn()
  185157. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185158. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185159. * necessarily available.
  185160. */
  185161. void PNGAPI
  185162. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185163. {
  185164. png_debug(1, "in png_init_io\n");
  185165. if(png_ptr == NULL) return;
  185166. png_ptr->io_ptr = (png_voidp)fp;
  185167. }
  185168. #endif
  185169. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185170. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185171. * a "Creation Time" or other text-based time string.
  185172. */
  185173. png_charp PNGAPI
  185174. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185175. {
  185176. static PNG_CONST char short_months[12][4] =
  185177. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185178. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185179. if(png_ptr == NULL) return (NULL);
  185180. if (png_ptr->time_buffer == NULL)
  185181. {
  185182. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185183. png_sizeof(char)));
  185184. }
  185185. #if defined(_WIN32_WCE)
  185186. {
  185187. wchar_t time_buf[29];
  185188. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185189. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185190. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185191. ptime->second % 61);
  185192. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185193. NULL, NULL);
  185194. }
  185195. #else
  185196. #ifdef USE_FAR_KEYWORD
  185197. {
  185198. char near_time_buf[29];
  185199. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185200. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185201. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185202. ptime->second % 61);
  185203. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185204. 29*png_sizeof(char));
  185205. }
  185206. #else
  185207. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185208. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185209. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185210. ptime->second % 61);
  185211. #endif
  185212. #endif /* _WIN32_WCE */
  185213. return ((png_charp)png_ptr->time_buffer);
  185214. }
  185215. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185216. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185217. png_charp PNGAPI
  185218. png_get_copyright(png_structp png_ptr)
  185219. {
  185220. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185221. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185222. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185223. Copyright (c) 1996-1997 Andreas Dilger\n\
  185224. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185225. }
  185226. /* The following return the library version as a short string in the
  185227. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185228. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185229. * is defined in png.h.
  185230. * Note: now there is no difference between png_get_libpng_ver() and
  185231. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185232. * it is guaranteed that png.c uses the correct version of png.h.
  185233. */
  185234. png_charp PNGAPI
  185235. png_get_libpng_ver(png_structp png_ptr)
  185236. {
  185237. /* Version of *.c files used when building libpng */
  185238. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185239. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185240. }
  185241. png_charp PNGAPI
  185242. png_get_header_ver(png_structp png_ptr)
  185243. {
  185244. /* Version of *.h files used when building libpng */
  185245. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185246. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185247. }
  185248. png_charp PNGAPI
  185249. png_get_header_version(png_structp png_ptr)
  185250. {
  185251. /* Returns longer string containing both version and date */
  185252. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185253. return ((png_charp) PNG_HEADER_VERSION_STRING
  185254. #ifndef PNG_READ_SUPPORTED
  185255. " (NO READ SUPPORT)"
  185256. #endif
  185257. "\n");
  185258. }
  185259. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185260. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185261. int PNGAPI
  185262. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185263. {
  185264. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185265. int i;
  185266. png_bytep p;
  185267. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185268. return 0;
  185269. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185270. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185271. if (!png_memcmp(chunk_name, p, 4))
  185272. return ((int)*(p+4));
  185273. return 0;
  185274. }
  185275. #endif
  185276. /* This function, added to libpng-1.0.6g, is untested. */
  185277. int PNGAPI
  185278. png_reset_zstream(png_structp png_ptr)
  185279. {
  185280. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185281. return (inflateReset(&png_ptr->zstream));
  185282. }
  185283. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185284. /* This function was added to libpng-1.0.7 */
  185285. png_uint_32 PNGAPI
  185286. png_access_version_number(void)
  185287. {
  185288. /* Version of *.c files used when building libpng */
  185289. return((png_uint_32) PNG_LIBPNG_VER);
  185290. }
  185291. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185292. #if !defined(PNG_1_0_X)
  185293. /* this function was added to libpng 1.2.0 */
  185294. int PNGAPI
  185295. png_mmx_support(void)
  185296. {
  185297. /* obsolete, to be removed from libpng-1.4.0 */
  185298. return -1;
  185299. }
  185300. #endif /* PNG_1_0_X */
  185301. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185302. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185303. #ifdef PNG_SIZE_T
  185304. /* Added at libpng version 1.2.6 */
  185305. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185306. png_size_t PNGAPI
  185307. png_convert_size(size_t size)
  185308. {
  185309. if (size > (png_size_t)-1)
  185310. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185311. return ((png_size_t)size);
  185312. }
  185313. #endif /* PNG_SIZE_T */
  185314. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185315. /*** End of inlined file: png.c ***/
  185316. /*** Start of inlined file: pngerror.c ***/
  185317. /* pngerror.c - stub functions for i/o and memory allocation
  185318. *
  185319. * Last changed in libpng 1.2.20 October 4, 2007
  185320. * For conditions of distribution and use, see copyright notice in png.h
  185321. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185322. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185323. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185324. *
  185325. * This file provides a location for all error handling. Users who
  185326. * need special error handling are expected to write replacement functions
  185327. * and use png_set_error_fn() to use those functions. See the instructions
  185328. * at each function.
  185329. */
  185330. #define PNG_INTERNAL
  185331. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185332. static void /* PRIVATE */
  185333. png_default_error PNGARG((png_structp png_ptr,
  185334. png_const_charp error_message));
  185335. #ifndef PNG_NO_WARNINGS
  185336. static void /* PRIVATE */
  185337. png_default_warning PNGARG((png_structp png_ptr,
  185338. png_const_charp warning_message));
  185339. #endif /* PNG_NO_WARNINGS */
  185340. /* This function is called whenever there is a fatal error. This function
  185341. * should not be changed. If there is a need to handle errors differently,
  185342. * you should supply a replacement error function and use png_set_error_fn()
  185343. * to replace the error function at run-time.
  185344. */
  185345. #ifndef PNG_NO_ERROR_TEXT
  185346. void PNGAPI
  185347. png_error(png_structp png_ptr, png_const_charp error_message)
  185348. {
  185349. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185350. char msg[16];
  185351. if (png_ptr != NULL)
  185352. {
  185353. if (png_ptr->flags&
  185354. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185355. {
  185356. if (*error_message == '#')
  185357. {
  185358. int offset;
  185359. for (offset=1; offset<15; offset++)
  185360. if (*(error_message+offset) == ' ')
  185361. break;
  185362. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185363. {
  185364. int i;
  185365. for (i=0; i<offset-1; i++)
  185366. msg[i]=error_message[i+1];
  185367. msg[i]='\0';
  185368. error_message=msg;
  185369. }
  185370. else
  185371. error_message+=offset;
  185372. }
  185373. else
  185374. {
  185375. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185376. {
  185377. msg[0]='0';
  185378. msg[1]='\0';
  185379. error_message=msg;
  185380. }
  185381. }
  185382. }
  185383. }
  185384. #endif
  185385. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185386. (*(png_ptr->error_fn))(png_ptr, error_message);
  185387. /* If the custom handler doesn't exist, or if it returns,
  185388. use the default handler, which will not return. */
  185389. png_default_error(png_ptr, error_message);
  185390. }
  185391. #else
  185392. void PNGAPI
  185393. png_err(png_structp png_ptr)
  185394. {
  185395. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185396. (*(png_ptr->error_fn))(png_ptr, '\0');
  185397. /* If the custom handler doesn't exist, or if it returns,
  185398. use the default handler, which will not return. */
  185399. png_default_error(png_ptr, '\0');
  185400. }
  185401. #endif /* PNG_NO_ERROR_TEXT */
  185402. #ifndef PNG_NO_WARNINGS
  185403. /* This function is called whenever there is a non-fatal error. This function
  185404. * should not be changed. If there is a need to handle warnings differently,
  185405. * you should supply a replacement warning function and use
  185406. * png_set_error_fn() to replace the warning function at run-time.
  185407. */
  185408. void PNGAPI
  185409. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185410. {
  185411. int offset = 0;
  185412. if (png_ptr != NULL)
  185413. {
  185414. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185415. if (png_ptr->flags&
  185416. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185417. #endif
  185418. {
  185419. if (*warning_message == '#')
  185420. {
  185421. for (offset=1; offset<15; offset++)
  185422. if (*(warning_message+offset) == ' ')
  185423. break;
  185424. }
  185425. }
  185426. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185427. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185428. }
  185429. else
  185430. png_default_warning(png_ptr, warning_message+offset);
  185431. }
  185432. #endif /* PNG_NO_WARNINGS */
  185433. /* These utilities are used internally to build an error message that relates
  185434. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185435. * this is used to prefix the message. The message is limited in length
  185436. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185437. * if the character is invalid.
  185438. */
  185439. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185440. /*static PNG_CONST char png_digit[16] = {
  185441. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185442. 'A', 'B', 'C', 'D', 'E', 'F'
  185443. };*/
  185444. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185445. static void /* PRIVATE */
  185446. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185447. error_message)
  185448. {
  185449. int iout = 0, iin = 0;
  185450. while (iin < 4)
  185451. {
  185452. int c = png_ptr->chunk_name[iin++];
  185453. if (isnonalpha(c))
  185454. {
  185455. buffer[iout++] = '[';
  185456. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185457. buffer[iout++] = png_digit[c & 0x0f];
  185458. buffer[iout++] = ']';
  185459. }
  185460. else
  185461. {
  185462. buffer[iout++] = (png_byte)c;
  185463. }
  185464. }
  185465. if (error_message == NULL)
  185466. buffer[iout] = 0;
  185467. else
  185468. {
  185469. buffer[iout++] = ':';
  185470. buffer[iout++] = ' ';
  185471. png_strncpy(buffer+iout, error_message, 63);
  185472. buffer[iout+63] = 0;
  185473. }
  185474. }
  185475. #ifdef PNG_READ_SUPPORTED
  185476. void PNGAPI
  185477. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185478. {
  185479. char msg[18+64];
  185480. if (png_ptr == NULL)
  185481. png_error(png_ptr, error_message);
  185482. else
  185483. {
  185484. png_format_buffer(png_ptr, msg, error_message);
  185485. png_error(png_ptr, msg);
  185486. }
  185487. }
  185488. #endif /* PNG_READ_SUPPORTED */
  185489. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185490. #ifndef PNG_NO_WARNINGS
  185491. void PNGAPI
  185492. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185493. {
  185494. char msg[18+64];
  185495. if (png_ptr == NULL)
  185496. png_warning(png_ptr, warning_message);
  185497. else
  185498. {
  185499. png_format_buffer(png_ptr, msg, warning_message);
  185500. png_warning(png_ptr, msg);
  185501. }
  185502. }
  185503. #endif /* PNG_NO_WARNINGS */
  185504. /* This is the default error handling function. Note that replacements for
  185505. * this function MUST NOT RETURN, or the program will likely crash. This
  185506. * function is used by default, or if the program supplies NULL for the
  185507. * error function pointer in png_set_error_fn().
  185508. */
  185509. static void /* PRIVATE */
  185510. png_default_error(png_structp, png_const_charp error_message)
  185511. {
  185512. #ifndef PNG_NO_CONSOLE_IO
  185513. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185514. if (*error_message == '#')
  185515. {
  185516. int offset;
  185517. char error_number[16];
  185518. for (offset=0; offset<15; offset++)
  185519. {
  185520. error_number[offset] = *(error_message+offset+1);
  185521. if (*(error_message+offset) == ' ')
  185522. break;
  185523. }
  185524. if((offset > 1) && (offset < 15))
  185525. {
  185526. error_number[offset-1]='\0';
  185527. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185528. error_message+offset);
  185529. }
  185530. else
  185531. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185532. }
  185533. else
  185534. #endif
  185535. fprintf(stderr, "libpng error: %s\n", error_message);
  185536. #endif
  185537. #ifdef PNG_SETJMP_SUPPORTED
  185538. if (png_ptr)
  185539. {
  185540. # ifdef USE_FAR_KEYWORD
  185541. {
  185542. jmp_buf jmpbuf;
  185543. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185544. longjmp(jmpbuf, 1);
  185545. }
  185546. # else
  185547. longjmp(png_ptr->jmpbuf, 1);
  185548. # endif
  185549. }
  185550. #else
  185551. PNG_ABORT();
  185552. #endif
  185553. #ifdef PNG_NO_CONSOLE_IO
  185554. error_message = error_message; /* make compiler happy */
  185555. #endif
  185556. }
  185557. #ifndef PNG_NO_WARNINGS
  185558. /* This function is called when there is a warning, but the library thinks
  185559. * it can continue anyway. Replacement functions don't have to do anything
  185560. * here if you don't want them to. In the default configuration, png_ptr is
  185561. * not used, but it is passed in case it may be useful.
  185562. */
  185563. static void /* PRIVATE */
  185564. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185565. {
  185566. #ifndef PNG_NO_CONSOLE_IO
  185567. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185568. if (*warning_message == '#')
  185569. {
  185570. int offset;
  185571. char warning_number[16];
  185572. for (offset=0; offset<15; offset++)
  185573. {
  185574. warning_number[offset]=*(warning_message+offset+1);
  185575. if (*(warning_message+offset) == ' ')
  185576. break;
  185577. }
  185578. if((offset > 1) && (offset < 15))
  185579. {
  185580. warning_number[offset-1]='\0';
  185581. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185582. warning_message+offset);
  185583. }
  185584. else
  185585. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185586. }
  185587. else
  185588. # endif
  185589. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185590. #else
  185591. warning_message = warning_message; /* make compiler happy */
  185592. #endif
  185593. png_ptr = png_ptr; /* make compiler happy */
  185594. }
  185595. #endif /* PNG_NO_WARNINGS */
  185596. /* This function is called when the application wants to use another method
  185597. * of handling errors and warnings. Note that the error function MUST NOT
  185598. * return to the calling routine or serious problems will occur. The return
  185599. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185600. */
  185601. void PNGAPI
  185602. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185603. png_error_ptr error_fn, png_error_ptr warning_fn)
  185604. {
  185605. if (png_ptr == NULL)
  185606. return;
  185607. png_ptr->error_ptr = error_ptr;
  185608. png_ptr->error_fn = error_fn;
  185609. png_ptr->warning_fn = warning_fn;
  185610. }
  185611. /* This function returns a pointer to the error_ptr associated with the user
  185612. * functions. The application should free any memory associated with this
  185613. * pointer before png_write_destroy and png_read_destroy are called.
  185614. */
  185615. png_voidp PNGAPI
  185616. png_get_error_ptr(png_structp png_ptr)
  185617. {
  185618. if (png_ptr == NULL)
  185619. return NULL;
  185620. return ((png_voidp)png_ptr->error_ptr);
  185621. }
  185622. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185623. void PNGAPI
  185624. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185625. {
  185626. if(png_ptr != NULL)
  185627. {
  185628. png_ptr->flags &=
  185629. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185630. }
  185631. }
  185632. #endif
  185633. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185634. /*** End of inlined file: pngerror.c ***/
  185635. /*** Start of inlined file: pngget.c ***/
  185636. /* pngget.c - retrieval of values from info struct
  185637. *
  185638. * Last changed in libpng 1.2.15 January 5, 2007
  185639. * For conditions of distribution and use, see copyright notice in png.h
  185640. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185641. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185642. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185643. */
  185644. #define PNG_INTERNAL
  185645. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185646. png_uint_32 PNGAPI
  185647. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185648. {
  185649. if (png_ptr != NULL && info_ptr != NULL)
  185650. return(info_ptr->valid & flag);
  185651. else
  185652. return(0);
  185653. }
  185654. png_uint_32 PNGAPI
  185655. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185656. {
  185657. if (png_ptr != NULL && info_ptr != NULL)
  185658. return(info_ptr->rowbytes);
  185659. else
  185660. return(0);
  185661. }
  185662. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185663. png_bytepp PNGAPI
  185664. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185665. {
  185666. if (png_ptr != NULL && info_ptr != NULL)
  185667. return(info_ptr->row_pointers);
  185668. else
  185669. return(0);
  185670. }
  185671. #endif
  185672. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185673. /* easy access to info, added in libpng-0.99 */
  185674. png_uint_32 PNGAPI
  185675. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185676. {
  185677. if (png_ptr != NULL && info_ptr != NULL)
  185678. {
  185679. return info_ptr->width;
  185680. }
  185681. return (0);
  185682. }
  185683. png_uint_32 PNGAPI
  185684. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185685. {
  185686. if (png_ptr != NULL && info_ptr != NULL)
  185687. {
  185688. return info_ptr->height;
  185689. }
  185690. return (0);
  185691. }
  185692. png_byte PNGAPI
  185693. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185694. {
  185695. if (png_ptr != NULL && info_ptr != NULL)
  185696. {
  185697. return info_ptr->bit_depth;
  185698. }
  185699. return (0);
  185700. }
  185701. png_byte PNGAPI
  185702. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185703. {
  185704. if (png_ptr != NULL && info_ptr != NULL)
  185705. {
  185706. return info_ptr->color_type;
  185707. }
  185708. return (0);
  185709. }
  185710. png_byte PNGAPI
  185711. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185712. {
  185713. if (png_ptr != NULL && info_ptr != NULL)
  185714. {
  185715. return info_ptr->filter_type;
  185716. }
  185717. return (0);
  185718. }
  185719. png_byte PNGAPI
  185720. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185721. {
  185722. if (png_ptr != NULL && info_ptr != NULL)
  185723. {
  185724. return info_ptr->interlace_type;
  185725. }
  185726. return (0);
  185727. }
  185728. png_byte PNGAPI
  185729. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185730. {
  185731. if (png_ptr != NULL && info_ptr != NULL)
  185732. {
  185733. return info_ptr->compression_type;
  185734. }
  185735. return (0);
  185736. }
  185737. png_uint_32 PNGAPI
  185738. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185739. {
  185740. if (png_ptr != NULL && info_ptr != NULL)
  185741. #if defined(PNG_pHYs_SUPPORTED)
  185742. if (info_ptr->valid & PNG_INFO_pHYs)
  185743. {
  185744. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185745. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185746. return (0);
  185747. else return (info_ptr->x_pixels_per_unit);
  185748. }
  185749. #else
  185750. return (0);
  185751. #endif
  185752. return (0);
  185753. }
  185754. png_uint_32 PNGAPI
  185755. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185756. {
  185757. if (png_ptr != NULL && info_ptr != NULL)
  185758. #if defined(PNG_pHYs_SUPPORTED)
  185759. if (info_ptr->valid & PNG_INFO_pHYs)
  185760. {
  185761. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185762. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185763. return (0);
  185764. else return (info_ptr->y_pixels_per_unit);
  185765. }
  185766. #else
  185767. return (0);
  185768. #endif
  185769. return (0);
  185770. }
  185771. png_uint_32 PNGAPI
  185772. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185773. {
  185774. if (png_ptr != NULL && info_ptr != NULL)
  185775. #if defined(PNG_pHYs_SUPPORTED)
  185776. if (info_ptr->valid & PNG_INFO_pHYs)
  185777. {
  185778. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185779. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185780. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185781. return (0);
  185782. else return (info_ptr->x_pixels_per_unit);
  185783. }
  185784. #else
  185785. return (0);
  185786. #endif
  185787. return (0);
  185788. }
  185789. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185790. float PNGAPI
  185791. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185792. {
  185793. if (png_ptr != NULL && info_ptr != NULL)
  185794. #if defined(PNG_pHYs_SUPPORTED)
  185795. if (info_ptr->valid & PNG_INFO_pHYs)
  185796. {
  185797. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185798. if (info_ptr->x_pixels_per_unit == 0)
  185799. return ((float)0.0);
  185800. else
  185801. return ((float)((float)info_ptr->y_pixels_per_unit
  185802. /(float)info_ptr->x_pixels_per_unit));
  185803. }
  185804. #else
  185805. return (0.0);
  185806. #endif
  185807. return ((float)0.0);
  185808. }
  185809. #endif
  185810. png_int_32 PNGAPI
  185811. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185812. {
  185813. if (png_ptr != NULL && info_ptr != NULL)
  185814. #if defined(PNG_oFFs_SUPPORTED)
  185815. if (info_ptr->valid & PNG_INFO_oFFs)
  185816. {
  185817. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185818. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185819. return (0);
  185820. else return (info_ptr->x_offset);
  185821. }
  185822. #else
  185823. return (0);
  185824. #endif
  185825. return (0);
  185826. }
  185827. png_int_32 PNGAPI
  185828. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185829. {
  185830. if (png_ptr != NULL && info_ptr != NULL)
  185831. #if defined(PNG_oFFs_SUPPORTED)
  185832. if (info_ptr->valid & PNG_INFO_oFFs)
  185833. {
  185834. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185835. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185836. return (0);
  185837. else return (info_ptr->y_offset);
  185838. }
  185839. #else
  185840. return (0);
  185841. #endif
  185842. return (0);
  185843. }
  185844. png_int_32 PNGAPI
  185845. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185846. {
  185847. if (png_ptr != NULL && info_ptr != NULL)
  185848. #if defined(PNG_oFFs_SUPPORTED)
  185849. if (info_ptr->valid & PNG_INFO_oFFs)
  185850. {
  185851. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185852. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185853. return (0);
  185854. else return (info_ptr->x_offset);
  185855. }
  185856. #else
  185857. return (0);
  185858. #endif
  185859. return (0);
  185860. }
  185861. png_int_32 PNGAPI
  185862. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185863. {
  185864. if (png_ptr != NULL && info_ptr != NULL)
  185865. #if defined(PNG_oFFs_SUPPORTED)
  185866. if (info_ptr->valid & PNG_INFO_oFFs)
  185867. {
  185868. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185869. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185870. return (0);
  185871. else return (info_ptr->y_offset);
  185872. }
  185873. #else
  185874. return (0);
  185875. #endif
  185876. return (0);
  185877. }
  185878. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185879. png_uint_32 PNGAPI
  185880. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185881. {
  185882. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185883. *.0254 +.5));
  185884. }
  185885. png_uint_32 PNGAPI
  185886. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185887. {
  185888. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185889. *.0254 +.5));
  185890. }
  185891. png_uint_32 PNGAPI
  185892. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185893. {
  185894. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185895. *.0254 +.5));
  185896. }
  185897. float PNGAPI
  185898. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185899. {
  185900. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185901. *.00003937);
  185902. }
  185903. float PNGAPI
  185904. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185905. {
  185906. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185907. *.00003937);
  185908. }
  185909. #if defined(PNG_pHYs_SUPPORTED)
  185910. png_uint_32 PNGAPI
  185911. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185912. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185913. {
  185914. png_uint_32 retval = 0;
  185915. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185916. {
  185917. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185918. if (res_x != NULL)
  185919. {
  185920. *res_x = info_ptr->x_pixels_per_unit;
  185921. retval |= PNG_INFO_pHYs;
  185922. }
  185923. if (res_y != NULL)
  185924. {
  185925. *res_y = info_ptr->y_pixels_per_unit;
  185926. retval |= PNG_INFO_pHYs;
  185927. }
  185928. if (unit_type != NULL)
  185929. {
  185930. *unit_type = (int)info_ptr->phys_unit_type;
  185931. retval |= PNG_INFO_pHYs;
  185932. if(*unit_type == 1)
  185933. {
  185934. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185935. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185936. }
  185937. }
  185938. }
  185939. return (retval);
  185940. }
  185941. #endif /* PNG_pHYs_SUPPORTED */
  185942. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185943. /* png_get_channels really belongs in here, too, but it's been around longer */
  185944. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185945. png_byte PNGAPI
  185946. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185947. {
  185948. if (png_ptr != NULL && info_ptr != NULL)
  185949. return(info_ptr->channels);
  185950. else
  185951. return (0);
  185952. }
  185953. png_bytep PNGAPI
  185954. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185955. {
  185956. if (png_ptr != NULL && info_ptr != NULL)
  185957. return(info_ptr->signature);
  185958. else
  185959. return (NULL);
  185960. }
  185961. #if defined(PNG_bKGD_SUPPORTED)
  185962. png_uint_32 PNGAPI
  185963. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185964. png_color_16p *background)
  185965. {
  185966. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185967. && background != NULL)
  185968. {
  185969. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185970. *background = &(info_ptr->background);
  185971. return (PNG_INFO_bKGD);
  185972. }
  185973. return (0);
  185974. }
  185975. #endif
  185976. #if defined(PNG_cHRM_SUPPORTED)
  185977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185978. png_uint_32 PNGAPI
  185979. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185980. double *white_x, double *white_y, double *red_x, double *red_y,
  185981. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185982. {
  185983. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185984. {
  185985. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185986. if (white_x != NULL)
  185987. *white_x = (double)info_ptr->x_white;
  185988. if (white_y != NULL)
  185989. *white_y = (double)info_ptr->y_white;
  185990. if (red_x != NULL)
  185991. *red_x = (double)info_ptr->x_red;
  185992. if (red_y != NULL)
  185993. *red_y = (double)info_ptr->y_red;
  185994. if (green_x != NULL)
  185995. *green_x = (double)info_ptr->x_green;
  185996. if (green_y != NULL)
  185997. *green_y = (double)info_ptr->y_green;
  185998. if (blue_x != NULL)
  185999. *blue_x = (double)info_ptr->x_blue;
  186000. if (blue_y != NULL)
  186001. *blue_y = (double)info_ptr->y_blue;
  186002. return (PNG_INFO_cHRM);
  186003. }
  186004. return (0);
  186005. }
  186006. #endif
  186007. #ifdef PNG_FIXED_POINT_SUPPORTED
  186008. png_uint_32 PNGAPI
  186009. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186010. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186011. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186012. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186013. {
  186014. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186015. {
  186016. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186017. if (white_x != NULL)
  186018. *white_x = info_ptr->int_x_white;
  186019. if (white_y != NULL)
  186020. *white_y = info_ptr->int_y_white;
  186021. if (red_x != NULL)
  186022. *red_x = info_ptr->int_x_red;
  186023. if (red_y != NULL)
  186024. *red_y = info_ptr->int_y_red;
  186025. if (green_x != NULL)
  186026. *green_x = info_ptr->int_x_green;
  186027. if (green_y != NULL)
  186028. *green_y = info_ptr->int_y_green;
  186029. if (blue_x != NULL)
  186030. *blue_x = info_ptr->int_x_blue;
  186031. if (blue_y != NULL)
  186032. *blue_y = info_ptr->int_y_blue;
  186033. return (PNG_INFO_cHRM);
  186034. }
  186035. return (0);
  186036. }
  186037. #endif
  186038. #endif
  186039. #if defined(PNG_gAMA_SUPPORTED)
  186040. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186041. png_uint_32 PNGAPI
  186042. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186043. {
  186044. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186045. && file_gamma != NULL)
  186046. {
  186047. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186048. *file_gamma = (double)info_ptr->gamma;
  186049. return (PNG_INFO_gAMA);
  186050. }
  186051. return (0);
  186052. }
  186053. #endif
  186054. #ifdef PNG_FIXED_POINT_SUPPORTED
  186055. png_uint_32 PNGAPI
  186056. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186057. png_fixed_point *int_file_gamma)
  186058. {
  186059. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186060. && int_file_gamma != NULL)
  186061. {
  186062. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186063. *int_file_gamma = info_ptr->int_gamma;
  186064. return (PNG_INFO_gAMA);
  186065. }
  186066. return (0);
  186067. }
  186068. #endif
  186069. #endif
  186070. #if defined(PNG_sRGB_SUPPORTED)
  186071. png_uint_32 PNGAPI
  186072. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186073. {
  186074. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186075. && file_srgb_intent != NULL)
  186076. {
  186077. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186078. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186079. return (PNG_INFO_sRGB);
  186080. }
  186081. return (0);
  186082. }
  186083. #endif
  186084. #if defined(PNG_iCCP_SUPPORTED)
  186085. png_uint_32 PNGAPI
  186086. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186087. png_charpp name, int *compression_type,
  186088. png_charpp profile, png_uint_32 *proflen)
  186089. {
  186090. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186091. && name != NULL && profile != NULL && proflen != NULL)
  186092. {
  186093. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186094. *name = info_ptr->iccp_name;
  186095. *profile = info_ptr->iccp_profile;
  186096. /* compression_type is a dummy so the API won't have to change
  186097. if we introduce multiple compression types later. */
  186098. *proflen = (int)info_ptr->iccp_proflen;
  186099. *compression_type = (int)info_ptr->iccp_compression;
  186100. return (PNG_INFO_iCCP);
  186101. }
  186102. return (0);
  186103. }
  186104. #endif
  186105. #if defined(PNG_sPLT_SUPPORTED)
  186106. png_uint_32 PNGAPI
  186107. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186108. png_sPLT_tpp spalettes)
  186109. {
  186110. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186111. {
  186112. *spalettes = info_ptr->splt_palettes;
  186113. return ((png_uint_32)info_ptr->splt_palettes_num);
  186114. }
  186115. return (0);
  186116. }
  186117. #endif
  186118. #if defined(PNG_hIST_SUPPORTED)
  186119. png_uint_32 PNGAPI
  186120. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186121. {
  186122. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186123. && hist != NULL)
  186124. {
  186125. png_debug1(1, "in %s retrieval function\n", "hIST");
  186126. *hist = info_ptr->hist;
  186127. return (PNG_INFO_hIST);
  186128. }
  186129. return (0);
  186130. }
  186131. #endif
  186132. png_uint_32 PNGAPI
  186133. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186134. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186135. int *color_type, int *interlace_type, int *compression_type,
  186136. int *filter_type)
  186137. {
  186138. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186139. bit_depth != NULL && color_type != NULL)
  186140. {
  186141. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186142. *width = info_ptr->width;
  186143. *height = info_ptr->height;
  186144. *bit_depth = info_ptr->bit_depth;
  186145. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186146. png_error(png_ptr, "Invalid bit depth");
  186147. *color_type = info_ptr->color_type;
  186148. if (info_ptr->color_type > 6)
  186149. png_error(png_ptr, "Invalid color type");
  186150. if (compression_type != NULL)
  186151. *compression_type = info_ptr->compression_type;
  186152. if (filter_type != NULL)
  186153. *filter_type = info_ptr->filter_type;
  186154. if (interlace_type != NULL)
  186155. *interlace_type = info_ptr->interlace_type;
  186156. /* check for potential overflow of rowbytes */
  186157. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186158. png_error(png_ptr, "Invalid image width");
  186159. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186160. png_error(png_ptr, "Invalid image height");
  186161. if (info_ptr->width > (PNG_UINT_32_MAX
  186162. >> 3) /* 8-byte RGBA pixels */
  186163. - 64 /* bigrowbuf hack */
  186164. - 1 /* filter byte */
  186165. - 7*8 /* rounding of width to multiple of 8 pixels */
  186166. - 8) /* extra max_pixel_depth pad */
  186167. {
  186168. png_warning(png_ptr,
  186169. "Width too large for libpng to process image data.");
  186170. }
  186171. return (1);
  186172. }
  186173. return (0);
  186174. }
  186175. #if defined(PNG_oFFs_SUPPORTED)
  186176. png_uint_32 PNGAPI
  186177. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186178. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186179. {
  186180. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186181. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186182. {
  186183. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186184. *offset_x = info_ptr->x_offset;
  186185. *offset_y = info_ptr->y_offset;
  186186. *unit_type = (int)info_ptr->offset_unit_type;
  186187. return (PNG_INFO_oFFs);
  186188. }
  186189. return (0);
  186190. }
  186191. #endif
  186192. #if defined(PNG_pCAL_SUPPORTED)
  186193. png_uint_32 PNGAPI
  186194. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186195. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186196. png_charp *units, png_charpp *params)
  186197. {
  186198. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186199. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186200. nparams != NULL && units != NULL && params != NULL)
  186201. {
  186202. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186203. *purpose = info_ptr->pcal_purpose;
  186204. *X0 = info_ptr->pcal_X0;
  186205. *X1 = info_ptr->pcal_X1;
  186206. *type = (int)info_ptr->pcal_type;
  186207. *nparams = (int)info_ptr->pcal_nparams;
  186208. *units = info_ptr->pcal_units;
  186209. *params = info_ptr->pcal_params;
  186210. return (PNG_INFO_pCAL);
  186211. }
  186212. return (0);
  186213. }
  186214. #endif
  186215. #if defined(PNG_sCAL_SUPPORTED)
  186216. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186217. png_uint_32 PNGAPI
  186218. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186219. int *unit, double *width, double *height)
  186220. {
  186221. if (png_ptr != NULL && info_ptr != NULL &&
  186222. (info_ptr->valid & PNG_INFO_sCAL))
  186223. {
  186224. *unit = info_ptr->scal_unit;
  186225. *width = info_ptr->scal_pixel_width;
  186226. *height = info_ptr->scal_pixel_height;
  186227. return (PNG_INFO_sCAL);
  186228. }
  186229. return(0);
  186230. }
  186231. #else
  186232. #ifdef PNG_FIXED_POINT_SUPPORTED
  186233. png_uint_32 PNGAPI
  186234. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186235. int *unit, png_charpp width, png_charpp height)
  186236. {
  186237. if (png_ptr != NULL && info_ptr != NULL &&
  186238. (info_ptr->valid & PNG_INFO_sCAL))
  186239. {
  186240. *unit = info_ptr->scal_unit;
  186241. *width = info_ptr->scal_s_width;
  186242. *height = info_ptr->scal_s_height;
  186243. return (PNG_INFO_sCAL);
  186244. }
  186245. return(0);
  186246. }
  186247. #endif
  186248. #endif
  186249. #endif
  186250. #if defined(PNG_pHYs_SUPPORTED)
  186251. png_uint_32 PNGAPI
  186252. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186253. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186254. {
  186255. png_uint_32 retval = 0;
  186256. if (png_ptr != NULL && info_ptr != NULL &&
  186257. (info_ptr->valid & PNG_INFO_pHYs))
  186258. {
  186259. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186260. if (res_x != NULL)
  186261. {
  186262. *res_x = info_ptr->x_pixels_per_unit;
  186263. retval |= PNG_INFO_pHYs;
  186264. }
  186265. if (res_y != NULL)
  186266. {
  186267. *res_y = info_ptr->y_pixels_per_unit;
  186268. retval |= PNG_INFO_pHYs;
  186269. }
  186270. if (unit_type != NULL)
  186271. {
  186272. *unit_type = (int)info_ptr->phys_unit_type;
  186273. retval |= PNG_INFO_pHYs;
  186274. }
  186275. }
  186276. return (retval);
  186277. }
  186278. #endif
  186279. png_uint_32 PNGAPI
  186280. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186281. int *num_palette)
  186282. {
  186283. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186284. && palette != NULL)
  186285. {
  186286. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186287. *palette = info_ptr->palette;
  186288. *num_palette = info_ptr->num_palette;
  186289. png_debug1(3, "num_palette = %d\n", *num_palette);
  186290. return (PNG_INFO_PLTE);
  186291. }
  186292. return (0);
  186293. }
  186294. #if defined(PNG_sBIT_SUPPORTED)
  186295. png_uint_32 PNGAPI
  186296. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186297. {
  186298. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186299. && sig_bit != NULL)
  186300. {
  186301. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186302. *sig_bit = &(info_ptr->sig_bit);
  186303. return (PNG_INFO_sBIT);
  186304. }
  186305. return (0);
  186306. }
  186307. #endif
  186308. #if defined(PNG_TEXT_SUPPORTED)
  186309. png_uint_32 PNGAPI
  186310. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186311. int *num_text)
  186312. {
  186313. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186314. {
  186315. png_debug1(1, "in %s retrieval function\n",
  186316. (png_ptr->chunk_name[0] == '\0' ? "text"
  186317. : (png_const_charp)png_ptr->chunk_name));
  186318. if (text_ptr != NULL)
  186319. *text_ptr = info_ptr->text;
  186320. if (num_text != NULL)
  186321. *num_text = info_ptr->num_text;
  186322. return ((png_uint_32)info_ptr->num_text);
  186323. }
  186324. if (num_text != NULL)
  186325. *num_text = 0;
  186326. return(0);
  186327. }
  186328. #endif
  186329. #if defined(PNG_tIME_SUPPORTED)
  186330. png_uint_32 PNGAPI
  186331. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186332. {
  186333. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186334. && mod_time != NULL)
  186335. {
  186336. png_debug1(1, "in %s retrieval function\n", "tIME");
  186337. *mod_time = &(info_ptr->mod_time);
  186338. return (PNG_INFO_tIME);
  186339. }
  186340. return (0);
  186341. }
  186342. #endif
  186343. #if defined(PNG_tRNS_SUPPORTED)
  186344. png_uint_32 PNGAPI
  186345. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186346. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186347. {
  186348. png_uint_32 retval = 0;
  186349. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186350. {
  186351. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186352. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186353. {
  186354. if (trans != NULL)
  186355. {
  186356. *trans = info_ptr->trans;
  186357. retval |= PNG_INFO_tRNS;
  186358. }
  186359. if (trans_values != NULL)
  186360. *trans_values = &(info_ptr->trans_values);
  186361. }
  186362. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186363. {
  186364. if (trans_values != NULL)
  186365. {
  186366. *trans_values = &(info_ptr->trans_values);
  186367. retval |= PNG_INFO_tRNS;
  186368. }
  186369. if(trans != NULL)
  186370. *trans = NULL;
  186371. }
  186372. if(num_trans != NULL)
  186373. {
  186374. *num_trans = info_ptr->num_trans;
  186375. retval |= PNG_INFO_tRNS;
  186376. }
  186377. }
  186378. return (retval);
  186379. }
  186380. #endif
  186381. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186382. png_uint_32 PNGAPI
  186383. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186384. png_unknown_chunkpp unknowns)
  186385. {
  186386. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186387. {
  186388. *unknowns = info_ptr->unknown_chunks;
  186389. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186390. }
  186391. return (0);
  186392. }
  186393. #endif
  186394. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186395. png_byte PNGAPI
  186396. png_get_rgb_to_gray_status (png_structp png_ptr)
  186397. {
  186398. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186399. }
  186400. #endif
  186401. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186402. png_voidp PNGAPI
  186403. png_get_user_chunk_ptr(png_structp png_ptr)
  186404. {
  186405. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186406. }
  186407. #endif
  186408. #ifdef PNG_WRITE_SUPPORTED
  186409. png_uint_32 PNGAPI
  186410. png_get_compression_buffer_size(png_structp png_ptr)
  186411. {
  186412. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186413. }
  186414. #endif
  186415. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186416. #ifndef PNG_1_0_X
  186417. /* this function was added to libpng 1.2.0 and should exist by default */
  186418. png_uint_32 PNGAPI
  186419. png_get_asm_flags (png_structp png_ptr)
  186420. {
  186421. /* obsolete, to be removed from libpng-1.4.0 */
  186422. return (png_ptr? 0L: 0L);
  186423. }
  186424. /* this function was added to libpng 1.2.0 and should exist by default */
  186425. png_uint_32 PNGAPI
  186426. png_get_asm_flagmask (int flag_select)
  186427. {
  186428. /* obsolete, to be removed from libpng-1.4.0 */
  186429. flag_select=flag_select;
  186430. return 0L;
  186431. }
  186432. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186433. /* this function was added to libpng 1.2.0 */
  186434. png_uint_32 PNGAPI
  186435. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186436. {
  186437. /* obsolete, to be removed from libpng-1.4.0 */
  186438. flag_select=flag_select;
  186439. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186440. return 0L;
  186441. }
  186442. /* this function was added to libpng 1.2.0 */
  186443. png_byte PNGAPI
  186444. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186445. {
  186446. /* obsolete, to be removed from libpng-1.4.0 */
  186447. return (png_ptr? 0: 0);
  186448. }
  186449. /* this function was added to libpng 1.2.0 */
  186450. png_uint_32 PNGAPI
  186451. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186452. {
  186453. /* obsolete, to be removed from libpng-1.4.0 */
  186454. return (png_ptr? 0L: 0L);
  186455. }
  186456. #endif /* ?PNG_1_0_X */
  186457. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186458. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186459. /* these functions were added to libpng 1.2.6 */
  186460. png_uint_32 PNGAPI
  186461. png_get_user_width_max (png_structp png_ptr)
  186462. {
  186463. return (png_ptr? png_ptr->user_width_max : 0);
  186464. }
  186465. png_uint_32 PNGAPI
  186466. png_get_user_height_max (png_structp png_ptr)
  186467. {
  186468. return (png_ptr? png_ptr->user_height_max : 0);
  186469. }
  186470. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186471. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186472. /*** End of inlined file: pngget.c ***/
  186473. /*** Start of inlined file: pngmem.c ***/
  186474. /* pngmem.c - stub functions for memory allocation
  186475. *
  186476. * Last changed in libpng 1.2.13 November 13, 2006
  186477. * For conditions of distribution and use, see copyright notice in png.h
  186478. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186479. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186480. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186481. *
  186482. * This file provides a location for all memory allocation. Users who
  186483. * need special memory handling are expected to supply replacement
  186484. * functions for png_malloc() and png_free(), and to use
  186485. * png_create_read_struct_2() and png_create_write_struct_2() to
  186486. * identify the replacement functions.
  186487. */
  186488. #define PNG_INTERNAL
  186489. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186490. /* Borland DOS special memory handler */
  186491. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186492. /* if you change this, be sure to change the one in png.h also */
  186493. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186494. by a single call to calloc() if this is thought to improve performance. */
  186495. png_voidp /* PRIVATE */
  186496. png_create_struct(int type)
  186497. {
  186498. #ifdef PNG_USER_MEM_SUPPORTED
  186499. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186500. }
  186501. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186502. png_voidp /* PRIVATE */
  186503. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186504. {
  186505. #endif /* PNG_USER_MEM_SUPPORTED */
  186506. png_size_t size;
  186507. png_voidp struct_ptr;
  186508. if (type == PNG_STRUCT_INFO)
  186509. size = png_sizeof(png_info);
  186510. else if (type == PNG_STRUCT_PNG)
  186511. size = png_sizeof(png_struct);
  186512. else
  186513. return (png_get_copyright(NULL));
  186514. #ifdef PNG_USER_MEM_SUPPORTED
  186515. if(malloc_fn != NULL)
  186516. {
  186517. png_struct dummy_struct;
  186518. png_structp png_ptr = &dummy_struct;
  186519. png_ptr->mem_ptr=mem_ptr;
  186520. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186521. }
  186522. else
  186523. #endif /* PNG_USER_MEM_SUPPORTED */
  186524. struct_ptr = (png_voidp)farmalloc(size);
  186525. if (struct_ptr != NULL)
  186526. png_memset(struct_ptr, 0, size);
  186527. return (struct_ptr);
  186528. }
  186529. /* Free memory allocated by a png_create_struct() call */
  186530. void /* PRIVATE */
  186531. png_destroy_struct(png_voidp struct_ptr)
  186532. {
  186533. #ifdef PNG_USER_MEM_SUPPORTED
  186534. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186535. }
  186536. /* Free memory allocated by a png_create_struct() call */
  186537. void /* PRIVATE */
  186538. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186539. png_voidp mem_ptr)
  186540. {
  186541. #endif
  186542. if (struct_ptr != NULL)
  186543. {
  186544. #ifdef PNG_USER_MEM_SUPPORTED
  186545. if(free_fn != NULL)
  186546. {
  186547. png_struct dummy_struct;
  186548. png_structp png_ptr = &dummy_struct;
  186549. png_ptr->mem_ptr=mem_ptr;
  186550. (*(free_fn))(png_ptr, struct_ptr);
  186551. return;
  186552. }
  186553. #endif /* PNG_USER_MEM_SUPPORTED */
  186554. farfree (struct_ptr);
  186555. }
  186556. }
  186557. /* Allocate memory. For reasonable files, size should never exceed
  186558. * 64K. However, zlib may allocate more then 64K if you don't tell
  186559. * it not to. See zconf.h and png.h for more information. zlib does
  186560. * need to allocate exactly 64K, so whatever you call here must
  186561. * have the ability to do that.
  186562. *
  186563. * Borland seems to have a problem in DOS mode for exactly 64K.
  186564. * It gives you a segment with an offset of 8 (perhaps to store its
  186565. * memory stuff). zlib doesn't like this at all, so we have to
  186566. * detect and deal with it. This code should not be needed in
  186567. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186568. * been updated by Alexander Lehmann for version 0.89 to waste less
  186569. * memory.
  186570. *
  186571. * Note that we can't use png_size_t for the "size" declaration,
  186572. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186573. * result, we would be truncating potentially larger memory requests
  186574. * (which should cause a fatal error) and introducing major problems.
  186575. */
  186576. png_voidp PNGAPI
  186577. png_malloc(png_structp png_ptr, png_uint_32 size)
  186578. {
  186579. png_voidp ret;
  186580. if (png_ptr == NULL || size == 0)
  186581. return (NULL);
  186582. #ifdef PNG_USER_MEM_SUPPORTED
  186583. if(png_ptr->malloc_fn != NULL)
  186584. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186585. else
  186586. ret = (png_malloc_default(png_ptr, size));
  186587. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186588. png_error(png_ptr, "Out of memory!");
  186589. return (ret);
  186590. }
  186591. png_voidp PNGAPI
  186592. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186593. {
  186594. png_voidp ret;
  186595. #endif /* PNG_USER_MEM_SUPPORTED */
  186596. if (png_ptr == NULL || size == 0)
  186597. return (NULL);
  186598. #ifdef PNG_MAX_MALLOC_64K
  186599. if (size > (png_uint_32)65536L)
  186600. {
  186601. png_warning(png_ptr, "Cannot Allocate > 64K");
  186602. ret = NULL;
  186603. }
  186604. else
  186605. #endif
  186606. if (size != (size_t)size)
  186607. ret = NULL;
  186608. else if (size == (png_uint_32)65536L)
  186609. {
  186610. if (png_ptr->offset_table == NULL)
  186611. {
  186612. /* try to see if we need to do any of this fancy stuff */
  186613. ret = farmalloc(size);
  186614. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186615. {
  186616. int num_blocks;
  186617. png_uint_32 total_size;
  186618. png_bytep table;
  186619. int i;
  186620. png_byte huge * hptr;
  186621. if (ret != NULL)
  186622. {
  186623. farfree(ret);
  186624. ret = NULL;
  186625. }
  186626. if(png_ptr->zlib_window_bits > 14)
  186627. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186628. else
  186629. num_blocks = 1;
  186630. if (png_ptr->zlib_mem_level >= 7)
  186631. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186632. else
  186633. num_blocks++;
  186634. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186635. table = farmalloc(total_size);
  186636. if (table == NULL)
  186637. {
  186638. #ifndef PNG_USER_MEM_SUPPORTED
  186639. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186640. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186641. else
  186642. png_warning(png_ptr, "Out Of Memory.");
  186643. #endif
  186644. return (NULL);
  186645. }
  186646. if ((png_size_t)table & 0xfff0)
  186647. {
  186648. #ifndef PNG_USER_MEM_SUPPORTED
  186649. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186650. png_error(png_ptr,
  186651. "Farmalloc didn't return normalized pointer");
  186652. else
  186653. png_warning(png_ptr,
  186654. "Farmalloc didn't return normalized pointer");
  186655. #endif
  186656. return (NULL);
  186657. }
  186658. png_ptr->offset_table = table;
  186659. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186660. png_sizeof (png_bytep));
  186661. if (png_ptr->offset_table_ptr == NULL)
  186662. {
  186663. #ifndef PNG_USER_MEM_SUPPORTED
  186664. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186665. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186666. else
  186667. png_warning(png_ptr, "Out Of memory.");
  186668. #endif
  186669. return (NULL);
  186670. }
  186671. hptr = (png_byte huge *)table;
  186672. if ((png_size_t)hptr & 0xf)
  186673. {
  186674. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186675. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186676. }
  186677. for (i = 0; i < num_blocks; i++)
  186678. {
  186679. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186680. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186681. }
  186682. png_ptr->offset_table_number = num_blocks;
  186683. png_ptr->offset_table_count = 0;
  186684. png_ptr->offset_table_count_free = 0;
  186685. }
  186686. }
  186687. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186688. {
  186689. #ifndef PNG_USER_MEM_SUPPORTED
  186690. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186691. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186692. else
  186693. png_warning(png_ptr, "Out of Memory.");
  186694. #endif
  186695. return (NULL);
  186696. }
  186697. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186698. }
  186699. else
  186700. ret = farmalloc(size);
  186701. #ifndef PNG_USER_MEM_SUPPORTED
  186702. if (ret == NULL)
  186703. {
  186704. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186705. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186706. else
  186707. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186708. }
  186709. #endif
  186710. return (ret);
  186711. }
  186712. /* free a pointer allocated by png_malloc(). In the default
  186713. configuration, png_ptr is not used, but is passed in case it
  186714. is needed. If ptr is NULL, return without taking any action. */
  186715. void PNGAPI
  186716. png_free(png_structp png_ptr, png_voidp ptr)
  186717. {
  186718. if (png_ptr == NULL || ptr == NULL)
  186719. return;
  186720. #ifdef PNG_USER_MEM_SUPPORTED
  186721. if (png_ptr->free_fn != NULL)
  186722. {
  186723. (*(png_ptr->free_fn))(png_ptr, ptr);
  186724. return;
  186725. }
  186726. else png_free_default(png_ptr, ptr);
  186727. }
  186728. void PNGAPI
  186729. png_free_default(png_structp png_ptr, png_voidp ptr)
  186730. {
  186731. #endif /* PNG_USER_MEM_SUPPORTED */
  186732. if(png_ptr == NULL) return;
  186733. if (png_ptr->offset_table != NULL)
  186734. {
  186735. int i;
  186736. for (i = 0; i < png_ptr->offset_table_count; i++)
  186737. {
  186738. if (ptr == png_ptr->offset_table_ptr[i])
  186739. {
  186740. ptr = NULL;
  186741. png_ptr->offset_table_count_free++;
  186742. break;
  186743. }
  186744. }
  186745. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186746. {
  186747. farfree(png_ptr->offset_table);
  186748. farfree(png_ptr->offset_table_ptr);
  186749. png_ptr->offset_table = NULL;
  186750. png_ptr->offset_table_ptr = NULL;
  186751. }
  186752. }
  186753. if (ptr != NULL)
  186754. {
  186755. farfree(ptr);
  186756. }
  186757. }
  186758. #else /* Not the Borland DOS special memory handler */
  186759. /* Allocate memory for a png_struct or a png_info. The malloc and
  186760. memset can be replaced by a single call to calloc() if this is thought
  186761. to improve performance noticably. */
  186762. png_voidp /* PRIVATE */
  186763. png_create_struct(int type)
  186764. {
  186765. #ifdef PNG_USER_MEM_SUPPORTED
  186766. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186767. }
  186768. /* Allocate memory for a png_struct or a png_info. The malloc and
  186769. memset can be replaced by a single call to calloc() if this is thought
  186770. to improve performance noticably. */
  186771. png_voidp /* PRIVATE */
  186772. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186773. {
  186774. #endif /* PNG_USER_MEM_SUPPORTED */
  186775. png_size_t size;
  186776. png_voidp struct_ptr;
  186777. if (type == PNG_STRUCT_INFO)
  186778. size = png_sizeof(png_info);
  186779. else if (type == PNG_STRUCT_PNG)
  186780. size = png_sizeof(png_struct);
  186781. else
  186782. return (NULL);
  186783. #ifdef PNG_USER_MEM_SUPPORTED
  186784. if(malloc_fn != NULL)
  186785. {
  186786. png_struct dummy_struct;
  186787. png_structp png_ptr = &dummy_struct;
  186788. png_ptr->mem_ptr=mem_ptr;
  186789. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186790. if (struct_ptr != NULL)
  186791. png_memset(struct_ptr, 0, size);
  186792. return (struct_ptr);
  186793. }
  186794. #endif /* PNG_USER_MEM_SUPPORTED */
  186795. #if defined(__TURBOC__) && !defined(__FLAT__)
  186796. struct_ptr = (png_voidp)farmalloc(size);
  186797. #else
  186798. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186799. struct_ptr = (png_voidp)halloc(size,1);
  186800. # else
  186801. struct_ptr = (png_voidp)malloc(size);
  186802. # endif
  186803. #endif
  186804. if (struct_ptr != NULL)
  186805. png_memset(struct_ptr, 0, size);
  186806. return (struct_ptr);
  186807. }
  186808. /* Free memory allocated by a png_create_struct() call */
  186809. void /* PRIVATE */
  186810. png_destroy_struct(png_voidp struct_ptr)
  186811. {
  186812. #ifdef PNG_USER_MEM_SUPPORTED
  186813. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186814. }
  186815. /* Free memory allocated by a png_create_struct() call */
  186816. void /* PRIVATE */
  186817. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186818. png_voidp mem_ptr)
  186819. {
  186820. #endif /* PNG_USER_MEM_SUPPORTED */
  186821. if (struct_ptr != NULL)
  186822. {
  186823. #ifdef PNG_USER_MEM_SUPPORTED
  186824. if(free_fn != NULL)
  186825. {
  186826. png_struct dummy_struct;
  186827. png_structp png_ptr = &dummy_struct;
  186828. png_ptr->mem_ptr=mem_ptr;
  186829. (*(free_fn))(png_ptr, struct_ptr);
  186830. return;
  186831. }
  186832. #endif /* PNG_USER_MEM_SUPPORTED */
  186833. #if defined(__TURBOC__) && !defined(__FLAT__)
  186834. farfree(struct_ptr);
  186835. #else
  186836. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186837. hfree(struct_ptr);
  186838. # else
  186839. free(struct_ptr);
  186840. # endif
  186841. #endif
  186842. }
  186843. }
  186844. /* Allocate memory. For reasonable files, size should never exceed
  186845. 64K. However, zlib may allocate more then 64K if you don't tell
  186846. it not to. See zconf.h and png.h for more information. zlib does
  186847. need to allocate exactly 64K, so whatever you call here must
  186848. have the ability to do that. */
  186849. png_voidp PNGAPI
  186850. png_malloc(png_structp png_ptr, png_uint_32 size)
  186851. {
  186852. png_voidp ret;
  186853. #ifdef PNG_USER_MEM_SUPPORTED
  186854. if (png_ptr == NULL || size == 0)
  186855. return (NULL);
  186856. if(png_ptr->malloc_fn != NULL)
  186857. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186858. else
  186859. ret = (png_malloc_default(png_ptr, size));
  186860. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186861. png_error(png_ptr, "Out of Memory!");
  186862. return (ret);
  186863. }
  186864. png_voidp PNGAPI
  186865. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186866. {
  186867. png_voidp ret;
  186868. #endif /* PNG_USER_MEM_SUPPORTED */
  186869. if (png_ptr == NULL || size == 0)
  186870. return (NULL);
  186871. #ifdef PNG_MAX_MALLOC_64K
  186872. if (size > (png_uint_32)65536L)
  186873. {
  186874. #ifndef PNG_USER_MEM_SUPPORTED
  186875. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186876. png_error(png_ptr, "Cannot Allocate > 64K");
  186877. else
  186878. #endif
  186879. return NULL;
  186880. }
  186881. #endif
  186882. /* Check for overflow */
  186883. #if defined(__TURBOC__) && !defined(__FLAT__)
  186884. if (size != (unsigned long)size)
  186885. ret = NULL;
  186886. else
  186887. ret = farmalloc(size);
  186888. #else
  186889. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186890. if (size != (unsigned long)size)
  186891. ret = NULL;
  186892. else
  186893. ret = halloc(size, 1);
  186894. # else
  186895. if (size != (size_t)size)
  186896. ret = NULL;
  186897. else
  186898. ret = malloc((size_t)size);
  186899. # endif
  186900. #endif
  186901. #ifndef PNG_USER_MEM_SUPPORTED
  186902. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186903. png_error(png_ptr, "Out of Memory");
  186904. #endif
  186905. return (ret);
  186906. }
  186907. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186908. without taking any action. */
  186909. void PNGAPI
  186910. png_free(png_structp png_ptr, png_voidp ptr)
  186911. {
  186912. if (png_ptr == NULL || ptr == NULL)
  186913. return;
  186914. #ifdef PNG_USER_MEM_SUPPORTED
  186915. if (png_ptr->free_fn != NULL)
  186916. {
  186917. (*(png_ptr->free_fn))(png_ptr, ptr);
  186918. return;
  186919. }
  186920. else png_free_default(png_ptr, ptr);
  186921. }
  186922. void PNGAPI
  186923. png_free_default(png_structp png_ptr, png_voidp ptr)
  186924. {
  186925. if (png_ptr == NULL || ptr == NULL)
  186926. return;
  186927. #endif /* PNG_USER_MEM_SUPPORTED */
  186928. #if defined(__TURBOC__) && !defined(__FLAT__)
  186929. farfree(ptr);
  186930. #else
  186931. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186932. hfree(ptr);
  186933. # else
  186934. free(ptr);
  186935. # endif
  186936. #endif
  186937. }
  186938. #endif /* Not Borland DOS special memory handler */
  186939. #if defined(PNG_1_0_X)
  186940. # define png_malloc_warn png_malloc
  186941. #else
  186942. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186943. * function will set up png_malloc() to issue a png_warning and return NULL
  186944. * instead of issuing a png_error, if it fails to allocate the requested
  186945. * memory.
  186946. */
  186947. png_voidp PNGAPI
  186948. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186949. {
  186950. png_voidp ptr;
  186951. png_uint_32 save_flags;
  186952. if(png_ptr == NULL) return (NULL);
  186953. save_flags=png_ptr->flags;
  186954. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186955. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186956. png_ptr->flags=save_flags;
  186957. return(ptr);
  186958. }
  186959. #endif
  186960. png_voidp PNGAPI
  186961. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186962. png_uint_32 length)
  186963. {
  186964. png_size_t size;
  186965. size = (png_size_t)length;
  186966. if ((png_uint_32)size != length)
  186967. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186968. return(png_memcpy (s1, s2, size));
  186969. }
  186970. png_voidp PNGAPI
  186971. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186972. png_uint_32 length)
  186973. {
  186974. png_size_t size;
  186975. size = (png_size_t)length;
  186976. if ((png_uint_32)size != length)
  186977. png_error(png_ptr,"Overflow in png_memset_check.");
  186978. return (png_memset (s1, value, size));
  186979. }
  186980. #ifdef PNG_USER_MEM_SUPPORTED
  186981. /* This function is called when the application wants to use another method
  186982. * of allocating and freeing memory.
  186983. */
  186984. void PNGAPI
  186985. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186986. malloc_fn, png_free_ptr free_fn)
  186987. {
  186988. if(png_ptr != NULL) {
  186989. png_ptr->mem_ptr = mem_ptr;
  186990. png_ptr->malloc_fn = malloc_fn;
  186991. png_ptr->free_fn = free_fn;
  186992. }
  186993. }
  186994. /* This function returns a pointer to the mem_ptr associated with the user
  186995. * functions. The application should free any memory associated with this
  186996. * pointer before png_write_destroy and png_read_destroy are called.
  186997. */
  186998. png_voidp PNGAPI
  186999. png_get_mem_ptr(png_structp png_ptr)
  187000. {
  187001. if(png_ptr == NULL) return (NULL);
  187002. return ((png_voidp)png_ptr->mem_ptr);
  187003. }
  187004. #endif /* PNG_USER_MEM_SUPPORTED */
  187005. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187006. /*** End of inlined file: pngmem.c ***/
  187007. /*** Start of inlined file: pngread.c ***/
  187008. /* pngread.c - read a PNG file
  187009. *
  187010. * Last changed in libpng 1.2.20 September 7, 2007
  187011. * For conditions of distribution and use, see copyright notice in png.h
  187012. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187013. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187014. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187015. *
  187016. * This file contains routines that an application calls directly to
  187017. * read a PNG file or stream.
  187018. */
  187019. #define PNG_INTERNAL
  187020. #if defined(PNG_READ_SUPPORTED)
  187021. /* Create a PNG structure for reading, and allocate any memory needed. */
  187022. png_structp PNGAPI
  187023. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187024. png_error_ptr error_fn, png_error_ptr warn_fn)
  187025. {
  187026. #ifdef PNG_USER_MEM_SUPPORTED
  187027. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187028. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187029. }
  187030. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187031. png_structp PNGAPI
  187032. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187033. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187034. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187035. {
  187036. #endif /* PNG_USER_MEM_SUPPORTED */
  187037. png_structp png_ptr;
  187038. #ifdef PNG_SETJMP_SUPPORTED
  187039. #ifdef USE_FAR_KEYWORD
  187040. jmp_buf jmpbuf;
  187041. #endif
  187042. #endif
  187043. int i;
  187044. png_debug(1, "in png_create_read_struct\n");
  187045. #ifdef PNG_USER_MEM_SUPPORTED
  187046. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187047. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187048. #else
  187049. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187050. #endif
  187051. if (png_ptr == NULL)
  187052. return (NULL);
  187053. /* added at libpng-1.2.6 */
  187054. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187055. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187056. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187057. #endif
  187058. #ifdef PNG_SETJMP_SUPPORTED
  187059. #ifdef USE_FAR_KEYWORD
  187060. if (setjmp(jmpbuf))
  187061. #else
  187062. if (setjmp(png_ptr->jmpbuf))
  187063. #endif
  187064. {
  187065. png_free(png_ptr, png_ptr->zbuf);
  187066. png_ptr->zbuf=NULL;
  187067. #ifdef PNG_USER_MEM_SUPPORTED
  187068. png_destroy_struct_2((png_voidp)png_ptr,
  187069. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187070. #else
  187071. png_destroy_struct((png_voidp)png_ptr);
  187072. #endif
  187073. return (NULL);
  187074. }
  187075. #ifdef USE_FAR_KEYWORD
  187076. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187077. #endif
  187078. #endif
  187079. #ifdef PNG_USER_MEM_SUPPORTED
  187080. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187081. #endif
  187082. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187083. i=0;
  187084. do
  187085. {
  187086. if(user_png_ver[i] != png_libpng_ver[i])
  187087. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187088. } while (png_libpng_ver[i++]);
  187089. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187090. {
  187091. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187092. * we must recompile any applications that use any older library version.
  187093. * For versions after libpng 1.0, we will be compatible, so we need
  187094. * only check the first digit.
  187095. */
  187096. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187097. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187098. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187099. {
  187100. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187101. char msg[80];
  187102. if (user_png_ver)
  187103. {
  187104. png_snprintf(msg, 80,
  187105. "Application was compiled with png.h from libpng-%.20s",
  187106. user_png_ver);
  187107. png_warning(png_ptr, msg);
  187108. }
  187109. png_snprintf(msg, 80,
  187110. "Application is running with png.c from libpng-%.20s",
  187111. png_libpng_ver);
  187112. png_warning(png_ptr, msg);
  187113. #endif
  187114. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187115. png_ptr->flags=0;
  187116. #endif
  187117. png_error(png_ptr,
  187118. "Incompatible libpng version in application and library");
  187119. }
  187120. }
  187121. /* initialize zbuf - compression buffer */
  187122. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187123. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187124. (png_uint_32)png_ptr->zbuf_size);
  187125. png_ptr->zstream.zalloc = png_zalloc;
  187126. png_ptr->zstream.zfree = png_zfree;
  187127. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187128. switch (inflateInit(&png_ptr->zstream))
  187129. {
  187130. case Z_OK: /* Do nothing */ break;
  187131. case Z_MEM_ERROR:
  187132. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187133. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187134. default: png_error(png_ptr, "Unknown zlib error");
  187135. }
  187136. png_ptr->zstream.next_out = png_ptr->zbuf;
  187137. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187138. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187139. #ifdef PNG_SETJMP_SUPPORTED
  187140. /* Applications that neglect to set up their own setjmp() and then encounter
  187141. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187142. abort instead of returning. */
  187143. #ifdef USE_FAR_KEYWORD
  187144. if (setjmp(jmpbuf))
  187145. PNG_ABORT();
  187146. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187147. #else
  187148. if (setjmp(png_ptr->jmpbuf))
  187149. PNG_ABORT();
  187150. #endif
  187151. #endif
  187152. return (png_ptr);
  187153. }
  187154. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187155. /* Initialize PNG structure for reading, and allocate any memory needed.
  187156. This interface is deprecated in favour of the png_create_read_struct(),
  187157. and it will disappear as of libpng-1.3.0. */
  187158. #undef png_read_init
  187159. void PNGAPI
  187160. png_read_init(png_structp png_ptr)
  187161. {
  187162. /* We only come here via pre-1.0.7-compiled applications */
  187163. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187164. }
  187165. void PNGAPI
  187166. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187167. png_size_t png_struct_size, png_size_t png_info_size)
  187168. {
  187169. /* We only come here via pre-1.0.12-compiled applications */
  187170. if(png_ptr == NULL) return;
  187171. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187172. if(png_sizeof(png_struct) > png_struct_size ||
  187173. png_sizeof(png_info) > png_info_size)
  187174. {
  187175. char msg[80];
  187176. png_ptr->warning_fn=NULL;
  187177. if (user_png_ver)
  187178. {
  187179. png_snprintf(msg, 80,
  187180. "Application was compiled with png.h from libpng-%.20s",
  187181. user_png_ver);
  187182. png_warning(png_ptr, msg);
  187183. }
  187184. png_snprintf(msg, 80,
  187185. "Application is running with png.c from libpng-%.20s",
  187186. png_libpng_ver);
  187187. png_warning(png_ptr, msg);
  187188. }
  187189. #endif
  187190. if(png_sizeof(png_struct) > png_struct_size)
  187191. {
  187192. png_ptr->error_fn=NULL;
  187193. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187194. png_ptr->flags=0;
  187195. #endif
  187196. png_error(png_ptr,
  187197. "The png struct allocated by the application for reading is too small.");
  187198. }
  187199. if(png_sizeof(png_info) > png_info_size)
  187200. {
  187201. png_ptr->error_fn=NULL;
  187202. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187203. png_ptr->flags=0;
  187204. #endif
  187205. png_error(png_ptr,
  187206. "The info struct allocated by application for reading is too small.");
  187207. }
  187208. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187209. }
  187210. #endif /* PNG_1_0_X || PNG_1_2_X */
  187211. void PNGAPI
  187212. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187213. png_size_t png_struct_size)
  187214. {
  187215. #ifdef PNG_SETJMP_SUPPORTED
  187216. jmp_buf tmp_jmp; /* to save current jump buffer */
  187217. #endif
  187218. int i=0;
  187219. png_structp png_ptr=*ptr_ptr;
  187220. if(png_ptr == NULL) return;
  187221. do
  187222. {
  187223. if(user_png_ver[i] != png_libpng_ver[i])
  187224. {
  187225. #ifdef PNG_LEGACY_SUPPORTED
  187226. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187227. #else
  187228. png_ptr->warning_fn=NULL;
  187229. png_warning(png_ptr,
  187230. "Application uses deprecated png_read_init() and should be recompiled.");
  187231. break;
  187232. #endif
  187233. }
  187234. } while (png_libpng_ver[i++]);
  187235. png_debug(1, "in png_read_init_3\n");
  187236. #ifdef PNG_SETJMP_SUPPORTED
  187237. /* save jump buffer and error functions */
  187238. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187239. #endif
  187240. if(png_sizeof(png_struct) > png_struct_size)
  187241. {
  187242. png_destroy_struct(png_ptr);
  187243. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187244. png_ptr = *ptr_ptr;
  187245. }
  187246. /* reset all variables to 0 */
  187247. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187248. #ifdef PNG_SETJMP_SUPPORTED
  187249. /* restore jump buffer */
  187250. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187251. #endif
  187252. /* added at libpng-1.2.6 */
  187253. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187254. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187255. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187256. #endif
  187257. /* initialize zbuf - compression buffer */
  187258. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187259. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187260. (png_uint_32)png_ptr->zbuf_size);
  187261. png_ptr->zstream.zalloc = png_zalloc;
  187262. png_ptr->zstream.zfree = png_zfree;
  187263. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187264. switch (inflateInit(&png_ptr->zstream))
  187265. {
  187266. case Z_OK: /* Do nothing */ break;
  187267. case Z_MEM_ERROR:
  187268. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187269. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187270. default: png_error(png_ptr, "Unknown zlib error");
  187271. }
  187272. png_ptr->zstream.next_out = png_ptr->zbuf;
  187273. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187274. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187275. }
  187276. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187277. /* Read the information before the actual image data. This has been
  187278. * changed in v0.90 to allow reading a file that already has the magic
  187279. * bytes read from the stream. You can tell libpng how many bytes have
  187280. * been read from the beginning of the stream (up to the maximum of 8)
  187281. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187282. * here. The application can then have access to the signature bytes we
  187283. * read if it is determined that this isn't a valid PNG file.
  187284. */
  187285. void PNGAPI
  187286. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187287. {
  187288. if(png_ptr == NULL) return;
  187289. png_debug(1, "in png_read_info\n");
  187290. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187291. if (png_ptr->sig_bytes < 8)
  187292. {
  187293. png_size_t num_checked = png_ptr->sig_bytes,
  187294. num_to_check = 8 - num_checked;
  187295. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187296. png_ptr->sig_bytes = 8;
  187297. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187298. {
  187299. if (num_checked < 4 &&
  187300. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187301. png_error(png_ptr, "Not a PNG file");
  187302. else
  187303. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187304. }
  187305. if (num_checked < 3)
  187306. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187307. }
  187308. for(;;)
  187309. {
  187310. #ifdef PNG_USE_LOCAL_ARRAYS
  187311. PNG_CONST PNG_IHDR;
  187312. PNG_CONST PNG_IDAT;
  187313. PNG_CONST PNG_IEND;
  187314. PNG_CONST PNG_PLTE;
  187315. #if defined(PNG_READ_bKGD_SUPPORTED)
  187316. PNG_CONST PNG_bKGD;
  187317. #endif
  187318. #if defined(PNG_READ_cHRM_SUPPORTED)
  187319. PNG_CONST PNG_cHRM;
  187320. #endif
  187321. #if defined(PNG_READ_gAMA_SUPPORTED)
  187322. PNG_CONST PNG_gAMA;
  187323. #endif
  187324. #if defined(PNG_READ_hIST_SUPPORTED)
  187325. PNG_CONST PNG_hIST;
  187326. #endif
  187327. #if defined(PNG_READ_iCCP_SUPPORTED)
  187328. PNG_CONST PNG_iCCP;
  187329. #endif
  187330. #if defined(PNG_READ_iTXt_SUPPORTED)
  187331. PNG_CONST PNG_iTXt;
  187332. #endif
  187333. #if defined(PNG_READ_oFFs_SUPPORTED)
  187334. PNG_CONST PNG_oFFs;
  187335. #endif
  187336. #if defined(PNG_READ_pCAL_SUPPORTED)
  187337. PNG_CONST PNG_pCAL;
  187338. #endif
  187339. #if defined(PNG_READ_pHYs_SUPPORTED)
  187340. PNG_CONST PNG_pHYs;
  187341. #endif
  187342. #if defined(PNG_READ_sBIT_SUPPORTED)
  187343. PNG_CONST PNG_sBIT;
  187344. #endif
  187345. #if defined(PNG_READ_sCAL_SUPPORTED)
  187346. PNG_CONST PNG_sCAL;
  187347. #endif
  187348. #if defined(PNG_READ_sPLT_SUPPORTED)
  187349. PNG_CONST PNG_sPLT;
  187350. #endif
  187351. #if defined(PNG_READ_sRGB_SUPPORTED)
  187352. PNG_CONST PNG_sRGB;
  187353. #endif
  187354. #if defined(PNG_READ_tEXt_SUPPORTED)
  187355. PNG_CONST PNG_tEXt;
  187356. #endif
  187357. #if defined(PNG_READ_tIME_SUPPORTED)
  187358. PNG_CONST PNG_tIME;
  187359. #endif
  187360. #if defined(PNG_READ_tRNS_SUPPORTED)
  187361. PNG_CONST PNG_tRNS;
  187362. #endif
  187363. #if defined(PNG_READ_zTXt_SUPPORTED)
  187364. PNG_CONST PNG_zTXt;
  187365. #endif
  187366. #endif /* PNG_USE_LOCAL_ARRAYS */
  187367. png_byte chunk_length[4];
  187368. png_uint_32 length;
  187369. png_read_data(png_ptr, chunk_length, 4);
  187370. length = png_get_uint_31(png_ptr,chunk_length);
  187371. png_reset_crc(png_ptr);
  187372. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187373. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187374. length);
  187375. /* This should be a binary subdivision search or a hash for
  187376. * matching the chunk name rather than a linear search.
  187377. */
  187378. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187379. if(png_ptr->mode & PNG_AFTER_IDAT)
  187380. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187381. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187382. png_handle_IHDR(png_ptr, info_ptr, length);
  187383. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187384. png_handle_IEND(png_ptr, info_ptr, length);
  187385. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187386. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187387. {
  187388. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187389. png_ptr->mode |= PNG_HAVE_IDAT;
  187390. png_handle_unknown(png_ptr, info_ptr, length);
  187391. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187392. png_ptr->mode |= PNG_HAVE_PLTE;
  187393. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187394. {
  187395. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187396. png_error(png_ptr, "Missing IHDR before IDAT");
  187397. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187398. !(png_ptr->mode & PNG_HAVE_PLTE))
  187399. png_error(png_ptr, "Missing PLTE before IDAT");
  187400. break;
  187401. }
  187402. }
  187403. #endif
  187404. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187405. png_handle_PLTE(png_ptr, info_ptr, length);
  187406. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187407. {
  187408. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187409. png_error(png_ptr, "Missing IHDR before IDAT");
  187410. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187411. !(png_ptr->mode & PNG_HAVE_PLTE))
  187412. png_error(png_ptr, "Missing PLTE before IDAT");
  187413. png_ptr->idat_size = length;
  187414. png_ptr->mode |= PNG_HAVE_IDAT;
  187415. break;
  187416. }
  187417. #if defined(PNG_READ_bKGD_SUPPORTED)
  187418. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187419. png_handle_bKGD(png_ptr, info_ptr, length);
  187420. #endif
  187421. #if defined(PNG_READ_cHRM_SUPPORTED)
  187422. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187423. png_handle_cHRM(png_ptr, info_ptr, length);
  187424. #endif
  187425. #if defined(PNG_READ_gAMA_SUPPORTED)
  187426. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187427. png_handle_gAMA(png_ptr, info_ptr, length);
  187428. #endif
  187429. #if defined(PNG_READ_hIST_SUPPORTED)
  187430. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187431. png_handle_hIST(png_ptr, info_ptr, length);
  187432. #endif
  187433. #if defined(PNG_READ_oFFs_SUPPORTED)
  187434. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187435. png_handle_oFFs(png_ptr, info_ptr, length);
  187436. #endif
  187437. #if defined(PNG_READ_pCAL_SUPPORTED)
  187438. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187439. png_handle_pCAL(png_ptr, info_ptr, length);
  187440. #endif
  187441. #if defined(PNG_READ_sCAL_SUPPORTED)
  187442. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187443. png_handle_sCAL(png_ptr, info_ptr, length);
  187444. #endif
  187445. #if defined(PNG_READ_pHYs_SUPPORTED)
  187446. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187447. png_handle_pHYs(png_ptr, info_ptr, length);
  187448. #endif
  187449. #if defined(PNG_READ_sBIT_SUPPORTED)
  187450. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187451. png_handle_sBIT(png_ptr, info_ptr, length);
  187452. #endif
  187453. #if defined(PNG_READ_sRGB_SUPPORTED)
  187454. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187455. png_handle_sRGB(png_ptr, info_ptr, length);
  187456. #endif
  187457. #if defined(PNG_READ_iCCP_SUPPORTED)
  187458. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187459. png_handle_iCCP(png_ptr, info_ptr, length);
  187460. #endif
  187461. #if defined(PNG_READ_sPLT_SUPPORTED)
  187462. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187463. png_handle_sPLT(png_ptr, info_ptr, length);
  187464. #endif
  187465. #if defined(PNG_READ_tEXt_SUPPORTED)
  187466. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187467. png_handle_tEXt(png_ptr, info_ptr, length);
  187468. #endif
  187469. #if defined(PNG_READ_tIME_SUPPORTED)
  187470. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187471. png_handle_tIME(png_ptr, info_ptr, length);
  187472. #endif
  187473. #if defined(PNG_READ_tRNS_SUPPORTED)
  187474. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187475. png_handle_tRNS(png_ptr, info_ptr, length);
  187476. #endif
  187477. #if defined(PNG_READ_zTXt_SUPPORTED)
  187478. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187479. png_handle_zTXt(png_ptr, info_ptr, length);
  187480. #endif
  187481. #if defined(PNG_READ_iTXt_SUPPORTED)
  187482. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187483. png_handle_iTXt(png_ptr, info_ptr, length);
  187484. #endif
  187485. else
  187486. png_handle_unknown(png_ptr, info_ptr, length);
  187487. }
  187488. }
  187489. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187490. /* optional call to update the users info_ptr structure */
  187491. void PNGAPI
  187492. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187493. {
  187494. png_debug(1, "in png_read_update_info\n");
  187495. if(png_ptr == NULL) return;
  187496. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187497. png_read_start_row(png_ptr);
  187498. else
  187499. png_warning(png_ptr,
  187500. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187501. png_read_transform_info(png_ptr, info_ptr);
  187502. }
  187503. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187504. /* Initialize palette, background, etc, after transformations
  187505. * are set, but before any reading takes place. This allows
  187506. * the user to obtain a gamma-corrected palette, for example.
  187507. * If the user doesn't call this, we will do it ourselves.
  187508. */
  187509. void PNGAPI
  187510. png_start_read_image(png_structp png_ptr)
  187511. {
  187512. png_debug(1, "in png_start_read_image\n");
  187513. if(png_ptr == NULL) return;
  187514. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187515. png_read_start_row(png_ptr);
  187516. }
  187517. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187518. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187519. void PNGAPI
  187520. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187521. {
  187522. #ifdef PNG_USE_LOCAL_ARRAYS
  187523. PNG_CONST PNG_IDAT;
  187524. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187525. 0xff};
  187526. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187527. #endif
  187528. int ret;
  187529. if(png_ptr == NULL) return;
  187530. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187531. png_ptr->row_number, png_ptr->pass);
  187532. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187533. png_read_start_row(png_ptr);
  187534. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187535. {
  187536. /* check for transforms that have been set but were defined out */
  187537. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187538. if (png_ptr->transformations & PNG_INVERT_MONO)
  187539. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187540. #endif
  187541. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187542. if (png_ptr->transformations & PNG_FILLER)
  187543. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187544. #endif
  187545. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187546. if (png_ptr->transformations & PNG_PACKSWAP)
  187547. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187548. #endif
  187549. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187550. if (png_ptr->transformations & PNG_PACK)
  187551. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187552. #endif
  187553. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187554. if (png_ptr->transformations & PNG_SHIFT)
  187555. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187556. #endif
  187557. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187558. if (png_ptr->transformations & PNG_BGR)
  187559. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187560. #endif
  187561. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187562. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187563. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187564. #endif
  187565. }
  187566. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187567. /* if interlaced and we do not need a new row, combine row and return */
  187568. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187569. {
  187570. switch (png_ptr->pass)
  187571. {
  187572. case 0:
  187573. if (png_ptr->row_number & 0x07)
  187574. {
  187575. if (dsp_row != NULL)
  187576. png_combine_row(png_ptr, dsp_row,
  187577. png_pass_dsp_mask[png_ptr->pass]);
  187578. png_read_finish_row(png_ptr);
  187579. return;
  187580. }
  187581. break;
  187582. case 1:
  187583. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187584. {
  187585. if (dsp_row != NULL)
  187586. png_combine_row(png_ptr, dsp_row,
  187587. png_pass_dsp_mask[png_ptr->pass]);
  187588. png_read_finish_row(png_ptr);
  187589. return;
  187590. }
  187591. break;
  187592. case 2:
  187593. if ((png_ptr->row_number & 0x07) != 4)
  187594. {
  187595. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187596. png_combine_row(png_ptr, dsp_row,
  187597. png_pass_dsp_mask[png_ptr->pass]);
  187598. png_read_finish_row(png_ptr);
  187599. return;
  187600. }
  187601. break;
  187602. case 3:
  187603. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187604. {
  187605. if (dsp_row != NULL)
  187606. png_combine_row(png_ptr, dsp_row,
  187607. png_pass_dsp_mask[png_ptr->pass]);
  187608. png_read_finish_row(png_ptr);
  187609. return;
  187610. }
  187611. break;
  187612. case 4:
  187613. if ((png_ptr->row_number & 3) != 2)
  187614. {
  187615. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187616. png_combine_row(png_ptr, dsp_row,
  187617. png_pass_dsp_mask[png_ptr->pass]);
  187618. png_read_finish_row(png_ptr);
  187619. return;
  187620. }
  187621. break;
  187622. case 5:
  187623. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187624. {
  187625. if (dsp_row != NULL)
  187626. png_combine_row(png_ptr, dsp_row,
  187627. png_pass_dsp_mask[png_ptr->pass]);
  187628. png_read_finish_row(png_ptr);
  187629. return;
  187630. }
  187631. break;
  187632. case 6:
  187633. if (!(png_ptr->row_number & 1))
  187634. {
  187635. png_read_finish_row(png_ptr);
  187636. return;
  187637. }
  187638. break;
  187639. }
  187640. }
  187641. #endif
  187642. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187643. png_error(png_ptr, "Invalid attempt to read row data");
  187644. png_ptr->zstream.next_out = png_ptr->row_buf;
  187645. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187646. do
  187647. {
  187648. if (!(png_ptr->zstream.avail_in))
  187649. {
  187650. while (!png_ptr->idat_size)
  187651. {
  187652. png_byte chunk_length[4];
  187653. png_crc_finish(png_ptr, 0);
  187654. png_read_data(png_ptr, chunk_length, 4);
  187655. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187656. png_reset_crc(png_ptr);
  187657. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187658. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187659. png_error(png_ptr, "Not enough image data");
  187660. }
  187661. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187662. png_ptr->zstream.next_in = png_ptr->zbuf;
  187663. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187664. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187665. png_crc_read(png_ptr, png_ptr->zbuf,
  187666. (png_size_t)png_ptr->zstream.avail_in);
  187667. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187668. }
  187669. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187670. if (ret == Z_STREAM_END)
  187671. {
  187672. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187673. png_ptr->idat_size)
  187674. png_error(png_ptr, "Extra compressed data");
  187675. png_ptr->mode |= PNG_AFTER_IDAT;
  187676. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187677. break;
  187678. }
  187679. if (ret != Z_OK)
  187680. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187681. "Decompression error");
  187682. } while (png_ptr->zstream.avail_out);
  187683. png_ptr->row_info.color_type = png_ptr->color_type;
  187684. png_ptr->row_info.width = png_ptr->iwidth;
  187685. png_ptr->row_info.channels = png_ptr->channels;
  187686. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187687. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187688. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187689. png_ptr->row_info.width);
  187690. if(png_ptr->row_buf[0])
  187691. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187692. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187693. (int)(png_ptr->row_buf[0]));
  187694. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187695. png_ptr->rowbytes + 1);
  187696. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187697. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187698. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187699. {
  187700. /* Intrapixel differencing */
  187701. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187702. }
  187703. #endif
  187704. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187705. png_do_read_transformations(png_ptr);
  187706. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187707. /* blow up interlaced rows to full size */
  187708. if (png_ptr->interlaced &&
  187709. (png_ptr->transformations & PNG_INTERLACE))
  187710. {
  187711. if (png_ptr->pass < 6)
  187712. /* old interface (pre-1.0.9):
  187713. png_do_read_interlace(&(png_ptr->row_info),
  187714. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187715. */
  187716. png_do_read_interlace(png_ptr);
  187717. if (dsp_row != NULL)
  187718. png_combine_row(png_ptr, dsp_row,
  187719. png_pass_dsp_mask[png_ptr->pass]);
  187720. if (row != NULL)
  187721. png_combine_row(png_ptr, row,
  187722. png_pass_mask[png_ptr->pass]);
  187723. }
  187724. else
  187725. #endif
  187726. {
  187727. if (row != NULL)
  187728. png_combine_row(png_ptr, row, 0xff);
  187729. if (dsp_row != NULL)
  187730. png_combine_row(png_ptr, dsp_row, 0xff);
  187731. }
  187732. png_read_finish_row(png_ptr);
  187733. if (png_ptr->read_row_fn != NULL)
  187734. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187735. }
  187736. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187737. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187738. /* Read one or more rows of image data. If the image is interlaced,
  187739. * and png_set_interlace_handling() has been called, the rows need to
  187740. * contain the contents of the rows from the previous pass. If the
  187741. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187742. * called, the rows contents must be initialized to the contents of the
  187743. * screen.
  187744. *
  187745. * "row" holds the actual image, and pixels are placed in it
  187746. * as they arrive. If the image is displayed after each pass, it will
  187747. * appear to "sparkle" in. "display_row" can be used to display a
  187748. * "chunky" progressive image, with finer detail added as it becomes
  187749. * available. If you do not want this "chunky" display, you may pass
  187750. * NULL for display_row. If you do not want the sparkle display, and
  187751. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187752. * If you have called png_handle_alpha(), and the image has either an
  187753. * alpha channel or a transparency chunk, you must provide a buffer for
  187754. * rows. In this case, you do not have to provide a display_row buffer
  187755. * also, but you may. If the image is not interlaced, or if you have
  187756. * not called png_set_interlace_handling(), the display_row buffer will
  187757. * be ignored, so pass NULL to it.
  187758. *
  187759. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187760. */
  187761. void PNGAPI
  187762. png_read_rows(png_structp png_ptr, png_bytepp row,
  187763. png_bytepp display_row, png_uint_32 num_rows)
  187764. {
  187765. png_uint_32 i;
  187766. png_bytepp rp;
  187767. png_bytepp dp;
  187768. png_debug(1, "in png_read_rows\n");
  187769. if(png_ptr == NULL) return;
  187770. rp = row;
  187771. dp = display_row;
  187772. if (rp != NULL && dp != NULL)
  187773. for (i = 0; i < num_rows; i++)
  187774. {
  187775. png_bytep rptr = *rp++;
  187776. png_bytep dptr = *dp++;
  187777. png_read_row(png_ptr, rptr, dptr);
  187778. }
  187779. else if(rp != NULL)
  187780. for (i = 0; i < num_rows; i++)
  187781. {
  187782. png_bytep rptr = *rp;
  187783. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187784. rp++;
  187785. }
  187786. else if(dp != NULL)
  187787. for (i = 0; i < num_rows; i++)
  187788. {
  187789. png_bytep dptr = *dp;
  187790. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187791. dp++;
  187792. }
  187793. }
  187794. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187795. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187796. /* Read the entire image. If the image has an alpha channel or a tRNS
  187797. * chunk, and you have called png_handle_alpha()[*], you will need to
  187798. * initialize the image to the current image that PNG will be overlaying.
  187799. * We set the num_rows again here, in case it was incorrectly set in
  187800. * png_read_start_row() by a call to png_read_update_info() or
  187801. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187802. * prior to either of these functions like it should have been. You can
  187803. * only call this function once. If you desire to have an image for
  187804. * each pass of a interlaced image, use png_read_rows() instead.
  187805. *
  187806. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187807. */
  187808. void PNGAPI
  187809. png_read_image(png_structp png_ptr, png_bytepp image)
  187810. {
  187811. png_uint_32 i,image_height;
  187812. int pass, j;
  187813. png_bytepp rp;
  187814. png_debug(1, "in png_read_image\n");
  187815. if(png_ptr == NULL) return;
  187816. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187817. pass = png_set_interlace_handling(png_ptr);
  187818. #else
  187819. if (png_ptr->interlaced)
  187820. png_error(png_ptr,
  187821. "Cannot read interlaced image -- interlace handler disabled.");
  187822. pass = 1;
  187823. #endif
  187824. image_height=png_ptr->height;
  187825. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187826. for (j = 0; j < pass; j++)
  187827. {
  187828. rp = image;
  187829. for (i = 0; i < image_height; i++)
  187830. {
  187831. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187832. rp++;
  187833. }
  187834. }
  187835. }
  187836. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187837. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187838. /* Read the end of the PNG file. Will not read past the end of the
  187839. * file, will verify the end is accurate, and will read any comments
  187840. * or time information at the end of the file, if info is not NULL.
  187841. */
  187842. void PNGAPI
  187843. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187844. {
  187845. png_byte chunk_length[4];
  187846. png_uint_32 length;
  187847. png_debug(1, "in png_read_end\n");
  187848. if(png_ptr == NULL) return;
  187849. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187850. do
  187851. {
  187852. #ifdef PNG_USE_LOCAL_ARRAYS
  187853. PNG_CONST PNG_IHDR;
  187854. PNG_CONST PNG_IDAT;
  187855. PNG_CONST PNG_IEND;
  187856. PNG_CONST PNG_PLTE;
  187857. #if defined(PNG_READ_bKGD_SUPPORTED)
  187858. PNG_CONST PNG_bKGD;
  187859. #endif
  187860. #if defined(PNG_READ_cHRM_SUPPORTED)
  187861. PNG_CONST PNG_cHRM;
  187862. #endif
  187863. #if defined(PNG_READ_gAMA_SUPPORTED)
  187864. PNG_CONST PNG_gAMA;
  187865. #endif
  187866. #if defined(PNG_READ_hIST_SUPPORTED)
  187867. PNG_CONST PNG_hIST;
  187868. #endif
  187869. #if defined(PNG_READ_iCCP_SUPPORTED)
  187870. PNG_CONST PNG_iCCP;
  187871. #endif
  187872. #if defined(PNG_READ_iTXt_SUPPORTED)
  187873. PNG_CONST PNG_iTXt;
  187874. #endif
  187875. #if defined(PNG_READ_oFFs_SUPPORTED)
  187876. PNG_CONST PNG_oFFs;
  187877. #endif
  187878. #if defined(PNG_READ_pCAL_SUPPORTED)
  187879. PNG_CONST PNG_pCAL;
  187880. #endif
  187881. #if defined(PNG_READ_pHYs_SUPPORTED)
  187882. PNG_CONST PNG_pHYs;
  187883. #endif
  187884. #if defined(PNG_READ_sBIT_SUPPORTED)
  187885. PNG_CONST PNG_sBIT;
  187886. #endif
  187887. #if defined(PNG_READ_sCAL_SUPPORTED)
  187888. PNG_CONST PNG_sCAL;
  187889. #endif
  187890. #if defined(PNG_READ_sPLT_SUPPORTED)
  187891. PNG_CONST PNG_sPLT;
  187892. #endif
  187893. #if defined(PNG_READ_sRGB_SUPPORTED)
  187894. PNG_CONST PNG_sRGB;
  187895. #endif
  187896. #if defined(PNG_READ_tEXt_SUPPORTED)
  187897. PNG_CONST PNG_tEXt;
  187898. #endif
  187899. #if defined(PNG_READ_tIME_SUPPORTED)
  187900. PNG_CONST PNG_tIME;
  187901. #endif
  187902. #if defined(PNG_READ_tRNS_SUPPORTED)
  187903. PNG_CONST PNG_tRNS;
  187904. #endif
  187905. #if defined(PNG_READ_zTXt_SUPPORTED)
  187906. PNG_CONST PNG_zTXt;
  187907. #endif
  187908. #endif /* PNG_USE_LOCAL_ARRAYS */
  187909. png_read_data(png_ptr, chunk_length, 4);
  187910. length = png_get_uint_31(png_ptr,chunk_length);
  187911. png_reset_crc(png_ptr);
  187912. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187913. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187914. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187915. png_handle_IHDR(png_ptr, info_ptr, length);
  187916. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187917. png_handle_IEND(png_ptr, info_ptr, length);
  187918. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187919. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187920. {
  187921. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187922. {
  187923. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187924. png_error(png_ptr, "Too many IDAT's found");
  187925. }
  187926. png_handle_unknown(png_ptr, info_ptr, length);
  187927. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187928. png_ptr->mode |= PNG_HAVE_PLTE;
  187929. }
  187930. #endif
  187931. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187932. {
  187933. /* Zero length IDATs are legal after the last IDAT has been
  187934. * read, but not after other chunks have been read.
  187935. */
  187936. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187937. png_error(png_ptr, "Too many IDAT's found");
  187938. png_crc_finish(png_ptr, length);
  187939. }
  187940. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187941. png_handle_PLTE(png_ptr, info_ptr, length);
  187942. #if defined(PNG_READ_bKGD_SUPPORTED)
  187943. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187944. png_handle_bKGD(png_ptr, info_ptr, length);
  187945. #endif
  187946. #if defined(PNG_READ_cHRM_SUPPORTED)
  187947. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187948. png_handle_cHRM(png_ptr, info_ptr, length);
  187949. #endif
  187950. #if defined(PNG_READ_gAMA_SUPPORTED)
  187951. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187952. png_handle_gAMA(png_ptr, info_ptr, length);
  187953. #endif
  187954. #if defined(PNG_READ_hIST_SUPPORTED)
  187955. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187956. png_handle_hIST(png_ptr, info_ptr, length);
  187957. #endif
  187958. #if defined(PNG_READ_oFFs_SUPPORTED)
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187960. png_handle_oFFs(png_ptr, info_ptr, length);
  187961. #endif
  187962. #if defined(PNG_READ_pCAL_SUPPORTED)
  187963. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187964. png_handle_pCAL(png_ptr, info_ptr, length);
  187965. #endif
  187966. #if defined(PNG_READ_sCAL_SUPPORTED)
  187967. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187968. png_handle_sCAL(png_ptr, info_ptr, length);
  187969. #endif
  187970. #if defined(PNG_READ_pHYs_SUPPORTED)
  187971. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187972. png_handle_pHYs(png_ptr, info_ptr, length);
  187973. #endif
  187974. #if defined(PNG_READ_sBIT_SUPPORTED)
  187975. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187976. png_handle_sBIT(png_ptr, info_ptr, length);
  187977. #endif
  187978. #if defined(PNG_READ_sRGB_SUPPORTED)
  187979. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187980. png_handle_sRGB(png_ptr, info_ptr, length);
  187981. #endif
  187982. #if defined(PNG_READ_iCCP_SUPPORTED)
  187983. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187984. png_handle_iCCP(png_ptr, info_ptr, length);
  187985. #endif
  187986. #if defined(PNG_READ_sPLT_SUPPORTED)
  187987. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187988. png_handle_sPLT(png_ptr, info_ptr, length);
  187989. #endif
  187990. #if defined(PNG_READ_tEXt_SUPPORTED)
  187991. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187992. png_handle_tEXt(png_ptr, info_ptr, length);
  187993. #endif
  187994. #if defined(PNG_READ_tIME_SUPPORTED)
  187995. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187996. png_handle_tIME(png_ptr, info_ptr, length);
  187997. #endif
  187998. #if defined(PNG_READ_tRNS_SUPPORTED)
  187999. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188000. png_handle_tRNS(png_ptr, info_ptr, length);
  188001. #endif
  188002. #if defined(PNG_READ_zTXt_SUPPORTED)
  188003. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188004. png_handle_zTXt(png_ptr, info_ptr, length);
  188005. #endif
  188006. #if defined(PNG_READ_iTXt_SUPPORTED)
  188007. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188008. png_handle_iTXt(png_ptr, info_ptr, length);
  188009. #endif
  188010. else
  188011. png_handle_unknown(png_ptr, info_ptr, length);
  188012. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188013. }
  188014. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188015. /* free all memory used by the read */
  188016. void PNGAPI
  188017. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188018. png_infopp end_info_ptr_ptr)
  188019. {
  188020. png_structp png_ptr = NULL;
  188021. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188022. #ifdef PNG_USER_MEM_SUPPORTED
  188023. png_free_ptr free_fn;
  188024. png_voidp mem_ptr;
  188025. #endif
  188026. png_debug(1, "in png_destroy_read_struct\n");
  188027. if (png_ptr_ptr != NULL)
  188028. png_ptr = *png_ptr_ptr;
  188029. if (info_ptr_ptr != NULL)
  188030. info_ptr = *info_ptr_ptr;
  188031. if (end_info_ptr_ptr != NULL)
  188032. end_info_ptr = *end_info_ptr_ptr;
  188033. #ifdef PNG_USER_MEM_SUPPORTED
  188034. free_fn = png_ptr->free_fn;
  188035. mem_ptr = png_ptr->mem_ptr;
  188036. #endif
  188037. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188038. if (info_ptr != NULL)
  188039. {
  188040. #if defined(PNG_TEXT_SUPPORTED)
  188041. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188042. #endif
  188043. #ifdef PNG_USER_MEM_SUPPORTED
  188044. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188045. (png_voidp)mem_ptr);
  188046. #else
  188047. png_destroy_struct((png_voidp)info_ptr);
  188048. #endif
  188049. *info_ptr_ptr = NULL;
  188050. }
  188051. if (end_info_ptr != NULL)
  188052. {
  188053. #if defined(PNG_READ_TEXT_SUPPORTED)
  188054. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188055. #endif
  188056. #ifdef PNG_USER_MEM_SUPPORTED
  188057. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188058. (png_voidp)mem_ptr);
  188059. #else
  188060. png_destroy_struct((png_voidp)end_info_ptr);
  188061. #endif
  188062. *end_info_ptr_ptr = NULL;
  188063. }
  188064. if (png_ptr != NULL)
  188065. {
  188066. #ifdef PNG_USER_MEM_SUPPORTED
  188067. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188068. (png_voidp)mem_ptr);
  188069. #else
  188070. png_destroy_struct((png_voidp)png_ptr);
  188071. #endif
  188072. *png_ptr_ptr = NULL;
  188073. }
  188074. }
  188075. /* free all memory used by the read (old method) */
  188076. void /* PRIVATE */
  188077. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188078. {
  188079. #ifdef PNG_SETJMP_SUPPORTED
  188080. jmp_buf tmp_jmp;
  188081. #endif
  188082. png_error_ptr error_fn;
  188083. png_error_ptr warning_fn;
  188084. png_voidp error_ptr;
  188085. #ifdef PNG_USER_MEM_SUPPORTED
  188086. png_free_ptr free_fn;
  188087. #endif
  188088. png_debug(1, "in png_read_destroy\n");
  188089. if (info_ptr != NULL)
  188090. png_info_destroy(png_ptr, info_ptr);
  188091. if (end_info_ptr != NULL)
  188092. png_info_destroy(png_ptr, end_info_ptr);
  188093. png_free(png_ptr, png_ptr->zbuf);
  188094. png_free(png_ptr, png_ptr->big_row_buf);
  188095. png_free(png_ptr, png_ptr->prev_row);
  188096. #if defined(PNG_READ_DITHER_SUPPORTED)
  188097. png_free(png_ptr, png_ptr->palette_lookup);
  188098. png_free(png_ptr, png_ptr->dither_index);
  188099. #endif
  188100. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188101. png_free(png_ptr, png_ptr->gamma_table);
  188102. #endif
  188103. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188104. png_free(png_ptr, png_ptr->gamma_from_1);
  188105. png_free(png_ptr, png_ptr->gamma_to_1);
  188106. #endif
  188107. #ifdef PNG_FREE_ME_SUPPORTED
  188108. if (png_ptr->free_me & PNG_FREE_PLTE)
  188109. png_zfree(png_ptr, png_ptr->palette);
  188110. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188111. #else
  188112. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188113. png_zfree(png_ptr, png_ptr->palette);
  188114. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188115. #endif
  188116. #if defined(PNG_tRNS_SUPPORTED) || \
  188117. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188118. #ifdef PNG_FREE_ME_SUPPORTED
  188119. if (png_ptr->free_me & PNG_FREE_TRNS)
  188120. png_free(png_ptr, png_ptr->trans);
  188121. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188122. #else
  188123. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188124. png_free(png_ptr, png_ptr->trans);
  188125. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188126. #endif
  188127. #endif
  188128. #if defined(PNG_READ_hIST_SUPPORTED)
  188129. #ifdef PNG_FREE_ME_SUPPORTED
  188130. if (png_ptr->free_me & PNG_FREE_HIST)
  188131. png_free(png_ptr, png_ptr->hist);
  188132. png_ptr->free_me &= ~PNG_FREE_HIST;
  188133. #else
  188134. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188135. png_free(png_ptr, png_ptr->hist);
  188136. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188137. #endif
  188138. #endif
  188139. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188140. if (png_ptr->gamma_16_table != NULL)
  188141. {
  188142. int i;
  188143. int istop = (1 << (8 - png_ptr->gamma_shift));
  188144. for (i = 0; i < istop; i++)
  188145. {
  188146. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188147. }
  188148. png_free(png_ptr, png_ptr->gamma_16_table);
  188149. }
  188150. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188151. if (png_ptr->gamma_16_from_1 != NULL)
  188152. {
  188153. int i;
  188154. int istop = (1 << (8 - png_ptr->gamma_shift));
  188155. for (i = 0; i < istop; i++)
  188156. {
  188157. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188158. }
  188159. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188160. }
  188161. if (png_ptr->gamma_16_to_1 != NULL)
  188162. {
  188163. int i;
  188164. int istop = (1 << (8 - png_ptr->gamma_shift));
  188165. for (i = 0; i < istop; i++)
  188166. {
  188167. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188168. }
  188169. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188170. }
  188171. #endif
  188172. #endif
  188173. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188174. png_free(png_ptr, png_ptr->time_buffer);
  188175. #endif
  188176. inflateEnd(&png_ptr->zstream);
  188177. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188178. png_free(png_ptr, png_ptr->save_buffer);
  188179. #endif
  188180. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188181. #ifdef PNG_TEXT_SUPPORTED
  188182. png_free(png_ptr, png_ptr->current_text);
  188183. #endif /* PNG_TEXT_SUPPORTED */
  188184. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188185. /* Save the important info out of the png_struct, in case it is
  188186. * being used again.
  188187. */
  188188. #ifdef PNG_SETJMP_SUPPORTED
  188189. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188190. #endif
  188191. error_fn = png_ptr->error_fn;
  188192. warning_fn = png_ptr->warning_fn;
  188193. error_ptr = png_ptr->error_ptr;
  188194. #ifdef PNG_USER_MEM_SUPPORTED
  188195. free_fn = png_ptr->free_fn;
  188196. #endif
  188197. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188198. png_ptr->error_fn = error_fn;
  188199. png_ptr->warning_fn = warning_fn;
  188200. png_ptr->error_ptr = error_ptr;
  188201. #ifdef PNG_USER_MEM_SUPPORTED
  188202. png_ptr->free_fn = free_fn;
  188203. #endif
  188204. #ifdef PNG_SETJMP_SUPPORTED
  188205. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188206. #endif
  188207. }
  188208. void PNGAPI
  188209. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188210. {
  188211. if(png_ptr == NULL) return;
  188212. png_ptr->read_row_fn = read_row_fn;
  188213. }
  188214. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188215. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188216. void PNGAPI
  188217. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188218. int transforms,
  188219. voidp params)
  188220. {
  188221. int row;
  188222. if(png_ptr == NULL) return;
  188223. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188224. /* invert the alpha channel from opacity to transparency
  188225. */
  188226. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188227. png_set_invert_alpha(png_ptr);
  188228. #endif
  188229. /* png_read_info() gives us all of the information from the
  188230. * PNG file before the first IDAT (image data chunk).
  188231. */
  188232. png_read_info(png_ptr, info_ptr);
  188233. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188234. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188235. /* -------------- image transformations start here ------------------- */
  188236. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188237. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188238. */
  188239. if (transforms & PNG_TRANSFORM_STRIP_16)
  188240. png_set_strip_16(png_ptr);
  188241. #endif
  188242. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188243. /* Strip alpha bytes from the input data without combining with
  188244. * the background (not recommended).
  188245. */
  188246. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188247. png_set_strip_alpha(png_ptr);
  188248. #endif
  188249. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188250. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188251. * byte into separate bytes (useful for paletted and grayscale images).
  188252. */
  188253. if (transforms & PNG_TRANSFORM_PACKING)
  188254. png_set_packing(png_ptr);
  188255. #endif
  188256. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188257. /* Change the order of packed pixels to least significant bit first
  188258. * (not useful if you are using png_set_packing).
  188259. */
  188260. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188261. png_set_packswap(png_ptr);
  188262. #endif
  188263. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188264. /* Expand paletted colors into true RGB triplets
  188265. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188266. * Expand paletted or RGB images with transparency to full alpha
  188267. * channels so the data will be available as RGBA quartets.
  188268. */
  188269. if (transforms & PNG_TRANSFORM_EXPAND)
  188270. if ((png_ptr->bit_depth < 8) ||
  188271. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188272. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188273. png_set_expand(png_ptr);
  188274. #endif
  188275. /* We don't handle background color or gamma transformation or dithering.
  188276. */
  188277. #if defined(PNG_READ_INVERT_SUPPORTED)
  188278. /* invert monochrome files to have 0 as white and 1 as black
  188279. */
  188280. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188281. png_set_invert_mono(png_ptr);
  188282. #endif
  188283. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188284. /* If you want to shift the pixel values from the range [0,255] or
  188285. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188286. * colors were originally in:
  188287. */
  188288. if ((transforms & PNG_TRANSFORM_SHIFT)
  188289. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188290. {
  188291. png_color_8p sig_bit;
  188292. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188293. png_set_shift(png_ptr, sig_bit);
  188294. }
  188295. #endif
  188296. #if defined(PNG_READ_BGR_SUPPORTED)
  188297. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188298. */
  188299. if (transforms & PNG_TRANSFORM_BGR)
  188300. png_set_bgr(png_ptr);
  188301. #endif
  188302. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188303. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188304. */
  188305. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188306. png_set_swap_alpha(png_ptr);
  188307. #endif
  188308. #if defined(PNG_READ_SWAP_SUPPORTED)
  188309. /* swap bytes of 16 bit files to least significant byte first
  188310. */
  188311. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188312. png_set_swap(png_ptr);
  188313. #endif
  188314. /* We don't handle adding filler bytes */
  188315. /* Optional call to gamma correct and add the background to the palette
  188316. * and update info structure. REQUIRED if you are expecting libpng to
  188317. * update the palette for you (i.e., you selected such a transform above).
  188318. */
  188319. png_read_update_info(png_ptr, info_ptr);
  188320. /* -------------- image transformations end here ------------------- */
  188321. #ifdef PNG_FREE_ME_SUPPORTED
  188322. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188323. #endif
  188324. if(info_ptr->row_pointers == NULL)
  188325. {
  188326. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188327. info_ptr->height * png_sizeof(png_bytep));
  188328. #ifdef PNG_FREE_ME_SUPPORTED
  188329. info_ptr->free_me |= PNG_FREE_ROWS;
  188330. #endif
  188331. for (row = 0; row < (int)info_ptr->height; row++)
  188332. {
  188333. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188334. png_get_rowbytes(png_ptr, info_ptr));
  188335. }
  188336. }
  188337. png_read_image(png_ptr, info_ptr->row_pointers);
  188338. info_ptr->valid |= PNG_INFO_IDAT;
  188339. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188340. png_read_end(png_ptr, info_ptr);
  188341. transforms = transforms; /* quiet compiler warnings */
  188342. params = params;
  188343. }
  188344. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188345. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188346. #endif /* PNG_READ_SUPPORTED */
  188347. /*** End of inlined file: pngread.c ***/
  188348. /*** Start of inlined file: pngpread.c ***/
  188349. /* pngpread.c - read a png file in push mode
  188350. *
  188351. * Last changed in libpng 1.2.21 October 4, 2007
  188352. * For conditions of distribution and use, see copyright notice in png.h
  188353. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188354. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188355. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188356. */
  188357. #define PNG_INTERNAL
  188358. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188359. /* push model modes */
  188360. #define PNG_READ_SIG_MODE 0
  188361. #define PNG_READ_CHUNK_MODE 1
  188362. #define PNG_READ_IDAT_MODE 2
  188363. #define PNG_SKIP_MODE 3
  188364. #define PNG_READ_tEXt_MODE 4
  188365. #define PNG_READ_zTXt_MODE 5
  188366. #define PNG_READ_DONE_MODE 6
  188367. #define PNG_READ_iTXt_MODE 7
  188368. #define PNG_ERROR_MODE 8
  188369. void PNGAPI
  188370. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188371. png_bytep buffer, png_size_t buffer_size)
  188372. {
  188373. if(png_ptr == NULL) return;
  188374. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188375. while (png_ptr->buffer_size)
  188376. {
  188377. png_process_some_data(png_ptr, info_ptr);
  188378. }
  188379. }
  188380. /* What we do with the incoming data depends on what we were previously
  188381. * doing before we ran out of data...
  188382. */
  188383. void /* PRIVATE */
  188384. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188385. {
  188386. if(png_ptr == NULL) return;
  188387. switch (png_ptr->process_mode)
  188388. {
  188389. case PNG_READ_SIG_MODE:
  188390. {
  188391. png_push_read_sig(png_ptr, info_ptr);
  188392. break;
  188393. }
  188394. case PNG_READ_CHUNK_MODE:
  188395. {
  188396. png_push_read_chunk(png_ptr, info_ptr);
  188397. break;
  188398. }
  188399. case PNG_READ_IDAT_MODE:
  188400. {
  188401. png_push_read_IDAT(png_ptr);
  188402. break;
  188403. }
  188404. #if defined(PNG_READ_tEXt_SUPPORTED)
  188405. case PNG_READ_tEXt_MODE:
  188406. {
  188407. png_push_read_tEXt(png_ptr, info_ptr);
  188408. break;
  188409. }
  188410. #endif
  188411. #if defined(PNG_READ_zTXt_SUPPORTED)
  188412. case PNG_READ_zTXt_MODE:
  188413. {
  188414. png_push_read_zTXt(png_ptr, info_ptr);
  188415. break;
  188416. }
  188417. #endif
  188418. #if defined(PNG_READ_iTXt_SUPPORTED)
  188419. case PNG_READ_iTXt_MODE:
  188420. {
  188421. png_push_read_iTXt(png_ptr, info_ptr);
  188422. break;
  188423. }
  188424. #endif
  188425. case PNG_SKIP_MODE:
  188426. {
  188427. png_push_crc_finish(png_ptr);
  188428. break;
  188429. }
  188430. default:
  188431. {
  188432. png_ptr->buffer_size = 0;
  188433. break;
  188434. }
  188435. }
  188436. }
  188437. /* Read any remaining signature bytes from the stream and compare them with
  188438. * the correct PNG signature. It is possible that this routine is called
  188439. * with bytes already read from the signature, either because they have been
  188440. * checked by the calling application, or because of multiple calls to this
  188441. * routine.
  188442. */
  188443. void /* PRIVATE */
  188444. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188445. {
  188446. png_size_t num_checked = png_ptr->sig_bytes,
  188447. num_to_check = 8 - num_checked;
  188448. if (png_ptr->buffer_size < num_to_check)
  188449. {
  188450. num_to_check = png_ptr->buffer_size;
  188451. }
  188452. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188453. num_to_check);
  188454. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188455. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188456. {
  188457. if (num_checked < 4 &&
  188458. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188459. png_error(png_ptr, "Not a PNG file");
  188460. else
  188461. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188462. }
  188463. else
  188464. {
  188465. if (png_ptr->sig_bytes >= 8)
  188466. {
  188467. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188468. }
  188469. }
  188470. }
  188471. void /* PRIVATE */
  188472. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188473. {
  188474. #ifdef PNG_USE_LOCAL_ARRAYS
  188475. PNG_CONST PNG_IHDR;
  188476. PNG_CONST PNG_IDAT;
  188477. PNG_CONST PNG_IEND;
  188478. PNG_CONST PNG_PLTE;
  188479. #if defined(PNG_READ_bKGD_SUPPORTED)
  188480. PNG_CONST PNG_bKGD;
  188481. #endif
  188482. #if defined(PNG_READ_cHRM_SUPPORTED)
  188483. PNG_CONST PNG_cHRM;
  188484. #endif
  188485. #if defined(PNG_READ_gAMA_SUPPORTED)
  188486. PNG_CONST PNG_gAMA;
  188487. #endif
  188488. #if defined(PNG_READ_hIST_SUPPORTED)
  188489. PNG_CONST PNG_hIST;
  188490. #endif
  188491. #if defined(PNG_READ_iCCP_SUPPORTED)
  188492. PNG_CONST PNG_iCCP;
  188493. #endif
  188494. #if defined(PNG_READ_iTXt_SUPPORTED)
  188495. PNG_CONST PNG_iTXt;
  188496. #endif
  188497. #if defined(PNG_READ_oFFs_SUPPORTED)
  188498. PNG_CONST PNG_oFFs;
  188499. #endif
  188500. #if defined(PNG_READ_pCAL_SUPPORTED)
  188501. PNG_CONST PNG_pCAL;
  188502. #endif
  188503. #if defined(PNG_READ_pHYs_SUPPORTED)
  188504. PNG_CONST PNG_pHYs;
  188505. #endif
  188506. #if defined(PNG_READ_sBIT_SUPPORTED)
  188507. PNG_CONST PNG_sBIT;
  188508. #endif
  188509. #if defined(PNG_READ_sCAL_SUPPORTED)
  188510. PNG_CONST PNG_sCAL;
  188511. #endif
  188512. #if defined(PNG_READ_sRGB_SUPPORTED)
  188513. PNG_CONST PNG_sRGB;
  188514. #endif
  188515. #if defined(PNG_READ_sPLT_SUPPORTED)
  188516. PNG_CONST PNG_sPLT;
  188517. #endif
  188518. #if defined(PNG_READ_tEXt_SUPPORTED)
  188519. PNG_CONST PNG_tEXt;
  188520. #endif
  188521. #if defined(PNG_READ_tIME_SUPPORTED)
  188522. PNG_CONST PNG_tIME;
  188523. #endif
  188524. #if defined(PNG_READ_tRNS_SUPPORTED)
  188525. PNG_CONST PNG_tRNS;
  188526. #endif
  188527. #if defined(PNG_READ_zTXt_SUPPORTED)
  188528. PNG_CONST PNG_zTXt;
  188529. #endif
  188530. #endif /* PNG_USE_LOCAL_ARRAYS */
  188531. /* First we make sure we have enough data for the 4 byte chunk name
  188532. * and the 4 byte chunk length before proceeding with decoding the
  188533. * chunk data. To fully decode each of these chunks, we also make
  188534. * sure we have enough data in the buffer for the 4 byte CRC at the
  188535. * end of every chunk (except IDAT, which is handled separately).
  188536. */
  188537. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188538. {
  188539. png_byte chunk_length[4];
  188540. if (png_ptr->buffer_size < 8)
  188541. {
  188542. png_push_save_buffer(png_ptr);
  188543. return;
  188544. }
  188545. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188546. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188547. png_reset_crc(png_ptr);
  188548. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188549. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188550. }
  188551. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188552. if(png_ptr->mode & PNG_AFTER_IDAT)
  188553. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188554. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188555. {
  188556. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188557. {
  188558. png_push_save_buffer(png_ptr);
  188559. return;
  188560. }
  188561. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188562. }
  188563. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188564. {
  188565. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188566. {
  188567. png_push_save_buffer(png_ptr);
  188568. return;
  188569. }
  188570. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188571. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188572. png_push_have_end(png_ptr, info_ptr);
  188573. }
  188574. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188575. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188576. {
  188577. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188578. {
  188579. png_push_save_buffer(png_ptr);
  188580. return;
  188581. }
  188582. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188583. png_ptr->mode |= PNG_HAVE_IDAT;
  188584. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188585. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188586. png_ptr->mode |= PNG_HAVE_PLTE;
  188587. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188588. {
  188589. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188590. png_error(png_ptr, "Missing IHDR before IDAT");
  188591. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188592. !(png_ptr->mode & PNG_HAVE_PLTE))
  188593. png_error(png_ptr, "Missing PLTE before IDAT");
  188594. }
  188595. }
  188596. #endif
  188597. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188598. {
  188599. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188600. {
  188601. png_push_save_buffer(png_ptr);
  188602. return;
  188603. }
  188604. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188605. }
  188606. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188607. {
  188608. /* If we reach an IDAT chunk, this means we have read all of the
  188609. * header chunks, and we can start reading the image (or if this
  188610. * is called after the image has been read - we have an error).
  188611. */
  188612. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188613. png_error(png_ptr, "Missing IHDR before IDAT");
  188614. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188615. !(png_ptr->mode & PNG_HAVE_PLTE))
  188616. png_error(png_ptr, "Missing PLTE before IDAT");
  188617. if (png_ptr->mode & PNG_HAVE_IDAT)
  188618. {
  188619. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188620. if (png_ptr->push_length == 0)
  188621. return;
  188622. if (png_ptr->mode & PNG_AFTER_IDAT)
  188623. png_error(png_ptr, "Too many IDAT's found");
  188624. }
  188625. png_ptr->idat_size = png_ptr->push_length;
  188626. png_ptr->mode |= PNG_HAVE_IDAT;
  188627. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188628. png_push_have_info(png_ptr, info_ptr);
  188629. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188630. png_ptr->zstream.next_out = png_ptr->row_buf;
  188631. return;
  188632. }
  188633. #if defined(PNG_READ_gAMA_SUPPORTED)
  188634. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188635. {
  188636. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188637. {
  188638. png_push_save_buffer(png_ptr);
  188639. return;
  188640. }
  188641. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188642. }
  188643. #endif
  188644. #if defined(PNG_READ_sBIT_SUPPORTED)
  188645. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188646. {
  188647. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188648. {
  188649. png_push_save_buffer(png_ptr);
  188650. return;
  188651. }
  188652. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188653. }
  188654. #endif
  188655. #if defined(PNG_READ_cHRM_SUPPORTED)
  188656. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188657. {
  188658. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188659. {
  188660. png_push_save_buffer(png_ptr);
  188661. return;
  188662. }
  188663. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188664. }
  188665. #endif
  188666. #if defined(PNG_READ_sRGB_SUPPORTED)
  188667. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188668. {
  188669. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188670. {
  188671. png_push_save_buffer(png_ptr);
  188672. return;
  188673. }
  188674. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188675. }
  188676. #endif
  188677. #if defined(PNG_READ_iCCP_SUPPORTED)
  188678. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188679. {
  188680. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188681. {
  188682. png_push_save_buffer(png_ptr);
  188683. return;
  188684. }
  188685. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188686. }
  188687. #endif
  188688. #if defined(PNG_READ_sPLT_SUPPORTED)
  188689. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188690. {
  188691. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188692. {
  188693. png_push_save_buffer(png_ptr);
  188694. return;
  188695. }
  188696. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188697. }
  188698. #endif
  188699. #if defined(PNG_READ_tRNS_SUPPORTED)
  188700. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188701. {
  188702. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188703. {
  188704. png_push_save_buffer(png_ptr);
  188705. return;
  188706. }
  188707. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188708. }
  188709. #endif
  188710. #if defined(PNG_READ_bKGD_SUPPORTED)
  188711. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188712. {
  188713. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188714. {
  188715. png_push_save_buffer(png_ptr);
  188716. return;
  188717. }
  188718. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188719. }
  188720. #endif
  188721. #if defined(PNG_READ_hIST_SUPPORTED)
  188722. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188723. {
  188724. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188725. {
  188726. png_push_save_buffer(png_ptr);
  188727. return;
  188728. }
  188729. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188730. }
  188731. #endif
  188732. #if defined(PNG_READ_pHYs_SUPPORTED)
  188733. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188734. {
  188735. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188736. {
  188737. png_push_save_buffer(png_ptr);
  188738. return;
  188739. }
  188740. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188741. }
  188742. #endif
  188743. #if defined(PNG_READ_oFFs_SUPPORTED)
  188744. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188745. {
  188746. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188747. {
  188748. png_push_save_buffer(png_ptr);
  188749. return;
  188750. }
  188751. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188752. }
  188753. #endif
  188754. #if defined(PNG_READ_pCAL_SUPPORTED)
  188755. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188756. {
  188757. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188758. {
  188759. png_push_save_buffer(png_ptr);
  188760. return;
  188761. }
  188762. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188763. }
  188764. #endif
  188765. #if defined(PNG_READ_sCAL_SUPPORTED)
  188766. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188767. {
  188768. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188769. {
  188770. png_push_save_buffer(png_ptr);
  188771. return;
  188772. }
  188773. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188774. }
  188775. #endif
  188776. #if defined(PNG_READ_tIME_SUPPORTED)
  188777. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188778. {
  188779. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188780. {
  188781. png_push_save_buffer(png_ptr);
  188782. return;
  188783. }
  188784. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188785. }
  188786. #endif
  188787. #if defined(PNG_READ_tEXt_SUPPORTED)
  188788. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188789. {
  188790. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188791. {
  188792. png_push_save_buffer(png_ptr);
  188793. return;
  188794. }
  188795. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188796. }
  188797. #endif
  188798. #if defined(PNG_READ_zTXt_SUPPORTED)
  188799. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 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_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188807. }
  188808. #endif
  188809. #if defined(PNG_READ_iTXt_SUPPORTED)
  188810. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188811. {
  188812. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188813. {
  188814. png_push_save_buffer(png_ptr);
  188815. return;
  188816. }
  188817. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188818. }
  188819. #endif
  188820. else
  188821. {
  188822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188823. {
  188824. png_push_save_buffer(png_ptr);
  188825. return;
  188826. }
  188827. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188828. }
  188829. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188830. }
  188831. void /* PRIVATE */
  188832. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188833. {
  188834. png_ptr->process_mode = PNG_SKIP_MODE;
  188835. png_ptr->skip_length = skip;
  188836. }
  188837. void /* PRIVATE */
  188838. png_push_crc_finish(png_structp png_ptr)
  188839. {
  188840. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188841. {
  188842. png_size_t save_size;
  188843. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188844. save_size = (png_size_t)png_ptr->skip_length;
  188845. else
  188846. save_size = png_ptr->save_buffer_size;
  188847. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188848. png_ptr->skip_length -= save_size;
  188849. png_ptr->buffer_size -= save_size;
  188850. png_ptr->save_buffer_size -= save_size;
  188851. png_ptr->save_buffer_ptr += save_size;
  188852. }
  188853. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188854. {
  188855. png_size_t save_size;
  188856. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188857. save_size = (png_size_t)png_ptr->skip_length;
  188858. else
  188859. save_size = png_ptr->current_buffer_size;
  188860. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188861. png_ptr->skip_length -= save_size;
  188862. png_ptr->buffer_size -= save_size;
  188863. png_ptr->current_buffer_size -= save_size;
  188864. png_ptr->current_buffer_ptr += save_size;
  188865. }
  188866. if (!png_ptr->skip_length)
  188867. {
  188868. if (png_ptr->buffer_size < 4)
  188869. {
  188870. png_push_save_buffer(png_ptr);
  188871. return;
  188872. }
  188873. png_crc_finish(png_ptr, 0);
  188874. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188875. }
  188876. }
  188877. void PNGAPI
  188878. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188879. {
  188880. png_bytep ptr;
  188881. if(png_ptr == NULL) return;
  188882. ptr = buffer;
  188883. if (png_ptr->save_buffer_size)
  188884. {
  188885. png_size_t save_size;
  188886. if (length < png_ptr->save_buffer_size)
  188887. save_size = length;
  188888. else
  188889. save_size = png_ptr->save_buffer_size;
  188890. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188891. length -= save_size;
  188892. ptr += save_size;
  188893. png_ptr->buffer_size -= save_size;
  188894. png_ptr->save_buffer_size -= save_size;
  188895. png_ptr->save_buffer_ptr += save_size;
  188896. }
  188897. if (length && png_ptr->current_buffer_size)
  188898. {
  188899. png_size_t save_size;
  188900. if (length < png_ptr->current_buffer_size)
  188901. save_size = length;
  188902. else
  188903. save_size = png_ptr->current_buffer_size;
  188904. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188905. png_ptr->buffer_size -= save_size;
  188906. png_ptr->current_buffer_size -= save_size;
  188907. png_ptr->current_buffer_ptr += save_size;
  188908. }
  188909. }
  188910. void /* PRIVATE */
  188911. png_push_save_buffer(png_structp png_ptr)
  188912. {
  188913. if (png_ptr->save_buffer_size)
  188914. {
  188915. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188916. {
  188917. png_size_t i,istop;
  188918. png_bytep sp;
  188919. png_bytep dp;
  188920. istop = png_ptr->save_buffer_size;
  188921. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188922. i < istop; i++, sp++, dp++)
  188923. {
  188924. *dp = *sp;
  188925. }
  188926. }
  188927. }
  188928. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188929. png_ptr->save_buffer_max)
  188930. {
  188931. png_size_t new_max;
  188932. png_bytep old_buffer;
  188933. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188934. (png_ptr->current_buffer_size + 256))
  188935. {
  188936. png_error(png_ptr, "Potential overflow of save_buffer");
  188937. }
  188938. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188939. old_buffer = png_ptr->save_buffer;
  188940. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188941. (png_uint_32)new_max);
  188942. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188943. png_free(png_ptr, old_buffer);
  188944. png_ptr->save_buffer_max = new_max;
  188945. }
  188946. if (png_ptr->current_buffer_size)
  188947. {
  188948. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188949. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188950. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188951. png_ptr->current_buffer_size = 0;
  188952. }
  188953. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188954. png_ptr->buffer_size = 0;
  188955. }
  188956. void /* PRIVATE */
  188957. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188958. png_size_t buffer_length)
  188959. {
  188960. png_ptr->current_buffer = buffer;
  188961. png_ptr->current_buffer_size = buffer_length;
  188962. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188963. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188964. }
  188965. void /* PRIVATE */
  188966. png_push_read_IDAT(png_structp png_ptr)
  188967. {
  188968. #ifdef PNG_USE_LOCAL_ARRAYS
  188969. PNG_CONST PNG_IDAT;
  188970. #endif
  188971. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188972. {
  188973. png_byte chunk_length[4];
  188974. if (png_ptr->buffer_size < 8)
  188975. {
  188976. png_push_save_buffer(png_ptr);
  188977. return;
  188978. }
  188979. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188980. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188981. png_reset_crc(png_ptr);
  188982. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188983. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188984. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188985. {
  188986. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188987. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188988. png_error(png_ptr, "Not enough compressed data");
  188989. return;
  188990. }
  188991. png_ptr->idat_size = png_ptr->push_length;
  188992. }
  188993. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188994. {
  188995. png_size_t save_size;
  188996. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188997. {
  188998. save_size = (png_size_t)png_ptr->idat_size;
  188999. /* check for overflow */
  189000. if((png_uint_32)save_size != png_ptr->idat_size)
  189001. png_error(png_ptr, "save_size overflowed in pngpread");
  189002. }
  189003. else
  189004. save_size = png_ptr->save_buffer_size;
  189005. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189006. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189007. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189008. png_ptr->idat_size -= save_size;
  189009. png_ptr->buffer_size -= save_size;
  189010. png_ptr->save_buffer_size -= save_size;
  189011. png_ptr->save_buffer_ptr += save_size;
  189012. }
  189013. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189014. {
  189015. png_size_t save_size;
  189016. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189017. {
  189018. save_size = (png_size_t)png_ptr->idat_size;
  189019. /* check for overflow */
  189020. if((png_uint_32)save_size != png_ptr->idat_size)
  189021. png_error(png_ptr, "save_size overflowed in pngpread");
  189022. }
  189023. else
  189024. save_size = png_ptr->current_buffer_size;
  189025. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189026. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189027. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189028. png_ptr->idat_size -= save_size;
  189029. png_ptr->buffer_size -= save_size;
  189030. png_ptr->current_buffer_size -= save_size;
  189031. png_ptr->current_buffer_ptr += save_size;
  189032. }
  189033. if (!png_ptr->idat_size)
  189034. {
  189035. if (png_ptr->buffer_size < 4)
  189036. {
  189037. png_push_save_buffer(png_ptr);
  189038. return;
  189039. }
  189040. png_crc_finish(png_ptr, 0);
  189041. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189042. png_ptr->mode |= PNG_AFTER_IDAT;
  189043. }
  189044. }
  189045. void /* PRIVATE */
  189046. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189047. png_size_t buffer_length)
  189048. {
  189049. int ret;
  189050. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189051. png_error(png_ptr, "Extra compression data");
  189052. png_ptr->zstream.next_in = buffer;
  189053. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189054. for(;;)
  189055. {
  189056. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189057. if (ret != Z_OK)
  189058. {
  189059. if (ret == Z_STREAM_END)
  189060. {
  189061. if (png_ptr->zstream.avail_in)
  189062. png_error(png_ptr, "Extra compressed data");
  189063. if (!(png_ptr->zstream.avail_out))
  189064. {
  189065. png_push_process_row(png_ptr);
  189066. }
  189067. png_ptr->mode |= PNG_AFTER_IDAT;
  189068. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189069. break;
  189070. }
  189071. else if (ret == Z_BUF_ERROR)
  189072. break;
  189073. else
  189074. png_error(png_ptr, "Decompression Error");
  189075. }
  189076. if (!(png_ptr->zstream.avail_out))
  189077. {
  189078. if ((
  189079. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189080. png_ptr->interlaced && png_ptr->pass > 6) ||
  189081. (!png_ptr->interlaced &&
  189082. #endif
  189083. png_ptr->row_number == png_ptr->num_rows))
  189084. {
  189085. if (png_ptr->zstream.avail_in)
  189086. {
  189087. png_warning(png_ptr, "Too much data in IDAT chunks");
  189088. }
  189089. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189090. break;
  189091. }
  189092. png_push_process_row(png_ptr);
  189093. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189094. png_ptr->zstream.next_out = png_ptr->row_buf;
  189095. }
  189096. else
  189097. break;
  189098. }
  189099. }
  189100. void /* PRIVATE */
  189101. png_push_process_row(png_structp png_ptr)
  189102. {
  189103. png_ptr->row_info.color_type = png_ptr->color_type;
  189104. png_ptr->row_info.width = png_ptr->iwidth;
  189105. png_ptr->row_info.channels = png_ptr->channels;
  189106. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189107. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189108. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189109. png_ptr->row_info.width);
  189110. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189111. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189112. (int)(png_ptr->row_buf[0]));
  189113. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189114. png_ptr->rowbytes + 1);
  189115. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189116. png_do_read_transformations(png_ptr);
  189117. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189118. /* blow up interlaced rows to full size */
  189119. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189120. {
  189121. if (png_ptr->pass < 6)
  189122. /* old interface (pre-1.0.9):
  189123. png_do_read_interlace(&(png_ptr->row_info),
  189124. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189125. */
  189126. png_do_read_interlace(png_ptr);
  189127. switch (png_ptr->pass)
  189128. {
  189129. case 0:
  189130. {
  189131. int i;
  189132. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189133. {
  189134. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189135. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189136. }
  189137. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189138. {
  189139. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189140. {
  189141. png_push_have_row(png_ptr, png_bytep_NULL);
  189142. png_read_push_finish_row(png_ptr);
  189143. }
  189144. }
  189145. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189146. {
  189147. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189148. {
  189149. png_push_have_row(png_ptr, png_bytep_NULL);
  189150. png_read_push_finish_row(png_ptr);
  189151. }
  189152. }
  189153. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189154. {
  189155. png_push_have_row(png_ptr, png_bytep_NULL);
  189156. png_read_push_finish_row(png_ptr);
  189157. }
  189158. break;
  189159. }
  189160. case 1:
  189161. {
  189162. int i;
  189163. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189164. {
  189165. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189166. png_read_push_finish_row(png_ptr);
  189167. }
  189168. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189169. {
  189170. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189171. {
  189172. png_push_have_row(png_ptr, png_bytep_NULL);
  189173. png_read_push_finish_row(png_ptr);
  189174. }
  189175. }
  189176. break;
  189177. }
  189178. case 2:
  189179. {
  189180. int i;
  189181. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189182. {
  189183. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189184. png_read_push_finish_row(png_ptr);
  189185. }
  189186. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189187. {
  189188. png_push_have_row(png_ptr, png_bytep_NULL);
  189189. png_read_push_finish_row(png_ptr);
  189190. }
  189191. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189192. {
  189193. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189194. {
  189195. png_push_have_row(png_ptr, png_bytep_NULL);
  189196. png_read_push_finish_row(png_ptr);
  189197. }
  189198. }
  189199. break;
  189200. }
  189201. case 3:
  189202. {
  189203. int i;
  189204. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189205. {
  189206. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189207. png_read_push_finish_row(png_ptr);
  189208. }
  189209. if (png_ptr->pass == 4) /* skip top two generated rows */
  189210. {
  189211. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189212. {
  189213. png_push_have_row(png_ptr, png_bytep_NULL);
  189214. png_read_push_finish_row(png_ptr);
  189215. }
  189216. }
  189217. break;
  189218. }
  189219. case 4:
  189220. {
  189221. int i;
  189222. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189223. {
  189224. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189225. png_read_push_finish_row(png_ptr);
  189226. }
  189227. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189228. {
  189229. png_push_have_row(png_ptr, png_bytep_NULL);
  189230. png_read_push_finish_row(png_ptr);
  189231. }
  189232. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189233. {
  189234. png_push_have_row(png_ptr, png_bytep_NULL);
  189235. png_read_push_finish_row(png_ptr);
  189236. }
  189237. break;
  189238. }
  189239. case 5:
  189240. {
  189241. int i;
  189242. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189243. {
  189244. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189245. png_read_push_finish_row(png_ptr);
  189246. }
  189247. if (png_ptr->pass == 6) /* skip top generated row */
  189248. {
  189249. png_push_have_row(png_ptr, png_bytep_NULL);
  189250. png_read_push_finish_row(png_ptr);
  189251. }
  189252. break;
  189253. }
  189254. case 6:
  189255. {
  189256. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189257. png_read_push_finish_row(png_ptr);
  189258. if (png_ptr->pass != 6)
  189259. break;
  189260. png_push_have_row(png_ptr, png_bytep_NULL);
  189261. png_read_push_finish_row(png_ptr);
  189262. }
  189263. }
  189264. }
  189265. else
  189266. #endif
  189267. {
  189268. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189269. png_read_push_finish_row(png_ptr);
  189270. }
  189271. }
  189272. void /* PRIVATE */
  189273. png_read_push_finish_row(png_structp png_ptr)
  189274. {
  189275. #ifdef PNG_USE_LOCAL_ARRAYS
  189276. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189277. /* start of interlace block */
  189278. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189279. /* offset to next interlace block */
  189280. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189281. /* start of interlace block in the y direction */
  189282. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189283. /* offset to next interlace block in the y direction */
  189284. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189285. /* Height of interlace block. This is not currently used - if you need
  189286. * it, uncomment it here and in png.h
  189287. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189288. */
  189289. #endif
  189290. png_ptr->row_number++;
  189291. if (png_ptr->row_number < png_ptr->num_rows)
  189292. return;
  189293. if (png_ptr->interlaced)
  189294. {
  189295. png_ptr->row_number = 0;
  189296. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189297. png_ptr->rowbytes + 1);
  189298. do
  189299. {
  189300. png_ptr->pass++;
  189301. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189302. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189303. (png_ptr->pass == 5 && png_ptr->width < 2))
  189304. png_ptr->pass++;
  189305. if (png_ptr->pass > 7)
  189306. png_ptr->pass--;
  189307. if (png_ptr->pass >= 7)
  189308. break;
  189309. png_ptr->iwidth = (png_ptr->width +
  189310. png_pass_inc[png_ptr->pass] - 1 -
  189311. png_pass_start[png_ptr->pass]) /
  189312. png_pass_inc[png_ptr->pass];
  189313. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189314. png_ptr->iwidth) + 1;
  189315. if (png_ptr->transformations & PNG_INTERLACE)
  189316. break;
  189317. png_ptr->num_rows = (png_ptr->height +
  189318. png_pass_yinc[png_ptr->pass] - 1 -
  189319. png_pass_ystart[png_ptr->pass]) /
  189320. png_pass_yinc[png_ptr->pass];
  189321. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189322. }
  189323. }
  189324. #if defined(PNG_READ_tEXt_SUPPORTED)
  189325. void /* PRIVATE */
  189326. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189327. length)
  189328. {
  189329. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189330. {
  189331. png_error(png_ptr, "Out of place tEXt");
  189332. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189333. }
  189334. #ifdef PNG_MAX_MALLOC_64K
  189335. png_ptr->skip_length = 0; /* This may not be necessary */
  189336. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189337. {
  189338. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189339. png_ptr->skip_length = length - (png_uint_32)65535L;
  189340. length = (png_uint_32)65535L;
  189341. }
  189342. #endif
  189343. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189344. (png_uint_32)(length+1));
  189345. png_ptr->current_text[length] = '\0';
  189346. png_ptr->current_text_ptr = png_ptr->current_text;
  189347. png_ptr->current_text_size = (png_size_t)length;
  189348. png_ptr->current_text_left = (png_size_t)length;
  189349. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189350. }
  189351. void /* PRIVATE */
  189352. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189353. {
  189354. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189355. {
  189356. png_size_t text_size;
  189357. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189358. text_size = png_ptr->buffer_size;
  189359. else
  189360. text_size = png_ptr->current_text_left;
  189361. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189362. png_ptr->current_text_left -= text_size;
  189363. png_ptr->current_text_ptr += text_size;
  189364. }
  189365. if (!(png_ptr->current_text_left))
  189366. {
  189367. png_textp text_ptr;
  189368. png_charp text;
  189369. png_charp key;
  189370. int ret;
  189371. if (png_ptr->buffer_size < 4)
  189372. {
  189373. png_push_save_buffer(png_ptr);
  189374. return;
  189375. }
  189376. png_push_crc_finish(png_ptr);
  189377. #if defined(PNG_MAX_MALLOC_64K)
  189378. if (png_ptr->skip_length)
  189379. return;
  189380. #endif
  189381. key = png_ptr->current_text;
  189382. for (text = key; *text; text++)
  189383. /* empty loop */ ;
  189384. if (text < key + png_ptr->current_text_size)
  189385. text++;
  189386. text_ptr = (png_textp)png_malloc(png_ptr,
  189387. (png_uint_32)png_sizeof(png_text));
  189388. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189389. text_ptr->key = key;
  189390. #ifdef PNG_iTXt_SUPPORTED
  189391. text_ptr->lang = NULL;
  189392. text_ptr->lang_key = NULL;
  189393. #endif
  189394. text_ptr->text = text;
  189395. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189396. png_free(png_ptr, key);
  189397. png_free(png_ptr, text_ptr);
  189398. png_ptr->current_text = NULL;
  189399. if (ret)
  189400. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189401. }
  189402. }
  189403. #endif
  189404. #if defined(PNG_READ_zTXt_SUPPORTED)
  189405. void /* PRIVATE */
  189406. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189407. length)
  189408. {
  189409. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189410. {
  189411. png_error(png_ptr, "Out of place zTXt");
  189412. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189413. }
  189414. #ifdef PNG_MAX_MALLOC_64K
  189415. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189416. * to be able to store the uncompressed data. Actually, the threshold
  189417. * is probably around 32K, but it isn't as definite as 64K is.
  189418. */
  189419. if (length > (png_uint_32)65535L)
  189420. {
  189421. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189422. png_push_crc_skip(png_ptr, length);
  189423. return;
  189424. }
  189425. #endif
  189426. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189427. (png_uint_32)(length+1));
  189428. png_ptr->current_text[length] = '\0';
  189429. png_ptr->current_text_ptr = png_ptr->current_text;
  189430. png_ptr->current_text_size = (png_size_t)length;
  189431. png_ptr->current_text_left = (png_size_t)length;
  189432. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189433. }
  189434. void /* PRIVATE */
  189435. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189436. {
  189437. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189438. {
  189439. png_size_t text_size;
  189440. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189441. text_size = png_ptr->buffer_size;
  189442. else
  189443. text_size = png_ptr->current_text_left;
  189444. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189445. png_ptr->current_text_left -= text_size;
  189446. png_ptr->current_text_ptr += text_size;
  189447. }
  189448. if (!(png_ptr->current_text_left))
  189449. {
  189450. png_textp text_ptr;
  189451. png_charp text;
  189452. png_charp key;
  189453. int ret;
  189454. png_size_t text_size, key_size;
  189455. if (png_ptr->buffer_size < 4)
  189456. {
  189457. png_push_save_buffer(png_ptr);
  189458. return;
  189459. }
  189460. png_push_crc_finish(png_ptr);
  189461. key = png_ptr->current_text;
  189462. for (text = key; *text; text++)
  189463. /* empty loop */ ;
  189464. /* zTXt can't have zero text */
  189465. if (text >= key + png_ptr->current_text_size)
  189466. {
  189467. png_ptr->current_text = NULL;
  189468. png_free(png_ptr, key);
  189469. return;
  189470. }
  189471. text++;
  189472. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189473. {
  189474. png_ptr->current_text = NULL;
  189475. png_free(png_ptr, key);
  189476. return;
  189477. }
  189478. text++;
  189479. png_ptr->zstream.next_in = (png_bytep )text;
  189480. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189481. (text - key));
  189482. png_ptr->zstream.next_out = png_ptr->zbuf;
  189483. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189484. key_size = text - key;
  189485. text_size = 0;
  189486. text = NULL;
  189487. ret = Z_STREAM_END;
  189488. while (png_ptr->zstream.avail_in)
  189489. {
  189490. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189491. if (ret != Z_OK && ret != Z_STREAM_END)
  189492. {
  189493. inflateReset(&png_ptr->zstream);
  189494. png_ptr->zstream.avail_in = 0;
  189495. png_ptr->current_text = NULL;
  189496. png_free(png_ptr, key);
  189497. png_free(png_ptr, text);
  189498. return;
  189499. }
  189500. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189501. {
  189502. if (text == NULL)
  189503. {
  189504. text = (png_charp)png_malloc(png_ptr,
  189505. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189506. + key_size + 1));
  189507. png_memcpy(text + key_size, png_ptr->zbuf,
  189508. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189509. png_memcpy(text, key, key_size);
  189510. text_size = key_size + png_ptr->zbuf_size -
  189511. png_ptr->zstream.avail_out;
  189512. *(text + text_size) = '\0';
  189513. }
  189514. else
  189515. {
  189516. png_charp tmp;
  189517. tmp = text;
  189518. text = (png_charp)png_malloc(png_ptr, text_size +
  189519. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189520. + 1));
  189521. png_memcpy(text, tmp, text_size);
  189522. png_free(png_ptr, tmp);
  189523. png_memcpy(text + text_size, png_ptr->zbuf,
  189524. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189525. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189526. *(text + text_size) = '\0';
  189527. }
  189528. if (ret != Z_STREAM_END)
  189529. {
  189530. png_ptr->zstream.next_out = png_ptr->zbuf;
  189531. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189532. }
  189533. }
  189534. else
  189535. {
  189536. break;
  189537. }
  189538. if (ret == Z_STREAM_END)
  189539. break;
  189540. }
  189541. inflateReset(&png_ptr->zstream);
  189542. png_ptr->zstream.avail_in = 0;
  189543. if (ret != Z_STREAM_END)
  189544. {
  189545. png_ptr->current_text = NULL;
  189546. png_free(png_ptr, key);
  189547. png_free(png_ptr, text);
  189548. return;
  189549. }
  189550. png_ptr->current_text = NULL;
  189551. png_free(png_ptr, key);
  189552. key = text;
  189553. text += key_size;
  189554. text_ptr = (png_textp)png_malloc(png_ptr,
  189555. (png_uint_32)png_sizeof(png_text));
  189556. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189557. text_ptr->key = key;
  189558. #ifdef PNG_iTXt_SUPPORTED
  189559. text_ptr->lang = NULL;
  189560. text_ptr->lang_key = NULL;
  189561. #endif
  189562. text_ptr->text = text;
  189563. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189564. png_free(png_ptr, key);
  189565. png_free(png_ptr, text_ptr);
  189566. if (ret)
  189567. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189568. }
  189569. }
  189570. #endif
  189571. #if defined(PNG_READ_iTXt_SUPPORTED)
  189572. void /* PRIVATE */
  189573. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189574. length)
  189575. {
  189576. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189577. {
  189578. png_error(png_ptr, "Out of place iTXt");
  189579. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189580. }
  189581. #ifdef PNG_MAX_MALLOC_64K
  189582. png_ptr->skip_length = 0; /* This may not be necessary */
  189583. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189584. {
  189585. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189586. png_ptr->skip_length = length - (png_uint_32)65535L;
  189587. length = (png_uint_32)65535L;
  189588. }
  189589. #endif
  189590. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189591. (png_uint_32)(length+1));
  189592. png_ptr->current_text[length] = '\0';
  189593. png_ptr->current_text_ptr = png_ptr->current_text;
  189594. png_ptr->current_text_size = (png_size_t)length;
  189595. png_ptr->current_text_left = (png_size_t)length;
  189596. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189597. }
  189598. void /* PRIVATE */
  189599. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189600. {
  189601. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189602. {
  189603. png_size_t text_size;
  189604. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189605. text_size = png_ptr->buffer_size;
  189606. else
  189607. text_size = png_ptr->current_text_left;
  189608. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189609. png_ptr->current_text_left -= text_size;
  189610. png_ptr->current_text_ptr += text_size;
  189611. }
  189612. if (!(png_ptr->current_text_left))
  189613. {
  189614. png_textp text_ptr;
  189615. png_charp key;
  189616. int comp_flag;
  189617. png_charp lang;
  189618. png_charp lang_key;
  189619. png_charp text;
  189620. int ret;
  189621. if (png_ptr->buffer_size < 4)
  189622. {
  189623. png_push_save_buffer(png_ptr);
  189624. return;
  189625. }
  189626. png_push_crc_finish(png_ptr);
  189627. #if defined(PNG_MAX_MALLOC_64K)
  189628. if (png_ptr->skip_length)
  189629. return;
  189630. #endif
  189631. key = png_ptr->current_text;
  189632. for (lang = key; *lang; lang++)
  189633. /* empty loop */ ;
  189634. if (lang < key + png_ptr->current_text_size - 3)
  189635. lang++;
  189636. comp_flag = *lang++;
  189637. lang++; /* skip comp_type, always zero */
  189638. for (lang_key = lang; *lang_key; lang_key++)
  189639. /* empty loop */ ;
  189640. lang_key++; /* skip NUL separator */
  189641. text=lang_key;
  189642. if (lang_key < key + png_ptr->current_text_size - 1)
  189643. {
  189644. for (; *text; text++)
  189645. /* empty loop */ ;
  189646. }
  189647. if (text < key + png_ptr->current_text_size)
  189648. text++;
  189649. text_ptr = (png_textp)png_malloc(png_ptr,
  189650. (png_uint_32)png_sizeof(png_text));
  189651. text_ptr->compression = comp_flag + 2;
  189652. text_ptr->key = key;
  189653. text_ptr->lang = lang;
  189654. text_ptr->lang_key = lang_key;
  189655. text_ptr->text = text;
  189656. text_ptr->text_length = 0;
  189657. text_ptr->itxt_length = png_strlen(text);
  189658. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189659. png_ptr->current_text = NULL;
  189660. png_free(png_ptr, text_ptr);
  189661. if (ret)
  189662. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189663. }
  189664. }
  189665. #endif
  189666. /* This function is called when we haven't found a handler for this
  189667. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189668. * name or a critical chunk), the chunk is (currently) silently ignored.
  189669. */
  189670. void /* PRIVATE */
  189671. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189672. length)
  189673. {
  189674. png_uint_32 skip=0;
  189675. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189676. if (!(png_ptr->chunk_name[0] & 0x20))
  189677. {
  189678. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189679. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189680. PNG_HANDLE_CHUNK_ALWAYS
  189681. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189682. && png_ptr->read_user_chunk_fn == NULL
  189683. #endif
  189684. )
  189685. #endif
  189686. png_chunk_error(png_ptr, "unknown critical chunk");
  189687. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189688. }
  189689. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189690. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189691. {
  189692. #ifdef PNG_MAX_MALLOC_64K
  189693. if (length > (png_uint_32)65535L)
  189694. {
  189695. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189696. skip = length - (png_uint_32)65535L;
  189697. length = (png_uint_32)65535L;
  189698. }
  189699. #endif
  189700. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189701. (png_charp)png_ptr->chunk_name, 5);
  189702. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189703. png_ptr->unknown_chunk.size = (png_size_t)length;
  189704. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189705. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189706. if(png_ptr->read_user_chunk_fn != NULL)
  189707. {
  189708. /* callback to user unknown chunk handler */
  189709. int ret;
  189710. ret = (*(png_ptr->read_user_chunk_fn))
  189711. (png_ptr, &png_ptr->unknown_chunk);
  189712. if (ret < 0)
  189713. png_chunk_error(png_ptr, "error in user chunk");
  189714. if (ret == 0)
  189715. {
  189716. if (!(png_ptr->chunk_name[0] & 0x20))
  189717. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189718. PNG_HANDLE_CHUNK_ALWAYS)
  189719. png_chunk_error(png_ptr, "unknown critical chunk");
  189720. png_set_unknown_chunks(png_ptr, info_ptr,
  189721. &png_ptr->unknown_chunk, 1);
  189722. }
  189723. }
  189724. #else
  189725. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189726. #endif
  189727. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189728. png_ptr->unknown_chunk.data = NULL;
  189729. }
  189730. else
  189731. #endif
  189732. skip=length;
  189733. png_push_crc_skip(png_ptr, skip);
  189734. }
  189735. void /* PRIVATE */
  189736. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189737. {
  189738. if (png_ptr->info_fn != NULL)
  189739. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189740. }
  189741. void /* PRIVATE */
  189742. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189743. {
  189744. if (png_ptr->end_fn != NULL)
  189745. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189746. }
  189747. void /* PRIVATE */
  189748. png_push_have_row(png_structp png_ptr, png_bytep row)
  189749. {
  189750. if (png_ptr->row_fn != NULL)
  189751. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189752. (int)png_ptr->pass);
  189753. }
  189754. void PNGAPI
  189755. png_progressive_combine_row (png_structp png_ptr,
  189756. png_bytep old_row, png_bytep new_row)
  189757. {
  189758. #ifdef PNG_USE_LOCAL_ARRAYS
  189759. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189760. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189761. #endif
  189762. if(png_ptr == NULL) return;
  189763. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189764. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189765. }
  189766. void PNGAPI
  189767. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189768. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189769. png_progressive_end_ptr end_fn)
  189770. {
  189771. if(png_ptr == NULL) return;
  189772. png_ptr->info_fn = info_fn;
  189773. png_ptr->row_fn = row_fn;
  189774. png_ptr->end_fn = end_fn;
  189775. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189776. }
  189777. png_voidp PNGAPI
  189778. png_get_progressive_ptr(png_structp png_ptr)
  189779. {
  189780. if(png_ptr == NULL) return (NULL);
  189781. return png_ptr->io_ptr;
  189782. }
  189783. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189784. /*** End of inlined file: pngpread.c ***/
  189785. /*** Start of inlined file: pngrio.c ***/
  189786. /* pngrio.c - functions for data input
  189787. *
  189788. * Last changed in libpng 1.2.13 November 13, 2006
  189789. * For conditions of distribution and use, see copyright notice in png.h
  189790. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189791. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189792. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189793. *
  189794. * This file provides a location for all input. Users who need
  189795. * special handling are expected to write a function that has the same
  189796. * arguments as this and performs a similar function, but that possibly
  189797. * has a different input method. Note that you shouldn't change this
  189798. * function, but rather write a replacement function and then make
  189799. * libpng use it at run time with png_set_read_fn(...).
  189800. */
  189801. #define PNG_INTERNAL
  189802. #if defined(PNG_READ_SUPPORTED)
  189803. /* Read the data from whatever input you are using. The default routine
  189804. reads from a file pointer. Note that this routine sometimes gets called
  189805. with very small lengths, so you should implement some kind of simple
  189806. buffering if you are using unbuffered reads. This should never be asked
  189807. to read more then 64K on a 16 bit machine. */
  189808. void /* PRIVATE */
  189809. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189810. {
  189811. png_debug1(4,"reading %d bytes\n", (int)length);
  189812. if (png_ptr->read_data_fn != NULL)
  189813. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189814. else
  189815. png_error(png_ptr, "Call to NULL read function");
  189816. }
  189817. #if !defined(PNG_NO_STDIO)
  189818. /* This is the function that does the actual reading of data. If you are
  189819. not reading from a standard C stream, you should create a replacement
  189820. read_data function and use it at run time with png_set_read_fn(), rather
  189821. than changing the library. */
  189822. #ifndef USE_FAR_KEYWORD
  189823. void PNGAPI
  189824. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189825. {
  189826. png_size_t check;
  189827. if(png_ptr == NULL) return;
  189828. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189829. * instead of an int, which is what fread() actually returns.
  189830. */
  189831. #if defined(_WIN32_WCE)
  189832. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189833. check = 0;
  189834. #else
  189835. check = (png_size_t)fread(data, (png_size_t)1, length,
  189836. (png_FILE_p)png_ptr->io_ptr);
  189837. #endif
  189838. if (check != length)
  189839. png_error(png_ptr, "Read Error");
  189840. }
  189841. #else
  189842. /* this is the model-independent version. Since the standard I/O library
  189843. can't handle far buffers in the medium and small models, we have to copy
  189844. the data.
  189845. */
  189846. #define NEAR_BUF_SIZE 1024
  189847. #define MIN(a,b) (a <= b ? a : b)
  189848. static void PNGAPI
  189849. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189850. {
  189851. int check;
  189852. png_byte *n_data;
  189853. png_FILE_p io_ptr;
  189854. if(png_ptr == NULL) return;
  189855. /* Check if data really is near. If so, use usual code. */
  189856. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189857. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189858. if ((png_bytep)n_data == data)
  189859. {
  189860. #if defined(_WIN32_WCE)
  189861. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189862. check = 0;
  189863. #else
  189864. check = fread(n_data, 1, length, io_ptr);
  189865. #endif
  189866. }
  189867. else
  189868. {
  189869. png_byte buf[NEAR_BUF_SIZE];
  189870. png_size_t read, remaining, err;
  189871. check = 0;
  189872. remaining = length;
  189873. do
  189874. {
  189875. read = MIN(NEAR_BUF_SIZE, remaining);
  189876. #if defined(_WIN32_WCE)
  189877. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189878. err = 0;
  189879. #else
  189880. err = fread(buf, (png_size_t)1, read, io_ptr);
  189881. #endif
  189882. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189883. if(err != read)
  189884. break;
  189885. else
  189886. check += err;
  189887. data += read;
  189888. remaining -= read;
  189889. }
  189890. while (remaining != 0);
  189891. }
  189892. if ((png_uint_32)check != (png_uint_32)length)
  189893. png_error(png_ptr, "read Error");
  189894. }
  189895. #endif
  189896. #endif
  189897. /* This function allows the application to supply a new input function
  189898. for libpng if standard C streams aren't being used.
  189899. This function takes as its arguments:
  189900. png_ptr - pointer to a png input data structure
  189901. io_ptr - pointer to user supplied structure containing info about
  189902. the input functions. May be NULL.
  189903. read_data_fn - pointer to a new input function that takes as its
  189904. arguments a pointer to a png_struct, a pointer to
  189905. a location where input data can be stored, and a 32-bit
  189906. unsigned int that is the number of bytes to be read.
  189907. To exit and output any fatal error messages the new write
  189908. function should call png_error(png_ptr, "Error msg"). */
  189909. void PNGAPI
  189910. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189911. png_rw_ptr read_data_fn)
  189912. {
  189913. if(png_ptr == NULL) return;
  189914. png_ptr->io_ptr = io_ptr;
  189915. #if !defined(PNG_NO_STDIO)
  189916. if (read_data_fn != NULL)
  189917. png_ptr->read_data_fn = read_data_fn;
  189918. else
  189919. png_ptr->read_data_fn = png_default_read_data;
  189920. #else
  189921. png_ptr->read_data_fn = read_data_fn;
  189922. #endif
  189923. /* It is an error to write to a read device */
  189924. if (png_ptr->write_data_fn != NULL)
  189925. {
  189926. png_ptr->write_data_fn = NULL;
  189927. png_warning(png_ptr,
  189928. "It's an error to set both read_data_fn and write_data_fn in the ");
  189929. png_warning(png_ptr,
  189930. "same structure. Resetting write_data_fn to NULL.");
  189931. }
  189932. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189933. png_ptr->output_flush_fn = NULL;
  189934. #endif
  189935. }
  189936. #endif /* PNG_READ_SUPPORTED */
  189937. /*** End of inlined file: pngrio.c ***/
  189938. /*** Start of inlined file: pngrtran.c ***/
  189939. /* pngrtran.c - transforms the data in a row for PNG readers
  189940. *
  189941. * Last changed in libpng 1.2.21 [October 4, 2007]
  189942. * For conditions of distribution and use, see copyright notice in png.h
  189943. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189944. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189945. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189946. *
  189947. * This file contains functions optionally called by an application
  189948. * in order to tell libpng how to handle data when reading a PNG.
  189949. * Transformations that are used in both reading and writing are
  189950. * in pngtrans.c.
  189951. */
  189952. #define PNG_INTERNAL
  189953. #if defined(PNG_READ_SUPPORTED)
  189954. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189955. void PNGAPI
  189956. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189957. {
  189958. png_debug(1, "in png_set_crc_action\n");
  189959. /* Tell libpng how we react to CRC errors in critical chunks */
  189960. if(png_ptr == NULL) return;
  189961. switch (crit_action)
  189962. {
  189963. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189964. break;
  189965. case PNG_CRC_WARN_USE: /* warn/use data */
  189966. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189967. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189968. break;
  189969. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189970. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189971. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189972. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189973. break;
  189974. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189975. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189976. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189977. case PNG_CRC_DEFAULT:
  189978. default:
  189979. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189980. break;
  189981. }
  189982. switch (ancil_action)
  189983. {
  189984. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189985. break;
  189986. case PNG_CRC_WARN_USE: /* warn/use data */
  189987. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189988. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189989. break;
  189990. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189991. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189992. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189993. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189994. break;
  189995. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189996. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189997. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189998. break;
  189999. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190000. case PNG_CRC_DEFAULT:
  190001. default:
  190002. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190003. break;
  190004. }
  190005. }
  190006. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190007. defined(PNG_FLOATING_POINT_SUPPORTED)
  190008. /* handle alpha and tRNS via a background color */
  190009. void PNGAPI
  190010. png_set_background(png_structp png_ptr,
  190011. png_color_16p background_color, int background_gamma_code,
  190012. int need_expand, double background_gamma)
  190013. {
  190014. png_debug(1, "in png_set_background\n");
  190015. if(png_ptr == NULL) return;
  190016. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190017. {
  190018. png_warning(png_ptr, "Application must supply a known background gamma");
  190019. return;
  190020. }
  190021. png_ptr->transformations |= PNG_BACKGROUND;
  190022. png_memcpy(&(png_ptr->background), background_color,
  190023. png_sizeof(png_color_16));
  190024. png_ptr->background_gamma = (float)background_gamma;
  190025. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190026. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190027. }
  190028. #endif
  190029. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190030. /* strip 16 bit depth files to 8 bit depth */
  190031. void PNGAPI
  190032. png_set_strip_16(png_structp png_ptr)
  190033. {
  190034. png_debug(1, "in png_set_strip_16\n");
  190035. if(png_ptr == NULL) return;
  190036. png_ptr->transformations |= PNG_16_TO_8;
  190037. }
  190038. #endif
  190039. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190040. void PNGAPI
  190041. png_set_strip_alpha(png_structp png_ptr)
  190042. {
  190043. png_debug(1, "in png_set_strip_alpha\n");
  190044. if(png_ptr == NULL) return;
  190045. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190046. }
  190047. #endif
  190048. #if defined(PNG_READ_DITHER_SUPPORTED)
  190049. /* Dither file to 8 bit. Supply a palette, the current number
  190050. * of elements in the palette, the maximum number of elements
  190051. * allowed, and a histogram if possible. If the current number
  190052. * of colors is greater then the maximum number, the palette will be
  190053. * modified to fit in the maximum number. "full_dither" indicates
  190054. * whether we need a dithering cube set up for RGB images, or if we
  190055. * simply are reducing the number of colors in a paletted image.
  190056. */
  190057. typedef struct png_dsort_struct
  190058. {
  190059. struct png_dsort_struct FAR * next;
  190060. png_byte left;
  190061. png_byte right;
  190062. } png_dsort;
  190063. typedef png_dsort FAR * png_dsortp;
  190064. typedef png_dsort FAR * FAR * png_dsortpp;
  190065. void PNGAPI
  190066. png_set_dither(png_structp png_ptr, png_colorp palette,
  190067. int num_palette, int maximum_colors, png_uint_16p histogram,
  190068. int full_dither)
  190069. {
  190070. png_debug(1, "in png_set_dither\n");
  190071. if(png_ptr == NULL) return;
  190072. png_ptr->transformations |= PNG_DITHER;
  190073. if (!full_dither)
  190074. {
  190075. int i;
  190076. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190077. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190078. for (i = 0; i < num_palette; i++)
  190079. png_ptr->dither_index[i] = (png_byte)i;
  190080. }
  190081. if (num_palette > maximum_colors)
  190082. {
  190083. if (histogram != NULL)
  190084. {
  190085. /* This is easy enough, just throw out the least used colors.
  190086. Perhaps not the best solution, but good enough. */
  190087. int i;
  190088. /* initialize an array to sort colors */
  190089. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190090. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190091. /* initialize the dither_sort array */
  190092. for (i = 0; i < num_palette; i++)
  190093. png_ptr->dither_sort[i] = (png_byte)i;
  190094. /* Find the least used palette entries by starting a
  190095. bubble sort, and running it until we have sorted
  190096. out enough colors. Note that we don't care about
  190097. sorting all the colors, just finding which are
  190098. least used. */
  190099. for (i = num_palette - 1; i >= maximum_colors; i--)
  190100. {
  190101. int done; /* to stop early if the list is pre-sorted */
  190102. int j;
  190103. done = 1;
  190104. for (j = 0; j < i; j++)
  190105. {
  190106. if (histogram[png_ptr->dither_sort[j]]
  190107. < histogram[png_ptr->dither_sort[j + 1]])
  190108. {
  190109. png_byte t;
  190110. t = png_ptr->dither_sort[j];
  190111. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190112. png_ptr->dither_sort[j + 1] = t;
  190113. done = 0;
  190114. }
  190115. }
  190116. if (done)
  190117. break;
  190118. }
  190119. /* swap the palette around, and set up a table, if necessary */
  190120. if (full_dither)
  190121. {
  190122. int j = num_palette;
  190123. /* put all the useful colors within the max, but don't
  190124. move the others */
  190125. for (i = 0; i < maximum_colors; i++)
  190126. {
  190127. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190128. {
  190129. do
  190130. j--;
  190131. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190132. palette[i] = palette[j];
  190133. }
  190134. }
  190135. }
  190136. else
  190137. {
  190138. int j = num_palette;
  190139. /* move all the used colors inside the max limit, and
  190140. develop a translation table */
  190141. for (i = 0; i < maximum_colors; i++)
  190142. {
  190143. /* only move the colors we need to */
  190144. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190145. {
  190146. png_color tmp_color;
  190147. do
  190148. j--;
  190149. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190150. tmp_color = palette[j];
  190151. palette[j] = palette[i];
  190152. palette[i] = tmp_color;
  190153. /* indicate where the color went */
  190154. png_ptr->dither_index[j] = (png_byte)i;
  190155. png_ptr->dither_index[i] = (png_byte)j;
  190156. }
  190157. }
  190158. /* find closest color for those colors we are not using */
  190159. for (i = 0; i < num_palette; i++)
  190160. {
  190161. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190162. {
  190163. int min_d, k, min_k, d_index;
  190164. /* find the closest color to one we threw out */
  190165. d_index = png_ptr->dither_index[i];
  190166. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190167. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190168. {
  190169. int d;
  190170. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190171. if (d < min_d)
  190172. {
  190173. min_d = d;
  190174. min_k = k;
  190175. }
  190176. }
  190177. /* point to closest color */
  190178. png_ptr->dither_index[i] = (png_byte)min_k;
  190179. }
  190180. }
  190181. }
  190182. png_free(png_ptr, png_ptr->dither_sort);
  190183. png_ptr->dither_sort=NULL;
  190184. }
  190185. else
  190186. {
  190187. /* This is much harder to do simply (and quickly). Perhaps
  190188. we need to go through a median cut routine, but those
  190189. don't always behave themselves with only a few colors
  190190. as input. So we will just find the closest two colors,
  190191. and throw out one of them (chosen somewhat randomly).
  190192. [We don't understand this at all, so if someone wants to
  190193. work on improving it, be our guest - AED, GRP]
  190194. */
  190195. int i;
  190196. int max_d;
  190197. int num_new_palette;
  190198. png_dsortp t;
  190199. png_dsortpp hash;
  190200. t=NULL;
  190201. /* initialize palette index arrays */
  190202. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190203. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190204. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190205. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190206. /* initialize the sort array */
  190207. for (i = 0; i < num_palette; i++)
  190208. {
  190209. png_ptr->index_to_palette[i] = (png_byte)i;
  190210. png_ptr->palette_to_index[i] = (png_byte)i;
  190211. }
  190212. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190213. png_sizeof (png_dsortp)));
  190214. for (i = 0; i < 769; i++)
  190215. hash[i] = NULL;
  190216. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190217. num_new_palette = num_palette;
  190218. /* initial wild guess at how far apart the farthest pixel
  190219. pair we will be eliminating will be. Larger
  190220. numbers mean more areas will be allocated, Smaller
  190221. numbers run the risk of not saving enough data, and
  190222. having to do this all over again.
  190223. I have not done extensive checking on this number.
  190224. */
  190225. max_d = 96;
  190226. while (num_new_palette > maximum_colors)
  190227. {
  190228. for (i = 0; i < num_new_palette - 1; i++)
  190229. {
  190230. int j;
  190231. for (j = i + 1; j < num_new_palette; j++)
  190232. {
  190233. int d;
  190234. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190235. if (d <= max_d)
  190236. {
  190237. t = (png_dsortp)png_malloc_warn(png_ptr,
  190238. (png_uint_32)(png_sizeof(png_dsort)));
  190239. if (t == NULL)
  190240. break;
  190241. t->next = hash[d];
  190242. t->left = (png_byte)i;
  190243. t->right = (png_byte)j;
  190244. hash[d] = t;
  190245. }
  190246. }
  190247. if (t == NULL)
  190248. break;
  190249. }
  190250. if (t != NULL)
  190251. for (i = 0; i <= max_d; i++)
  190252. {
  190253. if (hash[i] != NULL)
  190254. {
  190255. png_dsortp p;
  190256. for (p = hash[i]; p; p = p->next)
  190257. {
  190258. if ((int)png_ptr->index_to_palette[p->left]
  190259. < num_new_palette &&
  190260. (int)png_ptr->index_to_palette[p->right]
  190261. < num_new_palette)
  190262. {
  190263. int j, next_j;
  190264. if (num_new_palette & 0x01)
  190265. {
  190266. j = p->left;
  190267. next_j = p->right;
  190268. }
  190269. else
  190270. {
  190271. j = p->right;
  190272. next_j = p->left;
  190273. }
  190274. num_new_palette--;
  190275. palette[png_ptr->index_to_palette[j]]
  190276. = palette[num_new_palette];
  190277. if (!full_dither)
  190278. {
  190279. int k;
  190280. for (k = 0; k < num_palette; k++)
  190281. {
  190282. if (png_ptr->dither_index[k] ==
  190283. png_ptr->index_to_palette[j])
  190284. png_ptr->dither_index[k] =
  190285. png_ptr->index_to_palette[next_j];
  190286. if ((int)png_ptr->dither_index[k] ==
  190287. num_new_palette)
  190288. png_ptr->dither_index[k] =
  190289. png_ptr->index_to_palette[j];
  190290. }
  190291. }
  190292. png_ptr->index_to_palette[png_ptr->palette_to_index
  190293. [num_new_palette]] = png_ptr->index_to_palette[j];
  190294. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190295. = png_ptr->palette_to_index[num_new_palette];
  190296. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190297. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190298. }
  190299. if (num_new_palette <= maximum_colors)
  190300. break;
  190301. }
  190302. if (num_new_palette <= maximum_colors)
  190303. break;
  190304. }
  190305. }
  190306. for (i = 0; i < 769; i++)
  190307. {
  190308. if (hash[i] != NULL)
  190309. {
  190310. png_dsortp p = hash[i];
  190311. while (p)
  190312. {
  190313. t = p->next;
  190314. png_free(png_ptr, p);
  190315. p = t;
  190316. }
  190317. }
  190318. hash[i] = 0;
  190319. }
  190320. max_d += 96;
  190321. }
  190322. png_free(png_ptr, hash);
  190323. png_free(png_ptr, png_ptr->palette_to_index);
  190324. png_free(png_ptr, png_ptr->index_to_palette);
  190325. png_ptr->palette_to_index=NULL;
  190326. png_ptr->index_to_palette=NULL;
  190327. }
  190328. num_palette = maximum_colors;
  190329. }
  190330. if (png_ptr->palette == NULL)
  190331. {
  190332. png_ptr->palette = palette;
  190333. }
  190334. png_ptr->num_palette = (png_uint_16)num_palette;
  190335. if (full_dither)
  190336. {
  190337. int i;
  190338. png_bytep distance;
  190339. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190340. PNG_DITHER_BLUE_BITS;
  190341. int num_red = (1 << PNG_DITHER_RED_BITS);
  190342. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190343. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190344. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190345. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190346. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190347. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190348. png_sizeof (png_byte));
  190349. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190350. png_sizeof(png_byte)));
  190351. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190352. for (i = 0; i < num_palette; i++)
  190353. {
  190354. int ir, ig, ib;
  190355. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190356. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190357. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190358. for (ir = 0; ir < num_red; ir++)
  190359. {
  190360. /* int dr = abs(ir - r); */
  190361. int dr = ((ir > r) ? ir - r : r - ir);
  190362. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190363. for (ig = 0; ig < num_green; ig++)
  190364. {
  190365. /* int dg = abs(ig - g); */
  190366. int dg = ((ig > g) ? ig - g : g - ig);
  190367. int dt = dr + dg;
  190368. int dm = ((dr > dg) ? dr : dg);
  190369. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190370. for (ib = 0; ib < num_blue; ib++)
  190371. {
  190372. int d_index = index_g | ib;
  190373. /* int db = abs(ib - b); */
  190374. int db = ((ib > b) ? ib - b : b - ib);
  190375. int dmax = ((dm > db) ? dm : db);
  190376. int d = dmax + dt + db;
  190377. if (d < (int)distance[d_index])
  190378. {
  190379. distance[d_index] = (png_byte)d;
  190380. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190381. }
  190382. }
  190383. }
  190384. }
  190385. }
  190386. png_free(png_ptr, distance);
  190387. }
  190388. }
  190389. #endif
  190390. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190391. /* Transform the image from the file_gamma to the screen_gamma. We
  190392. * only do transformations on images where the file_gamma and screen_gamma
  190393. * are not close reciprocals, otherwise it slows things down slightly, and
  190394. * also needlessly introduces small errors.
  190395. *
  190396. * We will turn off gamma transformation later if no semitransparent entries
  190397. * are present in the tRNS array for palette images. We can't do it here
  190398. * because we don't necessarily have the tRNS chunk yet.
  190399. */
  190400. void PNGAPI
  190401. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190402. {
  190403. png_debug(1, "in png_set_gamma\n");
  190404. if(png_ptr == NULL) return;
  190405. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190406. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190407. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190408. png_ptr->transformations |= PNG_GAMMA;
  190409. png_ptr->gamma = (float)file_gamma;
  190410. png_ptr->screen_gamma = (float)scrn_gamma;
  190411. }
  190412. #endif
  190413. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190414. /* Expand paletted images to RGB, expand grayscale images of
  190415. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190416. * to alpha channels.
  190417. */
  190418. void PNGAPI
  190419. png_set_expand(png_structp png_ptr)
  190420. {
  190421. png_debug(1, "in png_set_expand\n");
  190422. if(png_ptr == NULL) return;
  190423. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190424. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190425. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190426. #endif
  190427. }
  190428. /* GRR 19990627: the following three functions currently are identical
  190429. * to png_set_expand(). However, it is entirely reasonable that someone
  190430. * might wish to expand an indexed image to RGB but *not* expand a single,
  190431. * fully transparent palette entry to a full alpha channel--perhaps instead
  190432. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190433. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190434. * IOW, a future version of the library may make the transformations flag
  190435. * a bit more fine-grained, with separate bits for each of these three
  190436. * functions.
  190437. *
  190438. * More to the point, these functions make it obvious what libpng will be
  190439. * doing, whereas "expand" can (and does) mean any number of things.
  190440. *
  190441. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190442. * to expand only the sample depth but not to expand the tRNS to alpha.
  190443. */
  190444. /* Expand paletted images to RGB. */
  190445. void PNGAPI
  190446. png_set_palette_to_rgb(png_structp png_ptr)
  190447. {
  190448. png_debug(1, "in png_set_palette_to_rgb\n");
  190449. if(png_ptr == NULL) return;
  190450. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190451. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190452. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190453. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190454. #endif
  190455. }
  190456. #if !defined(PNG_1_0_X)
  190457. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190458. void PNGAPI
  190459. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190460. {
  190461. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190462. if(png_ptr == NULL) return;
  190463. png_ptr->transformations |= PNG_EXPAND;
  190464. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190465. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190466. #endif
  190467. }
  190468. #endif
  190469. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190470. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190471. /* Deprecated as of libpng-1.2.9 */
  190472. void PNGAPI
  190473. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190474. {
  190475. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190476. if(png_ptr == NULL) return;
  190477. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190478. }
  190479. #endif
  190480. /* Expand tRNS chunks to alpha channels. */
  190481. void PNGAPI
  190482. png_set_tRNS_to_alpha(png_structp png_ptr)
  190483. {
  190484. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190485. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190486. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190487. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190488. #endif
  190489. }
  190490. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190491. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190492. void PNGAPI
  190493. png_set_gray_to_rgb(png_structp png_ptr)
  190494. {
  190495. png_debug(1, "in png_set_gray_to_rgb\n");
  190496. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190497. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190498. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190499. #endif
  190500. }
  190501. #endif
  190502. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190503. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190504. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190505. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190506. */
  190507. void PNGAPI
  190508. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190509. double green)
  190510. {
  190511. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190512. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190513. if(png_ptr == NULL) return;
  190514. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190515. }
  190516. #endif
  190517. void PNGAPI
  190518. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190519. png_fixed_point red, png_fixed_point green)
  190520. {
  190521. png_debug(1, "in png_set_rgb_to_gray\n");
  190522. if(png_ptr == NULL) return;
  190523. switch(error_action)
  190524. {
  190525. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190526. break;
  190527. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190528. break;
  190529. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190530. }
  190531. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190532. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190533. png_ptr->transformations |= PNG_EXPAND;
  190534. #else
  190535. {
  190536. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190537. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190538. }
  190539. #endif
  190540. {
  190541. png_uint_16 red_int, green_int;
  190542. if(red < 0 || green < 0)
  190543. {
  190544. red_int = 6968; /* .212671 * 32768 + .5 */
  190545. green_int = 23434; /* .715160 * 32768 + .5 */
  190546. }
  190547. else if(red + green < 100000L)
  190548. {
  190549. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190550. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190551. }
  190552. else
  190553. {
  190554. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190555. red_int = 6968;
  190556. green_int = 23434;
  190557. }
  190558. png_ptr->rgb_to_gray_red_coeff = red_int;
  190559. png_ptr->rgb_to_gray_green_coeff = green_int;
  190560. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190561. }
  190562. }
  190563. #endif
  190564. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190565. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190566. defined(PNG_LEGACY_SUPPORTED)
  190567. void PNGAPI
  190568. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190569. read_user_transform_fn)
  190570. {
  190571. png_debug(1, "in png_set_read_user_transform_fn\n");
  190572. if(png_ptr == NULL) return;
  190573. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190574. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190575. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190576. #endif
  190577. #ifdef PNG_LEGACY_SUPPORTED
  190578. if(read_user_transform_fn)
  190579. png_warning(png_ptr,
  190580. "This version of libpng does not support user transforms");
  190581. #endif
  190582. }
  190583. #endif
  190584. /* Initialize everything needed for the read. This includes modifying
  190585. * the palette.
  190586. */
  190587. void /* PRIVATE */
  190588. png_init_read_transformations(png_structp png_ptr)
  190589. {
  190590. png_debug(1, "in png_init_read_transformations\n");
  190591. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190592. if(png_ptr != NULL)
  190593. #endif
  190594. {
  190595. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190596. || defined(PNG_READ_GAMMA_SUPPORTED)
  190597. int color_type = png_ptr->color_type;
  190598. #endif
  190599. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190600. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190601. /* Detect gray background and attempt to enable optimization
  190602. * for gray --> RGB case */
  190603. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190604. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190605. * background color might actually be gray yet not be flagged as such.
  190606. * This is not a problem for the current code, which uses
  190607. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190608. * png_do_gray_to_rgb() transformation.
  190609. */
  190610. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190611. !(color_type & PNG_COLOR_MASK_COLOR))
  190612. {
  190613. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190614. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190615. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190616. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190617. png_ptr->background.red == png_ptr->background.green &&
  190618. png_ptr->background.red == png_ptr->background.blue)
  190619. {
  190620. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190621. png_ptr->background.gray = png_ptr->background.red;
  190622. }
  190623. #endif
  190624. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190625. (png_ptr->transformations & PNG_EXPAND))
  190626. {
  190627. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190628. {
  190629. /* expand background and tRNS chunks */
  190630. switch (png_ptr->bit_depth)
  190631. {
  190632. case 1:
  190633. png_ptr->background.gray *= (png_uint_16)0xff;
  190634. png_ptr->background.red = png_ptr->background.green
  190635. = png_ptr->background.blue = png_ptr->background.gray;
  190636. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190637. {
  190638. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190639. png_ptr->trans_values.red = png_ptr->trans_values.green
  190640. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190641. }
  190642. break;
  190643. case 2:
  190644. png_ptr->background.gray *= (png_uint_16)0x55;
  190645. png_ptr->background.red = png_ptr->background.green
  190646. = png_ptr->background.blue = png_ptr->background.gray;
  190647. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190648. {
  190649. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190650. png_ptr->trans_values.red = png_ptr->trans_values.green
  190651. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190652. }
  190653. break;
  190654. case 4:
  190655. png_ptr->background.gray *= (png_uint_16)0x11;
  190656. png_ptr->background.red = png_ptr->background.green
  190657. = png_ptr->background.blue = png_ptr->background.gray;
  190658. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190659. {
  190660. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190661. png_ptr->trans_values.red = png_ptr->trans_values.green
  190662. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190663. }
  190664. break;
  190665. case 8:
  190666. case 16:
  190667. png_ptr->background.red = png_ptr->background.green
  190668. = png_ptr->background.blue = png_ptr->background.gray;
  190669. break;
  190670. }
  190671. }
  190672. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190673. {
  190674. png_ptr->background.red =
  190675. png_ptr->palette[png_ptr->background.index].red;
  190676. png_ptr->background.green =
  190677. png_ptr->palette[png_ptr->background.index].green;
  190678. png_ptr->background.blue =
  190679. png_ptr->palette[png_ptr->background.index].blue;
  190680. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190681. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190682. {
  190683. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190684. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190685. #endif
  190686. {
  190687. /* invert the alpha channel (in tRNS) unless the pixels are
  190688. going to be expanded, in which case leave it for later */
  190689. int i,istop;
  190690. istop=(int)png_ptr->num_trans;
  190691. for (i=0; i<istop; i++)
  190692. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190693. }
  190694. }
  190695. #endif
  190696. }
  190697. }
  190698. #endif
  190699. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190700. png_ptr->background_1 = png_ptr->background;
  190701. #endif
  190702. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190703. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190704. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190705. < PNG_GAMMA_THRESHOLD))
  190706. {
  190707. int i,k;
  190708. k=0;
  190709. for (i=0; i<png_ptr->num_trans; i++)
  190710. {
  190711. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190712. k=1; /* partial transparency is present */
  190713. }
  190714. if (k == 0)
  190715. png_ptr->transformations &= (~PNG_GAMMA);
  190716. }
  190717. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190718. png_ptr->gamma != 0.0)
  190719. {
  190720. png_build_gamma_table(png_ptr);
  190721. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190722. if (png_ptr->transformations & PNG_BACKGROUND)
  190723. {
  190724. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190725. {
  190726. /* could skip if no transparency and
  190727. */
  190728. png_color back, back_1;
  190729. png_colorp palette = png_ptr->palette;
  190730. int num_palette = png_ptr->num_palette;
  190731. int i;
  190732. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190733. {
  190734. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190735. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190736. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190737. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190738. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190739. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190740. }
  190741. else
  190742. {
  190743. double g, gs;
  190744. switch (png_ptr->background_gamma_type)
  190745. {
  190746. case PNG_BACKGROUND_GAMMA_SCREEN:
  190747. g = (png_ptr->screen_gamma);
  190748. gs = 1.0;
  190749. break;
  190750. case PNG_BACKGROUND_GAMMA_FILE:
  190751. g = 1.0 / (png_ptr->gamma);
  190752. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190753. break;
  190754. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190755. g = 1.0 / (png_ptr->background_gamma);
  190756. gs = 1.0 / (png_ptr->background_gamma *
  190757. png_ptr->screen_gamma);
  190758. break;
  190759. default:
  190760. g = 1.0; /* back_1 */
  190761. gs = 1.0; /* back */
  190762. }
  190763. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190764. {
  190765. back.red = (png_byte)png_ptr->background.red;
  190766. back.green = (png_byte)png_ptr->background.green;
  190767. back.blue = (png_byte)png_ptr->background.blue;
  190768. }
  190769. else
  190770. {
  190771. back.red = (png_byte)(pow(
  190772. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190773. back.green = (png_byte)(pow(
  190774. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190775. back.blue = (png_byte)(pow(
  190776. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190777. }
  190778. back_1.red = (png_byte)(pow(
  190779. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190780. back_1.green = (png_byte)(pow(
  190781. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190782. back_1.blue = (png_byte)(pow(
  190783. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190784. }
  190785. for (i = 0; i < num_palette; i++)
  190786. {
  190787. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190788. {
  190789. if (png_ptr->trans[i] == 0)
  190790. {
  190791. palette[i] = back;
  190792. }
  190793. else /* if (png_ptr->trans[i] != 0xff) */
  190794. {
  190795. png_byte v, w;
  190796. v = png_ptr->gamma_to_1[palette[i].red];
  190797. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190798. palette[i].red = png_ptr->gamma_from_1[w];
  190799. v = png_ptr->gamma_to_1[palette[i].green];
  190800. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190801. palette[i].green = png_ptr->gamma_from_1[w];
  190802. v = png_ptr->gamma_to_1[palette[i].blue];
  190803. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190804. palette[i].blue = png_ptr->gamma_from_1[w];
  190805. }
  190806. }
  190807. else
  190808. {
  190809. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190810. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190811. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190812. }
  190813. }
  190814. }
  190815. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190816. else
  190817. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190818. {
  190819. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190820. double g = 1.0;
  190821. double gs = 1.0;
  190822. switch (png_ptr->background_gamma_type)
  190823. {
  190824. case PNG_BACKGROUND_GAMMA_SCREEN:
  190825. g = (png_ptr->screen_gamma);
  190826. gs = 1.0;
  190827. break;
  190828. case PNG_BACKGROUND_GAMMA_FILE:
  190829. g = 1.0 / (png_ptr->gamma);
  190830. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190831. break;
  190832. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190833. g = 1.0 / (png_ptr->background_gamma);
  190834. gs = 1.0 / (png_ptr->background_gamma *
  190835. png_ptr->screen_gamma);
  190836. break;
  190837. }
  190838. png_ptr->background_1.gray = (png_uint_16)(pow(
  190839. (double)png_ptr->background.gray / m, g) * m + .5);
  190840. png_ptr->background.gray = (png_uint_16)(pow(
  190841. (double)png_ptr->background.gray / m, gs) * m + .5);
  190842. if ((png_ptr->background.red != png_ptr->background.green) ||
  190843. (png_ptr->background.red != png_ptr->background.blue) ||
  190844. (png_ptr->background.red != png_ptr->background.gray))
  190845. {
  190846. /* RGB or RGBA with color background */
  190847. png_ptr->background_1.red = (png_uint_16)(pow(
  190848. (double)png_ptr->background.red / m, g) * m + .5);
  190849. png_ptr->background_1.green = (png_uint_16)(pow(
  190850. (double)png_ptr->background.green / m, g) * m + .5);
  190851. png_ptr->background_1.blue = (png_uint_16)(pow(
  190852. (double)png_ptr->background.blue / m, g) * m + .5);
  190853. png_ptr->background.red = (png_uint_16)(pow(
  190854. (double)png_ptr->background.red / m, gs) * m + .5);
  190855. png_ptr->background.green = (png_uint_16)(pow(
  190856. (double)png_ptr->background.green / m, gs) * m + .5);
  190857. png_ptr->background.blue = (png_uint_16)(pow(
  190858. (double)png_ptr->background.blue / m, gs) * m + .5);
  190859. }
  190860. else
  190861. {
  190862. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190863. png_ptr->background_1.red = png_ptr->background_1.green
  190864. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190865. png_ptr->background.red = png_ptr->background.green
  190866. = png_ptr->background.blue = png_ptr->background.gray;
  190867. }
  190868. }
  190869. }
  190870. else
  190871. /* transformation does not include PNG_BACKGROUND */
  190872. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190873. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190874. {
  190875. png_colorp palette = png_ptr->palette;
  190876. int num_palette = png_ptr->num_palette;
  190877. int i;
  190878. for (i = 0; i < num_palette; i++)
  190879. {
  190880. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190881. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190882. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190883. }
  190884. }
  190885. }
  190886. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190887. else
  190888. #endif
  190889. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190890. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190891. /* No GAMMA transformation */
  190892. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190893. (color_type == PNG_COLOR_TYPE_PALETTE))
  190894. {
  190895. int i;
  190896. int istop = (int)png_ptr->num_trans;
  190897. png_color back;
  190898. png_colorp palette = png_ptr->palette;
  190899. back.red = (png_byte)png_ptr->background.red;
  190900. back.green = (png_byte)png_ptr->background.green;
  190901. back.blue = (png_byte)png_ptr->background.blue;
  190902. for (i = 0; i < istop; i++)
  190903. {
  190904. if (png_ptr->trans[i] == 0)
  190905. {
  190906. palette[i] = back;
  190907. }
  190908. else if (png_ptr->trans[i] != 0xff)
  190909. {
  190910. /* The png_composite() macro is defined in png.h */
  190911. png_composite(palette[i].red, palette[i].red,
  190912. png_ptr->trans[i], back.red);
  190913. png_composite(palette[i].green, palette[i].green,
  190914. png_ptr->trans[i], back.green);
  190915. png_composite(palette[i].blue, palette[i].blue,
  190916. png_ptr->trans[i], back.blue);
  190917. }
  190918. }
  190919. }
  190920. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190921. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190922. if ((png_ptr->transformations & PNG_SHIFT) &&
  190923. (color_type == PNG_COLOR_TYPE_PALETTE))
  190924. {
  190925. png_uint_16 i;
  190926. png_uint_16 istop = png_ptr->num_palette;
  190927. int sr = 8 - png_ptr->sig_bit.red;
  190928. int sg = 8 - png_ptr->sig_bit.green;
  190929. int sb = 8 - png_ptr->sig_bit.blue;
  190930. if (sr < 0 || sr > 8)
  190931. sr = 0;
  190932. if (sg < 0 || sg > 8)
  190933. sg = 0;
  190934. if (sb < 0 || sb > 8)
  190935. sb = 0;
  190936. for (i = 0; i < istop; i++)
  190937. {
  190938. png_ptr->palette[i].red >>= sr;
  190939. png_ptr->palette[i].green >>= sg;
  190940. png_ptr->palette[i].blue >>= sb;
  190941. }
  190942. }
  190943. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190944. }
  190945. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190946. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190947. if(png_ptr)
  190948. return;
  190949. #endif
  190950. }
  190951. /* Modify the info structure to reflect the transformations. The
  190952. * info should be updated so a PNG file could be written with it,
  190953. * assuming the transformations result in valid PNG data.
  190954. */
  190955. void /* PRIVATE */
  190956. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190957. {
  190958. png_debug(1, "in png_read_transform_info\n");
  190959. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190960. if (png_ptr->transformations & PNG_EXPAND)
  190961. {
  190962. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190963. {
  190964. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190965. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190966. else
  190967. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190968. info_ptr->bit_depth = 8;
  190969. info_ptr->num_trans = 0;
  190970. }
  190971. else
  190972. {
  190973. if (png_ptr->num_trans)
  190974. {
  190975. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190976. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190977. else
  190978. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190979. }
  190980. if (info_ptr->bit_depth < 8)
  190981. info_ptr->bit_depth = 8;
  190982. info_ptr->num_trans = 0;
  190983. }
  190984. }
  190985. #endif
  190986. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190987. if (png_ptr->transformations & PNG_BACKGROUND)
  190988. {
  190989. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190990. info_ptr->num_trans = 0;
  190991. info_ptr->background = png_ptr->background;
  190992. }
  190993. #endif
  190994. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190995. if (png_ptr->transformations & PNG_GAMMA)
  190996. {
  190997. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190998. info_ptr->gamma = png_ptr->gamma;
  190999. #endif
  191000. #ifdef PNG_FIXED_POINT_SUPPORTED
  191001. info_ptr->int_gamma = png_ptr->int_gamma;
  191002. #endif
  191003. }
  191004. #endif
  191005. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191006. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191007. info_ptr->bit_depth = 8;
  191008. #endif
  191009. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191010. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191011. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191012. #endif
  191013. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191014. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191015. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191016. #endif
  191017. #if defined(PNG_READ_DITHER_SUPPORTED)
  191018. if (png_ptr->transformations & PNG_DITHER)
  191019. {
  191020. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191021. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191022. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191023. {
  191024. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191025. }
  191026. }
  191027. #endif
  191028. #if defined(PNG_READ_PACK_SUPPORTED)
  191029. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191030. info_ptr->bit_depth = 8;
  191031. #endif
  191032. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191033. info_ptr->channels = 1;
  191034. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191035. info_ptr->channels = 3;
  191036. else
  191037. info_ptr->channels = 1;
  191038. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191039. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191040. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191041. #endif
  191042. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191043. info_ptr->channels++;
  191044. #if defined(PNG_READ_FILLER_SUPPORTED)
  191045. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191046. if ((png_ptr->transformations & PNG_FILLER) &&
  191047. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191048. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191049. {
  191050. info_ptr->channels++;
  191051. /* if adding a true alpha channel not just filler */
  191052. #if !defined(PNG_1_0_X)
  191053. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191054. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191055. #endif
  191056. }
  191057. #endif
  191058. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191059. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191060. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191061. {
  191062. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191063. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191064. if(info_ptr->channels < png_ptr->user_transform_channels)
  191065. info_ptr->channels = png_ptr->user_transform_channels;
  191066. }
  191067. #endif
  191068. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191069. info_ptr->bit_depth);
  191070. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191071. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191072. if(png_ptr)
  191073. return;
  191074. #endif
  191075. }
  191076. /* Transform the row. The order of transformations is significant,
  191077. * and is very touchy. If you add a transformation, take care to
  191078. * decide how it fits in with the other transformations here.
  191079. */
  191080. void /* PRIVATE */
  191081. png_do_read_transformations(png_structp png_ptr)
  191082. {
  191083. png_debug(1, "in png_do_read_transformations\n");
  191084. if (png_ptr->row_buf == NULL)
  191085. {
  191086. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191087. char msg[50];
  191088. png_snprintf2(msg, 50,
  191089. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191090. png_ptr->pass);
  191091. png_error(png_ptr, msg);
  191092. #else
  191093. png_error(png_ptr, "NULL row buffer");
  191094. #endif
  191095. }
  191096. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191097. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191098. /* Application has failed to call either png_read_start_image()
  191099. * or png_read_update_info() after setting transforms that expand
  191100. * pixels. This check added to libpng-1.2.19 */
  191101. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191102. png_error(png_ptr, "Uninitialized row");
  191103. #else
  191104. png_warning(png_ptr, "Uninitialized row");
  191105. #endif
  191106. #endif
  191107. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191108. if (png_ptr->transformations & PNG_EXPAND)
  191109. {
  191110. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191111. {
  191112. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191113. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191114. }
  191115. else
  191116. {
  191117. if (png_ptr->num_trans &&
  191118. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191119. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191120. &(png_ptr->trans_values));
  191121. else
  191122. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191123. NULL);
  191124. }
  191125. }
  191126. #endif
  191127. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191128. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191129. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191130. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191131. #endif
  191132. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191133. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191134. {
  191135. int rgb_error =
  191136. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191137. if(rgb_error)
  191138. {
  191139. png_ptr->rgb_to_gray_status=1;
  191140. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191141. PNG_RGB_TO_GRAY_WARN)
  191142. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191143. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191144. PNG_RGB_TO_GRAY_ERR)
  191145. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191146. }
  191147. }
  191148. #endif
  191149. /*
  191150. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191151. In most cases, the "simple transparency" should be done prior to doing
  191152. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191153. pixel is transparent. You would also need to make sure that the
  191154. transparency information is upgraded to RGB.
  191155. To summarize, the current flow is:
  191156. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191157. with background "in place" if transparent,
  191158. convert to RGB if necessary
  191159. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191160. convert to RGB if necessary
  191161. To support RGB backgrounds for gray images we need:
  191162. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191163. 3 or 6 bytes and composite with background
  191164. "in place" if transparent (3x compare/pixel
  191165. compared to doing composite with gray bkgrnd)
  191166. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191167. remove alpha bytes (3x float operations/pixel
  191168. compared with composite on gray background)
  191169. Greg's change will do this. The reason it wasn't done before is for
  191170. performance, as this increases the per-pixel operations. If we would check
  191171. in advance if the background was gray or RGB, and position the gray-to-RGB
  191172. transform appropriately, then it would save a lot of work/time.
  191173. */
  191174. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191175. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191176. * for performance reasons */
  191177. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191178. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191179. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191180. #endif
  191181. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191182. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191183. ((png_ptr->num_trans != 0 ) ||
  191184. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191185. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191186. &(png_ptr->trans_values), &(png_ptr->background)
  191187. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191188. , &(png_ptr->background_1),
  191189. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191190. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191191. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191192. png_ptr->gamma_shift
  191193. #endif
  191194. );
  191195. #endif
  191196. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191197. if ((png_ptr->transformations & PNG_GAMMA) &&
  191198. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191199. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191200. ((png_ptr->num_trans != 0) ||
  191201. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191202. #endif
  191203. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191204. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191205. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191206. png_ptr->gamma_shift);
  191207. #endif
  191208. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191209. if (png_ptr->transformations & PNG_16_TO_8)
  191210. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191211. #endif
  191212. #if defined(PNG_READ_DITHER_SUPPORTED)
  191213. if (png_ptr->transformations & PNG_DITHER)
  191214. {
  191215. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191216. png_ptr->palette_lookup, png_ptr->dither_index);
  191217. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191218. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191219. }
  191220. #endif
  191221. #if defined(PNG_READ_INVERT_SUPPORTED)
  191222. if (png_ptr->transformations & PNG_INVERT_MONO)
  191223. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191224. #endif
  191225. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191226. if (png_ptr->transformations & PNG_SHIFT)
  191227. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191228. &(png_ptr->shift));
  191229. #endif
  191230. #if defined(PNG_READ_PACK_SUPPORTED)
  191231. if (png_ptr->transformations & PNG_PACK)
  191232. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191233. #endif
  191234. #if defined(PNG_READ_BGR_SUPPORTED)
  191235. if (png_ptr->transformations & PNG_BGR)
  191236. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191237. #endif
  191238. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191239. if (png_ptr->transformations & PNG_PACKSWAP)
  191240. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191241. #endif
  191242. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191243. /* if gray -> RGB, do so now only if we did not do so above */
  191244. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191245. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191246. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191247. #endif
  191248. #if defined(PNG_READ_FILLER_SUPPORTED)
  191249. if (png_ptr->transformations & PNG_FILLER)
  191250. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191251. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191252. #endif
  191253. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191254. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191255. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191256. #endif
  191257. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191258. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191259. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191260. #endif
  191261. #if defined(PNG_READ_SWAP_SUPPORTED)
  191262. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191263. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191264. #endif
  191265. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191266. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191267. {
  191268. if(png_ptr->read_user_transform_fn != NULL)
  191269. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191270. (png_ptr, /* png_ptr */
  191271. &(png_ptr->row_info), /* row_info: */
  191272. /* png_uint_32 width; width of row */
  191273. /* png_uint_32 rowbytes; number of bytes in row */
  191274. /* png_byte color_type; color type of pixels */
  191275. /* png_byte bit_depth; bit depth of samples */
  191276. /* png_byte channels; number of channels (1-4) */
  191277. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191278. png_ptr->row_buf + 1); /* start of pixel data for row */
  191279. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191280. if(png_ptr->user_transform_depth)
  191281. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191282. if(png_ptr->user_transform_channels)
  191283. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191284. #endif
  191285. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191286. png_ptr->row_info.channels);
  191287. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191288. png_ptr->row_info.width);
  191289. }
  191290. #endif
  191291. }
  191292. #if defined(PNG_READ_PACK_SUPPORTED)
  191293. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191294. * without changing the actual values. Thus, if you had a row with
  191295. * a bit depth of 1, you would end up with bytes that only contained
  191296. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191297. * png_do_shift() after this.
  191298. */
  191299. void /* PRIVATE */
  191300. png_do_unpack(png_row_infop row_info, png_bytep row)
  191301. {
  191302. png_debug(1, "in png_do_unpack\n");
  191303. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191304. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191305. #else
  191306. if (row_info->bit_depth < 8)
  191307. #endif
  191308. {
  191309. png_uint_32 i;
  191310. png_uint_32 row_width=row_info->width;
  191311. switch (row_info->bit_depth)
  191312. {
  191313. case 1:
  191314. {
  191315. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191316. png_bytep dp = row + (png_size_t)row_width - 1;
  191317. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191318. for (i = 0; i < row_width; i++)
  191319. {
  191320. *dp = (png_byte)((*sp >> shift) & 0x01);
  191321. if (shift == 7)
  191322. {
  191323. shift = 0;
  191324. sp--;
  191325. }
  191326. else
  191327. shift++;
  191328. dp--;
  191329. }
  191330. break;
  191331. }
  191332. case 2:
  191333. {
  191334. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191335. png_bytep dp = row + (png_size_t)row_width - 1;
  191336. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191337. for (i = 0; i < row_width; i++)
  191338. {
  191339. *dp = (png_byte)((*sp >> shift) & 0x03);
  191340. if (shift == 6)
  191341. {
  191342. shift = 0;
  191343. sp--;
  191344. }
  191345. else
  191346. shift += 2;
  191347. dp--;
  191348. }
  191349. break;
  191350. }
  191351. case 4:
  191352. {
  191353. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191354. png_bytep dp = row + (png_size_t)row_width - 1;
  191355. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191356. for (i = 0; i < row_width; i++)
  191357. {
  191358. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191359. if (shift == 4)
  191360. {
  191361. shift = 0;
  191362. sp--;
  191363. }
  191364. else
  191365. shift = 4;
  191366. dp--;
  191367. }
  191368. break;
  191369. }
  191370. }
  191371. row_info->bit_depth = 8;
  191372. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191373. row_info->rowbytes = row_width * row_info->channels;
  191374. }
  191375. }
  191376. #endif
  191377. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191378. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191379. * pixels back to their significant bits values. Thus, if you have
  191380. * a row of bit depth 8, but only 5 are significant, this will shift
  191381. * the values back to 0 through 31.
  191382. */
  191383. void /* PRIVATE */
  191384. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191385. {
  191386. png_debug(1, "in png_do_unshift\n");
  191387. if (
  191388. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191389. row != NULL && row_info != NULL && sig_bits != NULL &&
  191390. #endif
  191391. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191392. {
  191393. int shift[4];
  191394. int channels = 0;
  191395. int c;
  191396. png_uint_16 value = 0;
  191397. png_uint_32 row_width = row_info->width;
  191398. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191399. {
  191400. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191401. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191402. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191403. }
  191404. else
  191405. {
  191406. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191407. }
  191408. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191409. {
  191410. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191411. }
  191412. for (c = 0; c < channels; c++)
  191413. {
  191414. if (shift[c] <= 0)
  191415. shift[c] = 0;
  191416. else
  191417. value = 1;
  191418. }
  191419. if (!value)
  191420. return;
  191421. switch (row_info->bit_depth)
  191422. {
  191423. case 2:
  191424. {
  191425. png_bytep bp;
  191426. png_uint_32 i;
  191427. png_uint_32 istop = row_info->rowbytes;
  191428. for (bp = row, i = 0; i < istop; i++)
  191429. {
  191430. *bp >>= 1;
  191431. *bp++ &= 0x55;
  191432. }
  191433. break;
  191434. }
  191435. case 4:
  191436. {
  191437. png_bytep bp = row;
  191438. png_uint_32 i;
  191439. png_uint_32 istop = row_info->rowbytes;
  191440. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191441. (png_byte)((int)0xf >> shift[0]));
  191442. for (i = 0; i < istop; i++)
  191443. {
  191444. *bp >>= shift[0];
  191445. *bp++ &= mask;
  191446. }
  191447. break;
  191448. }
  191449. case 8:
  191450. {
  191451. png_bytep bp = row;
  191452. png_uint_32 i;
  191453. png_uint_32 istop = row_width * channels;
  191454. for (i = 0; i < istop; i++)
  191455. {
  191456. *bp++ >>= shift[i%channels];
  191457. }
  191458. break;
  191459. }
  191460. case 16:
  191461. {
  191462. png_bytep bp = row;
  191463. png_uint_32 i;
  191464. png_uint_32 istop = channels * row_width;
  191465. for (i = 0; i < istop; i++)
  191466. {
  191467. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191468. value >>= shift[i%channels];
  191469. *bp++ = (png_byte)(value >> 8);
  191470. *bp++ = (png_byte)(value & 0xff);
  191471. }
  191472. break;
  191473. }
  191474. }
  191475. }
  191476. }
  191477. #endif
  191478. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191479. /* chop rows of bit depth 16 down to 8 */
  191480. void /* PRIVATE */
  191481. png_do_chop(png_row_infop row_info, png_bytep row)
  191482. {
  191483. png_debug(1, "in png_do_chop\n");
  191484. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191485. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191486. #else
  191487. if (row_info->bit_depth == 16)
  191488. #endif
  191489. {
  191490. png_bytep sp = row;
  191491. png_bytep dp = row;
  191492. png_uint_32 i;
  191493. png_uint_32 istop = row_info->width * row_info->channels;
  191494. for (i = 0; i<istop; i++, sp += 2, dp++)
  191495. {
  191496. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191497. /* This does a more accurate scaling of the 16-bit color
  191498. * value, rather than a simple low-byte truncation.
  191499. *
  191500. * What the ideal calculation should be:
  191501. * *dp = (((((png_uint_32)(*sp) << 8) |
  191502. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191503. *
  191504. * GRR: no, I think this is what it really should be:
  191505. * *dp = (((((png_uint_32)(*sp) << 8) |
  191506. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191507. *
  191508. * GRR: here's the exact calculation with shifts:
  191509. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191510. * *dp = (temp - (temp >> 8)) >> 8;
  191511. *
  191512. * Approximate calculation with shift/add instead of multiply/divide:
  191513. * *dp = ((((png_uint_32)(*sp) << 8) |
  191514. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191515. *
  191516. * What we actually do to avoid extra shifting and conversion:
  191517. */
  191518. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191519. #else
  191520. /* Simply discard the low order byte */
  191521. *dp = *sp;
  191522. #endif
  191523. }
  191524. row_info->bit_depth = 8;
  191525. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191526. row_info->rowbytes = row_info->width * row_info->channels;
  191527. }
  191528. }
  191529. #endif
  191530. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191531. void /* PRIVATE */
  191532. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191533. {
  191534. png_debug(1, "in png_do_read_swap_alpha\n");
  191535. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191536. if (row != NULL && row_info != NULL)
  191537. #endif
  191538. {
  191539. png_uint_32 row_width = row_info->width;
  191540. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191541. {
  191542. /* This converts from RGBA to ARGB */
  191543. if (row_info->bit_depth == 8)
  191544. {
  191545. png_bytep sp = row + row_info->rowbytes;
  191546. png_bytep dp = sp;
  191547. png_byte save;
  191548. png_uint_32 i;
  191549. for (i = 0; i < row_width; i++)
  191550. {
  191551. save = *(--sp);
  191552. *(--dp) = *(--sp);
  191553. *(--dp) = *(--sp);
  191554. *(--dp) = *(--sp);
  191555. *(--dp) = save;
  191556. }
  191557. }
  191558. /* This converts from RRGGBBAA to AARRGGBB */
  191559. else
  191560. {
  191561. png_bytep sp = row + row_info->rowbytes;
  191562. png_bytep dp = sp;
  191563. png_byte save[2];
  191564. png_uint_32 i;
  191565. for (i = 0; i < row_width; i++)
  191566. {
  191567. save[0] = *(--sp);
  191568. save[1] = *(--sp);
  191569. *(--dp) = *(--sp);
  191570. *(--dp) = *(--sp);
  191571. *(--dp) = *(--sp);
  191572. *(--dp) = *(--sp);
  191573. *(--dp) = *(--sp);
  191574. *(--dp) = *(--sp);
  191575. *(--dp) = save[0];
  191576. *(--dp) = save[1];
  191577. }
  191578. }
  191579. }
  191580. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191581. {
  191582. /* This converts from GA to AG */
  191583. if (row_info->bit_depth == 8)
  191584. {
  191585. png_bytep sp = row + row_info->rowbytes;
  191586. png_bytep dp = sp;
  191587. png_byte save;
  191588. png_uint_32 i;
  191589. for (i = 0; i < row_width; i++)
  191590. {
  191591. save = *(--sp);
  191592. *(--dp) = *(--sp);
  191593. *(--dp) = save;
  191594. }
  191595. }
  191596. /* This converts from GGAA to AAGG */
  191597. else
  191598. {
  191599. png_bytep sp = row + row_info->rowbytes;
  191600. png_bytep dp = sp;
  191601. png_byte save[2];
  191602. png_uint_32 i;
  191603. for (i = 0; i < row_width; i++)
  191604. {
  191605. save[0] = *(--sp);
  191606. save[1] = *(--sp);
  191607. *(--dp) = *(--sp);
  191608. *(--dp) = *(--sp);
  191609. *(--dp) = save[0];
  191610. *(--dp) = save[1];
  191611. }
  191612. }
  191613. }
  191614. }
  191615. }
  191616. #endif
  191617. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191618. void /* PRIVATE */
  191619. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191620. {
  191621. png_debug(1, "in png_do_read_invert_alpha\n");
  191622. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191623. if (row != NULL && row_info != NULL)
  191624. #endif
  191625. {
  191626. png_uint_32 row_width = row_info->width;
  191627. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191628. {
  191629. /* This inverts the alpha channel in RGBA */
  191630. if (row_info->bit_depth == 8)
  191631. {
  191632. png_bytep sp = row + row_info->rowbytes;
  191633. png_bytep dp = sp;
  191634. png_uint_32 i;
  191635. for (i = 0; i < row_width; i++)
  191636. {
  191637. *(--dp) = (png_byte)(255 - *(--sp));
  191638. /* This does nothing:
  191639. *(--dp) = *(--sp);
  191640. *(--dp) = *(--sp);
  191641. *(--dp) = *(--sp);
  191642. We can replace it with:
  191643. */
  191644. sp-=3;
  191645. dp=sp;
  191646. }
  191647. }
  191648. /* This inverts the alpha channel in RRGGBBAA */
  191649. else
  191650. {
  191651. png_bytep sp = row + row_info->rowbytes;
  191652. png_bytep dp = sp;
  191653. png_uint_32 i;
  191654. for (i = 0; i < row_width; i++)
  191655. {
  191656. *(--dp) = (png_byte)(255 - *(--sp));
  191657. *(--dp) = (png_byte)(255 - *(--sp));
  191658. /* This does nothing:
  191659. *(--dp) = *(--sp);
  191660. *(--dp) = *(--sp);
  191661. *(--dp) = *(--sp);
  191662. *(--dp) = *(--sp);
  191663. *(--dp) = *(--sp);
  191664. *(--dp) = *(--sp);
  191665. We can replace it with:
  191666. */
  191667. sp-=6;
  191668. dp=sp;
  191669. }
  191670. }
  191671. }
  191672. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191673. {
  191674. /* This inverts the alpha channel in GA */
  191675. if (row_info->bit_depth == 8)
  191676. {
  191677. png_bytep sp = row + row_info->rowbytes;
  191678. png_bytep dp = sp;
  191679. png_uint_32 i;
  191680. for (i = 0; i < row_width; i++)
  191681. {
  191682. *(--dp) = (png_byte)(255 - *(--sp));
  191683. *(--dp) = *(--sp);
  191684. }
  191685. }
  191686. /* This inverts the alpha channel in GGAA */
  191687. else
  191688. {
  191689. png_bytep sp = row + row_info->rowbytes;
  191690. png_bytep dp = sp;
  191691. png_uint_32 i;
  191692. for (i = 0; i < row_width; i++)
  191693. {
  191694. *(--dp) = (png_byte)(255 - *(--sp));
  191695. *(--dp) = (png_byte)(255 - *(--sp));
  191696. /*
  191697. *(--dp) = *(--sp);
  191698. *(--dp) = *(--sp);
  191699. */
  191700. sp-=2;
  191701. dp=sp;
  191702. }
  191703. }
  191704. }
  191705. }
  191706. }
  191707. #endif
  191708. #if defined(PNG_READ_FILLER_SUPPORTED)
  191709. /* Add filler channel if we have RGB color */
  191710. void /* PRIVATE */
  191711. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191712. png_uint_32 filler, png_uint_32 flags)
  191713. {
  191714. png_uint_32 i;
  191715. png_uint_32 row_width = row_info->width;
  191716. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191717. png_byte lo_filler = (png_byte)(filler & 0xff);
  191718. png_debug(1, "in png_do_read_filler\n");
  191719. if (
  191720. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191721. row != NULL && row_info != NULL &&
  191722. #endif
  191723. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191724. {
  191725. if(row_info->bit_depth == 8)
  191726. {
  191727. /* This changes the data from G to GX */
  191728. if (flags & PNG_FLAG_FILLER_AFTER)
  191729. {
  191730. png_bytep sp = row + (png_size_t)row_width;
  191731. png_bytep dp = sp + (png_size_t)row_width;
  191732. for (i = 1; i < row_width; i++)
  191733. {
  191734. *(--dp) = lo_filler;
  191735. *(--dp) = *(--sp);
  191736. }
  191737. *(--dp) = lo_filler;
  191738. row_info->channels = 2;
  191739. row_info->pixel_depth = 16;
  191740. row_info->rowbytes = row_width * 2;
  191741. }
  191742. /* This changes the data from G to XG */
  191743. else
  191744. {
  191745. png_bytep sp = row + (png_size_t)row_width;
  191746. png_bytep dp = sp + (png_size_t)row_width;
  191747. for (i = 0; i < row_width; i++)
  191748. {
  191749. *(--dp) = *(--sp);
  191750. *(--dp) = lo_filler;
  191751. }
  191752. row_info->channels = 2;
  191753. row_info->pixel_depth = 16;
  191754. row_info->rowbytes = row_width * 2;
  191755. }
  191756. }
  191757. else if(row_info->bit_depth == 16)
  191758. {
  191759. /* This changes the data from GG to GGXX */
  191760. if (flags & PNG_FLAG_FILLER_AFTER)
  191761. {
  191762. png_bytep sp = row + (png_size_t)row_width * 2;
  191763. png_bytep dp = sp + (png_size_t)row_width * 2;
  191764. for (i = 1; i < row_width; i++)
  191765. {
  191766. *(--dp) = hi_filler;
  191767. *(--dp) = lo_filler;
  191768. *(--dp) = *(--sp);
  191769. *(--dp) = *(--sp);
  191770. }
  191771. *(--dp) = hi_filler;
  191772. *(--dp) = lo_filler;
  191773. row_info->channels = 2;
  191774. row_info->pixel_depth = 32;
  191775. row_info->rowbytes = row_width * 4;
  191776. }
  191777. /* This changes the data from GG to XXGG */
  191778. else
  191779. {
  191780. png_bytep sp = row + (png_size_t)row_width * 2;
  191781. png_bytep dp = sp + (png_size_t)row_width * 2;
  191782. for (i = 0; i < row_width; i++)
  191783. {
  191784. *(--dp) = *(--sp);
  191785. *(--dp) = *(--sp);
  191786. *(--dp) = hi_filler;
  191787. *(--dp) = lo_filler;
  191788. }
  191789. row_info->channels = 2;
  191790. row_info->pixel_depth = 32;
  191791. row_info->rowbytes = row_width * 4;
  191792. }
  191793. }
  191794. } /* COLOR_TYPE == GRAY */
  191795. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191796. {
  191797. if(row_info->bit_depth == 8)
  191798. {
  191799. /* This changes the data from RGB to RGBX */
  191800. if (flags & PNG_FLAG_FILLER_AFTER)
  191801. {
  191802. png_bytep sp = row + (png_size_t)row_width * 3;
  191803. png_bytep dp = sp + (png_size_t)row_width;
  191804. for (i = 1; i < row_width; i++)
  191805. {
  191806. *(--dp) = lo_filler;
  191807. *(--dp) = *(--sp);
  191808. *(--dp) = *(--sp);
  191809. *(--dp) = *(--sp);
  191810. }
  191811. *(--dp) = lo_filler;
  191812. row_info->channels = 4;
  191813. row_info->pixel_depth = 32;
  191814. row_info->rowbytes = row_width * 4;
  191815. }
  191816. /* This changes the data from RGB to XRGB */
  191817. else
  191818. {
  191819. png_bytep sp = row + (png_size_t)row_width * 3;
  191820. png_bytep dp = sp + (png_size_t)row_width;
  191821. for (i = 0; i < row_width; i++)
  191822. {
  191823. *(--dp) = *(--sp);
  191824. *(--dp) = *(--sp);
  191825. *(--dp) = *(--sp);
  191826. *(--dp) = lo_filler;
  191827. }
  191828. row_info->channels = 4;
  191829. row_info->pixel_depth = 32;
  191830. row_info->rowbytes = row_width * 4;
  191831. }
  191832. }
  191833. else if(row_info->bit_depth == 16)
  191834. {
  191835. /* This changes the data from RRGGBB to RRGGBBXX */
  191836. if (flags & PNG_FLAG_FILLER_AFTER)
  191837. {
  191838. png_bytep sp = row + (png_size_t)row_width * 6;
  191839. png_bytep dp = sp + (png_size_t)row_width * 2;
  191840. for (i = 1; i < row_width; i++)
  191841. {
  191842. *(--dp) = hi_filler;
  191843. *(--dp) = lo_filler;
  191844. *(--dp) = *(--sp);
  191845. *(--dp) = *(--sp);
  191846. *(--dp) = *(--sp);
  191847. *(--dp) = *(--sp);
  191848. *(--dp) = *(--sp);
  191849. *(--dp) = *(--sp);
  191850. }
  191851. *(--dp) = hi_filler;
  191852. *(--dp) = lo_filler;
  191853. row_info->channels = 4;
  191854. row_info->pixel_depth = 64;
  191855. row_info->rowbytes = row_width * 8;
  191856. }
  191857. /* This changes the data from RRGGBB to XXRRGGBB */
  191858. else
  191859. {
  191860. png_bytep sp = row + (png_size_t)row_width * 6;
  191861. png_bytep dp = sp + (png_size_t)row_width * 2;
  191862. for (i = 0; i < row_width; i++)
  191863. {
  191864. *(--dp) = *(--sp);
  191865. *(--dp) = *(--sp);
  191866. *(--dp) = *(--sp);
  191867. *(--dp) = *(--sp);
  191868. *(--dp) = *(--sp);
  191869. *(--dp) = *(--sp);
  191870. *(--dp) = hi_filler;
  191871. *(--dp) = lo_filler;
  191872. }
  191873. row_info->channels = 4;
  191874. row_info->pixel_depth = 64;
  191875. row_info->rowbytes = row_width * 8;
  191876. }
  191877. }
  191878. } /* COLOR_TYPE == RGB */
  191879. }
  191880. #endif
  191881. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191882. /* expand grayscale files to RGB, with or without alpha */
  191883. void /* PRIVATE */
  191884. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191885. {
  191886. png_uint_32 i;
  191887. png_uint_32 row_width = row_info->width;
  191888. png_debug(1, "in png_do_gray_to_rgb\n");
  191889. if (row_info->bit_depth >= 8 &&
  191890. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191891. row != NULL && row_info != NULL &&
  191892. #endif
  191893. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191894. {
  191895. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191896. {
  191897. if (row_info->bit_depth == 8)
  191898. {
  191899. png_bytep sp = row + (png_size_t)row_width - 1;
  191900. png_bytep dp = sp + (png_size_t)row_width * 2;
  191901. for (i = 0; i < row_width; i++)
  191902. {
  191903. *(dp--) = *sp;
  191904. *(dp--) = *sp;
  191905. *(dp--) = *(sp--);
  191906. }
  191907. }
  191908. else
  191909. {
  191910. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191911. png_bytep dp = sp + (png_size_t)row_width * 4;
  191912. for (i = 0; i < row_width; i++)
  191913. {
  191914. *(dp--) = *sp;
  191915. *(dp--) = *(sp - 1);
  191916. *(dp--) = *sp;
  191917. *(dp--) = *(sp - 1);
  191918. *(dp--) = *(sp--);
  191919. *(dp--) = *(sp--);
  191920. }
  191921. }
  191922. }
  191923. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191924. {
  191925. if (row_info->bit_depth == 8)
  191926. {
  191927. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191928. png_bytep dp = sp + (png_size_t)row_width * 2;
  191929. for (i = 0; i < row_width; i++)
  191930. {
  191931. *(dp--) = *(sp--);
  191932. *(dp--) = *sp;
  191933. *(dp--) = *sp;
  191934. *(dp--) = *(sp--);
  191935. }
  191936. }
  191937. else
  191938. {
  191939. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191940. png_bytep dp = sp + (png_size_t)row_width * 4;
  191941. for (i = 0; i < row_width; i++)
  191942. {
  191943. *(dp--) = *(sp--);
  191944. *(dp--) = *(sp--);
  191945. *(dp--) = *sp;
  191946. *(dp--) = *(sp - 1);
  191947. *(dp--) = *sp;
  191948. *(dp--) = *(sp - 1);
  191949. *(dp--) = *(sp--);
  191950. *(dp--) = *(sp--);
  191951. }
  191952. }
  191953. }
  191954. row_info->channels += (png_byte)2;
  191955. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191956. row_info->pixel_depth = (png_byte)(row_info->channels *
  191957. row_info->bit_depth);
  191958. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191959. }
  191960. }
  191961. #endif
  191962. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191963. /* reduce RGB files to grayscale, with or without alpha
  191964. * using the equation given in Poynton's ColorFAQ at
  191965. * <http://www.inforamp.net/~poynton/>
  191966. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191967. *
  191968. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191969. *
  191970. * We approximate this with
  191971. *
  191972. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191973. *
  191974. * which can be expressed with integers as
  191975. *
  191976. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191977. *
  191978. * The calculation is to be done in a linear colorspace.
  191979. *
  191980. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191981. */
  191982. int /* PRIVATE */
  191983. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191984. {
  191985. png_uint_32 i;
  191986. png_uint_32 row_width = row_info->width;
  191987. int rgb_error = 0;
  191988. png_debug(1, "in png_do_rgb_to_gray\n");
  191989. if (
  191990. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191991. row != NULL && row_info != NULL &&
  191992. #endif
  191993. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191994. {
  191995. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191996. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191997. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191998. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191999. {
  192000. if (row_info->bit_depth == 8)
  192001. {
  192002. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192003. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192004. {
  192005. png_bytep sp = row;
  192006. png_bytep dp = row;
  192007. for (i = 0; i < row_width; i++)
  192008. {
  192009. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192010. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192011. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192012. if(red != green || red != blue)
  192013. {
  192014. rgb_error |= 1;
  192015. *(dp++) = png_ptr->gamma_from_1[
  192016. (rc*red+gc*green+bc*blue)>>15];
  192017. }
  192018. else
  192019. *(dp++) = *(sp-1);
  192020. }
  192021. }
  192022. else
  192023. #endif
  192024. {
  192025. png_bytep sp = row;
  192026. png_bytep dp = row;
  192027. for (i = 0; i < row_width; i++)
  192028. {
  192029. png_byte red = *(sp++);
  192030. png_byte green = *(sp++);
  192031. png_byte blue = *(sp++);
  192032. if(red != green || red != blue)
  192033. {
  192034. rgb_error |= 1;
  192035. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192036. }
  192037. else
  192038. *(dp++) = *(sp-1);
  192039. }
  192040. }
  192041. }
  192042. else /* RGB bit_depth == 16 */
  192043. {
  192044. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192045. if (png_ptr->gamma_16_to_1 != NULL &&
  192046. png_ptr->gamma_16_from_1 != NULL)
  192047. {
  192048. png_bytep sp = row;
  192049. png_bytep dp = row;
  192050. for (i = 0; i < row_width; i++)
  192051. {
  192052. png_uint_16 red, green, blue, w;
  192053. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192054. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192055. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192056. if(red == green && red == blue)
  192057. w = red;
  192058. else
  192059. {
  192060. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192061. png_ptr->gamma_shift][red>>8];
  192062. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192063. png_ptr->gamma_shift][green>>8];
  192064. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192065. png_ptr->gamma_shift][blue>>8];
  192066. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192067. + bc*blue_1)>>15);
  192068. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192069. png_ptr->gamma_shift][gray16 >> 8];
  192070. rgb_error |= 1;
  192071. }
  192072. *(dp++) = (png_byte)((w>>8) & 0xff);
  192073. *(dp++) = (png_byte)(w & 0xff);
  192074. }
  192075. }
  192076. else
  192077. #endif
  192078. {
  192079. png_bytep sp = row;
  192080. png_bytep dp = row;
  192081. for (i = 0; i < row_width; i++)
  192082. {
  192083. png_uint_16 red, green, blue, gray16;
  192084. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192085. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192086. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192087. if(red != green || red != blue)
  192088. rgb_error |= 1;
  192089. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192090. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192091. *(dp++) = (png_byte)(gray16 & 0xff);
  192092. }
  192093. }
  192094. }
  192095. }
  192096. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192097. {
  192098. if (row_info->bit_depth == 8)
  192099. {
  192100. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192101. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192102. {
  192103. png_bytep sp = row;
  192104. png_bytep dp = row;
  192105. for (i = 0; i < row_width; i++)
  192106. {
  192107. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192108. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192109. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192110. if(red != green || red != blue)
  192111. rgb_error |= 1;
  192112. *(dp++) = png_ptr->gamma_from_1
  192113. [(rc*red + gc*green + bc*blue)>>15];
  192114. *(dp++) = *(sp++); /* alpha */
  192115. }
  192116. }
  192117. else
  192118. #endif
  192119. {
  192120. png_bytep sp = row;
  192121. png_bytep dp = row;
  192122. for (i = 0; i < row_width; i++)
  192123. {
  192124. png_byte red = *(sp++);
  192125. png_byte green = *(sp++);
  192126. png_byte blue = *(sp++);
  192127. if(red != green || red != blue)
  192128. rgb_error |= 1;
  192129. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192130. *(dp++) = *(sp++); /* alpha */
  192131. }
  192132. }
  192133. }
  192134. else /* RGBA bit_depth == 16 */
  192135. {
  192136. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192137. if (png_ptr->gamma_16_to_1 != NULL &&
  192138. png_ptr->gamma_16_from_1 != NULL)
  192139. {
  192140. png_bytep sp = row;
  192141. png_bytep dp = row;
  192142. for (i = 0; i < row_width; i++)
  192143. {
  192144. png_uint_16 red, green, blue, w;
  192145. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192146. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192147. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192148. if(red == green && red == blue)
  192149. w = red;
  192150. else
  192151. {
  192152. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192153. png_ptr->gamma_shift][red>>8];
  192154. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192155. png_ptr->gamma_shift][green>>8];
  192156. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192157. png_ptr->gamma_shift][blue>>8];
  192158. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192159. + gc * green_1 + bc * blue_1)>>15);
  192160. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192161. png_ptr->gamma_shift][gray16 >> 8];
  192162. rgb_error |= 1;
  192163. }
  192164. *(dp++) = (png_byte)((w>>8) & 0xff);
  192165. *(dp++) = (png_byte)(w & 0xff);
  192166. *(dp++) = *(sp++); /* alpha */
  192167. *(dp++) = *(sp++);
  192168. }
  192169. }
  192170. else
  192171. #endif
  192172. {
  192173. png_bytep sp = row;
  192174. png_bytep dp = row;
  192175. for (i = 0; i < row_width; i++)
  192176. {
  192177. png_uint_16 red, green, blue, gray16;
  192178. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192179. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192180. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192181. if(red != green || red != blue)
  192182. rgb_error |= 1;
  192183. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192184. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192185. *(dp++) = (png_byte)(gray16 & 0xff);
  192186. *(dp++) = *(sp++); /* alpha */
  192187. *(dp++) = *(sp++);
  192188. }
  192189. }
  192190. }
  192191. }
  192192. row_info->channels -= (png_byte)2;
  192193. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192194. row_info->pixel_depth = (png_byte)(row_info->channels *
  192195. row_info->bit_depth);
  192196. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192197. }
  192198. return rgb_error;
  192199. }
  192200. #endif
  192201. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192202. * large of png_color. This lets grayscale images be treated as
  192203. * paletted. Most useful for gamma correction and simplification
  192204. * of code.
  192205. */
  192206. void PNGAPI
  192207. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192208. {
  192209. int num_palette;
  192210. int color_inc;
  192211. int i;
  192212. int v;
  192213. png_debug(1, "in png_do_build_grayscale_palette\n");
  192214. if (palette == NULL)
  192215. return;
  192216. switch (bit_depth)
  192217. {
  192218. case 1:
  192219. num_palette = 2;
  192220. color_inc = 0xff;
  192221. break;
  192222. case 2:
  192223. num_palette = 4;
  192224. color_inc = 0x55;
  192225. break;
  192226. case 4:
  192227. num_palette = 16;
  192228. color_inc = 0x11;
  192229. break;
  192230. case 8:
  192231. num_palette = 256;
  192232. color_inc = 1;
  192233. break;
  192234. default:
  192235. num_palette = 0;
  192236. color_inc = 0;
  192237. break;
  192238. }
  192239. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192240. {
  192241. palette[i].red = (png_byte)v;
  192242. palette[i].green = (png_byte)v;
  192243. palette[i].blue = (png_byte)v;
  192244. }
  192245. }
  192246. /* This function is currently unused. Do we really need it? */
  192247. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192248. void /* PRIVATE */
  192249. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192250. int num_palette)
  192251. {
  192252. png_debug(1, "in png_correct_palette\n");
  192253. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192254. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192255. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192256. {
  192257. png_color back, back_1;
  192258. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192259. {
  192260. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192261. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192262. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192263. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192264. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192265. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192266. }
  192267. else
  192268. {
  192269. double g;
  192270. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192271. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192272. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192273. {
  192274. back.red = png_ptr->background.red;
  192275. back.green = png_ptr->background.green;
  192276. back.blue = png_ptr->background.blue;
  192277. }
  192278. else
  192279. {
  192280. back.red =
  192281. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192282. 255.0 + 0.5);
  192283. back.green =
  192284. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192285. 255.0 + 0.5);
  192286. back.blue =
  192287. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192288. 255.0 + 0.5);
  192289. }
  192290. g = 1.0 / png_ptr->background_gamma;
  192291. back_1.red =
  192292. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192293. 255.0 + 0.5);
  192294. back_1.green =
  192295. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192296. 255.0 + 0.5);
  192297. back_1.blue =
  192298. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192299. 255.0 + 0.5);
  192300. }
  192301. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192302. {
  192303. png_uint_32 i;
  192304. for (i = 0; i < (png_uint_32)num_palette; i++)
  192305. {
  192306. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192307. {
  192308. palette[i] = back;
  192309. }
  192310. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192311. {
  192312. png_byte v, w;
  192313. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192314. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192315. palette[i].red = png_ptr->gamma_from_1[w];
  192316. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192317. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192318. palette[i].green = png_ptr->gamma_from_1[w];
  192319. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192320. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192321. palette[i].blue = png_ptr->gamma_from_1[w];
  192322. }
  192323. else
  192324. {
  192325. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192326. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192327. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192328. }
  192329. }
  192330. }
  192331. else
  192332. {
  192333. int i;
  192334. for (i = 0; i < num_palette; i++)
  192335. {
  192336. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192337. {
  192338. palette[i] = back;
  192339. }
  192340. else
  192341. {
  192342. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192343. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192344. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192345. }
  192346. }
  192347. }
  192348. }
  192349. else
  192350. #endif
  192351. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192352. if (png_ptr->transformations & PNG_GAMMA)
  192353. {
  192354. int i;
  192355. for (i = 0; i < num_palette; i++)
  192356. {
  192357. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192358. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192359. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192360. }
  192361. }
  192362. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192363. else
  192364. #endif
  192365. #endif
  192366. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192367. if (png_ptr->transformations & PNG_BACKGROUND)
  192368. {
  192369. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192370. {
  192371. png_color back;
  192372. back.red = (png_byte)png_ptr->background.red;
  192373. back.green = (png_byte)png_ptr->background.green;
  192374. back.blue = (png_byte)png_ptr->background.blue;
  192375. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192376. {
  192377. if (png_ptr->trans[i] == 0)
  192378. {
  192379. palette[i].red = back.red;
  192380. palette[i].green = back.green;
  192381. palette[i].blue = back.blue;
  192382. }
  192383. else if (png_ptr->trans[i] != 0xff)
  192384. {
  192385. png_composite(palette[i].red, png_ptr->palette[i].red,
  192386. png_ptr->trans[i], back.red);
  192387. png_composite(palette[i].green, png_ptr->palette[i].green,
  192388. png_ptr->trans[i], back.green);
  192389. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192390. png_ptr->trans[i], back.blue);
  192391. }
  192392. }
  192393. }
  192394. else /* assume grayscale palette (what else could it be?) */
  192395. {
  192396. int i;
  192397. for (i = 0; i < num_palette; i++)
  192398. {
  192399. if (i == (png_byte)png_ptr->trans_values.gray)
  192400. {
  192401. palette[i].red = (png_byte)png_ptr->background.red;
  192402. palette[i].green = (png_byte)png_ptr->background.green;
  192403. palette[i].blue = (png_byte)png_ptr->background.blue;
  192404. }
  192405. }
  192406. }
  192407. }
  192408. #endif
  192409. }
  192410. #endif
  192411. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192412. /* Replace any alpha or transparency with the supplied background color.
  192413. * "background" is already in the screen gamma, while "background_1" is
  192414. * at a gamma of 1.0. Paletted files have already been taken care of.
  192415. */
  192416. void /* PRIVATE */
  192417. png_do_background(png_row_infop row_info, png_bytep row,
  192418. png_color_16p trans_values, png_color_16p background
  192419. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192420. , png_color_16p background_1,
  192421. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192422. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192423. png_uint_16pp gamma_16_to_1, int gamma_shift
  192424. #endif
  192425. )
  192426. {
  192427. png_bytep sp, dp;
  192428. png_uint_32 i;
  192429. png_uint_32 row_width=row_info->width;
  192430. int shift;
  192431. png_debug(1, "in png_do_background\n");
  192432. if (background != NULL &&
  192433. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192434. row != NULL && row_info != NULL &&
  192435. #endif
  192436. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192437. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192438. {
  192439. switch (row_info->color_type)
  192440. {
  192441. case PNG_COLOR_TYPE_GRAY:
  192442. {
  192443. switch (row_info->bit_depth)
  192444. {
  192445. case 1:
  192446. {
  192447. sp = row;
  192448. shift = 7;
  192449. for (i = 0; i < row_width; i++)
  192450. {
  192451. if ((png_uint_16)((*sp >> shift) & 0x01)
  192452. == trans_values->gray)
  192453. {
  192454. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192455. *sp |= (png_byte)(background->gray << shift);
  192456. }
  192457. if (!shift)
  192458. {
  192459. shift = 7;
  192460. sp++;
  192461. }
  192462. else
  192463. shift--;
  192464. }
  192465. break;
  192466. }
  192467. case 2:
  192468. {
  192469. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192470. if (gamma_table != NULL)
  192471. {
  192472. sp = row;
  192473. shift = 6;
  192474. for (i = 0; i < row_width; i++)
  192475. {
  192476. if ((png_uint_16)((*sp >> shift) & 0x03)
  192477. == trans_values->gray)
  192478. {
  192479. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192480. *sp |= (png_byte)(background->gray << shift);
  192481. }
  192482. else
  192483. {
  192484. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192485. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192486. (p << 4) | (p << 6)] >> 6) & 0x03);
  192487. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192488. *sp |= (png_byte)(g << shift);
  192489. }
  192490. if (!shift)
  192491. {
  192492. shift = 6;
  192493. sp++;
  192494. }
  192495. else
  192496. shift -= 2;
  192497. }
  192498. }
  192499. else
  192500. #endif
  192501. {
  192502. sp = row;
  192503. shift = 6;
  192504. for (i = 0; i < row_width; i++)
  192505. {
  192506. if ((png_uint_16)((*sp >> shift) & 0x03)
  192507. == trans_values->gray)
  192508. {
  192509. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192510. *sp |= (png_byte)(background->gray << shift);
  192511. }
  192512. if (!shift)
  192513. {
  192514. shift = 6;
  192515. sp++;
  192516. }
  192517. else
  192518. shift -= 2;
  192519. }
  192520. }
  192521. break;
  192522. }
  192523. case 4:
  192524. {
  192525. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192526. if (gamma_table != NULL)
  192527. {
  192528. sp = row;
  192529. shift = 4;
  192530. for (i = 0; i < row_width; i++)
  192531. {
  192532. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192533. == trans_values->gray)
  192534. {
  192535. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192536. *sp |= (png_byte)(background->gray << shift);
  192537. }
  192538. else
  192539. {
  192540. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192541. png_byte g = (png_byte)((gamma_table[p |
  192542. (p << 4)] >> 4) & 0x0f);
  192543. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192544. *sp |= (png_byte)(g << shift);
  192545. }
  192546. if (!shift)
  192547. {
  192548. shift = 4;
  192549. sp++;
  192550. }
  192551. else
  192552. shift -= 4;
  192553. }
  192554. }
  192555. else
  192556. #endif
  192557. {
  192558. sp = row;
  192559. shift = 4;
  192560. for (i = 0; i < row_width; i++)
  192561. {
  192562. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192563. == trans_values->gray)
  192564. {
  192565. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192566. *sp |= (png_byte)(background->gray << shift);
  192567. }
  192568. if (!shift)
  192569. {
  192570. shift = 4;
  192571. sp++;
  192572. }
  192573. else
  192574. shift -= 4;
  192575. }
  192576. }
  192577. break;
  192578. }
  192579. case 8:
  192580. {
  192581. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192582. if (gamma_table != NULL)
  192583. {
  192584. sp = row;
  192585. for (i = 0; i < row_width; i++, sp++)
  192586. {
  192587. if (*sp == trans_values->gray)
  192588. {
  192589. *sp = (png_byte)background->gray;
  192590. }
  192591. else
  192592. {
  192593. *sp = gamma_table[*sp];
  192594. }
  192595. }
  192596. }
  192597. else
  192598. #endif
  192599. {
  192600. sp = row;
  192601. for (i = 0; i < row_width; i++, sp++)
  192602. {
  192603. if (*sp == trans_values->gray)
  192604. {
  192605. *sp = (png_byte)background->gray;
  192606. }
  192607. }
  192608. }
  192609. break;
  192610. }
  192611. case 16:
  192612. {
  192613. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192614. if (gamma_16 != NULL)
  192615. {
  192616. sp = row;
  192617. for (i = 0; i < row_width; i++, sp += 2)
  192618. {
  192619. png_uint_16 v;
  192620. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192621. if (v == trans_values->gray)
  192622. {
  192623. /* background is already in screen gamma */
  192624. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192625. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192626. }
  192627. else
  192628. {
  192629. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192630. *sp = (png_byte)((v >> 8) & 0xff);
  192631. *(sp + 1) = (png_byte)(v & 0xff);
  192632. }
  192633. }
  192634. }
  192635. else
  192636. #endif
  192637. {
  192638. sp = row;
  192639. for (i = 0; i < row_width; i++, sp += 2)
  192640. {
  192641. png_uint_16 v;
  192642. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192643. if (v == trans_values->gray)
  192644. {
  192645. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192646. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192647. }
  192648. }
  192649. }
  192650. break;
  192651. }
  192652. }
  192653. break;
  192654. }
  192655. case PNG_COLOR_TYPE_RGB:
  192656. {
  192657. if (row_info->bit_depth == 8)
  192658. {
  192659. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192660. if (gamma_table != NULL)
  192661. {
  192662. sp = row;
  192663. for (i = 0; i < row_width; i++, sp += 3)
  192664. {
  192665. if (*sp == trans_values->red &&
  192666. *(sp + 1) == trans_values->green &&
  192667. *(sp + 2) == trans_values->blue)
  192668. {
  192669. *sp = (png_byte)background->red;
  192670. *(sp + 1) = (png_byte)background->green;
  192671. *(sp + 2) = (png_byte)background->blue;
  192672. }
  192673. else
  192674. {
  192675. *sp = gamma_table[*sp];
  192676. *(sp + 1) = gamma_table[*(sp + 1)];
  192677. *(sp + 2) = gamma_table[*(sp + 2)];
  192678. }
  192679. }
  192680. }
  192681. else
  192682. #endif
  192683. {
  192684. sp = row;
  192685. for (i = 0; i < row_width; i++, sp += 3)
  192686. {
  192687. if (*sp == trans_values->red &&
  192688. *(sp + 1) == trans_values->green &&
  192689. *(sp + 2) == trans_values->blue)
  192690. {
  192691. *sp = (png_byte)background->red;
  192692. *(sp + 1) = (png_byte)background->green;
  192693. *(sp + 2) = (png_byte)background->blue;
  192694. }
  192695. }
  192696. }
  192697. }
  192698. else /* if (row_info->bit_depth == 16) */
  192699. {
  192700. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192701. if (gamma_16 != NULL)
  192702. {
  192703. sp = row;
  192704. for (i = 0; i < row_width; i++, sp += 6)
  192705. {
  192706. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192707. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192708. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192709. if (r == trans_values->red && g == trans_values->green &&
  192710. b == trans_values->blue)
  192711. {
  192712. /* background is already in screen gamma */
  192713. *sp = (png_byte)((background->red >> 8) & 0xff);
  192714. *(sp + 1) = (png_byte)(background->red & 0xff);
  192715. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192716. *(sp + 3) = (png_byte)(background->green & 0xff);
  192717. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192718. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192719. }
  192720. else
  192721. {
  192722. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192723. *sp = (png_byte)((v >> 8) & 0xff);
  192724. *(sp + 1) = (png_byte)(v & 0xff);
  192725. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192726. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192727. *(sp + 3) = (png_byte)(v & 0xff);
  192728. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192729. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192730. *(sp + 5) = (png_byte)(v & 0xff);
  192731. }
  192732. }
  192733. }
  192734. else
  192735. #endif
  192736. {
  192737. sp = row;
  192738. for (i = 0; i < row_width; i++, sp += 6)
  192739. {
  192740. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192741. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192742. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192743. if (r == trans_values->red && g == trans_values->green &&
  192744. b == trans_values->blue)
  192745. {
  192746. *sp = (png_byte)((background->red >> 8) & 0xff);
  192747. *(sp + 1) = (png_byte)(background->red & 0xff);
  192748. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192749. *(sp + 3) = (png_byte)(background->green & 0xff);
  192750. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192751. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192752. }
  192753. }
  192754. }
  192755. }
  192756. break;
  192757. }
  192758. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192759. {
  192760. if (row_info->bit_depth == 8)
  192761. {
  192762. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192763. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192764. gamma_table != NULL)
  192765. {
  192766. sp = row;
  192767. dp = row;
  192768. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192769. {
  192770. png_uint_16 a = *(sp + 1);
  192771. if (a == 0xff)
  192772. {
  192773. *dp = gamma_table[*sp];
  192774. }
  192775. else if (a == 0)
  192776. {
  192777. /* background is already in screen gamma */
  192778. *dp = (png_byte)background->gray;
  192779. }
  192780. else
  192781. {
  192782. png_byte v, w;
  192783. v = gamma_to_1[*sp];
  192784. png_composite(w, v, a, background_1->gray);
  192785. *dp = gamma_from_1[w];
  192786. }
  192787. }
  192788. }
  192789. else
  192790. #endif
  192791. {
  192792. sp = row;
  192793. dp = row;
  192794. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192795. {
  192796. png_byte a = *(sp + 1);
  192797. if (a == 0xff)
  192798. {
  192799. *dp = *sp;
  192800. }
  192801. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192802. else if (a == 0)
  192803. {
  192804. *dp = (png_byte)background->gray;
  192805. }
  192806. else
  192807. {
  192808. png_composite(*dp, *sp, a, background_1->gray);
  192809. }
  192810. #else
  192811. *dp = (png_byte)background->gray;
  192812. #endif
  192813. }
  192814. }
  192815. }
  192816. else /* if (png_ptr->bit_depth == 16) */
  192817. {
  192818. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192819. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192820. gamma_16_to_1 != NULL)
  192821. {
  192822. sp = row;
  192823. dp = row;
  192824. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192825. {
  192826. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192827. if (a == (png_uint_16)0xffff)
  192828. {
  192829. png_uint_16 v;
  192830. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192831. *dp = (png_byte)((v >> 8) & 0xff);
  192832. *(dp + 1) = (png_byte)(v & 0xff);
  192833. }
  192834. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192835. else if (a == 0)
  192836. #else
  192837. else
  192838. #endif
  192839. {
  192840. /* background is already in screen gamma */
  192841. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192842. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192843. }
  192844. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192845. else
  192846. {
  192847. png_uint_16 g, v, w;
  192848. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192849. png_composite_16(v, g, a, background_1->gray);
  192850. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192851. *dp = (png_byte)((w >> 8) & 0xff);
  192852. *(dp + 1) = (png_byte)(w & 0xff);
  192853. }
  192854. #endif
  192855. }
  192856. }
  192857. else
  192858. #endif
  192859. {
  192860. sp = row;
  192861. dp = row;
  192862. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192863. {
  192864. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192865. if (a == (png_uint_16)0xffff)
  192866. {
  192867. png_memcpy(dp, sp, 2);
  192868. }
  192869. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192870. else if (a == 0)
  192871. #else
  192872. else
  192873. #endif
  192874. {
  192875. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192876. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192877. }
  192878. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192879. else
  192880. {
  192881. png_uint_16 g, v;
  192882. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192883. png_composite_16(v, g, a, background_1->gray);
  192884. *dp = (png_byte)((v >> 8) & 0xff);
  192885. *(dp + 1) = (png_byte)(v & 0xff);
  192886. }
  192887. #endif
  192888. }
  192889. }
  192890. }
  192891. break;
  192892. }
  192893. case PNG_COLOR_TYPE_RGB_ALPHA:
  192894. {
  192895. if (row_info->bit_depth == 8)
  192896. {
  192897. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192898. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192899. gamma_table != NULL)
  192900. {
  192901. sp = row;
  192902. dp = row;
  192903. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192904. {
  192905. png_byte a = *(sp + 3);
  192906. if (a == 0xff)
  192907. {
  192908. *dp = gamma_table[*sp];
  192909. *(dp + 1) = gamma_table[*(sp + 1)];
  192910. *(dp + 2) = gamma_table[*(sp + 2)];
  192911. }
  192912. else if (a == 0)
  192913. {
  192914. /* background is already in screen gamma */
  192915. *dp = (png_byte)background->red;
  192916. *(dp + 1) = (png_byte)background->green;
  192917. *(dp + 2) = (png_byte)background->blue;
  192918. }
  192919. else
  192920. {
  192921. png_byte v, w;
  192922. v = gamma_to_1[*sp];
  192923. png_composite(w, v, a, background_1->red);
  192924. *dp = gamma_from_1[w];
  192925. v = gamma_to_1[*(sp + 1)];
  192926. png_composite(w, v, a, background_1->green);
  192927. *(dp + 1) = gamma_from_1[w];
  192928. v = gamma_to_1[*(sp + 2)];
  192929. png_composite(w, v, a, background_1->blue);
  192930. *(dp + 2) = gamma_from_1[w];
  192931. }
  192932. }
  192933. }
  192934. else
  192935. #endif
  192936. {
  192937. sp = row;
  192938. dp = row;
  192939. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192940. {
  192941. png_byte a = *(sp + 3);
  192942. if (a == 0xff)
  192943. {
  192944. *dp = *sp;
  192945. *(dp + 1) = *(sp + 1);
  192946. *(dp + 2) = *(sp + 2);
  192947. }
  192948. else if (a == 0)
  192949. {
  192950. *dp = (png_byte)background->red;
  192951. *(dp + 1) = (png_byte)background->green;
  192952. *(dp + 2) = (png_byte)background->blue;
  192953. }
  192954. else
  192955. {
  192956. png_composite(*dp, *sp, a, background->red);
  192957. png_composite(*(dp + 1), *(sp + 1), a,
  192958. background->green);
  192959. png_composite(*(dp + 2), *(sp + 2), a,
  192960. background->blue);
  192961. }
  192962. }
  192963. }
  192964. }
  192965. else /* if (row_info->bit_depth == 16) */
  192966. {
  192967. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192968. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192969. gamma_16_to_1 != NULL)
  192970. {
  192971. sp = row;
  192972. dp = row;
  192973. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192974. {
  192975. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192976. << 8) + (png_uint_16)(*(sp + 7)));
  192977. if (a == (png_uint_16)0xffff)
  192978. {
  192979. png_uint_16 v;
  192980. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192981. *dp = (png_byte)((v >> 8) & 0xff);
  192982. *(dp + 1) = (png_byte)(v & 0xff);
  192983. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192984. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192985. *(dp + 3) = (png_byte)(v & 0xff);
  192986. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192987. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192988. *(dp + 5) = (png_byte)(v & 0xff);
  192989. }
  192990. else if (a == 0)
  192991. {
  192992. /* background is already in screen gamma */
  192993. *dp = (png_byte)((background->red >> 8) & 0xff);
  192994. *(dp + 1) = (png_byte)(background->red & 0xff);
  192995. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192996. *(dp + 3) = (png_byte)(background->green & 0xff);
  192997. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192998. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192999. }
  193000. else
  193001. {
  193002. png_uint_16 v, w, x;
  193003. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193004. png_composite_16(w, v, a, background_1->red);
  193005. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193006. *dp = (png_byte)((x >> 8) & 0xff);
  193007. *(dp + 1) = (png_byte)(x & 0xff);
  193008. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193009. png_composite_16(w, v, a, background_1->green);
  193010. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193011. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193012. *(dp + 3) = (png_byte)(x & 0xff);
  193013. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193014. png_composite_16(w, v, a, background_1->blue);
  193015. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193016. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193017. *(dp + 5) = (png_byte)(x & 0xff);
  193018. }
  193019. }
  193020. }
  193021. else
  193022. #endif
  193023. {
  193024. sp = row;
  193025. dp = row;
  193026. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193027. {
  193028. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193029. << 8) + (png_uint_16)(*(sp + 7)));
  193030. if (a == (png_uint_16)0xffff)
  193031. {
  193032. png_memcpy(dp, sp, 6);
  193033. }
  193034. else if (a == 0)
  193035. {
  193036. *dp = (png_byte)((background->red >> 8) & 0xff);
  193037. *(dp + 1) = (png_byte)(background->red & 0xff);
  193038. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193039. *(dp + 3) = (png_byte)(background->green & 0xff);
  193040. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193041. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193042. }
  193043. else
  193044. {
  193045. png_uint_16 v;
  193046. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193047. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193048. + *(sp + 3));
  193049. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193050. + *(sp + 5));
  193051. png_composite_16(v, r, a, background->red);
  193052. *dp = (png_byte)((v >> 8) & 0xff);
  193053. *(dp + 1) = (png_byte)(v & 0xff);
  193054. png_composite_16(v, g, a, background->green);
  193055. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193056. *(dp + 3) = (png_byte)(v & 0xff);
  193057. png_composite_16(v, b, a, background->blue);
  193058. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193059. *(dp + 5) = (png_byte)(v & 0xff);
  193060. }
  193061. }
  193062. }
  193063. }
  193064. break;
  193065. }
  193066. }
  193067. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193068. {
  193069. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193070. row_info->channels--;
  193071. row_info->pixel_depth = (png_byte)(row_info->channels *
  193072. row_info->bit_depth);
  193073. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193074. }
  193075. }
  193076. }
  193077. #endif
  193078. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193079. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193080. * you do this after you deal with the transparency issue on grayscale
  193081. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193082. * is 16, use gamma_16_table and gamma_shift. Build these with
  193083. * build_gamma_table().
  193084. */
  193085. void /* PRIVATE */
  193086. png_do_gamma(png_row_infop row_info, png_bytep row,
  193087. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193088. int gamma_shift)
  193089. {
  193090. png_bytep sp;
  193091. png_uint_32 i;
  193092. png_uint_32 row_width=row_info->width;
  193093. png_debug(1, "in png_do_gamma\n");
  193094. if (
  193095. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193096. row != NULL && row_info != NULL &&
  193097. #endif
  193098. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193099. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193100. {
  193101. switch (row_info->color_type)
  193102. {
  193103. case PNG_COLOR_TYPE_RGB:
  193104. {
  193105. if (row_info->bit_depth == 8)
  193106. {
  193107. sp = row;
  193108. for (i = 0; i < row_width; i++)
  193109. {
  193110. *sp = gamma_table[*sp];
  193111. sp++;
  193112. *sp = gamma_table[*sp];
  193113. sp++;
  193114. *sp = gamma_table[*sp];
  193115. sp++;
  193116. }
  193117. }
  193118. else /* if (row_info->bit_depth == 16) */
  193119. {
  193120. sp = row;
  193121. for (i = 0; i < row_width; i++)
  193122. {
  193123. png_uint_16 v;
  193124. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193125. *sp = (png_byte)((v >> 8) & 0xff);
  193126. *(sp + 1) = (png_byte)(v & 0xff);
  193127. sp += 2;
  193128. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193129. *sp = (png_byte)((v >> 8) & 0xff);
  193130. *(sp + 1) = (png_byte)(v & 0xff);
  193131. sp += 2;
  193132. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193133. *sp = (png_byte)((v >> 8) & 0xff);
  193134. *(sp + 1) = (png_byte)(v & 0xff);
  193135. sp += 2;
  193136. }
  193137. }
  193138. break;
  193139. }
  193140. case PNG_COLOR_TYPE_RGB_ALPHA:
  193141. {
  193142. if (row_info->bit_depth == 8)
  193143. {
  193144. sp = row;
  193145. for (i = 0; i < row_width; i++)
  193146. {
  193147. *sp = gamma_table[*sp];
  193148. sp++;
  193149. *sp = gamma_table[*sp];
  193150. sp++;
  193151. *sp = gamma_table[*sp];
  193152. sp++;
  193153. sp++;
  193154. }
  193155. }
  193156. else /* if (row_info->bit_depth == 16) */
  193157. {
  193158. sp = row;
  193159. for (i = 0; i < row_width; i++)
  193160. {
  193161. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193162. *sp = (png_byte)((v >> 8) & 0xff);
  193163. *(sp + 1) = (png_byte)(v & 0xff);
  193164. sp += 2;
  193165. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193166. *sp = (png_byte)((v >> 8) & 0xff);
  193167. *(sp + 1) = (png_byte)(v & 0xff);
  193168. sp += 2;
  193169. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193170. *sp = (png_byte)((v >> 8) & 0xff);
  193171. *(sp + 1) = (png_byte)(v & 0xff);
  193172. sp += 4;
  193173. }
  193174. }
  193175. break;
  193176. }
  193177. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193178. {
  193179. if (row_info->bit_depth == 8)
  193180. {
  193181. sp = row;
  193182. for (i = 0; i < row_width; i++)
  193183. {
  193184. *sp = gamma_table[*sp];
  193185. sp += 2;
  193186. }
  193187. }
  193188. else /* if (row_info->bit_depth == 16) */
  193189. {
  193190. sp = row;
  193191. for (i = 0; i < row_width; i++)
  193192. {
  193193. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193194. *sp = (png_byte)((v >> 8) & 0xff);
  193195. *(sp + 1) = (png_byte)(v & 0xff);
  193196. sp += 4;
  193197. }
  193198. }
  193199. break;
  193200. }
  193201. case PNG_COLOR_TYPE_GRAY:
  193202. {
  193203. if (row_info->bit_depth == 2)
  193204. {
  193205. sp = row;
  193206. for (i = 0; i < row_width; i += 4)
  193207. {
  193208. int a = *sp & 0xc0;
  193209. int b = *sp & 0x30;
  193210. int c = *sp & 0x0c;
  193211. int d = *sp & 0x03;
  193212. *sp = (png_byte)(
  193213. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193214. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193215. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193216. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193217. sp++;
  193218. }
  193219. }
  193220. if (row_info->bit_depth == 4)
  193221. {
  193222. sp = row;
  193223. for (i = 0; i < row_width; i += 2)
  193224. {
  193225. int msb = *sp & 0xf0;
  193226. int lsb = *sp & 0x0f;
  193227. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193228. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193229. sp++;
  193230. }
  193231. }
  193232. else if (row_info->bit_depth == 8)
  193233. {
  193234. sp = row;
  193235. for (i = 0; i < row_width; i++)
  193236. {
  193237. *sp = gamma_table[*sp];
  193238. sp++;
  193239. }
  193240. }
  193241. else if (row_info->bit_depth == 16)
  193242. {
  193243. sp = row;
  193244. for (i = 0; i < row_width; i++)
  193245. {
  193246. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193247. *sp = (png_byte)((v >> 8) & 0xff);
  193248. *(sp + 1) = (png_byte)(v & 0xff);
  193249. sp += 2;
  193250. }
  193251. }
  193252. break;
  193253. }
  193254. }
  193255. }
  193256. }
  193257. #endif
  193258. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193259. /* Expands a palette row to an RGB or RGBA row depending
  193260. * upon whether you supply trans and num_trans.
  193261. */
  193262. void /* PRIVATE */
  193263. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193264. png_colorp palette, png_bytep trans, int num_trans)
  193265. {
  193266. int shift, value;
  193267. png_bytep sp, dp;
  193268. png_uint_32 i;
  193269. png_uint_32 row_width=row_info->width;
  193270. png_debug(1, "in png_do_expand_palette\n");
  193271. if (
  193272. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193273. row != NULL && row_info != NULL &&
  193274. #endif
  193275. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193276. {
  193277. if (row_info->bit_depth < 8)
  193278. {
  193279. switch (row_info->bit_depth)
  193280. {
  193281. case 1:
  193282. {
  193283. sp = row + (png_size_t)((row_width - 1) >> 3);
  193284. dp = row + (png_size_t)row_width - 1;
  193285. shift = 7 - (int)((row_width + 7) & 0x07);
  193286. for (i = 0; i < row_width; i++)
  193287. {
  193288. if ((*sp >> shift) & 0x01)
  193289. *dp = 1;
  193290. else
  193291. *dp = 0;
  193292. if (shift == 7)
  193293. {
  193294. shift = 0;
  193295. sp--;
  193296. }
  193297. else
  193298. shift++;
  193299. dp--;
  193300. }
  193301. break;
  193302. }
  193303. case 2:
  193304. {
  193305. sp = row + (png_size_t)((row_width - 1) >> 2);
  193306. dp = row + (png_size_t)row_width - 1;
  193307. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193308. for (i = 0; i < row_width; i++)
  193309. {
  193310. value = (*sp >> shift) & 0x03;
  193311. *dp = (png_byte)value;
  193312. if (shift == 6)
  193313. {
  193314. shift = 0;
  193315. sp--;
  193316. }
  193317. else
  193318. shift += 2;
  193319. dp--;
  193320. }
  193321. break;
  193322. }
  193323. case 4:
  193324. {
  193325. sp = row + (png_size_t)((row_width - 1) >> 1);
  193326. dp = row + (png_size_t)row_width - 1;
  193327. shift = (int)((row_width & 0x01) << 2);
  193328. for (i = 0; i < row_width; i++)
  193329. {
  193330. value = (*sp >> shift) & 0x0f;
  193331. *dp = (png_byte)value;
  193332. if (shift == 4)
  193333. {
  193334. shift = 0;
  193335. sp--;
  193336. }
  193337. else
  193338. shift += 4;
  193339. dp--;
  193340. }
  193341. break;
  193342. }
  193343. }
  193344. row_info->bit_depth = 8;
  193345. row_info->pixel_depth = 8;
  193346. row_info->rowbytes = row_width;
  193347. }
  193348. switch (row_info->bit_depth)
  193349. {
  193350. case 8:
  193351. {
  193352. if (trans != NULL)
  193353. {
  193354. sp = row + (png_size_t)row_width - 1;
  193355. dp = row + (png_size_t)(row_width << 2) - 1;
  193356. for (i = 0; i < row_width; i++)
  193357. {
  193358. if ((int)(*sp) >= num_trans)
  193359. *dp-- = 0xff;
  193360. else
  193361. *dp-- = trans[*sp];
  193362. *dp-- = palette[*sp].blue;
  193363. *dp-- = palette[*sp].green;
  193364. *dp-- = palette[*sp].red;
  193365. sp--;
  193366. }
  193367. row_info->bit_depth = 8;
  193368. row_info->pixel_depth = 32;
  193369. row_info->rowbytes = row_width * 4;
  193370. row_info->color_type = 6;
  193371. row_info->channels = 4;
  193372. }
  193373. else
  193374. {
  193375. sp = row + (png_size_t)row_width - 1;
  193376. dp = row + (png_size_t)(row_width * 3) - 1;
  193377. for (i = 0; i < row_width; i++)
  193378. {
  193379. *dp-- = palette[*sp].blue;
  193380. *dp-- = palette[*sp].green;
  193381. *dp-- = palette[*sp].red;
  193382. sp--;
  193383. }
  193384. row_info->bit_depth = 8;
  193385. row_info->pixel_depth = 24;
  193386. row_info->rowbytes = row_width * 3;
  193387. row_info->color_type = 2;
  193388. row_info->channels = 3;
  193389. }
  193390. break;
  193391. }
  193392. }
  193393. }
  193394. }
  193395. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193396. * expanded transparency value is supplied, an alpha channel is built.
  193397. */
  193398. void /* PRIVATE */
  193399. png_do_expand(png_row_infop row_info, png_bytep row,
  193400. png_color_16p trans_value)
  193401. {
  193402. int shift, value;
  193403. png_bytep sp, dp;
  193404. png_uint_32 i;
  193405. png_uint_32 row_width=row_info->width;
  193406. png_debug(1, "in png_do_expand\n");
  193407. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193408. if (row != NULL && row_info != NULL)
  193409. #endif
  193410. {
  193411. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193412. {
  193413. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193414. if (row_info->bit_depth < 8)
  193415. {
  193416. switch (row_info->bit_depth)
  193417. {
  193418. case 1:
  193419. {
  193420. gray = (png_uint_16)((gray&0x01)*0xff);
  193421. sp = row + (png_size_t)((row_width - 1) >> 3);
  193422. dp = row + (png_size_t)row_width - 1;
  193423. shift = 7 - (int)((row_width + 7) & 0x07);
  193424. for (i = 0; i < row_width; i++)
  193425. {
  193426. if ((*sp >> shift) & 0x01)
  193427. *dp = 0xff;
  193428. else
  193429. *dp = 0;
  193430. if (shift == 7)
  193431. {
  193432. shift = 0;
  193433. sp--;
  193434. }
  193435. else
  193436. shift++;
  193437. dp--;
  193438. }
  193439. break;
  193440. }
  193441. case 2:
  193442. {
  193443. gray = (png_uint_16)((gray&0x03)*0x55);
  193444. sp = row + (png_size_t)((row_width - 1) >> 2);
  193445. dp = row + (png_size_t)row_width - 1;
  193446. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193447. for (i = 0; i < row_width; i++)
  193448. {
  193449. value = (*sp >> shift) & 0x03;
  193450. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193451. (value << 6));
  193452. if (shift == 6)
  193453. {
  193454. shift = 0;
  193455. sp--;
  193456. }
  193457. else
  193458. shift += 2;
  193459. dp--;
  193460. }
  193461. break;
  193462. }
  193463. case 4:
  193464. {
  193465. gray = (png_uint_16)((gray&0x0f)*0x11);
  193466. sp = row + (png_size_t)((row_width - 1) >> 1);
  193467. dp = row + (png_size_t)row_width - 1;
  193468. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193469. for (i = 0; i < row_width; i++)
  193470. {
  193471. value = (*sp >> shift) & 0x0f;
  193472. *dp = (png_byte)(value | (value << 4));
  193473. if (shift == 4)
  193474. {
  193475. shift = 0;
  193476. sp--;
  193477. }
  193478. else
  193479. shift = 4;
  193480. dp--;
  193481. }
  193482. break;
  193483. }
  193484. }
  193485. row_info->bit_depth = 8;
  193486. row_info->pixel_depth = 8;
  193487. row_info->rowbytes = row_width;
  193488. }
  193489. if (trans_value != NULL)
  193490. {
  193491. if (row_info->bit_depth == 8)
  193492. {
  193493. gray = gray & 0xff;
  193494. sp = row + (png_size_t)row_width - 1;
  193495. dp = row + (png_size_t)(row_width << 1) - 1;
  193496. for (i = 0; i < row_width; i++)
  193497. {
  193498. if (*sp == gray)
  193499. *dp-- = 0;
  193500. else
  193501. *dp-- = 0xff;
  193502. *dp-- = *sp--;
  193503. }
  193504. }
  193505. else if (row_info->bit_depth == 16)
  193506. {
  193507. png_byte gray_high = (gray >> 8) & 0xff;
  193508. png_byte gray_low = gray & 0xff;
  193509. sp = row + row_info->rowbytes - 1;
  193510. dp = row + (row_info->rowbytes << 1) - 1;
  193511. for (i = 0; i < row_width; i++)
  193512. {
  193513. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193514. {
  193515. *dp-- = 0;
  193516. *dp-- = 0;
  193517. }
  193518. else
  193519. {
  193520. *dp-- = 0xff;
  193521. *dp-- = 0xff;
  193522. }
  193523. *dp-- = *sp--;
  193524. *dp-- = *sp--;
  193525. }
  193526. }
  193527. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193528. row_info->channels = 2;
  193529. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193530. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193531. row_width);
  193532. }
  193533. }
  193534. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193535. {
  193536. if (row_info->bit_depth == 8)
  193537. {
  193538. png_byte red = trans_value->red & 0xff;
  193539. png_byte green = trans_value->green & 0xff;
  193540. png_byte blue = trans_value->blue & 0xff;
  193541. sp = row + (png_size_t)row_info->rowbytes - 1;
  193542. dp = row + (png_size_t)(row_width << 2) - 1;
  193543. for (i = 0; i < row_width; i++)
  193544. {
  193545. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193546. *dp-- = 0;
  193547. else
  193548. *dp-- = 0xff;
  193549. *dp-- = *sp--;
  193550. *dp-- = *sp--;
  193551. *dp-- = *sp--;
  193552. }
  193553. }
  193554. else if (row_info->bit_depth == 16)
  193555. {
  193556. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193557. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193558. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193559. png_byte red_low = trans_value->red & 0xff;
  193560. png_byte green_low = trans_value->green & 0xff;
  193561. png_byte blue_low = trans_value->blue & 0xff;
  193562. sp = row + row_info->rowbytes - 1;
  193563. dp = row + (png_size_t)(row_width << 3) - 1;
  193564. for (i = 0; i < row_width; i++)
  193565. {
  193566. if (*(sp - 5) == red_high &&
  193567. *(sp - 4) == red_low &&
  193568. *(sp - 3) == green_high &&
  193569. *(sp - 2) == green_low &&
  193570. *(sp - 1) == blue_high &&
  193571. *(sp ) == blue_low)
  193572. {
  193573. *dp-- = 0;
  193574. *dp-- = 0;
  193575. }
  193576. else
  193577. {
  193578. *dp-- = 0xff;
  193579. *dp-- = 0xff;
  193580. }
  193581. *dp-- = *sp--;
  193582. *dp-- = *sp--;
  193583. *dp-- = *sp--;
  193584. *dp-- = *sp--;
  193585. *dp-- = *sp--;
  193586. *dp-- = *sp--;
  193587. }
  193588. }
  193589. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193590. row_info->channels = 4;
  193591. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193592. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193593. }
  193594. }
  193595. }
  193596. #endif
  193597. #if defined(PNG_READ_DITHER_SUPPORTED)
  193598. void /* PRIVATE */
  193599. png_do_dither(png_row_infop row_info, png_bytep row,
  193600. png_bytep palette_lookup, png_bytep dither_lookup)
  193601. {
  193602. png_bytep sp, dp;
  193603. png_uint_32 i;
  193604. png_uint_32 row_width=row_info->width;
  193605. png_debug(1, "in png_do_dither\n");
  193606. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193607. if (row != NULL && row_info != NULL)
  193608. #endif
  193609. {
  193610. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193611. palette_lookup && row_info->bit_depth == 8)
  193612. {
  193613. int r, g, b, p;
  193614. sp = row;
  193615. dp = row;
  193616. for (i = 0; i < row_width; i++)
  193617. {
  193618. r = *sp++;
  193619. g = *sp++;
  193620. b = *sp++;
  193621. /* this looks real messy, but the compiler will reduce
  193622. it down to a reasonable formula. For example, with
  193623. 5 bits per color, we get:
  193624. p = (((r >> 3) & 0x1f) << 10) |
  193625. (((g >> 3) & 0x1f) << 5) |
  193626. ((b >> 3) & 0x1f);
  193627. */
  193628. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193629. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193630. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193631. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193632. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193633. (PNG_DITHER_BLUE_BITS)) |
  193634. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193635. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193636. *dp++ = palette_lookup[p];
  193637. }
  193638. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193639. row_info->channels = 1;
  193640. row_info->pixel_depth = row_info->bit_depth;
  193641. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193642. }
  193643. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193644. palette_lookup != NULL && row_info->bit_depth == 8)
  193645. {
  193646. int r, g, b, p;
  193647. sp = row;
  193648. dp = row;
  193649. for (i = 0; i < row_width; i++)
  193650. {
  193651. r = *sp++;
  193652. g = *sp++;
  193653. b = *sp++;
  193654. sp++;
  193655. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193656. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193657. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193658. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193659. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193660. (PNG_DITHER_BLUE_BITS)) |
  193661. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193662. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193663. *dp++ = palette_lookup[p];
  193664. }
  193665. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193666. row_info->channels = 1;
  193667. row_info->pixel_depth = row_info->bit_depth;
  193668. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193669. }
  193670. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193671. dither_lookup && row_info->bit_depth == 8)
  193672. {
  193673. sp = row;
  193674. for (i = 0; i < row_width; i++, sp++)
  193675. {
  193676. *sp = dither_lookup[*sp];
  193677. }
  193678. }
  193679. }
  193680. }
  193681. #endif
  193682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193683. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193684. static PNG_CONST int png_gamma_shift[] =
  193685. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193686. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193687. * tables, we don't make a full table if we are reducing to 8-bit in
  193688. * the future. Note also how the gamma_16 tables are segmented so that
  193689. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193690. */
  193691. void /* PRIVATE */
  193692. png_build_gamma_table(png_structp png_ptr)
  193693. {
  193694. png_debug(1, "in png_build_gamma_table\n");
  193695. if (png_ptr->bit_depth <= 8)
  193696. {
  193697. int i;
  193698. double g;
  193699. if (png_ptr->screen_gamma > .000001)
  193700. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193701. else
  193702. g = 1.0;
  193703. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193704. (png_uint_32)256);
  193705. for (i = 0; i < 256; i++)
  193706. {
  193707. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193708. g) * 255.0 + .5);
  193709. }
  193710. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193711. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193712. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193713. {
  193714. g = 1.0 / (png_ptr->gamma);
  193715. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193716. (png_uint_32)256);
  193717. for (i = 0; i < 256; i++)
  193718. {
  193719. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193720. g) * 255.0 + .5);
  193721. }
  193722. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193723. (png_uint_32)256);
  193724. if(png_ptr->screen_gamma > 0.000001)
  193725. g = 1.0 / png_ptr->screen_gamma;
  193726. else
  193727. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193728. for (i = 0; i < 256; i++)
  193729. {
  193730. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193731. g) * 255.0 + .5);
  193732. }
  193733. }
  193734. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193735. }
  193736. else
  193737. {
  193738. double g;
  193739. int i, j, shift, num;
  193740. int sig_bit;
  193741. png_uint_32 ig;
  193742. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193743. {
  193744. sig_bit = (int)png_ptr->sig_bit.red;
  193745. if ((int)png_ptr->sig_bit.green > sig_bit)
  193746. sig_bit = png_ptr->sig_bit.green;
  193747. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193748. sig_bit = png_ptr->sig_bit.blue;
  193749. }
  193750. else
  193751. {
  193752. sig_bit = (int)png_ptr->sig_bit.gray;
  193753. }
  193754. if (sig_bit > 0)
  193755. shift = 16 - sig_bit;
  193756. else
  193757. shift = 0;
  193758. if (png_ptr->transformations & PNG_16_TO_8)
  193759. {
  193760. if (shift < (16 - PNG_MAX_GAMMA_8))
  193761. shift = (16 - PNG_MAX_GAMMA_8);
  193762. }
  193763. if (shift > 8)
  193764. shift = 8;
  193765. if (shift < 0)
  193766. shift = 0;
  193767. png_ptr->gamma_shift = (png_byte)shift;
  193768. num = (1 << (8 - shift));
  193769. if (png_ptr->screen_gamma > .000001)
  193770. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193771. else
  193772. g = 1.0;
  193773. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193774. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193775. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193776. {
  193777. double fin, fout;
  193778. png_uint_32 last, max;
  193779. for (i = 0; i < num; i++)
  193780. {
  193781. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193782. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193783. }
  193784. g = 1.0 / g;
  193785. last = 0;
  193786. for (i = 0; i < 256; i++)
  193787. {
  193788. fout = ((double)i + 0.5) / 256.0;
  193789. fin = pow(fout, g);
  193790. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193791. while (last <= max)
  193792. {
  193793. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193794. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193795. (png_uint_16)i | ((png_uint_16)i << 8));
  193796. last++;
  193797. }
  193798. }
  193799. while (last < ((png_uint_32)num << 8))
  193800. {
  193801. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193802. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193803. last++;
  193804. }
  193805. }
  193806. else
  193807. {
  193808. for (i = 0; i < num; i++)
  193809. {
  193810. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193811. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193812. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193813. for (j = 0; j < 256; j++)
  193814. {
  193815. png_ptr->gamma_16_table[i][j] =
  193816. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193817. 65535.0, g) * 65535.0 + .5);
  193818. }
  193819. }
  193820. }
  193821. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193822. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193823. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193824. {
  193825. g = 1.0 / (png_ptr->gamma);
  193826. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193827. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193828. for (i = 0; i < num; i++)
  193829. {
  193830. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193831. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193832. ig = (((png_uint_32)i *
  193833. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193834. for (j = 0; j < 256; j++)
  193835. {
  193836. png_ptr->gamma_16_to_1[i][j] =
  193837. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193838. 65535.0, g) * 65535.0 + .5);
  193839. }
  193840. }
  193841. if(png_ptr->screen_gamma > 0.000001)
  193842. g = 1.0 / png_ptr->screen_gamma;
  193843. else
  193844. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193845. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193846. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193847. for (i = 0; i < num; i++)
  193848. {
  193849. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193850. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193851. ig = (((png_uint_32)i *
  193852. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193853. for (j = 0; j < 256; j++)
  193854. {
  193855. png_ptr->gamma_16_from_1[i][j] =
  193856. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193857. 65535.0, g) * 65535.0 + .5);
  193858. }
  193859. }
  193860. }
  193861. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193862. }
  193863. }
  193864. #endif
  193865. /* To do: install integer version of png_build_gamma_table here */
  193866. #endif
  193867. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193868. /* undoes intrapixel differencing */
  193869. void /* PRIVATE */
  193870. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193871. {
  193872. png_debug(1, "in png_do_read_intrapixel\n");
  193873. if (
  193874. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193875. row != NULL && row_info != NULL &&
  193876. #endif
  193877. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193878. {
  193879. int bytes_per_pixel;
  193880. png_uint_32 row_width = row_info->width;
  193881. if (row_info->bit_depth == 8)
  193882. {
  193883. png_bytep rp;
  193884. png_uint_32 i;
  193885. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193886. bytes_per_pixel = 3;
  193887. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193888. bytes_per_pixel = 4;
  193889. else
  193890. return;
  193891. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193892. {
  193893. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193894. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193895. }
  193896. }
  193897. else if (row_info->bit_depth == 16)
  193898. {
  193899. png_bytep rp;
  193900. png_uint_32 i;
  193901. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193902. bytes_per_pixel = 6;
  193903. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193904. bytes_per_pixel = 8;
  193905. else
  193906. return;
  193907. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193908. {
  193909. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193910. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193911. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193912. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193913. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193914. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193915. *(rp+1) = (png_byte)(red & 0xff);
  193916. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193917. *(rp+5) = (png_byte)(blue & 0xff);
  193918. }
  193919. }
  193920. }
  193921. }
  193922. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193923. #endif /* PNG_READ_SUPPORTED */
  193924. /*** End of inlined file: pngrtran.c ***/
  193925. /*** Start of inlined file: pngrutil.c ***/
  193926. /* pngrutil.c - utilities to read a PNG file
  193927. *
  193928. * Last changed in libpng 1.2.21 [October 4, 2007]
  193929. * For conditions of distribution and use, see copyright notice in png.h
  193930. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193931. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193932. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193933. *
  193934. * This file contains routines that are only called from within
  193935. * libpng itself during the course of reading an image.
  193936. */
  193937. #define PNG_INTERNAL
  193938. #if defined(PNG_READ_SUPPORTED)
  193939. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193940. # define WIN32_WCE_OLD
  193941. #endif
  193942. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193943. # if defined(WIN32_WCE_OLD)
  193944. /* strtod() function is not supported on WindowsCE */
  193945. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193946. {
  193947. double result = 0;
  193948. int len;
  193949. wchar_t *str, *end;
  193950. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193951. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193952. if ( NULL != str )
  193953. {
  193954. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193955. result = wcstod(str, &end);
  193956. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193957. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193958. png_free(png_ptr, str);
  193959. }
  193960. return result;
  193961. }
  193962. # else
  193963. # define png_strtod(p,a,b) strtod(a,b)
  193964. # endif
  193965. #endif
  193966. png_uint_32 PNGAPI
  193967. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193968. {
  193969. png_uint_32 i = png_get_uint_32(buf);
  193970. if (i > PNG_UINT_31_MAX)
  193971. png_error(png_ptr, "PNG unsigned integer out of range.");
  193972. return (i);
  193973. }
  193974. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193975. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193976. png_uint_32 PNGAPI
  193977. png_get_uint_32(png_bytep buf)
  193978. {
  193979. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193980. ((png_uint_32)(*(buf + 1)) << 16) +
  193981. ((png_uint_32)(*(buf + 2)) << 8) +
  193982. (png_uint_32)(*(buf + 3));
  193983. return (i);
  193984. }
  193985. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193986. * data is stored in the PNG file in two's complement format, and it is
  193987. * assumed that the machine format for signed integers is the same. */
  193988. png_int_32 PNGAPI
  193989. png_get_int_32(png_bytep buf)
  193990. {
  193991. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193992. ((png_int_32)(*(buf + 1)) << 16) +
  193993. ((png_int_32)(*(buf + 2)) << 8) +
  193994. (png_int_32)(*(buf + 3));
  193995. return (i);
  193996. }
  193997. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193998. png_uint_16 PNGAPI
  193999. png_get_uint_16(png_bytep buf)
  194000. {
  194001. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194002. (png_uint_16)(*(buf + 1)));
  194003. return (i);
  194004. }
  194005. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194006. /* Read data, and (optionally) run it through the CRC. */
  194007. void /* PRIVATE */
  194008. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194009. {
  194010. if(png_ptr == NULL) return;
  194011. png_read_data(png_ptr, buf, length);
  194012. png_calculate_crc(png_ptr, buf, length);
  194013. }
  194014. /* Optionally skip data and then check the CRC. Depending on whether we
  194015. are reading a ancillary or critical chunk, and how the program has set
  194016. things up, we may calculate the CRC on the data and print a message.
  194017. Returns '1' if there was a CRC error, '0' otherwise. */
  194018. int /* PRIVATE */
  194019. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194020. {
  194021. png_size_t i;
  194022. png_size_t istop = png_ptr->zbuf_size;
  194023. for (i = (png_size_t)skip; i > istop; i -= istop)
  194024. {
  194025. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194026. }
  194027. if (i)
  194028. {
  194029. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194030. }
  194031. if (png_crc_error(png_ptr))
  194032. {
  194033. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194034. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194035. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194036. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194037. {
  194038. png_chunk_warning(png_ptr, "CRC error");
  194039. }
  194040. else
  194041. {
  194042. png_chunk_error(png_ptr, "CRC error");
  194043. }
  194044. return (1);
  194045. }
  194046. return (0);
  194047. }
  194048. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194049. the data it has read thus far. */
  194050. int /* PRIVATE */
  194051. png_crc_error(png_structp png_ptr)
  194052. {
  194053. png_byte crc_bytes[4];
  194054. png_uint_32 crc;
  194055. int need_crc = 1;
  194056. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194057. {
  194058. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194059. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194060. need_crc = 0;
  194061. }
  194062. else /* critical */
  194063. {
  194064. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194065. need_crc = 0;
  194066. }
  194067. png_read_data(png_ptr, crc_bytes, 4);
  194068. if (need_crc)
  194069. {
  194070. crc = png_get_uint_32(crc_bytes);
  194071. return ((int)(crc != png_ptr->crc));
  194072. }
  194073. else
  194074. return (0);
  194075. }
  194076. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194077. defined(PNG_READ_iCCP_SUPPORTED)
  194078. /*
  194079. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194080. * points at an allocated area holding the contents of a chunk with a
  194081. * trailing compressed part. What we get back is an allocated area
  194082. * holding the original prefix part and an uncompressed version of the
  194083. * trailing part (the malloc area passed in is freed).
  194084. */
  194085. png_charp /* PRIVATE */
  194086. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194087. png_charp chunkdata, png_size_t chunklength,
  194088. png_size_t prefix_size, png_size_t *newlength)
  194089. {
  194090. static PNG_CONST char msg[] = "Error decoding compressed text";
  194091. png_charp text;
  194092. png_size_t text_size;
  194093. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194094. {
  194095. int ret = Z_OK;
  194096. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194097. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194098. png_ptr->zstream.next_out = png_ptr->zbuf;
  194099. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194100. text_size = 0;
  194101. text = NULL;
  194102. while (png_ptr->zstream.avail_in)
  194103. {
  194104. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194105. if (ret != Z_OK && ret != Z_STREAM_END)
  194106. {
  194107. if (png_ptr->zstream.msg != NULL)
  194108. png_warning(png_ptr, png_ptr->zstream.msg);
  194109. else
  194110. png_warning(png_ptr, msg);
  194111. inflateReset(&png_ptr->zstream);
  194112. png_ptr->zstream.avail_in = 0;
  194113. if (text == NULL)
  194114. {
  194115. text_size = prefix_size + png_sizeof(msg) + 1;
  194116. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194117. if (text == NULL)
  194118. {
  194119. png_free(png_ptr,chunkdata);
  194120. png_error(png_ptr,"Not enough memory to decompress chunk");
  194121. }
  194122. png_memcpy(text, chunkdata, prefix_size);
  194123. }
  194124. text[text_size - 1] = 0x00;
  194125. /* Copy what we can of the error message into the text chunk */
  194126. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194127. text_size = png_sizeof(msg) > text_size ? text_size :
  194128. png_sizeof(msg);
  194129. png_memcpy(text + prefix_size, msg, text_size + 1);
  194130. break;
  194131. }
  194132. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194133. {
  194134. if (text == NULL)
  194135. {
  194136. text_size = prefix_size +
  194137. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194138. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194139. if (text == NULL)
  194140. {
  194141. png_free(png_ptr,chunkdata);
  194142. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194143. }
  194144. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194145. text_size - prefix_size);
  194146. png_memcpy(text, chunkdata, prefix_size);
  194147. *(text + text_size) = 0x00;
  194148. }
  194149. else
  194150. {
  194151. png_charp tmp;
  194152. tmp = text;
  194153. text = (png_charp)png_malloc_warn(png_ptr,
  194154. (png_uint_32)(text_size +
  194155. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194156. if (text == NULL)
  194157. {
  194158. png_free(png_ptr, tmp);
  194159. png_free(png_ptr, chunkdata);
  194160. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194161. }
  194162. png_memcpy(text, tmp, text_size);
  194163. png_free(png_ptr, tmp);
  194164. png_memcpy(text + text_size, png_ptr->zbuf,
  194165. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194166. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194167. *(text + text_size) = 0x00;
  194168. }
  194169. if (ret == Z_STREAM_END)
  194170. break;
  194171. else
  194172. {
  194173. png_ptr->zstream.next_out = png_ptr->zbuf;
  194174. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194175. }
  194176. }
  194177. }
  194178. if (ret != Z_STREAM_END)
  194179. {
  194180. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194181. char umsg[52];
  194182. if (ret == Z_BUF_ERROR)
  194183. png_snprintf(umsg, 52,
  194184. "Buffer error in compressed datastream in %s chunk",
  194185. png_ptr->chunk_name);
  194186. else if (ret == Z_DATA_ERROR)
  194187. png_snprintf(umsg, 52,
  194188. "Data error in compressed datastream in %s chunk",
  194189. png_ptr->chunk_name);
  194190. else
  194191. png_snprintf(umsg, 52,
  194192. "Incomplete compressed datastream in %s chunk",
  194193. png_ptr->chunk_name);
  194194. png_warning(png_ptr, umsg);
  194195. #else
  194196. png_warning(png_ptr,
  194197. "Incomplete compressed datastream in chunk other than IDAT");
  194198. #endif
  194199. text_size=prefix_size;
  194200. if (text == NULL)
  194201. {
  194202. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194203. if (text == NULL)
  194204. {
  194205. png_free(png_ptr, chunkdata);
  194206. png_error(png_ptr,"Not enough memory for text.");
  194207. }
  194208. png_memcpy(text, chunkdata, prefix_size);
  194209. }
  194210. *(text + text_size) = 0x00;
  194211. }
  194212. inflateReset(&png_ptr->zstream);
  194213. png_ptr->zstream.avail_in = 0;
  194214. png_free(png_ptr, chunkdata);
  194215. chunkdata = text;
  194216. *newlength=text_size;
  194217. }
  194218. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194219. {
  194220. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194221. char umsg[50];
  194222. png_snprintf(umsg, 50,
  194223. "Unknown zTXt compression type %d", comp_type);
  194224. png_warning(png_ptr, umsg);
  194225. #else
  194226. png_warning(png_ptr, "Unknown zTXt compression type");
  194227. #endif
  194228. *(chunkdata + prefix_size) = 0x00;
  194229. *newlength=prefix_size;
  194230. }
  194231. return chunkdata;
  194232. }
  194233. #endif
  194234. /* read and check the IDHR chunk */
  194235. void /* PRIVATE */
  194236. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194237. {
  194238. png_byte buf[13];
  194239. png_uint_32 width, height;
  194240. int bit_depth, color_type, compression_type, filter_type;
  194241. int interlace_type;
  194242. png_debug(1, "in png_handle_IHDR\n");
  194243. if (png_ptr->mode & PNG_HAVE_IHDR)
  194244. png_error(png_ptr, "Out of place IHDR");
  194245. /* check the length */
  194246. if (length != 13)
  194247. png_error(png_ptr, "Invalid IHDR chunk");
  194248. png_ptr->mode |= PNG_HAVE_IHDR;
  194249. png_crc_read(png_ptr, buf, 13);
  194250. png_crc_finish(png_ptr, 0);
  194251. width = png_get_uint_31(png_ptr, buf);
  194252. height = png_get_uint_31(png_ptr, buf + 4);
  194253. bit_depth = buf[8];
  194254. color_type = buf[9];
  194255. compression_type = buf[10];
  194256. filter_type = buf[11];
  194257. interlace_type = buf[12];
  194258. /* set internal variables */
  194259. png_ptr->width = width;
  194260. png_ptr->height = height;
  194261. png_ptr->bit_depth = (png_byte)bit_depth;
  194262. png_ptr->interlaced = (png_byte)interlace_type;
  194263. png_ptr->color_type = (png_byte)color_type;
  194264. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194265. png_ptr->filter_type = (png_byte)filter_type;
  194266. #endif
  194267. png_ptr->compression_type = (png_byte)compression_type;
  194268. /* find number of channels */
  194269. switch (png_ptr->color_type)
  194270. {
  194271. case PNG_COLOR_TYPE_GRAY:
  194272. case PNG_COLOR_TYPE_PALETTE:
  194273. png_ptr->channels = 1;
  194274. break;
  194275. case PNG_COLOR_TYPE_RGB:
  194276. png_ptr->channels = 3;
  194277. break;
  194278. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194279. png_ptr->channels = 2;
  194280. break;
  194281. case PNG_COLOR_TYPE_RGB_ALPHA:
  194282. png_ptr->channels = 4;
  194283. break;
  194284. }
  194285. /* set up other useful info */
  194286. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194287. png_ptr->channels);
  194288. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194289. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194290. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194291. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194292. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194293. color_type, interlace_type, compression_type, filter_type);
  194294. }
  194295. /* read and check the palette */
  194296. void /* PRIVATE */
  194297. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194298. {
  194299. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194300. int num, i;
  194301. #ifndef PNG_NO_POINTER_INDEXING
  194302. png_colorp pal_ptr;
  194303. #endif
  194304. png_debug(1, "in png_handle_PLTE\n");
  194305. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194306. png_error(png_ptr, "Missing IHDR before PLTE");
  194307. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194308. {
  194309. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194310. png_crc_finish(png_ptr, length);
  194311. return;
  194312. }
  194313. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194314. png_error(png_ptr, "Duplicate PLTE chunk");
  194315. png_ptr->mode |= PNG_HAVE_PLTE;
  194316. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194317. {
  194318. png_warning(png_ptr,
  194319. "Ignoring PLTE chunk in grayscale PNG");
  194320. png_crc_finish(png_ptr, length);
  194321. return;
  194322. }
  194323. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194324. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194325. {
  194326. png_crc_finish(png_ptr, length);
  194327. return;
  194328. }
  194329. #endif
  194330. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194331. {
  194332. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194333. {
  194334. png_warning(png_ptr, "Invalid palette chunk");
  194335. png_crc_finish(png_ptr, length);
  194336. return;
  194337. }
  194338. else
  194339. {
  194340. png_error(png_ptr, "Invalid palette chunk");
  194341. }
  194342. }
  194343. num = (int)length / 3;
  194344. #ifndef PNG_NO_POINTER_INDEXING
  194345. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194346. {
  194347. png_byte buf[3];
  194348. png_crc_read(png_ptr, buf, 3);
  194349. pal_ptr->red = buf[0];
  194350. pal_ptr->green = buf[1];
  194351. pal_ptr->blue = buf[2];
  194352. }
  194353. #else
  194354. for (i = 0; i < num; i++)
  194355. {
  194356. png_byte buf[3];
  194357. png_crc_read(png_ptr, buf, 3);
  194358. /* don't depend upon png_color being any order */
  194359. palette[i].red = buf[0];
  194360. palette[i].green = buf[1];
  194361. palette[i].blue = buf[2];
  194362. }
  194363. #endif
  194364. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194365. whatever the normal CRC configuration tells us. However, if we
  194366. have an RGB image, the PLTE can be considered ancillary, so
  194367. we will act as though it is. */
  194368. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194369. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194370. #endif
  194371. {
  194372. png_crc_finish(png_ptr, 0);
  194373. }
  194374. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194375. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194376. {
  194377. /* If we don't want to use the data from an ancillary chunk,
  194378. we have two options: an error abort, or a warning and we
  194379. ignore the data in this chunk (which should be OK, since
  194380. it's considered ancillary for a RGB or RGBA image). */
  194381. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194382. {
  194383. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194384. {
  194385. png_chunk_error(png_ptr, "CRC error");
  194386. }
  194387. else
  194388. {
  194389. png_chunk_warning(png_ptr, "CRC error");
  194390. return;
  194391. }
  194392. }
  194393. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194394. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194395. {
  194396. png_chunk_warning(png_ptr, "CRC error");
  194397. }
  194398. }
  194399. #endif
  194400. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194401. #if defined(PNG_READ_tRNS_SUPPORTED)
  194402. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194403. {
  194404. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194405. {
  194406. if (png_ptr->num_trans > (png_uint_16)num)
  194407. {
  194408. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194409. png_ptr->num_trans = (png_uint_16)num;
  194410. }
  194411. if (info_ptr->num_trans > (png_uint_16)num)
  194412. {
  194413. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194414. info_ptr->num_trans = (png_uint_16)num;
  194415. }
  194416. }
  194417. }
  194418. #endif
  194419. }
  194420. void /* PRIVATE */
  194421. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194422. {
  194423. png_debug(1, "in png_handle_IEND\n");
  194424. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194425. {
  194426. png_error(png_ptr, "No image in file");
  194427. }
  194428. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194429. if (length != 0)
  194430. {
  194431. png_warning(png_ptr, "Incorrect IEND chunk length");
  194432. }
  194433. png_crc_finish(png_ptr, length);
  194434. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194435. }
  194436. #if defined(PNG_READ_gAMA_SUPPORTED)
  194437. void /* PRIVATE */
  194438. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194439. {
  194440. png_fixed_point igamma;
  194441. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194442. float file_gamma;
  194443. #endif
  194444. png_byte buf[4];
  194445. png_debug(1, "in png_handle_gAMA\n");
  194446. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194447. png_error(png_ptr, "Missing IHDR before gAMA");
  194448. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194449. {
  194450. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194451. png_crc_finish(png_ptr, length);
  194452. return;
  194453. }
  194454. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194455. /* Should be an error, but we can cope with it */
  194456. png_warning(png_ptr, "Out of place gAMA chunk");
  194457. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194458. #if defined(PNG_READ_sRGB_SUPPORTED)
  194459. && !(info_ptr->valid & PNG_INFO_sRGB)
  194460. #endif
  194461. )
  194462. {
  194463. png_warning(png_ptr, "Duplicate gAMA chunk");
  194464. png_crc_finish(png_ptr, length);
  194465. return;
  194466. }
  194467. if (length != 4)
  194468. {
  194469. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194470. png_crc_finish(png_ptr, length);
  194471. return;
  194472. }
  194473. png_crc_read(png_ptr, buf, 4);
  194474. if (png_crc_finish(png_ptr, 0))
  194475. return;
  194476. igamma = (png_fixed_point)png_get_uint_32(buf);
  194477. /* check for zero gamma */
  194478. if (igamma == 0)
  194479. {
  194480. png_warning(png_ptr,
  194481. "Ignoring gAMA chunk with gamma=0");
  194482. return;
  194483. }
  194484. #if defined(PNG_READ_sRGB_SUPPORTED)
  194485. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194486. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194487. {
  194488. png_warning(png_ptr,
  194489. "Ignoring incorrect gAMA value when sRGB is also present");
  194490. #ifndef PNG_NO_CONSOLE_IO
  194491. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194492. #endif
  194493. return;
  194494. }
  194495. #endif /* PNG_READ_sRGB_SUPPORTED */
  194496. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194497. file_gamma = (float)igamma / (float)100000.0;
  194498. # ifdef PNG_READ_GAMMA_SUPPORTED
  194499. png_ptr->gamma = file_gamma;
  194500. # endif
  194501. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194502. #endif
  194503. #ifdef PNG_FIXED_POINT_SUPPORTED
  194504. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194505. #endif
  194506. }
  194507. #endif
  194508. #if defined(PNG_READ_sBIT_SUPPORTED)
  194509. void /* PRIVATE */
  194510. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194511. {
  194512. png_size_t truelen;
  194513. png_byte buf[4];
  194514. png_debug(1, "in png_handle_sBIT\n");
  194515. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194516. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194517. png_error(png_ptr, "Missing IHDR before sBIT");
  194518. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194519. {
  194520. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194521. png_crc_finish(png_ptr, length);
  194522. return;
  194523. }
  194524. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194525. {
  194526. /* Should be an error, but we can cope with it */
  194527. png_warning(png_ptr, "Out of place sBIT chunk");
  194528. }
  194529. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194530. {
  194531. png_warning(png_ptr, "Duplicate sBIT chunk");
  194532. png_crc_finish(png_ptr, length);
  194533. return;
  194534. }
  194535. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194536. truelen = 3;
  194537. else
  194538. truelen = (png_size_t)png_ptr->channels;
  194539. if (length != truelen || length > 4)
  194540. {
  194541. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194542. png_crc_finish(png_ptr, length);
  194543. return;
  194544. }
  194545. png_crc_read(png_ptr, buf, truelen);
  194546. if (png_crc_finish(png_ptr, 0))
  194547. return;
  194548. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194549. {
  194550. png_ptr->sig_bit.red = buf[0];
  194551. png_ptr->sig_bit.green = buf[1];
  194552. png_ptr->sig_bit.blue = buf[2];
  194553. png_ptr->sig_bit.alpha = buf[3];
  194554. }
  194555. else
  194556. {
  194557. png_ptr->sig_bit.gray = buf[0];
  194558. png_ptr->sig_bit.red = buf[0];
  194559. png_ptr->sig_bit.green = buf[0];
  194560. png_ptr->sig_bit.blue = buf[0];
  194561. png_ptr->sig_bit.alpha = buf[1];
  194562. }
  194563. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194564. }
  194565. #endif
  194566. #if defined(PNG_READ_cHRM_SUPPORTED)
  194567. void /* PRIVATE */
  194568. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194569. {
  194570. png_byte buf[4];
  194571. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194572. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194573. #endif
  194574. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194575. int_y_green, int_x_blue, int_y_blue;
  194576. png_uint_32 uint_x, uint_y;
  194577. png_debug(1, "in png_handle_cHRM\n");
  194578. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194579. png_error(png_ptr, "Missing IHDR before cHRM");
  194580. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194581. {
  194582. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194583. png_crc_finish(png_ptr, length);
  194584. return;
  194585. }
  194586. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194587. /* Should be an error, but we can cope with it */
  194588. png_warning(png_ptr, "Missing PLTE before cHRM");
  194589. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194590. #if defined(PNG_READ_sRGB_SUPPORTED)
  194591. && !(info_ptr->valid & PNG_INFO_sRGB)
  194592. #endif
  194593. )
  194594. {
  194595. png_warning(png_ptr, "Duplicate cHRM chunk");
  194596. png_crc_finish(png_ptr, length);
  194597. return;
  194598. }
  194599. if (length != 32)
  194600. {
  194601. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194602. png_crc_finish(png_ptr, length);
  194603. return;
  194604. }
  194605. png_crc_read(png_ptr, buf, 4);
  194606. uint_x = png_get_uint_32(buf);
  194607. png_crc_read(png_ptr, buf, 4);
  194608. uint_y = png_get_uint_32(buf);
  194609. if (uint_x > 80000L || uint_y > 80000L ||
  194610. uint_x + uint_y > 100000L)
  194611. {
  194612. png_warning(png_ptr, "Invalid cHRM white point");
  194613. png_crc_finish(png_ptr, 24);
  194614. return;
  194615. }
  194616. int_x_white = (png_fixed_point)uint_x;
  194617. int_y_white = (png_fixed_point)uint_y;
  194618. png_crc_read(png_ptr, buf, 4);
  194619. uint_x = png_get_uint_32(buf);
  194620. png_crc_read(png_ptr, buf, 4);
  194621. uint_y = png_get_uint_32(buf);
  194622. if (uint_x + uint_y > 100000L)
  194623. {
  194624. png_warning(png_ptr, "Invalid cHRM red point");
  194625. png_crc_finish(png_ptr, 16);
  194626. return;
  194627. }
  194628. int_x_red = (png_fixed_point)uint_x;
  194629. int_y_red = (png_fixed_point)uint_y;
  194630. png_crc_read(png_ptr, buf, 4);
  194631. uint_x = png_get_uint_32(buf);
  194632. png_crc_read(png_ptr, buf, 4);
  194633. uint_y = png_get_uint_32(buf);
  194634. if (uint_x + uint_y > 100000L)
  194635. {
  194636. png_warning(png_ptr, "Invalid cHRM green point");
  194637. png_crc_finish(png_ptr, 8);
  194638. return;
  194639. }
  194640. int_x_green = (png_fixed_point)uint_x;
  194641. int_y_green = (png_fixed_point)uint_y;
  194642. png_crc_read(png_ptr, buf, 4);
  194643. uint_x = png_get_uint_32(buf);
  194644. png_crc_read(png_ptr, buf, 4);
  194645. uint_y = png_get_uint_32(buf);
  194646. if (uint_x + uint_y > 100000L)
  194647. {
  194648. png_warning(png_ptr, "Invalid cHRM blue point");
  194649. png_crc_finish(png_ptr, 0);
  194650. return;
  194651. }
  194652. int_x_blue = (png_fixed_point)uint_x;
  194653. int_y_blue = (png_fixed_point)uint_y;
  194654. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194655. white_x = (float)int_x_white / (float)100000.0;
  194656. white_y = (float)int_y_white / (float)100000.0;
  194657. red_x = (float)int_x_red / (float)100000.0;
  194658. red_y = (float)int_y_red / (float)100000.0;
  194659. green_x = (float)int_x_green / (float)100000.0;
  194660. green_y = (float)int_y_green / (float)100000.0;
  194661. blue_x = (float)int_x_blue / (float)100000.0;
  194662. blue_y = (float)int_y_blue / (float)100000.0;
  194663. #endif
  194664. #if defined(PNG_READ_sRGB_SUPPORTED)
  194665. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194666. {
  194667. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194668. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194669. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194670. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194671. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194672. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194673. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194674. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194675. {
  194676. png_warning(png_ptr,
  194677. "Ignoring incorrect cHRM value when sRGB is also present");
  194678. #ifndef PNG_NO_CONSOLE_IO
  194679. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194680. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194681. white_x, white_y, red_x, red_y);
  194682. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194683. green_x, green_y, blue_x, blue_y);
  194684. #else
  194685. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194686. int_x_white, int_y_white, int_x_red, int_y_red);
  194687. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194688. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194689. #endif
  194690. #endif /* PNG_NO_CONSOLE_IO */
  194691. }
  194692. png_crc_finish(png_ptr, 0);
  194693. return;
  194694. }
  194695. #endif /* PNG_READ_sRGB_SUPPORTED */
  194696. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194697. png_set_cHRM(png_ptr, info_ptr,
  194698. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194699. #endif
  194700. #ifdef PNG_FIXED_POINT_SUPPORTED
  194701. png_set_cHRM_fixed(png_ptr, info_ptr,
  194702. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194703. int_y_green, int_x_blue, int_y_blue);
  194704. #endif
  194705. if (png_crc_finish(png_ptr, 0))
  194706. return;
  194707. }
  194708. #endif
  194709. #if defined(PNG_READ_sRGB_SUPPORTED)
  194710. void /* PRIVATE */
  194711. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194712. {
  194713. int intent;
  194714. png_byte buf[1];
  194715. png_debug(1, "in png_handle_sRGB\n");
  194716. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194717. png_error(png_ptr, "Missing IHDR before sRGB");
  194718. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194719. {
  194720. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194721. png_crc_finish(png_ptr, length);
  194722. return;
  194723. }
  194724. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194725. /* Should be an error, but we can cope with it */
  194726. png_warning(png_ptr, "Out of place sRGB chunk");
  194727. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194728. {
  194729. png_warning(png_ptr, "Duplicate sRGB chunk");
  194730. png_crc_finish(png_ptr, length);
  194731. return;
  194732. }
  194733. if (length != 1)
  194734. {
  194735. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194736. png_crc_finish(png_ptr, length);
  194737. return;
  194738. }
  194739. png_crc_read(png_ptr, buf, 1);
  194740. if (png_crc_finish(png_ptr, 0))
  194741. return;
  194742. intent = buf[0];
  194743. /* check for bad intent */
  194744. if (intent >= PNG_sRGB_INTENT_LAST)
  194745. {
  194746. png_warning(png_ptr, "Unknown sRGB intent");
  194747. return;
  194748. }
  194749. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194750. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194751. {
  194752. png_fixed_point igamma;
  194753. #ifdef PNG_FIXED_POINT_SUPPORTED
  194754. igamma=info_ptr->int_gamma;
  194755. #else
  194756. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194757. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194758. # endif
  194759. #endif
  194760. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194761. {
  194762. png_warning(png_ptr,
  194763. "Ignoring incorrect gAMA value when sRGB is also present");
  194764. #ifndef PNG_NO_CONSOLE_IO
  194765. # ifdef PNG_FIXED_POINT_SUPPORTED
  194766. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194767. # else
  194768. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194769. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194770. # endif
  194771. # endif
  194772. #endif
  194773. }
  194774. }
  194775. #endif /* PNG_READ_gAMA_SUPPORTED */
  194776. #ifdef PNG_READ_cHRM_SUPPORTED
  194777. #ifdef PNG_FIXED_POINT_SUPPORTED
  194778. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194779. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194780. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194781. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194782. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194783. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194784. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194785. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194786. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194787. {
  194788. png_warning(png_ptr,
  194789. "Ignoring incorrect cHRM value when sRGB is also present");
  194790. }
  194791. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194792. #endif /* PNG_READ_cHRM_SUPPORTED */
  194793. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194794. }
  194795. #endif /* PNG_READ_sRGB_SUPPORTED */
  194796. #if defined(PNG_READ_iCCP_SUPPORTED)
  194797. void /* PRIVATE */
  194798. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194799. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194800. {
  194801. png_charp chunkdata;
  194802. png_byte compression_type;
  194803. png_bytep pC;
  194804. png_charp profile;
  194805. png_uint_32 skip = 0;
  194806. png_uint_32 profile_size, profile_length;
  194807. png_size_t slength, prefix_length, data_length;
  194808. png_debug(1, "in png_handle_iCCP\n");
  194809. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194810. png_error(png_ptr, "Missing IHDR before iCCP");
  194811. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194812. {
  194813. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194814. png_crc_finish(png_ptr, length);
  194815. return;
  194816. }
  194817. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194818. /* Should be an error, but we can cope with it */
  194819. png_warning(png_ptr, "Out of place iCCP chunk");
  194820. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194821. {
  194822. png_warning(png_ptr, "Duplicate iCCP chunk");
  194823. png_crc_finish(png_ptr, length);
  194824. return;
  194825. }
  194826. #ifdef PNG_MAX_MALLOC_64K
  194827. if (length > (png_uint_32)65535L)
  194828. {
  194829. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194830. skip = length - (png_uint_32)65535L;
  194831. length = (png_uint_32)65535L;
  194832. }
  194833. #endif
  194834. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194835. slength = (png_size_t)length;
  194836. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194837. if (png_crc_finish(png_ptr, skip))
  194838. {
  194839. png_free(png_ptr, chunkdata);
  194840. return;
  194841. }
  194842. chunkdata[slength] = 0x00;
  194843. for (profile = chunkdata; *profile; profile++)
  194844. /* empty loop to find end of name */ ;
  194845. ++profile;
  194846. /* there should be at least one zero (the compression type byte)
  194847. following the separator, and we should be on it */
  194848. if ( profile >= chunkdata + slength - 1)
  194849. {
  194850. png_free(png_ptr, chunkdata);
  194851. png_warning(png_ptr, "Malformed iCCP chunk");
  194852. return;
  194853. }
  194854. /* compression_type should always be zero */
  194855. compression_type = *profile++;
  194856. if (compression_type)
  194857. {
  194858. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194859. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194860. wrote nonzero) */
  194861. }
  194862. prefix_length = profile - chunkdata;
  194863. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194864. slength, prefix_length, &data_length);
  194865. profile_length = data_length - prefix_length;
  194866. if ( prefix_length > data_length || profile_length < 4)
  194867. {
  194868. png_free(png_ptr, chunkdata);
  194869. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194870. return;
  194871. }
  194872. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194873. pC = (png_bytep)(chunkdata+prefix_length);
  194874. profile_size = ((*(pC ))<<24) |
  194875. ((*(pC+1))<<16) |
  194876. ((*(pC+2))<< 8) |
  194877. ((*(pC+3)) );
  194878. if(profile_size < profile_length)
  194879. profile_length = profile_size;
  194880. if(profile_size > profile_length)
  194881. {
  194882. png_free(png_ptr, chunkdata);
  194883. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194884. return;
  194885. }
  194886. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194887. chunkdata + prefix_length, profile_length);
  194888. png_free(png_ptr, chunkdata);
  194889. }
  194890. #endif /* PNG_READ_iCCP_SUPPORTED */
  194891. #if defined(PNG_READ_sPLT_SUPPORTED)
  194892. void /* PRIVATE */
  194893. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194894. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194895. {
  194896. png_bytep chunkdata;
  194897. png_bytep entry_start;
  194898. png_sPLT_t new_palette;
  194899. #ifdef PNG_NO_POINTER_INDEXING
  194900. png_sPLT_entryp pp;
  194901. #endif
  194902. int data_length, entry_size, i;
  194903. png_uint_32 skip = 0;
  194904. png_size_t slength;
  194905. png_debug(1, "in png_handle_sPLT\n");
  194906. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194907. png_error(png_ptr, "Missing IHDR before sPLT");
  194908. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194909. {
  194910. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194911. png_crc_finish(png_ptr, length);
  194912. return;
  194913. }
  194914. #ifdef PNG_MAX_MALLOC_64K
  194915. if (length > (png_uint_32)65535L)
  194916. {
  194917. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194918. skip = length - (png_uint_32)65535L;
  194919. length = (png_uint_32)65535L;
  194920. }
  194921. #endif
  194922. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194923. slength = (png_size_t)length;
  194924. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194925. if (png_crc_finish(png_ptr, skip))
  194926. {
  194927. png_free(png_ptr, chunkdata);
  194928. return;
  194929. }
  194930. chunkdata[slength] = 0x00;
  194931. for (entry_start = chunkdata; *entry_start; entry_start++)
  194932. /* empty loop to find end of name */ ;
  194933. ++entry_start;
  194934. /* a sample depth should follow the separator, and we should be on it */
  194935. if (entry_start > chunkdata + slength - 2)
  194936. {
  194937. png_free(png_ptr, chunkdata);
  194938. png_warning(png_ptr, "malformed sPLT chunk");
  194939. return;
  194940. }
  194941. new_palette.depth = *entry_start++;
  194942. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194943. data_length = (slength - (entry_start - chunkdata));
  194944. /* integrity-check the data length */
  194945. if (data_length % entry_size)
  194946. {
  194947. png_free(png_ptr, chunkdata);
  194948. png_warning(png_ptr, "sPLT chunk has bad length");
  194949. return;
  194950. }
  194951. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194952. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194953. png_sizeof(png_sPLT_entry)))
  194954. {
  194955. png_warning(png_ptr, "sPLT chunk too long");
  194956. return;
  194957. }
  194958. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194959. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194960. if (new_palette.entries == NULL)
  194961. {
  194962. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194963. return;
  194964. }
  194965. #ifndef PNG_NO_POINTER_INDEXING
  194966. for (i = 0; i < new_palette.nentries; i++)
  194967. {
  194968. png_sPLT_entryp pp = new_palette.entries + i;
  194969. if (new_palette.depth == 8)
  194970. {
  194971. pp->red = *entry_start++;
  194972. pp->green = *entry_start++;
  194973. pp->blue = *entry_start++;
  194974. pp->alpha = *entry_start++;
  194975. }
  194976. else
  194977. {
  194978. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194979. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194980. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194981. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194982. }
  194983. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194984. }
  194985. #else
  194986. pp = new_palette.entries;
  194987. for (i = 0; i < new_palette.nentries; i++)
  194988. {
  194989. if (new_palette.depth == 8)
  194990. {
  194991. pp[i].red = *entry_start++;
  194992. pp[i].green = *entry_start++;
  194993. pp[i].blue = *entry_start++;
  194994. pp[i].alpha = *entry_start++;
  194995. }
  194996. else
  194997. {
  194998. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194999. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195000. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195001. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195002. }
  195003. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195004. }
  195005. #endif
  195006. /* discard all chunk data except the name and stash that */
  195007. new_palette.name = (png_charp)chunkdata;
  195008. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195009. png_free(png_ptr, chunkdata);
  195010. png_free(png_ptr, new_palette.entries);
  195011. }
  195012. #endif /* PNG_READ_sPLT_SUPPORTED */
  195013. #if defined(PNG_READ_tRNS_SUPPORTED)
  195014. void /* PRIVATE */
  195015. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195016. {
  195017. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195018. int bit_mask;
  195019. png_debug(1, "in png_handle_tRNS\n");
  195020. /* For non-indexed color, mask off any bits in the tRNS value that
  195021. * exceed the bit depth. Some creators were writing extra bits there.
  195022. * This is not needed for indexed color. */
  195023. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195024. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195025. png_error(png_ptr, "Missing IHDR before tRNS");
  195026. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195027. {
  195028. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195029. png_crc_finish(png_ptr, length);
  195030. return;
  195031. }
  195032. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195033. {
  195034. png_warning(png_ptr, "Duplicate tRNS chunk");
  195035. png_crc_finish(png_ptr, length);
  195036. return;
  195037. }
  195038. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195039. {
  195040. png_byte buf[2];
  195041. if (length != 2)
  195042. {
  195043. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195044. png_crc_finish(png_ptr, length);
  195045. return;
  195046. }
  195047. png_crc_read(png_ptr, buf, 2);
  195048. png_ptr->num_trans = 1;
  195049. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195050. }
  195051. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195052. {
  195053. png_byte buf[6];
  195054. if (length != 6)
  195055. {
  195056. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195057. png_crc_finish(png_ptr, length);
  195058. return;
  195059. }
  195060. png_crc_read(png_ptr, buf, (png_size_t)length);
  195061. png_ptr->num_trans = 1;
  195062. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195063. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195064. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195065. }
  195066. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195067. {
  195068. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195069. {
  195070. /* Should be an error, but we can cope with it. */
  195071. png_warning(png_ptr, "Missing PLTE before tRNS");
  195072. }
  195073. if (length > (png_uint_32)png_ptr->num_palette ||
  195074. length > PNG_MAX_PALETTE_LENGTH)
  195075. {
  195076. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195077. png_crc_finish(png_ptr, length);
  195078. return;
  195079. }
  195080. if (length == 0)
  195081. {
  195082. png_warning(png_ptr, "Zero length tRNS chunk");
  195083. png_crc_finish(png_ptr, length);
  195084. return;
  195085. }
  195086. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195087. png_ptr->num_trans = (png_uint_16)length;
  195088. }
  195089. else
  195090. {
  195091. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195092. png_crc_finish(png_ptr, length);
  195093. return;
  195094. }
  195095. if (png_crc_finish(png_ptr, 0))
  195096. {
  195097. png_ptr->num_trans = 0;
  195098. return;
  195099. }
  195100. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195101. &(png_ptr->trans_values));
  195102. }
  195103. #endif
  195104. #if defined(PNG_READ_bKGD_SUPPORTED)
  195105. void /* PRIVATE */
  195106. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195107. {
  195108. png_size_t truelen;
  195109. png_byte buf[6];
  195110. png_debug(1, "in png_handle_bKGD\n");
  195111. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195112. png_error(png_ptr, "Missing IHDR before bKGD");
  195113. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195114. {
  195115. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195116. png_crc_finish(png_ptr, length);
  195117. return;
  195118. }
  195119. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195120. !(png_ptr->mode & PNG_HAVE_PLTE))
  195121. {
  195122. png_warning(png_ptr, "Missing PLTE before bKGD");
  195123. png_crc_finish(png_ptr, length);
  195124. return;
  195125. }
  195126. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195127. {
  195128. png_warning(png_ptr, "Duplicate bKGD chunk");
  195129. png_crc_finish(png_ptr, length);
  195130. return;
  195131. }
  195132. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195133. truelen = 1;
  195134. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195135. truelen = 6;
  195136. else
  195137. truelen = 2;
  195138. if (length != truelen)
  195139. {
  195140. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195141. png_crc_finish(png_ptr, length);
  195142. return;
  195143. }
  195144. png_crc_read(png_ptr, buf, truelen);
  195145. if (png_crc_finish(png_ptr, 0))
  195146. return;
  195147. /* We convert the index value into RGB components so that we can allow
  195148. * arbitrary RGB values for background when we have transparency, and
  195149. * so it is easy to determine the RGB values of the background color
  195150. * from the info_ptr struct. */
  195151. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195152. {
  195153. png_ptr->background.index = buf[0];
  195154. if(info_ptr->num_palette)
  195155. {
  195156. if(buf[0] > info_ptr->num_palette)
  195157. {
  195158. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195159. return;
  195160. }
  195161. png_ptr->background.red =
  195162. (png_uint_16)png_ptr->palette[buf[0]].red;
  195163. png_ptr->background.green =
  195164. (png_uint_16)png_ptr->palette[buf[0]].green;
  195165. png_ptr->background.blue =
  195166. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195167. }
  195168. }
  195169. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195170. {
  195171. png_ptr->background.red =
  195172. png_ptr->background.green =
  195173. png_ptr->background.blue =
  195174. png_ptr->background.gray = png_get_uint_16(buf);
  195175. }
  195176. else
  195177. {
  195178. png_ptr->background.red = png_get_uint_16(buf);
  195179. png_ptr->background.green = png_get_uint_16(buf + 2);
  195180. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195181. }
  195182. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195183. }
  195184. #endif
  195185. #if defined(PNG_READ_hIST_SUPPORTED)
  195186. void /* PRIVATE */
  195187. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195188. {
  195189. unsigned int num, i;
  195190. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195191. png_debug(1, "in png_handle_hIST\n");
  195192. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195193. png_error(png_ptr, "Missing IHDR before hIST");
  195194. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195195. {
  195196. png_warning(png_ptr, "Invalid hIST after IDAT");
  195197. png_crc_finish(png_ptr, length);
  195198. return;
  195199. }
  195200. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195201. {
  195202. png_warning(png_ptr, "Missing PLTE before hIST");
  195203. png_crc_finish(png_ptr, length);
  195204. return;
  195205. }
  195206. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195207. {
  195208. png_warning(png_ptr, "Duplicate hIST chunk");
  195209. png_crc_finish(png_ptr, length);
  195210. return;
  195211. }
  195212. num = length / 2 ;
  195213. if (num != (unsigned int) png_ptr->num_palette || num >
  195214. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195215. {
  195216. png_warning(png_ptr, "Incorrect hIST chunk length");
  195217. png_crc_finish(png_ptr, length);
  195218. return;
  195219. }
  195220. for (i = 0; i < num; i++)
  195221. {
  195222. png_byte buf[2];
  195223. png_crc_read(png_ptr, buf, 2);
  195224. readbuf[i] = png_get_uint_16(buf);
  195225. }
  195226. if (png_crc_finish(png_ptr, 0))
  195227. return;
  195228. png_set_hIST(png_ptr, info_ptr, readbuf);
  195229. }
  195230. #endif
  195231. #if defined(PNG_READ_pHYs_SUPPORTED)
  195232. void /* PRIVATE */
  195233. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195234. {
  195235. png_byte buf[9];
  195236. png_uint_32 res_x, res_y;
  195237. int unit_type;
  195238. png_debug(1, "in png_handle_pHYs\n");
  195239. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195240. png_error(png_ptr, "Missing IHDR before pHYs");
  195241. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195242. {
  195243. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195244. png_crc_finish(png_ptr, length);
  195245. return;
  195246. }
  195247. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195248. {
  195249. png_warning(png_ptr, "Duplicate pHYs chunk");
  195250. png_crc_finish(png_ptr, length);
  195251. return;
  195252. }
  195253. if (length != 9)
  195254. {
  195255. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195256. png_crc_finish(png_ptr, length);
  195257. return;
  195258. }
  195259. png_crc_read(png_ptr, buf, 9);
  195260. if (png_crc_finish(png_ptr, 0))
  195261. return;
  195262. res_x = png_get_uint_32(buf);
  195263. res_y = png_get_uint_32(buf + 4);
  195264. unit_type = buf[8];
  195265. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195266. }
  195267. #endif
  195268. #if defined(PNG_READ_oFFs_SUPPORTED)
  195269. void /* PRIVATE */
  195270. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195271. {
  195272. png_byte buf[9];
  195273. png_int_32 offset_x, offset_y;
  195274. int unit_type;
  195275. png_debug(1, "in png_handle_oFFs\n");
  195276. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195277. png_error(png_ptr, "Missing IHDR before oFFs");
  195278. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195279. {
  195280. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195281. png_crc_finish(png_ptr, length);
  195282. return;
  195283. }
  195284. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195285. {
  195286. png_warning(png_ptr, "Duplicate oFFs chunk");
  195287. png_crc_finish(png_ptr, length);
  195288. return;
  195289. }
  195290. if (length != 9)
  195291. {
  195292. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. png_crc_read(png_ptr, buf, 9);
  195297. if (png_crc_finish(png_ptr, 0))
  195298. return;
  195299. offset_x = png_get_int_32(buf);
  195300. offset_y = png_get_int_32(buf + 4);
  195301. unit_type = buf[8];
  195302. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195303. }
  195304. #endif
  195305. #if defined(PNG_READ_pCAL_SUPPORTED)
  195306. /* read the pCAL chunk (described in the PNG Extensions document) */
  195307. void /* PRIVATE */
  195308. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195309. {
  195310. png_charp purpose;
  195311. png_int_32 X0, X1;
  195312. png_byte type, nparams;
  195313. png_charp buf, units, endptr;
  195314. png_charpp params;
  195315. png_size_t slength;
  195316. int i;
  195317. png_debug(1, "in png_handle_pCAL\n");
  195318. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195319. png_error(png_ptr, "Missing IHDR before pCAL");
  195320. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195321. {
  195322. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195323. png_crc_finish(png_ptr, length);
  195324. return;
  195325. }
  195326. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195327. {
  195328. png_warning(png_ptr, "Duplicate pCAL chunk");
  195329. png_crc_finish(png_ptr, length);
  195330. return;
  195331. }
  195332. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195333. length + 1);
  195334. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195335. if (purpose == NULL)
  195336. {
  195337. png_warning(png_ptr, "No memory for pCAL purpose.");
  195338. return;
  195339. }
  195340. slength = (png_size_t)length;
  195341. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195342. if (png_crc_finish(png_ptr, 0))
  195343. {
  195344. png_free(png_ptr, purpose);
  195345. return;
  195346. }
  195347. purpose[slength] = 0x00; /* null terminate the last string */
  195348. png_debug(3, "Finding end of pCAL purpose string\n");
  195349. for (buf = purpose; *buf; buf++)
  195350. /* empty loop */ ;
  195351. endptr = purpose + slength;
  195352. /* We need to have at least 12 bytes after the purpose string
  195353. in order to get the parameter information. */
  195354. if (endptr <= buf + 12)
  195355. {
  195356. png_warning(png_ptr, "Invalid pCAL data");
  195357. png_free(png_ptr, purpose);
  195358. return;
  195359. }
  195360. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195361. X0 = png_get_int_32((png_bytep)buf+1);
  195362. X1 = png_get_int_32((png_bytep)buf+5);
  195363. type = buf[9];
  195364. nparams = buf[10];
  195365. units = buf + 11;
  195366. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195367. /* Check that we have the right number of parameters for known
  195368. equation types. */
  195369. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195370. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195371. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195372. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195373. {
  195374. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195375. png_free(png_ptr, purpose);
  195376. return;
  195377. }
  195378. else if (type >= PNG_EQUATION_LAST)
  195379. {
  195380. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195381. }
  195382. for (buf = units; *buf; buf++)
  195383. /* Empty loop to move past the units string. */ ;
  195384. png_debug(3, "Allocating pCAL parameters array\n");
  195385. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195386. *png_sizeof(png_charp))) ;
  195387. if (params == NULL)
  195388. {
  195389. png_free(png_ptr, purpose);
  195390. png_warning(png_ptr, "No memory for pCAL params.");
  195391. return;
  195392. }
  195393. /* Get pointers to the start of each parameter string. */
  195394. for (i = 0; i < (int)nparams; i++)
  195395. {
  195396. buf++; /* Skip the null string terminator from previous parameter. */
  195397. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195398. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195399. /* Empty loop to move past each parameter string */ ;
  195400. /* Make sure we haven't run out of data yet */
  195401. if (buf > endptr)
  195402. {
  195403. png_warning(png_ptr, "Invalid pCAL data");
  195404. png_free(png_ptr, purpose);
  195405. png_free(png_ptr, params);
  195406. return;
  195407. }
  195408. }
  195409. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195410. units, params);
  195411. png_free(png_ptr, purpose);
  195412. png_free(png_ptr, params);
  195413. }
  195414. #endif
  195415. #if defined(PNG_READ_sCAL_SUPPORTED)
  195416. /* read the sCAL chunk */
  195417. void /* PRIVATE */
  195418. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195419. {
  195420. png_charp buffer, ep;
  195421. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195422. double width, height;
  195423. png_charp vp;
  195424. #else
  195425. #ifdef PNG_FIXED_POINT_SUPPORTED
  195426. png_charp swidth, sheight;
  195427. #endif
  195428. #endif
  195429. png_size_t slength;
  195430. png_debug(1, "in png_handle_sCAL\n");
  195431. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195432. png_error(png_ptr, "Missing IHDR before sCAL");
  195433. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195434. {
  195435. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195436. png_crc_finish(png_ptr, length);
  195437. return;
  195438. }
  195439. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195440. {
  195441. png_warning(png_ptr, "Duplicate sCAL chunk");
  195442. png_crc_finish(png_ptr, length);
  195443. return;
  195444. }
  195445. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195446. length + 1);
  195447. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195448. if (buffer == NULL)
  195449. {
  195450. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195451. return;
  195452. }
  195453. slength = (png_size_t)length;
  195454. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195455. if (png_crc_finish(png_ptr, 0))
  195456. {
  195457. png_free(png_ptr, buffer);
  195458. return;
  195459. }
  195460. buffer[slength] = 0x00; /* null terminate the last string */
  195461. ep = buffer + 1; /* skip unit byte */
  195462. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195463. width = png_strtod(png_ptr, ep, &vp);
  195464. if (*vp)
  195465. {
  195466. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195467. return;
  195468. }
  195469. #else
  195470. #ifdef PNG_FIXED_POINT_SUPPORTED
  195471. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195472. if (swidth == NULL)
  195473. {
  195474. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195475. return;
  195476. }
  195477. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195478. #endif
  195479. #endif
  195480. for (ep = buffer; *ep; ep++)
  195481. /* empty loop */ ;
  195482. ep++;
  195483. if (buffer + slength < ep)
  195484. {
  195485. png_warning(png_ptr, "Truncated sCAL chunk");
  195486. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195487. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195488. png_free(png_ptr, swidth);
  195489. #endif
  195490. png_free(png_ptr, buffer);
  195491. return;
  195492. }
  195493. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195494. height = png_strtod(png_ptr, ep, &vp);
  195495. if (*vp)
  195496. {
  195497. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195498. return;
  195499. }
  195500. #else
  195501. #ifdef PNG_FIXED_POINT_SUPPORTED
  195502. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195503. if (swidth == NULL)
  195504. {
  195505. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195506. return;
  195507. }
  195508. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195509. #endif
  195510. #endif
  195511. if (buffer + slength < ep
  195512. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195513. || width <= 0. || height <= 0.
  195514. #endif
  195515. )
  195516. {
  195517. png_warning(png_ptr, "Invalid sCAL data");
  195518. png_free(png_ptr, buffer);
  195519. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195520. png_free(png_ptr, swidth);
  195521. png_free(png_ptr, sheight);
  195522. #endif
  195523. return;
  195524. }
  195525. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195526. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195527. #else
  195528. #ifdef PNG_FIXED_POINT_SUPPORTED
  195529. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195530. #endif
  195531. #endif
  195532. png_free(png_ptr, buffer);
  195533. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195534. png_free(png_ptr, swidth);
  195535. png_free(png_ptr, sheight);
  195536. #endif
  195537. }
  195538. #endif
  195539. #if defined(PNG_READ_tIME_SUPPORTED)
  195540. void /* PRIVATE */
  195541. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195542. {
  195543. png_byte buf[7];
  195544. png_time mod_time;
  195545. png_debug(1, "in png_handle_tIME\n");
  195546. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195547. png_error(png_ptr, "Out of place tIME chunk");
  195548. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195549. {
  195550. png_warning(png_ptr, "Duplicate tIME chunk");
  195551. png_crc_finish(png_ptr, length);
  195552. return;
  195553. }
  195554. if (png_ptr->mode & PNG_HAVE_IDAT)
  195555. png_ptr->mode |= PNG_AFTER_IDAT;
  195556. if (length != 7)
  195557. {
  195558. png_warning(png_ptr, "Incorrect tIME chunk length");
  195559. png_crc_finish(png_ptr, length);
  195560. return;
  195561. }
  195562. png_crc_read(png_ptr, buf, 7);
  195563. if (png_crc_finish(png_ptr, 0))
  195564. return;
  195565. mod_time.second = buf[6];
  195566. mod_time.minute = buf[5];
  195567. mod_time.hour = buf[4];
  195568. mod_time.day = buf[3];
  195569. mod_time.month = buf[2];
  195570. mod_time.year = png_get_uint_16(buf);
  195571. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195572. }
  195573. #endif
  195574. #if defined(PNG_READ_tEXt_SUPPORTED)
  195575. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195576. void /* PRIVATE */
  195577. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195578. {
  195579. png_textp text_ptr;
  195580. png_charp key;
  195581. png_charp text;
  195582. png_uint_32 skip = 0;
  195583. png_size_t slength;
  195584. int ret;
  195585. png_debug(1, "in png_handle_tEXt\n");
  195586. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195587. png_error(png_ptr, "Missing IHDR before tEXt");
  195588. if (png_ptr->mode & PNG_HAVE_IDAT)
  195589. png_ptr->mode |= PNG_AFTER_IDAT;
  195590. #ifdef PNG_MAX_MALLOC_64K
  195591. if (length > (png_uint_32)65535L)
  195592. {
  195593. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195594. skip = length - (png_uint_32)65535L;
  195595. length = (png_uint_32)65535L;
  195596. }
  195597. #endif
  195598. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195599. if (key == NULL)
  195600. {
  195601. png_warning(png_ptr, "No memory to process text chunk.");
  195602. return;
  195603. }
  195604. slength = (png_size_t)length;
  195605. png_crc_read(png_ptr, (png_bytep)key, slength);
  195606. if (png_crc_finish(png_ptr, skip))
  195607. {
  195608. png_free(png_ptr, key);
  195609. return;
  195610. }
  195611. key[slength] = 0x00;
  195612. for (text = key; *text; text++)
  195613. /* empty loop to find end of key */ ;
  195614. if (text != key + slength)
  195615. text++;
  195616. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195617. (png_uint_32)png_sizeof(png_text));
  195618. if (text_ptr == NULL)
  195619. {
  195620. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195621. png_free(png_ptr, key);
  195622. return;
  195623. }
  195624. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195625. text_ptr->key = key;
  195626. #ifdef PNG_iTXt_SUPPORTED
  195627. text_ptr->lang = NULL;
  195628. text_ptr->lang_key = NULL;
  195629. text_ptr->itxt_length = 0;
  195630. #endif
  195631. text_ptr->text = text;
  195632. text_ptr->text_length = png_strlen(text);
  195633. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195634. png_free(png_ptr, key);
  195635. png_free(png_ptr, text_ptr);
  195636. if (ret)
  195637. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195638. }
  195639. #endif
  195640. #if defined(PNG_READ_zTXt_SUPPORTED)
  195641. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195642. void /* PRIVATE */
  195643. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195644. {
  195645. png_textp text_ptr;
  195646. png_charp chunkdata;
  195647. png_charp text;
  195648. int comp_type;
  195649. int ret;
  195650. png_size_t slength, prefix_len, data_len;
  195651. png_debug(1, "in png_handle_zTXt\n");
  195652. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195653. png_error(png_ptr, "Missing IHDR before zTXt");
  195654. if (png_ptr->mode & PNG_HAVE_IDAT)
  195655. png_ptr->mode |= PNG_AFTER_IDAT;
  195656. #ifdef PNG_MAX_MALLOC_64K
  195657. /* We will no doubt have problems with chunks even half this size, but
  195658. there is no hard and fast rule to tell us where to stop. */
  195659. if (length > (png_uint_32)65535L)
  195660. {
  195661. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195662. png_crc_finish(png_ptr, length);
  195663. return;
  195664. }
  195665. #endif
  195666. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195667. if (chunkdata == NULL)
  195668. {
  195669. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195670. return;
  195671. }
  195672. slength = (png_size_t)length;
  195673. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195674. if (png_crc_finish(png_ptr, 0))
  195675. {
  195676. png_free(png_ptr, chunkdata);
  195677. return;
  195678. }
  195679. chunkdata[slength] = 0x00;
  195680. for (text = chunkdata; *text; text++)
  195681. /* empty loop */ ;
  195682. /* zTXt must have some text after the chunkdataword */
  195683. if (text >= chunkdata + slength - 2)
  195684. {
  195685. png_warning(png_ptr, "Truncated zTXt chunk");
  195686. png_free(png_ptr, chunkdata);
  195687. return;
  195688. }
  195689. else
  195690. {
  195691. comp_type = *(++text);
  195692. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195693. {
  195694. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195695. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195696. }
  195697. text++; /* skip the compression_method byte */
  195698. }
  195699. prefix_len = text - chunkdata;
  195700. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195701. (png_size_t)length, prefix_len, &data_len);
  195702. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195703. (png_uint_32)png_sizeof(png_text));
  195704. if (text_ptr == NULL)
  195705. {
  195706. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195707. png_free(png_ptr, chunkdata);
  195708. return;
  195709. }
  195710. text_ptr->compression = comp_type;
  195711. text_ptr->key = chunkdata;
  195712. #ifdef PNG_iTXt_SUPPORTED
  195713. text_ptr->lang = NULL;
  195714. text_ptr->lang_key = NULL;
  195715. text_ptr->itxt_length = 0;
  195716. #endif
  195717. text_ptr->text = chunkdata + prefix_len;
  195718. text_ptr->text_length = data_len;
  195719. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195720. png_free(png_ptr, text_ptr);
  195721. png_free(png_ptr, chunkdata);
  195722. if (ret)
  195723. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195724. }
  195725. #endif
  195726. #if defined(PNG_READ_iTXt_SUPPORTED)
  195727. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195728. void /* PRIVATE */
  195729. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195730. {
  195731. png_textp text_ptr;
  195732. png_charp chunkdata;
  195733. png_charp key, lang, text, lang_key;
  195734. int comp_flag;
  195735. int comp_type = 0;
  195736. int ret;
  195737. png_size_t slength, prefix_len, data_len;
  195738. png_debug(1, "in png_handle_iTXt\n");
  195739. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195740. png_error(png_ptr, "Missing IHDR before iTXt");
  195741. if (png_ptr->mode & PNG_HAVE_IDAT)
  195742. png_ptr->mode |= PNG_AFTER_IDAT;
  195743. #ifdef PNG_MAX_MALLOC_64K
  195744. /* We will no doubt have problems with chunks even half this size, but
  195745. there is no hard and fast rule to tell us where to stop. */
  195746. if (length > (png_uint_32)65535L)
  195747. {
  195748. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195749. png_crc_finish(png_ptr, length);
  195750. return;
  195751. }
  195752. #endif
  195753. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195754. if (chunkdata == NULL)
  195755. {
  195756. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195757. return;
  195758. }
  195759. slength = (png_size_t)length;
  195760. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195761. if (png_crc_finish(png_ptr, 0))
  195762. {
  195763. png_free(png_ptr, chunkdata);
  195764. return;
  195765. }
  195766. chunkdata[slength] = 0x00;
  195767. for (lang = chunkdata; *lang; lang++)
  195768. /* empty loop */ ;
  195769. lang++; /* skip NUL separator */
  195770. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195771. translated keyword (possibly empty), and possibly some text after the
  195772. keyword */
  195773. if (lang >= chunkdata + slength - 3)
  195774. {
  195775. png_warning(png_ptr, "Truncated iTXt chunk");
  195776. png_free(png_ptr, chunkdata);
  195777. return;
  195778. }
  195779. else
  195780. {
  195781. comp_flag = *lang++;
  195782. comp_type = *lang++;
  195783. }
  195784. for (lang_key = lang; *lang_key; lang_key++)
  195785. /* empty loop */ ;
  195786. lang_key++; /* skip NUL separator */
  195787. if (lang_key >= chunkdata + slength)
  195788. {
  195789. png_warning(png_ptr, "Truncated iTXt chunk");
  195790. png_free(png_ptr, chunkdata);
  195791. return;
  195792. }
  195793. for (text = lang_key; *text; text++)
  195794. /* empty loop */ ;
  195795. text++; /* skip NUL separator */
  195796. if (text >= chunkdata + slength)
  195797. {
  195798. png_warning(png_ptr, "Malformed iTXt chunk");
  195799. png_free(png_ptr, chunkdata);
  195800. return;
  195801. }
  195802. prefix_len = text - chunkdata;
  195803. key=chunkdata;
  195804. if (comp_flag)
  195805. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195806. (size_t)length, prefix_len, &data_len);
  195807. else
  195808. data_len=png_strlen(chunkdata + prefix_len);
  195809. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195810. (png_uint_32)png_sizeof(png_text));
  195811. if (text_ptr == NULL)
  195812. {
  195813. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195814. png_free(png_ptr, chunkdata);
  195815. return;
  195816. }
  195817. text_ptr->compression = (int)comp_flag + 1;
  195818. text_ptr->lang_key = chunkdata+(lang_key-key);
  195819. text_ptr->lang = chunkdata+(lang-key);
  195820. text_ptr->itxt_length = data_len;
  195821. text_ptr->text_length = 0;
  195822. text_ptr->key = chunkdata;
  195823. text_ptr->text = chunkdata + prefix_len;
  195824. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195825. png_free(png_ptr, text_ptr);
  195826. png_free(png_ptr, chunkdata);
  195827. if (ret)
  195828. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195829. }
  195830. #endif
  195831. /* This function is called when we haven't found a handler for a
  195832. chunk. If there isn't a problem with the chunk itself (ie bad
  195833. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195834. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195835. case it will be saved away to be written out later. */
  195836. void /* PRIVATE */
  195837. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195838. {
  195839. png_uint_32 skip = 0;
  195840. png_debug(1, "in png_handle_unknown\n");
  195841. if (png_ptr->mode & PNG_HAVE_IDAT)
  195842. {
  195843. #ifdef PNG_USE_LOCAL_ARRAYS
  195844. PNG_CONST PNG_IDAT;
  195845. #endif
  195846. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195847. png_ptr->mode |= PNG_AFTER_IDAT;
  195848. }
  195849. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195850. if (!(png_ptr->chunk_name[0] & 0x20))
  195851. {
  195852. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195853. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195854. PNG_HANDLE_CHUNK_ALWAYS
  195855. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195856. && png_ptr->read_user_chunk_fn == NULL
  195857. #endif
  195858. )
  195859. #endif
  195860. png_chunk_error(png_ptr, "unknown critical chunk");
  195861. }
  195862. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195863. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195864. (png_ptr->read_user_chunk_fn != NULL))
  195865. {
  195866. #ifdef PNG_MAX_MALLOC_64K
  195867. if (length > (png_uint_32)65535L)
  195868. {
  195869. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195870. skip = length - (png_uint_32)65535L;
  195871. length = (png_uint_32)65535L;
  195872. }
  195873. #endif
  195874. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195875. (png_charp)png_ptr->chunk_name, 5);
  195876. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195877. png_ptr->unknown_chunk.size = (png_size_t)length;
  195878. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195879. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195880. if(png_ptr->read_user_chunk_fn != NULL)
  195881. {
  195882. /* callback to user unknown chunk handler */
  195883. int ret;
  195884. ret = (*(png_ptr->read_user_chunk_fn))
  195885. (png_ptr, &png_ptr->unknown_chunk);
  195886. if (ret < 0)
  195887. png_chunk_error(png_ptr, "error in user chunk");
  195888. if (ret == 0)
  195889. {
  195890. if (!(png_ptr->chunk_name[0] & 0x20))
  195891. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195892. PNG_HANDLE_CHUNK_ALWAYS)
  195893. png_chunk_error(png_ptr, "unknown critical chunk");
  195894. png_set_unknown_chunks(png_ptr, info_ptr,
  195895. &png_ptr->unknown_chunk, 1);
  195896. }
  195897. }
  195898. #else
  195899. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195900. #endif
  195901. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195902. png_ptr->unknown_chunk.data = NULL;
  195903. }
  195904. else
  195905. #endif
  195906. skip = length;
  195907. png_crc_finish(png_ptr, skip);
  195908. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195909. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195910. #endif
  195911. }
  195912. /* This function is called to verify that a chunk name is valid.
  195913. This function can't have the "critical chunk check" incorporated
  195914. into it, since in the future we will need to be able to call user
  195915. functions to handle unknown critical chunks after we check that
  195916. the chunk name itself is valid. */
  195917. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195918. void /* PRIVATE */
  195919. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195920. {
  195921. png_debug(1, "in png_check_chunk_name\n");
  195922. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195923. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195924. {
  195925. png_chunk_error(png_ptr, "invalid chunk type");
  195926. }
  195927. }
  195928. /* Combines the row recently read in with the existing pixels in the
  195929. row. This routine takes care of alpha and transparency if requested.
  195930. This routine also handles the two methods of progressive display
  195931. of interlaced images, depending on the mask value.
  195932. The mask value describes which pixels are to be combined with
  195933. the row. The pattern always repeats every 8 pixels, so just 8
  195934. bits are needed. A one indicates the pixel is to be combined,
  195935. a zero indicates the pixel is to be skipped. This is in addition
  195936. to any alpha or transparency value associated with the pixel. If
  195937. you want all pixels to be combined, pass 0xff (255) in mask. */
  195938. void /* PRIVATE */
  195939. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195940. {
  195941. png_debug(1,"in png_combine_row\n");
  195942. if (mask == 0xff)
  195943. {
  195944. png_memcpy(row, png_ptr->row_buf + 1,
  195945. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195946. }
  195947. else
  195948. {
  195949. switch (png_ptr->row_info.pixel_depth)
  195950. {
  195951. case 1:
  195952. {
  195953. png_bytep sp = png_ptr->row_buf + 1;
  195954. png_bytep dp = row;
  195955. int s_inc, s_start, s_end;
  195956. int m = 0x80;
  195957. int shift;
  195958. png_uint_32 i;
  195959. png_uint_32 row_width = png_ptr->width;
  195960. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195961. if (png_ptr->transformations & PNG_PACKSWAP)
  195962. {
  195963. s_start = 0;
  195964. s_end = 7;
  195965. s_inc = 1;
  195966. }
  195967. else
  195968. #endif
  195969. {
  195970. s_start = 7;
  195971. s_end = 0;
  195972. s_inc = -1;
  195973. }
  195974. shift = s_start;
  195975. for (i = 0; i < row_width; i++)
  195976. {
  195977. if (m & mask)
  195978. {
  195979. int value;
  195980. value = (*sp >> shift) & 0x01;
  195981. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195982. *dp |= (png_byte)(value << shift);
  195983. }
  195984. if (shift == s_end)
  195985. {
  195986. shift = s_start;
  195987. sp++;
  195988. dp++;
  195989. }
  195990. else
  195991. shift += s_inc;
  195992. if (m == 1)
  195993. m = 0x80;
  195994. else
  195995. m >>= 1;
  195996. }
  195997. break;
  195998. }
  195999. case 2:
  196000. {
  196001. png_bytep sp = png_ptr->row_buf + 1;
  196002. png_bytep dp = row;
  196003. int s_start, s_end, s_inc;
  196004. int m = 0x80;
  196005. int shift;
  196006. png_uint_32 i;
  196007. png_uint_32 row_width = png_ptr->width;
  196008. int value;
  196009. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196010. if (png_ptr->transformations & PNG_PACKSWAP)
  196011. {
  196012. s_start = 0;
  196013. s_end = 6;
  196014. s_inc = 2;
  196015. }
  196016. else
  196017. #endif
  196018. {
  196019. s_start = 6;
  196020. s_end = 0;
  196021. s_inc = -2;
  196022. }
  196023. shift = s_start;
  196024. for (i = 0; i < row_width; i++)
  196025. {
  196026. if (m & mask)
  196027. {
  196028. value = (*sp >> shift) & 0x03;
  196029. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196030. *dp |= (png_byte)(value << shift);
  196031. }
  196032. if (shift == s_end)
  196033. {
  196034. shift = s_start;
  196035. sp++;
  196036. dp++;
  196037. }
  196038. else
  196039. shift += s_inc;
  196040. if (m == 1)
  196041. m = 0x80;
  196042. else
  196043. m >>= 1;
  196044. }
  196045. break;
  196046. }
  196047. case 4:
  196048. {
  196049. png_bytep sp = png_ptr->row_buf + 1;
  196050. png_bytep dp = row;
  196051. int s_start, s_end, s_inc;
  196052. int m = 0x80;
  196053. int shift;
  196054. png_uint_32 i;
  196055. png_uint_32 row_width = png_ptr->width;
  196056. int value;
  196057. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196058. if (png_ptr->transformations & PNG_PACKSWAP)
  196059. {
  196060. s_start = 0;
  196061. s_end = 4;
  196062. s_inc = 4;
  196063. }
  196064. else
  196065. #endif
  196066. {
  196067. s_start = 4;
  196068. s_end = 0;
  196069. s_inc = -4;
  196070. }
  196071. shift = s_start;
  196072. for (i = 0; i < row_width; i++)
  196073. {
  196074. if (m & mask)
  196075. {
  196076. value = (*sp >> shift) & 0xf;
  196077. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196078. *dp |= (png_byte)(value << shift);
  196079. }
  196080. if (shift == s_end)
  196081. {
  196082. shift = s_start;
  196083. sp++;
  196084. dp++;
  196085. }
  196086. else
  196087. shift += s_inc;
  196088. if (m == 1)
  196089. m = 0x80;
  196090. else
  196091. m >>= 1;
  196092. }
  196093. break;
  196094. }
  196095. default:
  196096. {
  196097. png_bytep sp = png_ptr->row_buf + 1;
  196098. png_bytep dp = row;
  196099. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196100. png_uint_32 i;
  196101. png_uint_32 row_width = png_ptr->width;
  196102. png_byte m = 0x80;
  196103. for (i = 0; i < row_width; i++)
  196104. {
  196105. if (m & mask)
  196106. {
  196107. png_memcpy(dp, sp, pixel_bytes);
  196108. }
  196109. sp += pixel_bytes;
  196110. dp += pixel_bytes;
  196111. if (m == 1)
  196112. m = 0x80;
  196113. else
  196114. m >>= 1;
  196115. }
  196116. break;
  196117. }
  196118. }
  196119. }
  196120. }
  196121. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196122. /* OLD pre-1.0.9 interface:
  196123. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196124. png_uint_32 transformations)
  196125. */
  196126. void /* PRIVATE */
  196127. png_do_read_interlace(png_structp png_ptr)
  196128. {
  196129. png_row_infop row_info = &(png_ptr->row_info);
  196130. png_bytep row = png_ptr->row_buf + 1;
  196131. int pass = png_ptr->pass;
  196132. png_uint_32 transformations = png_ptr->transformations;
  196133. #ifdef PNG_USE_LOCAL_ARRAYS
  196134. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196135. /* offset to next interlace block */
  196136. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196137. #endif
  196138. png_debug(1,"in png_do_read_interlace\n");
  196139. if (row != NULL && row_info != NULL)
  196140. {
  196141. png_uint_32 final_width;
  196142. final_width = row_info->width * png_pass_inc[pass];
  196143. switch (row_info->pixel_depth)
  196144. {
  196145. case 1:
  196146. {
  196147. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196148. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196149. int sshift, dshift;
  196150. int s_start, s_end, s_inc;
  196151. int jstop = png_pass_inc[pass];
  196152. png_byte v;
  196153. png_uint_32 i;
  196154. int j;
  196155. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196156. if (transformations & PNG_PACKSWAP)
  196157. {
  196158. sshift = (int)((row_info->width + 7) & 0x07);
  196159. dshift = (int)((final_width + 7) & 0x07);
  196160. s_start = 7;
  196161. s_end = 0;
  196162. s_inc = -1;
  196163. }
  196164. else
  196165. #endif
  196166. {
  196167. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196168. dshift = 7 - (int)((final_width + 7) & 0x07);
  196169. s_start = 0;
  196170. s_end = 7;
  196171. s_inc = 1;
  196172. }
  196173. for (i = 0; i < row_info->width; i++)
  196174. {
  196175. v = (png_byte)((*sp >> sshift) & 0x01);
  196176. for (j = 0; j < jstop; j++)
  196177. {
  196178. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196179. *dp |= (png_byte)(v << dshift);
  196180. if (dshift == s_end)
  196181. {
  196182. dshift = s_start;
  196183. dp--;
  196184. }
  196185. else
  196186. dshift += s_inc;
  196187. }
  196188. if (sshift == s_end)
  196189. {
  196190. sshift = s_start;
  196191. sp--;
  196192. }
  196193. else
  196194. sshift += s_inc;
  196195. }
  196196. break;
  196197. }
  196198. case 2:
  196199. {
  196200. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196201. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196202. int sshift, dshift;
  196203. int s_start, s_end, s_inc;
  196204. int jstop = png_pass_inc[pass];
  196205. png_uint_32 i;
  196206. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196207. if (transformations & PNG_PACKSWAP)
  196208. {
  196209. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196210. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196211. s_start = 6;
  196212. s_end = 0;
  196213. s_inc = -2;
  196214. }
  196215. else
  196216. #endif
  196217. {
  196218. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196219. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196220. s_start = 0;
  196221. s_end = 6;
  196222. s_inc = 2;
  196223. }
  196224. for (i = 0; i < row_info->width; i++)
  196225. {
  196226. png_byte v;
  196227. int j;
  196228. v = (png_byte)((*sp >> sshift) & 0x03);
  196229. for (j = 0; j < jstop; j++)
  196230. {
  196231. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196232. *dp |= (png_byte)(v << dshift);
  196233. if (dshift == s_end)
  196234. {
  196235. dshift = s_start;
  196236. dp--;
  196237. }
  196238. else
  196239. dshift += s_inc;
  196240. }
  196241. if (sshift == s_end)
  196242. {
  196243. sshift = s_start;
  196244. sp--;
  196245. }
  196246. else
  196247. sshift += s_inc;
  196248. }
  196249. break;
  196250. }
  196251. case 4:
  196252. {
  196253. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196254. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196255. int sshift, dshift;
  196256. int s_start, s_end, s_inc;
  196257. png_uint_32 i;
  196258. int jstop = png_pass_inc[pass];
  196259. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196260. if (transformations & PNG_PACKSWAP)
  196261. {
  196262. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196263. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196264. s_start = 4;
  196265. s_end = 0;
  196266. s_inc = -4;
  196267. }
  196268. else
  196269. #endif
  196270. {
  196271. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196272. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196273. s_start = 0;
  196274. s_end = 4;
  196275. s_inc = 4;
  196276. }
  196277. for (i = 0; i < row_info->width; i++)
  196278. {
  196279. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196280. int j;
  196281. for (j = 0; j < jstop; j++)
  196282. {
  196283. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196284. *dp |= (png_byte)(v << dshift);
  196285. if (dshift == s_end)
  196286. {
  196287. dshift = s_start;
  196288. dp--;
  196289. }
  196290. else
  196291. dshift += s_inc;
  196292. }
  196293. if (sshift == s_end)
  196294. {
  196295. sshift = s_start;
  196296. sp--;
  196297. }
  196298. else
  196299. sshift += s_inc;
  196300. }
  196301. break;
  196302. }
  196303. default:
  196304. {
  196305. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196306. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196307. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196308. int jstop = png_pass_inc[pass];
  196309. png_uint_32 i;
  196310. for (i = 0; i < row_info->width; i++)
  196311. {
  196312. png_byte v[8];
  196313. int j;
  196314. png_memcpy(v, sp, pixel_bytes);
  196315. for (j = 0; j < jstop; j++)
  196316. {
  196317. png_memcpy(dp, v, pixel_bytes);
  196318. dp -= pixel_bytes;
  196319. }
  196320. sp -= pixel_bytes;
  196321. }
  196322. break;
  196323. }
  196324. }
  196325. row_info->width = final_width;
  196326. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196327. }
  196328. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196329. transformations = transformations; /* silence compiler warning */
  196330. #endif
  196331. }
  196332. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196333. void /* PRIVATE */
  196334. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196335. png_bytep prev_row, int filter)
  196336. {
  196337. png_debug(1, "in png_read_filter_row\n");
  196338. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196339. switch (filter)
  196340. {
  196341. case PNG_FILTER_VALUE_NONE:
  196342. break;
  196343. case PNG_FILTER_VALUE_SUB:
  196344. {
  196345. png_uint_32 i;
  196346. png_uint_32 istop = row_info->rowbytes;
  196347. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196348. png_bytep rp = row + bpp;
  196349. png_bytep lp = row;
  196350. for (i = bpp; i < istop; i++)
  196351. {
  196352. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196353. rp++;
  196354. }
  196355. break;
  196356. }
  196357. case PNG_FILTER_VALUE_UP:
  196358. {
  196359. png_uint_32 i;
  196360. png_uint_32 istop = row_info->rowbytes;
  196361. png_bytep rp = row;
  196362. png_bytep pp = prev_row;
  196363. for (i = 0; i < istop; i++)
  196364. {
  196365. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196366. rp++;
  196367. }
  196368. break;
  196369. }
  196370. case PNG_FILTER_VALUE_AVG:
  196371. {
  196372. png_uint_32 i;
  196373. png_bytep rp = row;
  196374. png_bytep pp = prev_row;
  196375. png_bytep lp = row;
  196376. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196377. png_uint_32 istop = row_info->rowbytes - bpp;
  196378. for (i = 0; i < bpp; i++)
  196379. {
  196380. *rp = (png_byte)(((int)(*rp) +
  196381. ((int)(*pp++) / 2 )) & 0xff);
  196382. rp++;
  196383. }
  196384. for (i = 0; i < istop; i++)
  196385. {
  196386. *rp = (png_byte)(((int)(*rp) +
  196387. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196388. rp++;
  196389. }
  196390. break;
  196391. }
  196392. case PNG_FILTER_VALUE_PAETH:
  196393. {
  196394. png_uint_32 i;
  196395. png_bytep rp = row;
  196396. png_bytep pp = prev_row;
  196397. png_bytep lp = row;
  196398. png_bytep cp = prev_row;
  196399. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196400. png_uint_32 istop=row_info->rowbytes - bpp;
  196401. for (i = 0; i < bpp; i++)
  196402. {
  196403. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196404. rp++;
  196405. }
  196406. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196407. {
  196408. int a, b, c, pa, pb, pc, p;
  196409. a = *lp++;
  196410. b = *pp++;
  196411. c = *cp++;
  196412. p = b - c;
  196413. pc = a - c;
  196414. #ifdef PNG_USE_ABS
  196415. pa = abs(p);
  196416. pb = abs(pc);
  196417. pc = abs(p + pc);
  196418. #else
  196419. pa = p < 0 ? -p : p;
  196420. pb = pc < 0 ? -pc : pc;
  196421. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196422. #endif
  196423. /*
  196424. if (pa <= pb && pa <= pc)
  196425. p = a;
  196426. else if (pb <= pc)
  196427. p = b;
  196428. else
  196429. p = c;
  196430. */
  196431. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196432. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196433. rp++;
  196434. }
  196435. break;
  196436. }
  196437. default:
  196438. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196439. *row=0;
  196440. break;
  196441. }
  196442. }
  196443. void /* PRIVATE */
  196444. png_read_finish_row(png_structp png_ptr)
  196445. {
  196446. #ifdef PNG_USE_LOCAL_ARRAYS
  196447. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196448. /* start of interlace block */
  196449. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196450. /* offset to next interlace block */
  196451. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196452. /* start of interlace block in the y direction */
  196453. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196454. /* offset to next interlace block in the y direction */
  196455. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196456. #endif
  196457. png_debug(1, "in png_read_finish_row\n");
  196458. png_ptr->row_number++;
  196459. if (png_ptr->row_number < png_ptr->num_rows)
  196460. return;
  196461. if (png_ptr->interlaced)
  196462. {
  196463. png_ptr->row_number = 0;
  196464. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196465. png_ptr->rowbytes + 1);
  196466. do
  196467. {
  196468. png_ptr->pass++;
  196469. if (png_ptr->pass >= 7)
  196470. break;
  196471. png_ptr->iwidth = (png_ptr->width +
  196472. png_pass_inc[png_ptr->pass] - 1 -
  196473. png_pass_start[png_ptr->pass]) /
  196474. png_pass_inc[png_ptr->pass];
  196475. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196476. png_ptr->iwidth) + 1;
  196477. if (!(png_ptr->transformations & PNG_INTERLACE))
  196478. {
  196479. png_ptr->num_rows = (png_ptr->height +
  196480. png_pass_yinc[png_ptr->pass] - 1 -
  196481. png_pass_ystart[png_ptr->pass]) /
  196482. png_pass_yinc[png_ptr->pass];
  196483. if (!(png_ptr->num_rows))
  196484. continue;
  196485. }
  196486. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196487. break;
  196488. } while (png_ptr->iwidth == 0);
  196489. if (png_ptr->pass < 7)
  196490. return;
  196491. }
  196492. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196493. {
  196494. #ifdef PNG_USE_LOCAL_ARRAYS
  196495. PNG_CONST PNG_IDAT;
  196496. #endif
  196497. char extra;
  196498. int ret;
  196499. png_ptr->zstream.next_out = (Bytef *)&extra;
  196500. png_ptr->zstream.avail_out = (uInt)1;
  196501. for(;;)
  196502. {
  196503. if (!(png_ptr->zstream.avail_in))
  196504. {
  196505. while (!png_ptr->idat_size)
  196506. {
  196507. png_byte chunk_length[4];
  196508. png_crc_finish(png_ptr, 0);
  196509. png_read_data(png_ptr, chunk_length, 4);
  196510. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196511. png_reset_crc(png_ptr);
  196512. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196513. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196514. png_error(png_ptr, "Not enough image data");
  196515. }
  196516. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196517. png_ptr->zstream.next_in = png_ptr->zbuf;
  196518. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196519. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196520. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196521. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196522. }
  196523. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196524. if (ret == Z_STREAM_END)
  196525. {
  196526. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196527. png_ptr->idat_size)
  196528. png_warning(png_ptr, "Extra compressed data");
  196529. png_ptr->mode |= PNG_AFTER_IDAT;
  196530. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196531. break;
  196532. }
  196533. if (ret != Z_OK)
  196534. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196535. "Decompression Error");
  196536. if (!(png_ptr->zstream.avail_out))
  196537. {
  196538. png_warning(png_ptr, "Extra compressed data.");
  196539. png_ptr->mode |= PNG_AFTER_IDAT;
  196540. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196541. break;
  196542. }
  196543. }
  196544. png_ptr->zstream.avail_out = 0;
  196545. }
  196546. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196547. png_warning(png_ptr, "Extra compression data");
  196548. inflateReset(&png_ptr->zstream);
  196549. png_ptr->mode |= PNG_AFTER_IDAT;
  196550. }
  196551. void /* PRIVATE */
  196552. png_read_start_row(png_structp png_ptr)
  196553. {
  196554. #ifdef PNG_USE_LOCAL_ARRAYS
  196555. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196556. /* start of interlace block */
  196557. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196558. /* offset to next interlace block */
  196559. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196560. /* start of interlace block in the y direction */
  196561. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196562. /* offset to next interlace block in the y direction */
  196563. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196564. #endif
  196565. int max_pixel_depth;
  196566. png_uint_32 row_bytes;
  196567. png_debug(1, "in png_read_start_row\n");
  196568. png_ptr->zstream.avail_in = 0;
  196569. png_init_read_transformations(png_ptr);
  196570. if (png_ptr->interlaced)
  196571. {
  196572. if (!(png_ptr->transformations & PNG_INTERLACE))
  196573. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196574. png_pass_ystart[0]) / png_pass_yinc[0];
  196575. else
  196576. png_ptr->num_rows = png_ptr->height;
  196577. png_ptr->iwidth = (png_ptr->width +
  196578. png_pass_inc[png_ptr->pass] - 1 -
  196579. png_pass_start[png_ptr->pass]) /
  196580. png_pass_inc[png_ptr->pass];
  196581. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196582. png_ptr->irowbytes = (png_size_t)row_bytes;
  196583. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196584. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196585. }
  196586. else
  196587. {
  196588. png_ptr->num_rows = png_ptr->height;
  196589. png_ptr->iwidth = png_ptr->width;
  196590. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196591. }
  196592. max_pixel_depth = png_ptr->pixel_depth;
  196593. #if defined(PNG_READ_PACK_SUPPORTED)
  196594. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196595. max_pixel_depth = 8;
  196596. #endif
  196597. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196598. if (png_ptr->transformations & PNG_EXPAND)
  196599. {
  196600. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196601. {
  196602. if (png_ptr->num_trans)
  196603. max_pixel_depth = 32;
  196604. else
  196605. max_pixel_depth = 24;
  196606. }
  196607. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196608. {
  196609. if (max_pixel_depth < 8)
  196610. max_pixel_depth = 8;
  196611. if (png_ptr->num_trans)
  196612. max_pixel_depth *= 2;
  196613. }
  196614. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196615. {
  196616. if (png_ptr->num_trans)
  196617. {
  196618. max_pixel_depth *= 4;
  196619. max_pixel_depth /= 3;
  196620. }
  196621. }
  196622. }
  196623. #endif
  196624. #if defined(PNG_READ_FILLER_SUPPORTED)
  196625. if (png_ptr->transformations & (PNG_FILLER))
  196626. {
  196627. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196628. max_pixel_depth = 32;
  196629. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196630. {
  196631. if (max_pixel_depth <= 8)
  196632. max_pixel_depth = 16;
  196633. else
  196634. max_pixel_depth = 32;
  196635. }
  196636. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196637. {
  196638. if (max_pixel_depth <= 32)
  196639. max_pixel_depth = 32;
  196640. else
  196641. max_pixel_depth = 64;
  196642. }
  196643. }
  196644. #endif
  196645. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196646. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196647. {
  196648. if (
  196649. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196650. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196651. #endif
  196652. #if defined(PNG_READ_FILLER_SUPPORTED)
  196653. (png_ptr->transformations & (PNG_FILLER)) ||
  196654. #endif
  196655. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196656. {
  196657. if (max_pixel_depth <= 16)
  196658. max_pixel_depth = 32;
  196659. else
  196660. max_pixel_depth = 64;
  196661. }
  196662. else
  196663. {
  196664. if (max_pixel_depth <= 8)
  196665. {
  196666. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196667. max_pixel_depth = 32;
  196668. else
  196669. max_pixel_depth = 24;
  196670. }
  196671. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196672. max_pixel_depth = 64;
  196673. else
  196674. max_pixel_depth = 48;
  196675. }
  196676. }
  196677. #endif
  196678. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196679. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196680. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196681. {
  196682. int user_pixel_depth=png_ptr->user_transform_depth*
  196683. png_ptr->user_transform_channels;
  196684. if(user_pixel_depth > max_pixel_depth)
  196685. max_pixel_depth=user_pixel_depth;
  196686. }
  196687. #endif
  196688. /* align the width on the next larger 8 pixels. Mainly used
  196689. for interlacing */
  196690. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196691. /* calculate the maximum bytes needed, adding a byte and a pixel
  196692. for safety's sake */
  196693. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196694. 1 + ((max_pixel_depth + 7) >> 3);
  196695. #ifdef PNG_MAX_MALLOC_64K
  196696. if (row_bytes > (png_uint_32)65536L)
  196697. png_error(png_ptr, "This image requires a row greater than 64KB");
  196698. #endif
  196699. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196700. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196701. #ifdef PNG_MAX_MALLOC_64K
  196702. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196703. png_error(png_ptr, "This image requires a row greater than 64KB");
  196704. #endif
  196705. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196706. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196707. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196708. png_ptr->rowbytes + 1));
  196709. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196710. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196711. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196712. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196713. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196714. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196715. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196716. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196717. }
  196718. #endif /* PNG_READ_SUPPORTED */
  196719. /*** End of inlined file: pngrutil.c ***/
  196720. /*** Start of inlined file: pngset.c ***/
  196721. /* pngset.c - storage of image information into info struct
  196722. *
  196723. * Last changed in libpng 1.2.21 [October 4, 2007]
  196724. * For conditions of distribution and use, see copyright notice in png.h
  196725. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196726. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196727. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196728. *
  196729. * The functions here are used during reads to store data from the file
  196730. * into the info struct, and during writes to store application data
  196731. * into the info struct for writing into the file. This abstracts the
  196732. * info struct and allows us to change the structure in the future.
  196733. */
  196734. #define PNG_INTERNAL
  196735. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196736. #if defined(PNG_bKGD_SUPPORTED)
  196737. void PNGAPI
  196738. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196739. {
  196740. png_debug1(1, "in %s storage function\n", "bKGD");
  196741. if (png_ptr == NULL || info_ptr == NULL)
  196742. return;
  196743. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196744. info_ptr->valid |= PNG_INFO_bKGD;
  196745. }
  196746. #endif
  196747. #if defined(PNG_cHRM_SUPPORTED)
  196748. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196749. void PNGAPI
  196750. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196751. double white_x, double white_y, double red_x, double red_y,
  196752. double green_x, double green_y, double blue_x, double blue_y)
  196753. {
  196754. png_debug1(1, "in %s storage function\n", "cHRM");
  196755. if (png_ptr == NULL || info_ptr == NULL)
  196756. return;
  196757. if (white_x < 0.0 || white_y < 0.0 ||
  196758. red_x < 0.0 || red_y < 0.0 ||
  196759. green_x < 0.0 || green_y < 0.0 ||
  196760. blue_x < 0.0 || blue_y < 0.0)
  196761. {
  196762. png_warning(png_ptr,
  196763. "Ignoring attempt to set negative chromaticity value");
  196764. return;
  196765. }
  196766. if (white_x > 21474.83 || white_y > 21474.83 ||
  196767. red_x > 21474.83 || red_y > 21474.83 ||
  196768. green_x > 21474.83 || green_y > 21474.83 ||
  196769. blue_x > 21474.83 || blue_y > 21474.83)
  196770. {
  196771. png_warning(png_ptr,
  196772. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196773. return;
  196774. }
  196775. info_ptr->x_white = (float)white_x;
  196776. info_ptr->y_white = (float)white_y;
  196777. info_ptr->x_red = (float)red_x;
  196778. info_ptr->y_red = (float)red_y;
  196779. info_ptr->x_green = (float)green_x;
  196780. info_ptr->y_green = (float)green_y;
  196781. info_ptr->x_blue = (float)blue_x;
  196782. info_ptr->y_blue = (float)blue_y;
  196783. #ifdef PNG_FIXED_POINT_SUPPORTED
  196784. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196785. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196786. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196787. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196788. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196789. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196790. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196791. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196792. #endif
  196793. info_ptr->valid |= PNG_INFO_cHRM;
  196794. }
  196795. #endif
  196796. #ifdef PNG_FIXED_POINT_SUPPORTED
  196797. void PNGAPI
  196798. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196799. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196800. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196801. png_fixed_point blue_x, png_fixed_point blue_y)
  196802. {
  196803. png_debug1(1, "in %s storage function\n", "cHRM");
  196804. if (png_ptr == NULL || info_ptr == NULL)
  196805. return;
  196806. if (white_x < 0 || white_y < 0 ||
  196807. red_x < 0 || red_y < 0 ||
  196808. green_x < 0 || green_y < 0 ||
  196809. blue_x < 0 || blue_y < 0)
  196810. {
  196811. png_warning(png_ptr,
  196812. "Ignoring attempt to set negative chromaticity value");
  196813. return;
  196814. }
  196815. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196816. if (white_x > (double) PNG_UINT_31_MAX ||
  196817. white_y > (double) PNG_UINT_31_MAX ||
  196818. red_x > (double) PNG_UINT_31_MAX ||
  196819. red_y > (double) PNG_UINT_31_MAX ||
  196820. green_x > (double) PNG_UINT_31_MAX ||
  196821. green_y > (double) PNG_UINT_31_MAX ||
  196822. blue_x > (double) PNG_UINT_31_MAX ||
  196823. blue_y > (double) PNG_UINT_31_MAX)
  196824. #else
  196825. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196826. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196827. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196828. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196829. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196830. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196831. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196832. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196833. #endif
  196834. {
  196835. png_warning(png_ptr,
  196836. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196837. return;
  196838. }
  196839. info_ptr->int_x_white = white_x;
  196840. info_ptr->int_y_white = white_y;
  196841. info_ptr->int_x_red = red_x;
  196842. info_ptr->int_y_red = red_y;
  196843. info_ptr->int_x_green = green_x;
  196844. info_ptr->int_y_green = green_y;
  196845. info_ptr->int_x_blue = blue_x;
  196846. info_ptr->int_y_blue = blue_y;
  196847. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196848. info_ptr->x_white = (float)(white_x/100000.);
  196849. info_ptr->y_white = (float)(white_y/100000.);
  196850. info_ptr->x_red = (float)( red_x/100000.);
  196851. info_ptr->y_red = (float)( red_y/100000.);
  196852. info_ptr->x_green = (float)(green_x/100000.);
  196853. info_ptr->y_green = (float)(green_y/100000.);
  196854. info_ptr->x_blue = (float)( blue_x/100000.);
  196855. info_ptr->y_blue = (float)( blue_y/100000.);
  196856. #endif
  196857. info_ptr->valid |= PNG_INFO_cHRM;
  196858. }
  196859. #endif
  196860. #endif
  196861. #if defined(PNG_gAMA_SUPPORTED)
  196862. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196863. void PNGAPI
  196864. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196865. {
  196866. double gamma;
  196867. png_debug1(1, "in %s storage function\n", "gAMA");
  196868. if (png_ptr == NULL || info_ptr == NULL)
  196869. return;
  196870. /* Check for overflow */
  196871. if (file_gamma > 21474.83)
  196872. {
  196873. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196874. gamma=21474.83;
  196875. }
  196876. else
  196877. gamma=file_gamma;
  196878. info_ptr->gamma = (float)gamma;
  196879. #ifdef PNG_FIXED_POINT_SUPPORTED
  196880. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196881. #endif
  196882. info_ptr->valid |= PNG_INFO_gAMA;
  196883. if(gamma == 0.0)
  196884. png_warning(png_ptr, "Setting gamma=0");
  196885. }
  196886. #endif
  196887. void PNGAPI
  196888. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196889. int_gamma)
  196890. {
  196891. png_fixed_point gamma;
  196892. png_debug1(1, "in %s storage function\n", "gAMA");
  196893. if (png_ptr == NULL || info_ptr == NULL)
  196894. return;
  196895. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196896. {
  196897. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196898. gamma=PNG_UINT_31_MAX;
  196899. }
  196900. else
  196901. {
  196902. if (int_gamma < 0)
  196903. {
  196904. png_warning(png_ptr, "Setting negative gamma to zero");
  196905. gamma=0;
  196906. }
  196907. else
  196908. gamma=int_gamma;
  196909. }
  196910. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196911. info_ptr->gamma = (float)(gamma/100000.);
  196912. #endif
  196913. #ifdef PNG_FIXED_POINT_SUPPORTED
  196914. info_ptr->int_gamma = gamma;
  196915. #endif
  196916. info_ptr->valid |= PNG_INFO_gAMA;
  196917. if(gamma == 0)
  196918. png_warning(png_ptr, "Setting gamma=0");
  196919. }
  196920. #endif
  196921. #if defined(PNG_hIST_SUPPORTED)
  196922. void PNGAPI
  196923. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196924. {
  196925. int i;
  196926. png_debug1(1, "in %s storage function\n", "hIST");
  196927. if (png_ptr == NULL || info_ptr == NULL)
  196928. return;
  196929. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196930. > PNG_MAX_PALETTE_LENGTH)
  196931. {
  196932. png_warning(png_ptr,
  196933. "Invalid palette size, hIST allocation skipped.");
  196934. return;
  196935. }
  196936. #ifdef PNG_FREE_ME_SUPPORTED
  196937. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196938. #endif
  196939. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196940. 1.2.1 */
  196941. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196942. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196943. if (png_ptr->hist == NULL)
  196944. {
  196945. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196946. return;
  196947. }
  196948. for (i = 0; i < info_ptr->num_palette; i++)
  196949. png_ptr->hist[i] = hist[i];
  196950. info_ptr->hist = png_ptr->hist;
  196951. info_ptr->valid |= PNG_INFO_hIST;
  196952. #ifdef PNG_FREE_ME_SUPPORTED
  196953. info_ptr->free_me |= PNG_FREE_HIST;
  196954. #else
  196955. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196956. #endif
  196957. }
  196958. #endif
  196959. void PNGAPI
  196960. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196961. png_uint_32 width, png_uint_32 height, int bit_depth,
  196962. int color_type, int interlace_type, int compression_type,
  196963. int filter_type)
  196964. {
  196965. png_debug1(1, "in %s storage function\n", "IHDR");
  196966. if (png_ptr == NULL || info_ptr == NULL)
  196967. return;
  196968. /* check for width and height valid values */
  196969. if (width == 0 || height == 0)
  196970. png_error(png_ptr, "Image width or height is zero in IHDR");
  196971. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196972. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196973. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196974. #else
  196975. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196976. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196977. #endif
  196978. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196979. png_error(png_ptr, "Invalid image size in IHDR");
  196980. if ( width > (PNG_UINT_32_MAX
  196981. >> 3) /* 8-byte RGBA pixels */
  196982. - 64 /* bigrowbuf hack */
  196983. - 1 /* filter byte */
  196984. - 7*8 /* rounding of width to multiple of 8 pixels */
  196985. - 8) /* extra max_pixel_depth pad */
  196986. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196987. /* check other values */
  196988. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196989. bit_depth != 8 && bit_depth != 16)
  196990. png_error(png_ptr, "Invalid bit depth in IHDR");
  196991. if (color_type < 0 || color_type == 1 ||
  196992. color_type == 5 || color_type > 6)
  196993. png_error(png_ptr, "Invalid color type in IHDR");
  196994. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196995. ((color_type == PNG_COLOR_TYPE_RGB ||
  196996. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196997. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196998. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196999. if (interlace_type >= PNG_INTERLACE_LAST)
  197000. png_error(png_ptr, "Unknown interlace method in IHDR");
  197001. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197002. png_error(png_ptr, "Unknown compression method in IHDR");
  197003. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197004. /* Accept filter_method 64 (intrapixel differencing) only if
  197005. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197006. * 2. Libpng did not read a PNG signature (this filter_method is only
  197007. * used in PNG datastreams that are embedded in MNG datastreams) and
  197008. * 3. The application called png_permit_mng_features with a mask that
  197009. * included PNG_FLAG_MNG_FILTER_64 and
  197010. * 4. The filter_method is 64 and
  197011. * 5. The color_type is RGB or RGBA
  197012. */
  197013. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197014. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197015. if(filter_type != PNG_FILTER_TYPE_BASE)
  197016. {
  197017. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197018. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197019. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197020. (color_type == PNG_COLOR_TYPE_RGB ||
  197021. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197022. png_error(png_ptr, "Unknown filter method in IHDR");
  197023. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197024. png_warning(png_ptr, "Invalid filter method in IHDR");
  197025. }
  197026. #else
  197027. if(filter_type != PNG_FILTER_TYPE_BASE)
  197028. png_error(png_ptr, "Unknown filter method in IHDR");
  197029. #endif
  197030. info_ptr->width = width;
  197031. info_ptr->height = height;
  197032. info_ptr->bit_depth = (png_byte)bit_depth;
  197033. info_ptr->color_type =(png_byte) color_type;
  197034. info_ptr->compression_type = (png_byte)compression_type;
  197035. info_ptr->filter_type = (png_byte)filter_type;
  197036. info_ptr->interlace_type = (png_byte)interlace_type;
  197037. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197038. info_ptr->channels = 1;
  197039. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197040. info_ptr->channels = 3;
  197041. else
  197042. info_ptr->channels = 1;
  197043. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197044. info_ptr->channels++;
  197045. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197046. /* check for potential overflow */
  197047. if (width > (PNG_UINT_32_MAX
  197048. >> 3) /* 8-byte RGBA pixels */
  197049. - 64 /* bigrowbuf hack */
  197050. - 1 /* filter byte */
  197051. - 7*8 /* rounding of width to multiple of 8 pixels */
  197052. - 8) /* extra max_pixel_depth pad */
  197053. info_ptr->rowbytes = (png_size_t)0;
  197054. else
  197055. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197056. }
  197057. #if defined(PNG_oFFs_SUPPORTED)
  197058. void PNGAPI
  197059. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197060. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197061. {
  197062. png_debug1(1, "in %s storage function\n", "oFFs");
  197063. if (png_ptr == NULL || info_ptr == NULL)
  197064. return;
  197065. info_ptr->x_offset = offset_x;
  197066. info_ptr->y_offset = offset_y;
  197067. info_ptr->offset_unit_type = (png_byte)unit_type;
  197068. info_ptr->valid |= PNG_INFO_oFFs;
  197069. }
  197070. #endif
  197071. #if defined(PNG_pCAL_SUPPORTED)
  197072. void PNGAPI
  197073. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197074. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197075. png_charp units, png_charpp params)
  197076. {
  197077. png_uint_32 length;
  197078. int i;
  197079. png_debug1(1, "in %s storage function\n", "pCAL");
  197080. if (png_ptr == NULL || info_ptr == NULL)
  197081. return;
  197082. length = png_strlen(purpose) + 1;
  197083. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197084. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197085. if (info_ptr->pcal_purpose == NULL)
  197086. {
  197087. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197088. return;
  197089. }
  197090. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197091. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197092. info_ptr->pcal_X0 = X0;
  197093. info_ptr->pcal_X1 = X1;
  197094. info_ptr->pcal_type = (png_byte)type;
  197095. info_ptr->pcal_nparams = (png_byte)nparams;
  197096. length = png_strlen(units) + 1;
  197097. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197098. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197099. if (info_ptr->pcal_units == NULL)
  197100. {
  197101. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197102. return;
  197103. }
  197104. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197105. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197106. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197107. if (info_ptr->pcal_params == NULL)
  197108. {
  197109. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197110. return;
  197111. }
  197112. info_ptr->pcal_params[nparams] = NULL;
  197113. for (i = 0; i < nparams; i++)
  197114. {
  197115. length = png_strlen(params[i]) + 1;
  197116. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197117. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197118. if (info_ptr->pcal_params[i] == NULL)
  197119. {
  197120. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197121. return;
  197122. }
  197123. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197124. }
  197125. info_ptr->valid |= PNG_INFO_pCAL;
  197126. #ifdef PNG_FREE_ME_SUPPORTED
  197127. info_ptr->free_me |= PNG_FREE_PCAL;
  197128. #endif
  197129. }
  197130. #endif
  197131. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197132. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197133. void PNGAPI
  197134. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197135. int unit, double width, double height)
  197136. {
  197137. png_debug1(1, "in %s storage function\n", "sCAL");
  197138. if (png_ptr == NULL || info_ptr == NULL)
  197139. return;
  197140. info_ptr->scal_unit = (png_byte)unit;
  197141. info_ptr->scal_pixel_width = width;
  197142. info_ptr->scal_pixel_height = height;
  197143. info_ptr->valid |= PNG_INFO_sCAL;
  197144. }
  197145. #else
  197146. #ifdef PNG_FIXED_POINT_SUPPORTED
  197147. void PNGAPI
  197148. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197149. int unit, png_charp swidth, png_charp sheight)
  197150. {
  197151. png_uint_32 length;
  197152. png_debug1(1, "in %s storage function\n", "sCAL");
  197153. if (png_ptr == NULL || info_ptr == NULL)
  197154. return;
  197155. info_ptr->scal_unit = (png_byte)unit;
  197156. length = png_strlen(swidth) + 1;
  197157. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197158. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197159. if (info_ptr->scal_s_width == NULL)
  197160. {
  197161. png_warning(png_ptr,
  197162. "Memory allocation failed while processing sCAL.");
  197163. }
  197164. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197165. length = png_strlen(sheight) + 1;
  197166. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197167. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197168. if (info_ptr->scal_s_height == NULL)
  197169. {
  197170. png_free (png_ptr, info_ptr->scal_s_width);
  197171. png_warning(png_ptr,
  197172. "Memory allocation failed while processing sCAL.");
  197173. }
  197174. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197175. info_ptr->valid |= PNG_INFO_sCAL;
  197176. #ifdef PNG_FREE_ME_SUPPORTED
  197177. info_ptr->free_me |= PNG_FREE_SCAL;
  197178. #endif
  197179. }
  197180. #endif
  197181. #endif
  197182. #endif
  197183. #if defined(PNG_pHYs_SUPPORTED)
  197184. void PNGAPI
  197185. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197186. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197187. {
  197188. png_debug1(1, "in %s storage function\n", "pHYs");
  197189. if (png_ptr == NULL || info_ptr == NULL)
  197190. return;
  197191. info_ptr->x_pixels_per_unit = res_x;
  197192. info_ptr->y_pixels_per_unit = res_y;
  197193. info_ptr->phys_unit_type = (png_byte)unit_type;
  197194. info_ptr->valid |= PNG_INFO_pHYs;
  197195. }
  197196. #endif
  197197. void PNGAPI
  197198. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197199. png_colorp palette, int num_palette)
  197200. {
  197201. png_debug1(1, "in %s storage function\n", "PLTE");
  197202. if (png_ptr == NULL || info_ptr == NULL)
  197203. return;
  197204. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197205. {
  197206. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197207. png_error(png_ptr, "Invalid palette length");
  197208. else
  197209. {
  197210. png_warning(png_ptr, "Invalid palette length");
  197211. return;
  197212. }
  197213. }
  197214. /*
  197215. * It may not actually be necessary to set png_ptr->palette here;
  197216. * we do it for backward compatibility with the way the png_handle_tRNS
  197217. * function used to do the allocation.
  197218. */
  197219. #ifdef PNG_FREE_ME_SUPPORTED
  197220. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197221. #endif
  197222. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197223. of num_palette entries,
  197224. in case of an invalid PNG file that has too-large sample values. */
  197225. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197226. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197227. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197228. png_sizeof(png_color));
  197229. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197230. info_ptr->palette = png_ptr->palette;
  197231. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197232. #ifdef PNG_FREE_ME_SUPPORTED
  197233. info_ptr->free_me |= PNG_FREE_PLTE;
  197234. #else
  197235. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197236. #endif
  197237. info_ptr->valid |= PNG_INFO_PLTE;
  197238. }
  197239. #if defined(PNG_sBIT_SUPPORTED)
  197240. void PNGAPI
  197241. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197242. png_color_8p sig_bit)
  197243. {
  197244. png_debug1(1, "in %s storage function\n", "sBIT");
  197245. if (png_ptr == NULL || info_ptr == NULL)
  197246. return;
  197247. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197248. info_ptr->valid |= PNG_INFO_sBIT;
  197249. }
  197250. #endif
  197251. #if defined(PNG_sRGB_SUPPORTED)
  197252. void PNGAPI
  197253. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197254. {
  197255. png_debug1(1, "in %s storage function\n", "sRGB");
  197256. if (png_ptr == NULL || info_ptr == NULL)
  197257. return;
  197258. info_ptr->srgb_intent = (png_byte)intent;
  197259. info_ptr->valid |= PNG_INFO_sRGB;
  197260. }
  197261. void PNGAPI
  197262. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197263. int intent)
  197264. {
  197265. #if defined(PNG_gAMA_SUPPORTED)
  197266. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197267. float file_gamma;
  197268. #endif
  197269. #ifdef PNG_FIXED_POINT_SUPPORTED
  197270. png_fixed_point int_file_gamma;
  197271. #endif
  197272. #endif
  197273. #if defined(PNG_cHRM_SUPPORTED)
  197274. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197275. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197276. #endif
  197277. #ifdef PNG_FIXED_POINT_SUPPORTED
  197278. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197279. int_green_y, int_blue_x, int_blue_y;
  197280. #endif
  197281. #endif
  197282. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197283. if (png_ptr == NULL || info_ptr == NULL)
  197284. return;
  197285. png_set_sRGB(png_ptr, info_ptr, intent);
  197286. #if defined(PNG_gAMA_SUPPORTED)
  197287. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197288. file_gamma = (float).45455;
  197289. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197290. #endif
  197291. #ifdef PNG_FIXED_POINT_SUPPORTED
  197292. int_file_gamma = 45455L;
  197293. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197294. #endif
  197295. #endif
  197296. #if defined(PNG_cHRM_SUPPORTED)
  197297. #ifdef PNG_FIXED_POINT_SUPPORTED
  197298. int_white_x = 31270L;
  197299. int_white_y = 32900L;
  197300. int_red_x = 64000L;
  197301. int_red_y = 33000L;
  197302. int_green_x = 30000L;
  197303. int_green_y = 60000L;
  197304. int_blue_x = 15000L;
  197305. int_blue_y = 6000L;
  197306. png_set_cHRM_fixed(png_ptr, info_ptr,
  197307. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197308. int_blue_x, int_blue_y);
  197309. #endif
  197310. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197311. white_x = (float).3127;
  197312. white_y = (float).3290;
  197313. red_x = (float).64;
  197314. red_y = (float).33;
  197315. green_x = (float).30;
  197316. green_y = (float).60;
  197317. blue_x = (float).15;
  197318. blue_y = (float).06;
  197319. png_set_cHRM(png_ptr, info_ptr,
  197320. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197321. #endif
  197322. #endif
  197323. }
  197324. #endif
  197325. #if defined(PNG_iCCP_SUPPORTED)
  197326. void PNGAPI
  197327. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197328. png_charp name, int compression_type,
  197329. png_charp profile, png_uint_32 proflen)
  197330. {
  197331. png_charp new_iccp_name;
  197332. png_charp new_iccp_profile;
  197333. png_debug1(1, "in %s storage function\n", "iCCP");
  197334. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197335. return;
  197336. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197337. if (new_iccp_name == NULL)
  197338. {
  197339. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197340. return;
  197341. }
  197342. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197343. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197344. if (new_iccp_profile == NULL)
  197345. {
  197346. png_free (png_ptr, new_iccp_name);
  197347. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197348. return;
  197349. }
  197350. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197351. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197352. info_ptr->iccp_proflen = proflen;
  197353. info_ptr->iccp_name = new_iccp_name;
  197354. info_ptr->iccp_profile = new_iccp_profile;
  197355. /* Compression is always zero but is here so the API and info structure
  197356. * does not have to change if we introduce multiple compression types */
  197357. info_ptr->iccp_compression = (png_byte)compression_type;
  197358. #ifdef PNG_FREE_ME_SUPPORTED
  197359. info_ptr->free_me |= PNG_FREE_ICCP;
  197360. #endif
  197361. info_ptr->valid |= PNG_INFO_iCCP;
  197362. }
  197363. #endif
  197364. #if defined(PNG_TEXT_SUPPORTED)
  197365. void PNGAPI
  197366. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197367. int num_text)
  197368. {
  197369. int ret;
  197370. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197371. if (ret)
  197372. png_error(png_ptr, "Insufficient memory to store text");
  197373. }
  197374. int /* PRIVATE */
  197375. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197376. int num_text)
  197377. {
  197378. int i;
  197379. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197380. "text" : (png_const_charp)png_ptr->chunk_name));
  197381. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197382. return(0);
  197383. /* Make sure we have enough space in the "text" array in info_struct
  197384. * to hold all of the incoming text_ptr objects.
  197385. */
  197386. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197387. {
  197388. if (info_ptr->text != NULL)
  197389. {
  197390. png_textp old_text;
  197391. int old_max;
  197392. old_max = info_ptr->max_text;
  197393. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197394. old_text = info_ptr->text;
  197395. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197396. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197397. if (info_ptr->text == NULL)
  197398. {
  197399. png_free(png_ptr, old_text);
  197400. return(1);
  197401. }
  197402. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197403. png_sizeof(png_text)));
  197404. png_free(png_ptr, old_text);
  197405. }
  197406. else
  197407. {
  197408. info_ptr->max_text = num_text + 8;
  197409. info_ptr->num_text = 0;
  197410. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197411. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197412. if (info_ptr->text == NULL)
  197413. return(1);
  197414. #ifdef PNG_FREE_ME_SUPPORTED
  197415. info_ptr->free_me |= PNG_FREE_TEXT;
  197416. #endif
  197417. }
  197418. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197419. info_ptr->max_text);
  197420. }
  197421. for (i = 0; i < num_text; i++)
  197422. {
  197423. png_size_t text_length,key_len;
  197424. png_size_t lang_len,lang_key_len;
  197425. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197426. if (text_ptr[i].key == NULL)
  197427. continue;
  197428. key_len = png_strlen(text_ptr[i].key);
  197429. if(text_ptr[i].compression <= 0)
  197430. {
  197431. lang_len = 0;
  197432. lang_key_len = 0;
  197433. }
  197434. else
  197435. #ifdef PNG_iTXt_SUPPORTED
  197436. {
  197437. /* set iTXt data */
  197438. if (text_ptr[i].lang != NULL)
  197439. lang_len = png_strlen(text_ptr[i].lang);
  197440. else
  197441. lang_len = 0;
  197442. if (text_ptr[i].lang_key != NULL)
  197443. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197444. else
  197445. lang_key_len = 0;
  197446. }
  197447. #else
  197448. {
  197449. png_warning(png_ptr, "iTXt chunk not supported.");
  197450. continue;
  197451. }
  197452. #endif
  197453. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197454. {
  197455. text_length = 0;
  197456. #ifdef PNG_iTXt_SUPPORTED
  197457. if(text_ptr[i].compression > 0)
  197458. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197459. else
  197460. #endif
  197461. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197462. }
  197463. else
  197464. {
  197465. text_length = png_strlen(text_ptr[i].text);
  197466. textp->compression = text_ptr[i].compression;
  197467. }
  197468. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197469. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197470. if (textp->key == NULL)
  197471. return(1);
  197472. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197473. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197474. (int)textp->key);
  197475. png_memcpy(textp->key, text_ptr[i].key,
  197476. (png_size_t)(key_len));
  197477. *(textp->key+key_len) = '\0';
  197478. #ifdef PNG_iTXt_SUPPORTED
  197479. if (text_ptr[i].compression > 0)
  197480. {
  197481. textp->lang=textp->key + key_len + 1;
  197482. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197483. *(textp->lang+lang_len) = '\0';
  197484. textp->lang_key=textp->lang + lang_len + 1;
  197485. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197486. *(textp->lang_key+lang_key_len) = '\0';
  197487. textp->text=textp->lang_key + lang_key_len + 1;
  197488. }
  197489. else
  197490. #endif
  197491. {
  197492. #ifdef PNG_iTXt_SUPPORTED
  197493. textp->lang=NULL;
  197494. textp->lang_key=NULL;
  197495. #endif
  197496. textp->text=textp->key + key_len + 1;
  197497. }
  197498. if(text_length)
  197499. png_memcpy(textp->text, text_ptr[i].text,
  197500. (png_size_t)(text_length));
  197501. *(textp->text+text_length) = '\0';
  197502. #ifdef PNG_iTXt_SUPPORTED
  197503. if(textp->compression > 0)
  197504. {
  197505. textp->text_length = 0;
  197506. textp->itxt_length = text_length;
  197507. }
  197508. else
  197509. #endif
  197510. {
  197511. textp->text_length = text_length;
  197512. #ifdef PNG_iTXt_SUPPORTED
  197513. textp->itxt_length = 0;
  197514. #endif
  197515. }
  197516. info_ptr->num_text++;
  197517. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197518. }
  197519. return(0);
  197520. }
  197521. #endif
  197522. #if defined(PNG_tIME_SUPPORTED)
  197523. void PNGAPI
  197524. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197525. {
  197526. png_debug1(1, "in %s storage function\n", "tIME");
  197527. if (png_ptr == NULL || info_ptr == NULL ||
  197528. (png_ptr->mode & PNG_WROTE_tIME))
  197529. return;
  197530. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197531. info_ptr->valid |= PNG_INFO_tIME;
  197532. }
  197533. #endif
  197534. #if defined(PNG_tRNS_SUPPORTED)
  197535. void PNGAPI
  197536. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197537. png_bytep trans, int num_trans, png_color_16p trans_values)
  197538. {
  197539. png_debug1(1, "in %s storage function\n", "tRNS");
  197540. if (png_ptr == NULL || info_ptr == NULL)
  197541. return;
  197542. if (trans != NULL)
  197543. {
  197544. /*
  197545. * It may not actually be necessary to set png_ptr->trans here;
  197546. * we do it for backward compatibility with the way the png_handle_tRNS
  197547. * function used to do the allocation.
  197548. */
  197549. #ifdef PNG_FREE_ME_SUPPORTED
  197550. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197551. #endif
  197552. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197553. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197554. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197555. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197556. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197557. #ifdef PNG_FREE_ME_SUPPORTED
  197558. info_ptr->free_me |= PNG_FREE_TRNS;
  197559. #else
  197560. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197561. #endif
  197562. }
  197563. if (trans_values != NULL)
  197564. {
  197565. png_memcpy(&(info_ptr->trans_values), trans_values,
  197566. png_sizeof(png_color_16));
  197567. if (num_trans == 0)
  197568. num_trans = 1;
  197569. }
  197570. info_ptr->num_trans = (png_uint_16)num_trans;
  197571. info_ptr->valid |= PNG_INFO_tRNS;
  197572. }
  197573. #endif
  197574. #if defined(PNG_sPLT_SUPPORTED)
  197575. void PNGAPI
  197576. png_set_sPLT(png_structp png_ptr,
  197577. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197578. {
  197579. png_sPLT_tp np;
  197580. int i;
  197581. if (png_ptr == NULL || info_ptr == NULL)
  197582. return;
  197583. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197584. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197585. if (np == NULL)
  197586. {
  197587. png_warning(png_ptr, "No memory for sPLT palettes.");
  197588. return;
  197589. }
  197590. png_memcpy(np, info_ptr->splt_palettes,
  197591. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197592. png_free(png_ptr, info_ptr->splt_palettes);
  197593. info_ptr->splt_palettes=NULL;
  197594. for (i = 0; i < nentries; i++)
  197595. {
  197596. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197597. png_sPLT_tp from = entries + i;
  197598. to->name = (png_charp)png_malloc_warn(png_ptr,
  197599. png_strlen(from->name) + 1);
  197600. if (to->name == NULL)
  197601. {
  197602. png_warning(png_ptr,
  197603. "Out of memory while processing sPLT chunk");
  197604. }
  197605. /* TODO: use png_malloc_warn */
  197606. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197607. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197608. from->nentries * png_sizeof(png_sPLT_entry));
  197609. /* TODO: use png_malloc_warn */
  197610. png_memcpy(to->entries, from->entries,
  197611. from->nentries * png_sizeof(png_sPLT_entry));
  197612. if (to->entries == NULL)
  197613. {
  197614. png_warning(png_ptr,
  197615. "Out of memory while processing sPLT chunk");
  197616. png_free(png_ptr,to->name);
  197617. to->name = NULL;
  197618. }
  197619. to->nentries = from->nentries;
  197620. to->depth = from->depth;
  197621. }
  197622. info_ptr->splt_palettes = np;
  197623. info_ptr->splt_palettes_num += nentries;
  197624. info_ptr->valid |= PNG_INFO_sPLT;
  197625. #ifdef PNG_FREE_ME_SUPPORTED
  197626. info_ptr->free_me |= PNG_FREE_SPLT;
  197627. #endif
  197628. }
  197629. #endif /* PNG_sPLT_SUPPORTED */
  197630. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197631. void PNGAPI
  197632. png_set_unknown_chunks(png_structp png_ptr,
  197633. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197634. {
  197635. png_unknown_chunkp np;
  197636. int i;
  197637. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197638. return;
  197639. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197640. (info_ptr->unknown_chunks_num + num_unknowns) *
  197641. png_sizeof(png_unknown_chunk));
  197642. if (np == NULL)
  197643. {
  197644. png_warning(png_ptr,
  197645. "Out of memory while processing unknown chunk.");
  197646. return;
  197647. }
  197648. png_memcpy(np, info_ptr->unknown_chunks,
  197649. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197650. png_free(png_ptr, info_ptr->unknown_chunks);
  197651. info_ptr->unknown_chunks=NULL;
  197652. for (i = 0; i < num_unknowns; i++)
  197653. {
  197654. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197655. png_unknown_chunkp from = unknowns + i;
  197656. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197657. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197658. if (to->data == NULL)
  197659. {
  197660. png_warning(png_ptr,
  197661. "Out of memory while processing unknown chunk.");
  197662. }
  197663. else
  197664. {
  197665. png_memcpy(to->data, from->data, from->size);
  197666. to->size = from->size;
  197667. /* note our location in the read or write sequence */
  197668. to->location = (png_byte)(png_ptr->mode & 0xff);
  197669. }
  197670. }
  197671. info_ptr->unknown_chunks = np;
  197672. info_ptr->unknown_chunks_num += num_unknowns;
  197673. #ifdef PNG_FREE_ME_SUPPORTED
  197674. info_ptr->free_me |= PNG_FREE_UNKN;
  197675. #endif
  197676. }
  197677. void PNGAPI
  197678. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197679. int chunk, int location)
  197680. {
  197681. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197682. (int)info_ptr->unknown_chunks_num)
  197683. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197684. }
  197685. #endif
  197686. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197687. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197688. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197689. void PNGAPI
  197690. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197691. {
  197692. /* This function is deprecated in favor of png_permit_mng_features()
  197693. and will be removed from libpng-1.3.0 */
  197694. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197695. if (png_ptr == NULL)
  197696. return;
  197697. png_ptr->mng_features_permitted = (png_byte)
  197698. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197699. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197700. }
  197701. #endif
  197702. #endif
  197703. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197704. png_uint_32 PNGAPI
  197705. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197706. {
  197707. png_debug(1, "in png_permit_mng_features\n");
  197708. if (png_ptr == NULL)
  197709. return (png_uint_32)0;
  197710. png_ptr->mng_features_permitted =
  197711. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197712. return (png_uint_32)png_ptr->mng_features_permitted;
  197713. }
  197714. #endif
  197715. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197716. void PNGAPI
  197717. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197718. chunk_list, int num_chunks)
  197719. {
  197720. png_bytep new_list, p;
  197721. int i, old_num_chunks;
  197722. if (png_ptr == NULL)
  197723. return;
  197724. if (num_chunks == 0)
  197725. {
  197726. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197727. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197728. else
  197729. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197730. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197731. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197732. else
  197733. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197734. return;
  197735. }
  197736. if (chunk_list == NULL)
  197737. return;
  197738. old_num_chunks=png_ptr->num_chunk_list;
  197739. new_list=(png_bytep)png_malloc(png_ptr,
  197740. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197741. if(png_ptr->chunk_list != NULL)
  197742. {
  197743. png_memcpy(new_list, png_ptr->chunk_list,
  197744. (png_size_t)(5*old_num_chunks));
  197745. png_free(png_ptr, png_ptr->chunk_list);
  197746. png_ptr->chunk_list=NULL;
  197747. }
  197748. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197749. (png_size_t)(5*num_chunks));
  197750. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197751. *p=(png_byte)keep;
  197752. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197753. png_ptr->chunk_list=new_list;
  197754. #ifdef PNG_FREE_ME_SUPPORTED
  197755. png_ptr->free_me |= PNG_FREE_LIST;
  197756. #endif
  197757. }
  197758. #endif
  197759. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197760. void PNGAPI
  197761. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197762. png_user_chunk_ptr read_user_chunk_fn)
  197763. {
  197764. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197765. if (png_ptr == NULL)
  197766. return;
  197767. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197768. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197769. }
  197770. #endif
  197771. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197772. void PNGAPI
  197773. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197774. {
  197775. png_debug1(1, "in %s storage function\n", "rows");
  197776. if (png_ptr == NULL || info_ptr == NULL)
  197777. return;
  197778. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197779. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197780. info_ptr->row_pointers = row_pointers;
  197781. if(row_pointers)
  197782. info_ptr->valid |= PNG_INFO_IDAT;
  197783. }
  197784. #endif
  197785. #ifdef PNG_WRITE_SUPPORTED
  197786. void PNGAPI
  197787. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197788. {
  197789. if (png_ptr == NULL)
  197790. return;
  197791. if(png_ptr->zbuf)
  197792. png_free(png_ptr, png_ptr->zbuf);
  197793. png_ptr->zbuf_size = (png_size_t)size;
  197794. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197795. png_ptr->zstream.next_out = png_ptr->zbuf;
  197796. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197797. }
  197798. #endif
  197799. void PNGAPI
  197800. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197801. {
  197802. if (png_ptr && info_ptr)
  197803. info_ptr->valid &= ~(mask);
  197804. }
  197805. #ifndef PNG_1_0_X
  197806. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197807. /* function was added to libpng 1.2.0 and should always exist by default */
  197808. void PNGAPI
  197809. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197810. {
  197811. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197812. if (png_ptr != NULL)
  197813. png_ptr->asm_flags = 0;
  197814. }
  197815. /* this function was added to libpng 1.2.0 */
  197816. void PNGAPI
  197817. png_set_mmx_thresholds (png_structp png_ptr,
  197818. png_byte,
  197819. png_uint_32)
  197820. {
  197821. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197822. if (png_ptr == NULL)
  197823. return;
  197824. }
  197825. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197826. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197827. /* this function was added to libpng 1.2.6 */
  197828. void PNGAPI
  197829. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197830. png_uint_32 user_height_max)
  197831. {
  197832. /* Images with dimensions larger than these limits will be
  197833. * rejected by png_set_IHDR(). To accept any PNG datastream
  197834. * regardless of dimensions, set both limits to 0x7ffffffL.
  197835. */
  197836. if(png_ptr == NULL) return;
  197837. png_ptr->user_width_max = user_width_max;
  197838. png_ptr->user_height_max = user_height_max;
  197839. }
  197840. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197841. #endif /* ?PNG_1_0_X */
  197842. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197843. /*** End of inlined file: pngset.c ***/
  197844. /*** Start of inlined file: pngtrans.c ***/
  197845. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197846. *
  197847. * Last changed in libpng 1.2.17 May 15, 2007
  197848. * For conditions of distribution and use, see copyright notice in png.h
  197849. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197850. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197851. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197852. */
  197853. #define PNG_INTERNAL
  197854. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197855. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197856. /* turn on BGR-to-RGB mapping */
  197857. void PNGAPI
  197858. png_set_bgr(png_structp png_ptr)
  197859. {
  197860. png_debug(1, "in png_set_bgr\n");
  197861. if(png_ptr == NULL) return;
  197862. png_ptr->transformations |= PNG_BGR;
  197863. }
  197864. #endif
  197865. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197866. /* turn on 16 bit byte swapping */
  197867. void PNGAPI
  197868. png_set_swap(png_structp png_ptr)
  197869. {
  197870. png_debug(1, "in png_set_swap\n");
  197871. if(png_ptr == NULL) return;
  197872. if (png_ptr->bit_depth == 16)
  197873. png_ptr->transformations |= PNG_SWAP_BYTES;
  197874. }
  197875. #endif
  197876. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197877. /* turn on pixel packing */
  197878. void PNGAPI
  197879. png_set_packing(png_structp png_ptr)
  197880. {
  197881. png_debug(1, "in png_set_packing\n");
  197882. if(png_ptr == NULL) return;
  197883. if (png_ptr->bit_depth < 8)
  197884. {
  197885. png_ptr->transformations |= PNG_PACK;
  197886. png_ptr->usr_bit_depth = 8;
  197887. }
  197888. }
  197889. #endif
  197890. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197891. /* turn on packed pixel swapping */
  197892. void PNGAPI
  197893. png_set_packswap(png_structp png_ptr)
  197894. {
  197895. png_debug(1, "in png_set_packswap\n");
  197896. if(png_ptr == NULL) return;
  197897. if (png_ptr->bit_depth < 8)
  197898. png_ptr->transformations |= PNG_PACKSWAP;
  197899. }
  197900. #endif
  197901. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197902. void PNGAPI
  197903. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197904. {
  197905. png_debug(1, "in png_set_shift\n");
  197906. if(png_ptr == NULL) return;
  197907. png_ptr->transformations |= PNG_SHIFT;
  197908. png_ptr->shift = *true_bits;
  197909. }
  197910. #endif
  197911. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197912. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197913. int PNGAPI
  197914. png_set_interlace_handling(png_structp png_ptr)
  197915. {
  197916. png_debug(1, "in png_set_interlace handling\n");
  197917. if (png_ptr && png_ptr->interlaced)
  197918. {
  197919. png_ptr->transformations |= PNG_INTERLACE;
  197920. return (7);
  197921. }
  197922. return (1);
  197923. }
  197924. #endif
  197925. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197926. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197927. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197928. * for 48-bit input data, as well as to avoid problems with some compilers
  197929. * that don't like bytes as parameters.
  197930. */
  197931. void PNGAPI
  197932. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197933. {
  197934. png_debug(1, "in png_set_filler\n");
  197935. if(png_ptr == NULL) return;
  197936. png_ptr->transformations |= PNG_FILLER;
  197937. png_ptr->filler = (png_byte)filler;
  197938. if (filler_loc == PNG_FILLER_AFTER)
  197939. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197940. else
  197941. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197942. /* This should probably go in the "do_read_filler" routine.
  197943. * I attempted to do that in libpng-1.0.1a but that caused problems
  197944. * so I restored it in libpng-1.0.2a
  197945. */
  197946. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197947. {
  197948. png_ptr->usr_channels = 4;
  197949. }
  197950. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197951. * a less-than-8-bit grayscale to GA? */
  197952. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197953. {
  197954. png_ptr->usr_channels = 2;
  197955. }
  197956. }
  197957. #if !defined(PNG_1_0_X)
  197958. /* Added to libpng-1.2.7 */
  197959. void PNGAPI
  197960. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197961. {
  197962. png_debug(1, "in png_set_add_alpha\n");
  197963. if(png_ptr == NULL) return;
  197964. png_set_filler(png_ptr, filler, filler_loc);
  197965. png_ptr->transformations |= PNG_ADD_ALPHA;
  197966. }
  197967. #endif
  197968. #endif
  197969. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197970. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197971. void PNGAPI
  197972. png_set_swap_alpha(png_structp png_ptr)
  197973. {
  197974. png_debug(1, "in png_set_swap_alpha\n");
  197975. if(png_ptr == NULL) return;
  197976. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197977. }
  197978. #endif
  197979. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197980. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197981. void PNGAPI
  197982. png_set_invert_alpha(png_structp png_ptr)
  197983. {
  197984. png_debug(1, "in png_set_invert_alpha\n");
  197985. if(png_ptr == NULL) return;
  197986. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197987. }
  197988. #endif
  197989. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197990. void PNGAPI
  197991. png_set_invert_mono(png_structp png_ptr)
  197992. {
  197993. png_debug(1, "in png_set_invert_mono\n");
  197994. if(png_ptr == NULL) return;
  197995. png_ptr->transformations |= PNG_INVERT_MONO;
  197996. }
  197997. /* invert monochrome grayscale data */
  197998. void /* PRIVATE */
  197999. png_do_invert(png_row_infop row_info, png_bytep row)
  198000. {
  198001. png_debug(1, "in png_do_invert\n");
  198002. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198003. * if (row_info->bit_depth == 1 &&
  198004. */
  198005. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198006. if (row == NULL || row_info == NULL)
  198007. return;
  198008. #endif
  198009. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198010. {
  198011. png_bytep rp = row;
  198012. png_uint_32 i;
  198013. png_uint_32 istop = row_info->rowbytes;
  198014. for (i = 0; i < istop; i++)
  198015. {
  198016. *rp = (png_byte)(~(*rp));
  198017. rp++;
  198018. }
  198019. }
  198020. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198021. row_info->bit_depth == 8)
  198022. {
  198023. png_bytep rp = row;
  198024. png_uint_32 i;
  198025. png_uint_32 istop = row_info->rowbytes;
  198026. for (i = 0; i < istop; i+=2)
  198027. {
  198028. *rp = (png_byte)(~(*rp));
  198029. rp+=2;
  198030. }
  198031. }
  198032. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198033. row_info->bit_depth == 16)
  198034. {
  198035. png_bytep rp = row;
  198036. png_uint_32 i;
  198037. png_uint_32 istop = row_info->rowbytes;
  198038. for (i = 0; i < istop; i+=4)
  198039. {
  198040. *rp = (png_byte)(~(*rp));
  198041. *(rp+1) = (png_byte)(~(*(rp+1)));
  198042. rp+=4;
  198043. }
  198044. }
  198045. }
  198046. #endif
  198047. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198048. /* swaps byte order on 16 bit depth images */
  198049. void /* PRIVATE */
  198050. png_do_swap(png_row_infop row_info, png_bytep row)
  198051. {
  198052. png_debug(1, "in png_do_swap\n");
  198053. if (
  198054. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198055. row != NULL && row_info != NULL &&
  198056. #endif
  198057. row_info->bit_depth == 16)
  198058. {
  198059. png_bytep rp = row;
  198060. png_uint_32 i;
  198061. png_uint_32 istop= row_info->width * row_info->channels;
  198062. for (i = 0; i < istop; i++, rp += 2)
  198063. {
  198064. png_byte t = *rp;
  198065. *rp = *(rp + 1);
  198066. *(rp + 1) = t;
  198067. }
  198068. }
  198069. }
  198070. #endif
  198071. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198072. static PNG_CONST png_byte onebppswaptable[256] = {
  198073. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198074. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198075. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198076. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198077. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198078. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198079. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198080. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198081. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198082. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198083. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198084. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198085. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198086. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198087. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198088. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198089. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198090. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198091. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198092. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198093. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198094. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198095. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198096. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198097. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198098. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198099. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198100. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198101. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198102. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198103. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198104. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198105. };
  198106. static PNG_CONST png_byte twobppswaptable[256] = {
  198107. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198108. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198109. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198110. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198111. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198112. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198113. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198114. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198115. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198116. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198117. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198118. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198119. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198120. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198121. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198122. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198123. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198124. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198125. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198126. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198127. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198128. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198129. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198130. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198131. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198132. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198133. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198134. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198135. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198136. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198137. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198138. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198139. };
  198140. static PNG_CONST png_byte fourbppswaptable[256] = {
  198141. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198142. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198143. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198144. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198145. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198146. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198147. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198148. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198149. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198150. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198151. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198152. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198153. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198154. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198155. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198156. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198157. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198158. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198159. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198160. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198161. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198162. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198163. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198164. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198165. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198166. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198167. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198168. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198169. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198170. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198171. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198172. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198173. };
  198174. /* swaps pixel packing order within bytes */
  198175. void /* PRIVATE */
  198176. png_do_packswap(png_row_infop row_info, png_bytep row)
  198177. {
  198178. png_debug(1, "in png_do_packswap\n");
  198179. if (
  198180. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198181. row != NULL && row_info != NULL &&
  198182. #endif
  198183. row_info->bit_depth < 8)
  198184. {
  198185. png_bytep rp, end, table;
  198186. end = row + row_info->rowbytes;
  198187. if (row_info->bit_depth == 1)
  198188. table = (png_bytep)onebppswaptable;
  198189. else if (row_info->bit_depth == 2)
  198190. table = (png_bytep)twobppswaptable;
  198191. else if (row_info->bit_depth == 4)
  198192. table = (png_bytep)fourbppswaptable;
  198193. else
  198194. return;
  198195. for (rp = row; rp < end; rp++)
  198196. *rp = table[*rp];
  198197. }
  198198. }
  198199. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198200. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198201. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198202. /* remove filler or alpha byte(s) */
  198203. void /* PRIVATE */
  198204. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198205. {
  198206. png_debug(1, "in png_do_strip_filler\n");
  198207. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198208. if (row != NULL && row_info != NULL)
  198209. #endif
  198210. {
  198211. png_bytep sp=row;
  198212. png_bytep dp=row;
  198213. png_uint_32 row_width=row_info->width;
  198214. png_uint_32 i;
  198215. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198216. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198217. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198218. row_info->channels == 4)
  198219. {
  198220. if (row_info->bit_depth == 8)
  198221. {
  198222. /* This converts from RGBX or RGBA to RGB */
  198223. if (flags & PNG_FLAG_FILLER_AFTER)
  198224. {
  198225. dp+=3; sp+=4;
  198226. for (i = 1; i < row_width; i++)
  198227. {
  198228. *dp++ = *sp++;
  198229. *dp++ = *sp++;
  198230. *dp++ = *sp++;
  198231. sp++;
  198232. }
  198233. }
  198234. /* This converts from XRGB or ARGB to RGB */
  198235. else
  198236. {
  198237. for (i = 0; i < row_width; i++)
  198238. {
  198239. sp++;
  198240. *dp++ = *sp++;
  198241. *dp++ = *sp++;
  198242. *dp++ = *sp++;
  198243. }
  198244. }
  198245. row_info->pixel_depth = 24;
  198246. row_info->rowbytes = row_width * 3;
  198247. }
  198248. else /* if (row_info->bit_depth == 16) */
  198249. {
  198250. if (flags & PNG_FLAG_FILLER_AFTER)
  198251. {
  198252. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198253. sp += 8; dp += 6;
  198254. for (i = 1; i < row_width; i++)
  198255. {
  198256. /* This could be (although png_memcpy is probably slower):
  198257. png_memcpy(dp, sp, 6);
  198258. sp += 8;
  198259. dp += 6;
  198260. */
  198261. *dp++ = *sp++;
  198262. *dp++ = *sp++;
  198263. *dp++ = *sp++;
  198264. *dp++ = *sp++;
  198265. *dp++ = *sp++;
  198266. *dp++ = *sp++;
  198267. sp += 2;
  198268. }
  198269. }
  198270. else
  198271. {
  198272. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198273. for (i = 0; i < row_width; i++)
  198274. {
  198275. /* This could be (although png_memcpy is probably slower):
  198276. png_memcpy(dp, sp, 6);
  198277. sp += 8;
  198278. dp += 6;
  198279. */
  198280. sp+=2;
  198281. *dp++ = *sp++;
  198282. *dp++ = *sp++;
  198283. *dp++ = *sp++;
  198284. *dp++ = *sp++;
  198285. *dp++ = *sp++;
  198286. *dp++ = *sp++;
  198287. }
  198288. }
  198289. row_info->pixel_depth = 48;
  198290. row_info->rowbytes = row_width * 6;
  198291. }
  198292. row_info->channels = 3;
  198293. }
  198294. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198295. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198296. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198297. row_info->channels == 2)
  198298. {
  198299. if (row_info->bit_depth == 8)
  198300. {
  198301. /* This converts from GX or GA to G */
  198302. if (flags & PNG_FLAG_FILLER_AFTER)
  198303. {
  198304. for (i = 0; i < row_width; i++)
  198305. {
  198306. *dp++ = *sp++;
  198307. sp++;
  198308. }
  198309. }
  198310. /* This converts from XG or AG to G */
  198311. else
  198312. {
  198313. for (i = 0; i < row_width; i++)
  198314. {
  198315. sp++;
  198316. *dp++ = *sp++;
  198317. }
  198318. }
  198319. row_info->pixel_depth = 8;
  198320. row_info->rowbytes = row_width;
  198321. }
  198322. else /* if (row_info->bit_depth == 16) */
  198323. {
  198324. if (flags & PNG_FLAG_FILLER_AFTER)
  198325. {
  198326. /* This converts from GGXX or GGAA to GG */
  198327. sp += 4; dp += 2;
  198328. for (i = 1; i < row_width; i++)
  198329. {
  198330. *dp++ = *sp++;
  198331. *dp++ = *sp++;
  198332. sp += 2;
  198333. }
  198334. }
  198335. else
  198336. {
  198337. /* This converts from XXGG or AAGG to GG */
  198338. for (i = 0; i < row_width; i++)
  198339. {
  198340. sp += 2;
  198341. *dp++ = *sp++;
  198342. *dp++ = *sp++;
  198343. }
  198344. }
  198345. row_info->pixel_depth = 16;
  198346. row_info->rowbytes = row_width * 2;
  198347. }
  198348. row_info->channels = 1;
  198349. }
  198350. if (flags & PNG_FLAG_STRIP_ALPHA)
  198351. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198352. }
  198353. }
  198354. #endif
  198355. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198356. /* swaps red and blue bytes within a pixel */
  198357. void /* PRIVATE */
  198358. png_do_bgr(png_row_infop row_info, png_bytep row)
  198359. {
  198360. png_debug(1, "in png_do_bgr\n");
  198361. if (
  198362. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198363. row != NULL && row_info != NULL &&
  198364. #endif
  198365. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198366. {
  198367. png_uint_32 row_width = row_info->width;
  198368. if (row_info->bit_depth == 8)
  198369. {
  198370. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198371. {
  198372. png_bytep rp;
  198373. png_uint_32 i;
  198374. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198375. {
  198376. png_byte save = *rp;
  198377. *rp = *(rp + 2);
  198378. *(rp + 2) = save;
  198379. }
  198380. }
  198381. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198382. {
  198383. png_bytep rp;
  198384. png_uint_32 i;
  198385. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198386. {
  198387. png_byte save = *rp;
  198388. *rp = *(rp + 2);
  198389. *(rp + 2) = save;
  198390. }
  198391. }
  198392. }
  198393. else if (row_info->bit_depth == 16)
  198394. {
  198395. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198396. {
  198397. png_bytep rp;
  198398. png_uint_32 i;
  198399. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198400. {
  198401. png_byte save = *rp;
  198402. *rp = *(rp + 4);
  198403. *(rp + 4) = save;
  198404. save = *(rp + 1);
  198405. *(rp + 1) = *(rp + 5);
  198406. *(rp + 5) = save;
  198407. }
  198408. }
  198409. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198410. {
  198411. png_bytep rp;
  198412. png_uint_32 i;
  198413. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198414. {
  198415. png_byte save = *rp;
  198416. *rp = *(rp + 4);
  198417. *(rp + 4) = save;
  198418. save = *(rp + 1);
  198419. *(rp + 1) = *(rp + 5);
  198420. *(rp + 5) = save;
  198421. }
  198422. }
  198423. }
  198424. }
  198425. }
  198426. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198428. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198429. defined(PNG_LEGACY_SUPPORTED)
  198430. void PNGAPI
  198431. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198432. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198433. {
  198434. png_debug(1, "in png_set_user_transform_info\n");
  198435. if(png_ptr == NULL) return;
  198436. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198437. png_ptr->user_transform_ptr = user_transform_ptr;
  198438. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198439. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198440. #else
  198441. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198442. png_warning(png_ptr,
  198443. "This version of libpng does not support user transform info");
  198444. #endif
  198445. }
  198446. #endif
  198447. /* This function returns a pointer to the user_transform_ptr associated with
  198448. * the user transform functions. The application should free any memory
  198449. * associated with this pointer before png_write_destroy and png_read_destroy
  198450. * are called.
  198451. */
  198452. png_voidp PNGAPI
  198453. png_get_user_transform_ptr(png_structp png_ptr)
  198454. {
  198455. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198456. if (png_ptr == NULL) return (NULL);
  198457. return ((png_voidp)png_ptr->user_transform_ptr);
  198458. #else
  198459. return (NULL);
  198460. #endif
  198461. }
  198462. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198463. /*** End of inlined file: pngtrans.c ***/
  198464. /*** Start of inlined file: pngwio.c ***/
  198465. /* pngwio.c - functions for data output
  198466. *
  198467. * Last changed in libpng 1.2.13 November 13, 2006
  198468. * For conditions of distribution and use, see copyright notice in png.h
  198469. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198470. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198471. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198472. *
  198473. * This file provides a location for all output. Users who need
  198474. * special handling are expected to write functions that have the same
  198475. * arguments as these and perform similar functions, but that possibly
  198476. * use different output methods. Note that you shouldn't change these
  198477. * functions, but rather write replacement functions and then change
  198478. * them at run time with png_set_write_fn(...).
  198479. */
  198480. #define PNG_INTERNAL
  198481. #ifdef PNG_WRITE_SUPPORTED
  198482. /* Write the data to whatever output you are using. The default routine
  198483. writes to a file pointer. Note that this routine sometimes gets called
  198484. with very small lengths, so you should implement some kind of simple
  198485. buffering if you are using unbuffered writes. This should never be asked
  198486. to write more than 64K on a 16 bit machine. */
  198487. void /* PRIVATE */
  198488. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198489. {
  198490. if (png_ptr->write_data_fn != NULL )
  198491. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198492. else
  198493. png_error(png_ptr, "Call to NULL write function");
  198494. }
  198495. #if !defined(PNG_NO_STDIO)
  198496. /* This is the function that does the actual writing of data. If you are
  198497. not writing to a standard C stream, you should create a replacement
  198498. write_data function and use it at run time with png_set_write_fn(), rather
  198499. than changing the library. */
  198500. #ifndef USE_FAR_KEYWORD
  198501. void PNGAPI
  198502. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198503. {
  198504. png_uint_32 check;
  198505. if(png_ptr == NULL) return;
  198506. #if defined(_WIN32_WCE)
  198507. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198508. check = 0;
  198509. #else
  198510. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198511. #endif
  198512. if (check != length)
  198513. png_error(png_ptr, "Write Error");
  198514. }
  198515. #else
  198516. /* this is the model-independent version. Since the standard I/O library
  198517. can't handle far buffers in the medium and small models, we have to copy
  198518. the data.
  198519. */
  198520. #define NEAR_BUF_SIZE 1024
  198521. #define MIN(a,b) (a <= b ? a : b)
  198522. void PNGAPI
  198523. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198524. {
  198525. png_uint_32 check;
  198526. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198527. png_FILE_p io_ptr;
  198528. if(png_ptr == NULL) return;
  198529. /* Check if data really is near. If so, use usual code. */
  198530. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198531. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198532. if ((png_bytep)near_data == data)
  198533. {
  198534. #if defined(_WIN32_WCE)
  198535. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198536. check = 0;
  198537. #else
  198538. check = fwrite(near_data, 1, length, io_ptr);
  198539. #endif
  198540. }
  198541. else
  198542. {
  198543. png_byte buf[NEAR_BUF_SIZE];
  198544. png_size_t written, remaining, err;
  198545. check = 0;
  198546. remaining = length;
  198547. do
  198548. {
  198549. written = MIN(NEAR_BUF_SIZE, remaining);
  198550. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198551. #if defined(_WIN32_WCE)
  198552. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198553. err = 0;
  198554. #else
  198555. err = fwrite(buf, 1, written, io_ptr);
  198556. #endif
  198557. if (err != written)
  198558. break;
  198559. else
  198560. check += err;
  198561. data += written;
  198562. remaining -= written;
  198563. }
  198564. while (remaining != 0);
  198565. }
  198566. if (check != length)
  198567. png_error(png_ptr, "Write Error");
  198568. }
  198569. #endif
  198570. #endif
  198571. /* This function is called to output any data pending writing (normally
  198572. to disk). After png_flush is called, there should be no data pending
  198573. writing in any buffers. */
  198574. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198575. void /* PRIVATE */
  198576. png_flush(png_structp png_ptr)
  198577. {
  198578. if (png_ptr->output_flush_fn != NULL)
  198579. (*(png_ptr->output_flush_fn))(png_ptr);
  198580. }
  198581. #if !defined(PNG_NO_STDIO)
  198582. void PNGAPI
  198583. png_default_flush(png_structp png_ptr)
  198584. {
  198585. #if !defined(_WIN32_WCE)
  198586. png_FILE_p io_ptr;
  198587. #endif
  198588. if(png_ptr == NULL) return;
  198589. #if !defined(_WIN32_WCE)
  198590. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198591. if (io_ptr != NULL)
  198592. fflush(io_ptr);
  198593. #endif
  198594. }
  198595. #endif
  198596. #endif
  198597. /* This function allows the application to supply new output functions for
  198598. libpng if standard C streams aren't being used.
  198599. This function takes as its arguments:
  198600. png_ptr - pointer to a png output data structure
  198601. io_ptr - pointer to user supplied structure containing info about
  198602. the output functions. May be NULL.
  198603. write_data_fn - pointer to a new output function that takes as its
  198604. arguments a pointer to a png_struct, a pointer to
  198605. data to be written, and a 32-bit unsigned int that is
  198606. the number of bytes to be written. The new write
  198607. function should call png_error(png_ptr, "Error msg")
  198608. to exit and output any fatal error messages.
  198609. flush_data_fn - pointer to a new flush function that takes as its
  198610. arguments a pointer to a png_struct. After a call to
  198611. the flush function, there should be no data in any buffers
  198612. or pending transmission. If the output method doesn't do
  198613. any buffering of ouput, a function prototype must still be
  198614. supplied although it doesn't have to do anything. If
  198615. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198616. time, output_flush_fn will be ignored, although it must be
  198617. supplied for compatibility. */
  198618. void PNGAPI
  198619. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198620. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198621. {
  198622. if(png_ptr == NULL) return;
  198623. png_ptr->io_ptr = io_ptr;
  198624. #if !defined(PNG_NO_STDIO)
  198625. if (write_data_fn != NULL)
  198626. png_ptr->write_data_fn = write_data_fn;
  198627. else
  198628. png_ptr->write_data_fn = png_default_write_data;
  198629. #else
  198630. png_ptr->write_data_fn = write_data_fn;
  198631. #endif
  198632. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198633. #if !defined(PNG_NO_STDIO)
  198634. if (output_flush_fn != NULL)
  198635. png_ptr->output_flush_fn = output_flush_fn;
  198636. else
  198637. png_ptr->output_flush_fn = png_default_flush;
  198638. #else
  198639. png_ptr->output_flush_fn = output_flush_fn;
  198640. #endif
  198641. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198642. /* It is an error to read while writing a png file */
  198643. if (png_ptr->read_data_fn != NULL)
  198644. {
  198645. png_ptr->read_data_fn = NULL;
  198646. png_warning(png_ptr,
  198647. "Attempted to set both read_data_fn and write_data_fn in");
  198648. png_warning(png_ptr,
  198649. "the same structure. Resetting read_data_fn to NULL.");
  198650. }
  198651. }
  198652. #if defined(USE_FAR_KEYWORD)
  198653. #if defined(_MSC_VER)
  198654. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198655. {
  198656. void *near_ptr;
  198657. void FAR *far_ptr;
  198658. FP_OFF(near_ptr) = FP_OFF(ptr);
  198659. far_ptr = (void FAR *)near_ptr;
  198660. if(check != 0)
  198661. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198662. png_error(png_ptr,"segment lost in conversion");
  198663. return(near_ptr);
  198664. }
  198665. # else
  198666. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198667. {
  198668. void *near_ptr;
  198669. void FAR *far_ptr;
  198670. near_ptr = (void FAR *)ptr;
  198671. far_ptr = (void FAR *)near_ptr;
  198672. if(check != 0)
  198673. if(far_ptr != ptr)
  198674. png_error(png_ptr,"segment lost in conversion");
  198675. return(near_ptr);
  198676. }
  198677. # endif
  198678. # endif
  198679. #endif /* PNG_WRITE_SUPPORTED */
  198680. /*** End of inlined file: pngwio.c ***/
  198681. /*** Start of inlined file: pngwrite.c ***/
  198682. /* pngwrite.c - general routines to write a PNG file
  198683. *
  198684. * Last changed in libpng 1.2.15 January 5, 2007
  198685. * For conditions of distribution and use, see copyright notice in png.h
  198686. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198687. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198688. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198689. */
  198690. /* get internal access to png.h */
  198691. #define PNG_INTERNAL
  198692. #ifdef PNG_WRITE_SUPPORTED
  198693. /* Writes all the PNG information. This is the suggested way to use the
  198694. * library. If you have a new chunk to add, make a function to write it,
  198695. * and put it in the correct location here. If you want the chunk written
  198696. * after the image data, put it in png_write_end(). I strongly encourage
  198697. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198698. * the chunk, as that will keep the code from breaking if you want to just
  198699. * write a plain PNG file. If you have long comments, I suggest writing
  198700. * them in png_write_end(), and compressing them.
  198701. */
  198702. void PNGAPI
  198703. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198704. {
  198705. png_debug(1, "in png_write_info_before_PLTE\n");
  198706. if (png_ptr == NULL || info_ptr == NULL)
  198707. return;
  198708. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198709. {
  198710. png_write_sig(png_ptr); /* write PNG signature */
  198711. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198712. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198713. {
  198714. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198715. png_ptr->mng_features_permitted=0;
  198716. }
  198717. #endif
  198718. /* write IHDR information. */
  198719. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198720. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198721. info_ptr->filter_type,
  198722. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198723. info_ptr->interlace_type);
  198724. #else
  198725. 0);
  198726. #endif
  198727. /* the rest of these check to see if the valid field has the appropriate
  198728. flag set, and if it does, writes the chunk. */
  198729. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198730. if (info_ptr->valid & PNG_INFO_gAMA)
  198731. {
  198732. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198733. png_write_gAMA(png_ptr, info_ptr->gamma);
  198734. #else
  198735. #ifdef PNG_FIXED_POINT_SUPPORTED
  198736. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198737. # endif
  198738. #endif
  198739. }
  198740. #endif
  198741. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198742. if (info_ptr->valid & PNG_INFO_sRGB)
  198743. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198744. #endif
  198745. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198746. if (info_ptr->valid & PNG_INFO_iCCP)
  198747. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198748. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198749. #endif
  198750. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198751. if (info_ptr->valid & PNG_INFO_sBIT)
  198752. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198753. #endif
  198754. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198755. if (info_ptr->valid & PNG_INFO_cHRM)
  198756. {
  198757. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198758. png_write_cHRM(png_ptr,
  198759. info_ptr->x_white, info_ptr->y_white,
  198760. info_ptr->x_red, info_ptr->y_red,
  198761. info_ptr->x_green, info_ptr->y_green,
  198762. info_ptr->x_blue, info_ptr->y_blue);
  198763. #else
  198764. # ifdef PNG_FIXED_POINT_SUPPORTED
  198765. png_write_cHRM_fixed(png_ptr,
  198766. info_ptr->int_x_white, info_ptr->int_y_white,
  198767. info_ptr->int_x_red, info_ptr->int_y_red,
  198768. info_ptr->int_x_green, info_ptr->int_y_green,
  198769. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198770. # endif
  198771. #endif
  198772. }
  198773. #endif
  198774. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198775. if (info_ptr->unknown_chunks_num)
  198776. {
  198777. png_unknown_chunk *up;
  198778. png_debug(5, "writing extra chunks\n");
  198779. for (up = info_ptr->unknown_chunks;
  198780. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198781. up++)
  198782. {
  198783. int keep=png_handle_as_unknown(png_ptr, up->name);
  198784. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198785. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198786. !(up->location & PNG_HAVE_IDAT) &&
  198787. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198788. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198789. {
  198790. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198791. }
  198792. }
  198793. }
  198794. #endif
  198795. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198796. }
  198797. }
  198798. void PNGAPI
  198799. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198800. {
  198801. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198802. int i;
  198803. #endif
  198804. png_debug(1, "in png_write_info\n");
  198805. if (png_ptr == NULL || info_ptr == NULL)
  198806. return;
  198807. png_write_info_before_PLTE(png_ptr, info_ptr);
  198808. if (info_ptr->valid & PNG_INFO_PLTE)
  198809. png_write_PLTE(png_ptr, info_ptr->palette,
  198810. (png_uint_32)info_ptr->num_palette);
  198811. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198812. png_error(png_ptr, "Valid palette required for paletted images");
  198813. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198814. if (info_ptr->valid & PNG_INFO_tRNS)
  198815. {
  198816. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198817. /* invert the alpha channel (in tRNS) */
  198818. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198819. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198820. {
  198821. int j;
  198822. for (j=0; j<(int)info_ptr->num_trans; j++)
  198823. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198824. }
  198825. #endif
  198826. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198827. info_ptr->num_trans, info_ptr->color_type);
  198828. }
  198829. #endif
  198830. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198831. if (info_ptr->valid & PNG_INFO_bKGD)
  198832. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198833. #endif
  198834. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198835. if (info_ptr->valid & PNG_INFO_hIST)
  198836. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198837. #endif
  198838. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198839. if (info_ptr->valid & PNG_INFO_oFFs)
  198840. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198841. info_ptr->offset_unit_type);
  198842. #endif
  198843. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198844. if (info_ptr->valid & PNG_INFO_pCAL)
  198845. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198846. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198847. info_ptr->pcal_units, info_ptr->pcal_params);
  198848. #endif
  198849. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198850. if (info_ptr->valid & PNG_INFO_sCAL)
  198851. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198852. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198853. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198854. #else
  198855. #ifdef PNG_FIXED_POINT_SUPPORTED
  198856. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198857. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198858. #else
  198859. png_warning(png_ptr,
  198860. "png_write_sCAL not supported; sCAL chunk not written.");
  198861. #endif
  198862. #endif
  198863. #endif
  198864. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198865. if (info_ptr->valid & PNG_INFO_pHYs)
  198866. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198867. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198868. #endif
  198869. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198870. if (info_ptr->valid & PNG_INFO_tIME)
  198871. {
  198872. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198873. png_ptr->mode |= PNG_WROTE_tIME;
  198874. }
  198875. #endif
  198876. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198877. if (info_ptr->valid & PNG_INFO_sPLT)
  198878. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198879. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198880. #endif
  198881. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198882. /* Check to see if we need to write text chunks */
  198883. for (i = 0; i < info_ptr->num_text; i++)
  198884. {
  198885. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198886. info_ptr->text[i].compression);
  198887. /* an internationalized chunk? */
  198888. if (info_ptr->text[i].compression > 0)
  198889. {
  198890. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198891. /* write international chunk */
  198892. png_write_iTXt(png_ptr,
  198893. info_ptr->text[i].compression,
  198894. info_ptr->text[i].key,
  198895. info_ptr->text[i].lang,
  198896. info_ptr->text[i].lang_key,
  198897. info_ptr->text[i].text);
  198898. #else
  198899. png_warning(png_ptr, "Unable to write international text");
  198900. #endif
  198901. /* Mark this chunk as written */
  198902. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198903. }
  198904. /* If we want a compressed text chunk */
  198905. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198906. {
  198907. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198908. /* write compressed chunk */
  198909. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198910. info_ptr->text[i].text, 0,
  198911. info_ptr->text[i].compression);
  198912. #else
  198913. png_warning(png_ptr, "Unable to write compressed text");
  198914. #endif
  198915. /* Mark this chunk as written */
  198916. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198917. }
  198918. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198919. {
  198920. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198921. /* write uncompressed chunk */
  198922. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198923. info_ptr->text[i].text,
  198924. 0);
  198925. #else
  198926. png_warning(png_ptr, "Unable to write uncompressed text");
  198927. #endif
  198928. /* Mark this chunk as written */
  198929. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198930. }
  198931. }
  198932. #endif
  198933. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198934. if (info_ptr->unknown_chunks_num)
  198935. {
  198936. png_unknown_chunk *up;
  198937. png_debug(5, "writing extra chunks\n");
  198938. for (up = info_ptr->unknown_chunks;
  198939. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198940. up++)
  198941. {
  198942. int keep=png_handle_as_unknown(png_ptr, up->name);
  198943. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198944. up->location && (up->location & PNG_HAVE_PLTE) &&
  198945. !(up->location & PNG_HAVE_IDAT) &&
  198946. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198947. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198948. {
  198949. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198950. }
  198951. }
  198952. }
  198953. #endif
  198954. }
  198955. /* Writes the end of the PNG file. If you don't want to write comments or
  198956. * time information, you can pass NULL for info. If you already wrote these
  198957. * in png_write_info(), do not write them again here. If you have long
  198958. * comments, I suggest writing them here, and compressing them.
  198959. */
  198960. void PNGAPI
  198961. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198962. {
  198963. png_debug(1, "in png_write_end\n");
  198964. if (png_ptr == NULL)
  198965. return;
  198966. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198967. png_error(png_ptr, "No IDATs written into file");
  198968. /* see if user wants us to write information chunks */
  198969. if (info_ptr != NULL)
  198970. {
  198971. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198972. int i; /* local index variable */
  198973. #endif
  198974. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198975. /* check to see if user has supplied a time chunk */
  198976. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198977. !(png_ptr->mode & PNG_WROTE_tIME))
  198978. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198979. #endif
  198980. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198981. /* loop through comment chunks */
  198982. for (i = 0; i < info_ptr->num_text; i++)
  198983. {
  198984. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198985. info_ptr->text[i].compression);
  198986. /* an internationalized chunk? */
  198987. if (info_ptr->text[i].compression > 0)
  198988. {
  198989. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198990. /* write international chunk */
  198991. png_write_iTXt(png_ptr,
  198992. info_ptr->text[i].compression,
  198993. info_ptr->text[i].key,
  198994. info_ptr->text[i].lang,
  198995. info_ptr->text[i].lang_key,
  198996. info_ptr->text[i].text);
  198997. #else
  198998. png_warning(png_ptr, "Unable to write international text");
  198999. #endif
  199000. /* Mark this chunk as written */
  199001. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199002. }
  199003. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199004. {
  199005. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199006. /* write compressed chunk */
  199007. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199008. info_ptr->text[i].text, 0,
  199009. info_ptr->text[i].compression);
  199010. #else
  199011. png_warning(png_ptr, "Unable to write compressed text");
  199012. #endif
  199013. /* Mark this chunk as written */
  199014. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199015. }
  199016. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199017. {
  199018. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199019. /* write uncompressed chunk */
  199020. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199021. info_ptr->text[i].text, 0);
  199022. #else
  199023. png_warning(png_ptr, "Unable to write uncompressed text");
  199024. #endif
  199025. /* Mark this chunk as written */
  199026. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199027. }
  199028. }
  199029. #endif
  199030. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199031. if (info_ptr->unknown_chunks_num)
  199032. {
  199033. png_unknown_chunk *up;
  199034. png_debug(5, "writing extra chunks\n");
  199035. for (up = info_ptr->unknown_chunks;
  199036. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199037. up++)
  199038. {
  199039. int keep=png_handle_as_unknown(png_ptr, up->name);
  199040. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199041. up->location && (up->location & PNG_AFTER_IDAT) &&
  199042. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199043. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199044. {
  199045. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199046. }
  199047. }
  199048. }
  199049. #endif
  199050. }
  199051. png_ptr->mode |= PNG_AFTER_IDAT;
  199052. /* write end of PNG file */
  199053. png_write_IEND(png_ptr);
  199054. }
  199055. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199056. #if !defined(_WIN32_WCE)
  199057. /* "time.h" functions are not supported on WindowsCE */
  199058. void PNGAPI
  199059. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199060. {
  199061. png_debug(1, "in png_convert_from_struct_tm\n");
  199062. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199063. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199064. ptime->day = (png_byte)ttime->tm_mday;
  199065. ptime->hour = (png_byte)ttime->tm_hour;
  199066. ptime->minute = (png_byte)ttime->tm_min;
  199067. ptime->second = (png_byte)ttime->tm_sec;
  199068. }
  199069. void PNGAPI
  199070. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199071. {
  199072. struct tm *tbuf;
  199073. png_debug(1, "in png_convert_from_time_t\n");
  199074. tbuf = gmtime(&ttime);
  199075. png_convert_from_struct_tm(ptime, tbuf);
  199076. }
  199077. #endif
  199078. #endif
  199079. /* Initialize png_ptr structure, and allocate any memory needed */
  199080. png_structp PNGAPI
  199081. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199082. png_error_ptr error_fn, png_error_ptr warn_fn)
  199083. {
  199084. #ifdef PNG_USER_MEM_SUPPORTED
  199085. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199086. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199087. }
  199088. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199089. png_structp PNGAPI
  199090. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199091. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199092. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199093. {
  199094. #endif /* PNG_USER_MEM_SUPPORTED */
  199095. png_structp png_ptr;
  199096. #ifdef PNG_SETJMP_SUPPORTED
  199097. #ifdef USE_FAR_KEYWORD
  199098. jmp_buf jmpbuf;
  199099. #endif
  199100. #endif
  199101. int i;
  199102. png_debug(1, "in png_create_write_struct\n");
  199103. #ifdef PNG_USER_MEM_SUPPORTED
  199104. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199105. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199106. #else
  199107. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199108. #endif /* PNG_USER_MEM_SUPPORTED */
  199109. if (png_ptr == NULL)
  199110. return (NULL);
  199111. /* added at libpng-1.2.6 */
  199112. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199113. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199114. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199115. #endif
  199116. #ifdef PNG_SETJMP_SUPPORTED
  199117. #ifdef USE_FAR_KEYWORD
  199118. if (setjmp(jmpbuf))
  199119. #else
  199120. if (setjmp(png_ptr->jmpbuf))
  199121. #endif
  199122. {
  199123. png_free(png_ptr, png_ptr->zbuf);
  199124. png_ptr->zbuf=NULL;
  199125. png_destroy_struct(png_ptr);
  199126. return (NULL);
  199127. }
  199128. #ifdef USE_FAR_KEYWORD
  199129. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199130. #endif
  199131. #endif
  199132. #ifdef PNG_USER_MEM_SUPPORTED
  199133. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199134. #endif /* PNG_USER_MEM_SUPPORTED */
  199135. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199136. i=0;
  199137. do
  199138. {
  199139. if(user_png_ver[i] != png_libpng_ver[i])
  199140. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199141. } while (png_libpng_ver[i++]);
  199142. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199143. {
  199144. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199145. * we must recompile any applications that use any older library version.
  199146. * For versions after libpng 1.0, we will be compatible, so we need
  199147. * only check the first digit.
  199148. */
  199149. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199150. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199151. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199152. {
  199153. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199154. char msg[80];
  199155. if (user_png_ver)
  199156. {
  199157. png_snprintf(msg, 80,
  199158. "Application was compiled with png.h from libpng-%.20s",
  199159. user_png_ver);
  199160. png_warning(png_ptr, msg);
  199161. }
  199162. png_snprintf(msg, 80,
  199163. "Application is running with png.c from libpng-%.20s",
  199164. png_libpng_ver);
  199165. png_warning(png_ptr, msg);
  199166. #endif
  199167. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199168. png_ptr->flags=0;
  199169. #endif
  199170. png_error(png_ptr,
  199171. "Incompatible libpng version in application and library");
  199172. }
  199173. }
  199174. /* initialize zbuf - compression buffer */
  199175. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199176. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199177. (png_uint_32)png_ptr->zbuf_size);
  199178. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199179. png_flush_ptr_NULL);
  199180. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199181. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199182. 1, png_doublep_NULL, png_doublep_NULL);
  199183. #endif
  199184. #ifdef PNG_SETJMP_SUPPORTED
  199185. /* Applications that neglect to set up their own setjmp() and then encounter
  199186. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199187. abort instead of returning. */
  199188. #ifdef USE_FAR_KEYWORD
  199189. if (setjmp(jmpbuf))
  199190. PNG_ABORT();
  199191. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199192. #else
  199193. if (setjmp(png_ptr->jmpbuf))
  199194. PNG_ABORT();
  199195. #endif
  199196. #endif
  199197. return (png_ptr);
  199198. }
  199199. /* Initialize png_ptr structure, and allocate any memory needed */
  199200. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199201. /* Deprecated. */
  199202. #undef png_write_init
  199203. void PNGAPI
  199204. png_write_init(png_structp png_ptr)
  199205. {
  199206. /* We only come here via pre-1.0.7-compiled applications */
  199207. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199208. }
  199209. void PNGAPI
  199210. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199211. png_size_t png_struct_size, png_size_t png_info_size)
  199212. {
  199213. /* We only come here via pre-1.0.12-compiled applications */
  199214. if(png_ptr == NULL) return;
  199215. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199216. if(png_sizeof(png_struct) > png_struct_size ||
  199217. png_sizeof(png_info) > png_info_size)
  199218. {
  199219. char msg[80];
  199220. png_ptr->warning_fn=NULL;
  199221. if (user_png_ver)
  199222. {
  199223. png_snprintf(msg, 80,
  199224. "Application was compiled with png.h from libpng-%.20s",
  199225. user_png_ver);
  199226. png_warning(png_ptr, msg);
  199227. }
  199228. png_snprintf(msg, 80,
  199229. "Application is running with png.c from libpng-%.20s",
  199230. png_libpng_ver);
  199231. png_warning(png_ptr, msg);
  199232. }
  199233. #endif
  199234. if(png_sizeof(png_struct) > png_struct_size)
  199235. {
  199236. png_ptr->error_fn=NULL;
  199237. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199238. png_ptr->flags=0;
  199239. #endif
  199240. png_error(png_ptr,
  199241. "The png struct allocated by the application for writing is too small.");
  199242. }
  199243. if(png_sizeof(png_info) > png_info_size)
  199244. {
  199245. png_ptr->error_fn=NULL;
  199246. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199247. png_ptr->flags=0;
  199248. #endif
  199249. png_error(png_ptr,
  199250. "The info struct allocated by the application for writing is too small.");
  199251. }
  199252. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199253. }
  199254. #endif /* PNG_1_0_X || PNG_1_2_X */
  199255. void PNGAPI
  199256. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199257. png_size_t png_struct_size)
  199258. {
  199259. png_structp png_ptr=*ptr_ptr;
  199260. #ifdef PNG_SETJMP_SUPPORTED
  199261. jmp_buf tmp_jmp; /* to save current jump buffer */
  199262. #endif
  199263. int i = 0;
  199264. if (png_ptr == NULL)
  199265. return;
  199266. do
  199267. {
  199268. if (user_png_ver[i] != png_libpng_ver[i])
  199269. {
  199270. #ifdef PNG_LEGACY_SUPPORTED
  199271. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199272. #else
  199273. png_ptr->warning_fn=NULL;
  199274. png_warning(png_ptr,
  199275. "Application uses deprecated png_write_init() and should be recompiled.");
  199276. break;
  199277. #endif
  199278. }
  199279. } while (png_libpng_ver[i++]);
  199280. png_debug(1, "in png_write_init_3\n");
  199281. #ifdef PNG_SETJMP_SUPPORTED
  199282. /* save jump buffer and error functions */
  199283. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199284. #endif
  199285. if (png_sizeof(png_struct) > png_struct_size)
  199286. {
  199287. png_destroy_struct(png_ptr);
  199288. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199289. *ptr_ptr = png_ptr;
  199290. }
  199291. /* reset all variables to 0 */
  199292. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199293. /* added at libpng-1.2.6 */
  199294. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199295. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199296. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199297. #endif
  199298. #ifdef PNG_SETJMP_SUPPORTED
  199299. /* restore jump buffer */
  199300. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199301. #endif
  199302. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199303. png_flush_ptr_NULL);
  199304. /* initialize zbuf - compression buffer */
  199305. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199306. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199307. (png_uint_32)png_ptr->zbuf_size);
  199308. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199309. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199310. 1, png_doublep_NULL, png_doublep_NULL);
  199311. #endif
  199312. }
  199313. /* Write a few rows of image data. If the image is interlaced,
  199314. * either you will have to write the 7 sub images, or, if you
  199315. * have called png_set_interlace_handling(), you will have to
  199316. * "write" the image seven times.
  199317. */
  199318. void PNGAPI
  199319. png_write_rows(png_structp png_ptr, png_bytepp row,
  199320. png_uint_32 num_rows)
  199321. {
  199322. png_uint_32 i; /* row counter */
  199323. png_bytepp rp; /* row pointer */
  199324. png_debug(1, "in png_write_rows\n");
  199325. if (png_ptr == NULL)
  199326. return;
  199327. /* loop through the rows */
  199328. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199329. {
  199330. png_write_row(png_ptr, *rp);
  199331. }
  199332. }
  199333. /* Write the image. You only need to call this function once, even
  199334. * if you are writing an interlaced image.
  199335. */
  199336. void PNGAPI
  199337. png_write_image(png_structp png_ptr, png_bytepp image)
  199338. {
  199339. png_uint_32 i; /* row index */
  199340. int pass, num_pass; /* pass variables */
  199341. png_bytepp rp; /* points to current row */
  199342. if (png_ptr == NULL)
  199343. return;
  199344. png_debug(1, "in png_write_image\n");
  199345. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199346. /* intialize interlace handling. If image is not interlaced,
  199347. this will set pass to 1 */
  199348. num_pass = png_set_interlace_handling(png_ptr);
  199349. #else
  199350. num_pass = 1;
  199351. #endif
  199352. /* loop through passes */
  199353. for (pass = 0; pass < num_pass; pass++)
  199354. {
  199355. /* loop through image */
  199356. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199357. {
  199358. png_write_row(png_ptr, *rp);
  199359. }
  199360. }
  199361. }
  199362. /* called by user to write a row of image data */
  199363. void PNGAPI
  199364. png_write_row(png_structp png_ptr, png_bytep row)
  199365. {
  199366. if (png_ptr == NULL)
  199367. return;
  199368. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199369. png_ptr->row_number, png_ptr->pass);
  199370. /* initialize transformations and other stuff if first time */
  199371. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199372. {
  199373. /* make sure we wrote the header info */
  199374. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199375. png_error(png_ptr,
  199376. "png_write_info was never called before png_write_row.");
  199377. /* check for transforms that have been set but were defined out */
  199378. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199379. if (png_ptr->transformations & PNG_INVERT_MONO)
  199380. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199381. #endif
  199382. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199383. if (png_ptr->transformations & PNG_FILLER)
  199384. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199385. #endif
  199386. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199387. if (png_ptr->transformations & PNG_PACKSWAP)
  199388. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199389. #endif
  199390. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199391. if (png_ptr->transformations & PNG_PACK)
  199392. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199393. #endif
  199394. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199395. if (png_ptr->transformations & PNG_SHIFT)
  199396. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199397. #endif
  199398. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199399. if (png_ptr->transformations & PNG_BGR)
  199400. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199401. #endif
  199402. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199403. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199404. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199405. #endif
  199406. png_write_start_row(png_ptr);
  199407. }
  199408. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199409. /* if interlaced and not interested in row, return */
  199410. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199411. {
  199412. switch (png_ptr->pass)
  199413. {
  199414. case 0:
  199415. if (png_ptr->row_number & 0x07)
  199416. {
  199417. png_write_finish_row(png_ptr);
  199418. return;
  199419. }
  199420. break;
  199421. case 1:
  199422. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199423. {
  199424. png_write_finish_row(png_ptr);
  199425. return;
  199426. }
  199427. break;
  199428. case 2:
  199429. if ((png_ptr->row_number & 0x07) != 4)
  199430. {
  199431. png_write_finish_row(png_ptr);
  199432. return;
  199433. }
  199434. break;
  199435. case 3:
  199436. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199437. {
  199438. png_write_finish_row(png_ptr);
  199439. return;
  199440. }
  199441. break;
  199442. case 4:
  199443. if ((png_ptr->row_number & 0x03) != 2)
  199444. {
  199445. png_write_finish_row(png_ptr);
  199446. return;
  199447. }
  199448. break;
  199449. case 5:
  199450. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199451. {
  199452. png_write_finish_row(png_ptr);
  199453. return;
  199454. }
  199455. break;
  199456. case 6:
  199457. if (!(png_ptr->row_number & 0x01))
  199458. {
  199459. png_write_finish_row(png_ptr);
  199460. return;
  199461. }
  199462. break;
  199463. }
  199464. }
  199465. #endif
  199466. /* set up row info for transformations */
  199467. png_ptr->row_info.color_type = png_ptr->color_type;
  199468. png_ptr->row_info.width = png_ptr->usr_width;
  199469. png_ptr->row_info.channels = png_ptr->usr_channels;
  199470. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199471. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199472. png_ptr->row_info.channels);
  199473. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199474. png_ptr->row_info.width);
  199475. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199476. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199477. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199478. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199479. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199480. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199481. /* Copy user's row into buffer, leaving room for filter byte. */
  199482. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199483. png_ptr->row_info.rowbytes);
  199484. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199485. /* handle interlacing */
  199486. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199487. (png_ptr->transformations & PNG_INTERLACE))
  199488. {
  199489. png_do_write_interlace(&(png_ptr->row_info),
  199490. png_ptr->row_buf + 1, png_ptr->pass);
  199491. /* this should always get caught above, but still ... */
  199492. if (!(png_ptr->row_info.width))
  199493. {
  199494. png_write_finish_row(png_ptr);
  199495. return;
  199496. }
  199497. }
  199498. #endif
  199499. /* handle other transformations */
  199500. if (png_ptr->transformations)
  199501. png_do_write_transformations(png_ptr);
  199502. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199503. /* Write filter_method 64 (intrapixel differencing) only if
  199504. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199505. * 2. Libpng did not write a PNG signature (this filter_method is only
  199506. * used in PNG datastreams that are embedded in MNG datastreams) and
  199507. * 3. The application called png_permit_mng_features with a mask that
  199508. * included PNG_FLAG_MNG_FILTER_64 and
  199509. * 4. The filter_method is 64 and
  199510. * 5. The color_type is RGB or RGBA
  199511. */
  199512. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199513. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199514. {
  199515. /* Intrapixel differencing */
  199516. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199517. }
  199518. #endif
  199519. /* Find a filter if necessary, filter the row and write it out. */
  199520. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199521. if (png_ptr->write_row_fn != NULL)
  199522. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199523. }
  199524. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199525. /* Set the automatic flush interval or 0 to turn flushing off */
  199526. void PNGAPI
  199527. png_set_flush(png_structp png_ptr, int nrows)
  199528. {
  199529. png_debug(1, "in png_set_flush\n");
  199530. if (png_ptr == NULL)
  199531. return;
  199532. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199533. }
  199534. /* flush the current output buffers now */
  199535. void PNGAPI
  199536. png_write_flush(png_structp png_ptr)
  199537. {
  199538. int wrote_IDAT;
  199539. png_debug(1, "in png_write_flush\n");
  199540. if (png_ptr == NULL)
  199541. return;
  199542. /* We have already written out all of the data */
  199543. if (png_ptr->row_number >= png_ptr->num_rows)
  199544. return;
  199545. do
  199546. {
  199547. int ret;
  199548. /* compress the data */
  199549. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199550. wrote_IDAT = 0;
  199551. /* check for compression errors */
  199552. if (ret != Z_OK)
  199553. {
  199554. if (png_ptr->zstream.msg != NULL)
  199555. png_error(png_ptr, png_ptr->zstream.msg);
  199556. else
  199557. png_error(png_ptr, "zlib error");
  199558. }
  199559. if (!(png_ptr->zstream.avail_out))
  199560. {
  199561. /* write the IDAT and reset the zlib output buffer */
  199562. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199563. png_ptr->zbuf_size);
  199564. png_ptr->zstream.next_out = png_ptr->zbuf;
  199565. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199566. wrote_IDAT = 1;
  199567. }
  199568. } while(wrote_IDAT == 1);
  199569. /* If there is any data left to be output, write it into a new IDAT */
  199570. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199571. {
  199572. /* write the IDAT and reset the zlib output buffer */
  199573. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199574. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199575. png_ptr->zstream.next_out = png_ptr->zbuf;
  199576. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199577. }
  199578. png_ptr->flush_rows = 0;
  199579. png_flush(png_ptr);
  199580. }
  199581. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199582. /* free all memory used by the write */
  199583. void PNGAPI
  199584. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199585. {
  199586. png_structp png_ptr = NULL;
  199587. png_infop info_ptr = NULL;
  199588. #ifdef PNG_USER_MEM_SUPPORTED
  199589. png_free_ptr free_fn = NULL;
  199590. png_voidp mem_ptr = NULL;
  199591. #endif
  199592. png_debug(1, "in png_destroy_write_struct\n");
  199593. if (png_ptr_ptr != NULL)
  199594. {
  199595. png_ptr = *png_ptr_ptr;
  199596. #ifdef PNG_USER_MEM_SUPPORTED
  199597. free_fn = png_ptr->free_fn;
  199598. mem_ptr = png_ptr->mem_ptr;
  199599. #endif
  199600. }
  199601. if (info_ptr_ptr != NULL)
  199602. info_ptr = *info_ptr_ptr;
  199603. if (info_ptr != NULL)
  199604. {
  199605. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199606. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199607. if (png_ptr->num_chunk_list)
  199608. {
  199609. png_free(png_ptr, png_ptr->chunk_list);
  199610. png_ptr->chunk_list=NULL;
  199611. png_ptr->num_chunk_list=0;
  199612. }
  199613. #endif
  199614. #ifdef PNG_USER_MEM_SUPPORTED
  199615. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199616. (png_voidp)mem_ptr);
  199617. #else
  199618. png_destroy_struct((png_voidp)info_ptr);
  199619. #endif
  199620. *info_ptr_ptr = NULL;
  199621. }
  199622. if (png_ptr != NULL)
  199623. {
  199624. png_write_destroy(png_ptr);
  199625. #ifdef PNG_USER_MEM_SUPPORTED
  199626. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199627. (png_voidp)mem_ptr);
  199628. #else
  199629. png_destroy_struct((png_voidp)png_ptr);
  199630. #endif
  199631. *png_ptr_ptr = NULL;
  199632. }
  199633. }
  199634. /* Free any memory used in png_ptr struct (old method) */
  199635. void /* PRIVATE */
  199636. png_write_destroy(png_structp png_ptr)
  199637. {
  199638. #ifdef PNG_SETJMP_SUPPORTED
  199639. jmp_buf tmp_jmp; /* save jump buffer */
  199640. #endif
  199641. png_error_ptr error_fn;
  199642. png_error_ptr warning_fn;
  199643. png_voidp error_ptr;
  199644. #ifdef PNG_USER_MEM_SUPPORTED
  199645. png_free_ptr free_fn;
  199646. #endif
  199647. png_debug(1, "in png_write_destroy\n");
  199648. /* free any memory zlib uses */
  199649. deflateEnd(&png_ptr->zstream);
  199650. /* free our memory. png_free checks NULL for us. */
  199651. png_free(png_ptr, png_ptr->zbuf);
  199652. png_free(png_ptr, png_ptr->row_buf);
  199653. png_free(png_ptr, png_ptr->prev_row);
  199654. png_free(png_ptr, png_ptr->sub_row);
  199655. png_free(png_ptr, png_ptr->up_row);
  199656. png_free(png_ptr, png_ptr->avg_row);
  199657. png_free(png_ptr, png_ptr->paeth_row);
  199658. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199659. png_free(png_ptr, png_ptr->time_buffer);
  199660. #endif
  199661. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199662. png_free(png_ptr, png_ptr->prev_filters);
  199663. png_free(png_ptr, png_ptr->filter_weights);
  199664. png_free(png_ptr, png_ptr->inv_filter_weights);
  199665. png_free(png_ptr, png_ptr->filter_costs);
  199666. png_free(png_ptr, png_ptr->inv_filter_costs);
  199667. #endif
  199668. #ifdef PNG_SETJMP_SUPPORTED
  199669. /* reset structure */
  199670. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199671. #endif
  199672. error_fn = png_ptr->error_fn;
  199673. warning_fn = png_ptr->warning_fn;
  199674. error_ptr = png_ptr->error_ptr;
  199675. #ifdef PNG_USER_MEM_SUPPORTED
  199676. free_fn = png_ptr->free_fn;
  199677. #endif
  199678. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199679. png_ptr->error_fn = error_fn;
  199680. png_ptr->warning_fn = warning_fn;
  199681. png_ptr->error_ptr = error_ptr;
  199682. #ifdef PNG_USER_MEM_SUPPORTED
  199683. png_ptr->free_fn = free_fn;
  199684. #endif
  199685. #ifdef PNG_SETJMP_SUPPORTED
  199686. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199687. #endif
  199688. }
  199689. /* Allow the application to select one or more row filters to use. */
  199690. void PNGAPI
  199691. png_set_filter(png_structp png_ptr, int method, int filters)
  199692. {
  199693. png_debug(1, "in png_set_filter\n");
  199694. if (png_ptr == NULL)
  199695. return;
  199696. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199697. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199698. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199699. method = PNG_FILTER_TYPE_BASE;
  199700. #endif
  199701. if (method == PNG_FILTER_TYPE_BASE)
  199702. {
  199703. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199704. {
  199705. #ifndef PNG_NO_WRITE_FILTER
  199706. case 5:
  199707. case 6:
  199708. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199709. #endif /* PNG_NO_WRITE_FILTER */
  199710. case PNG_FILTER_VALUE_NONE:
  199711. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199712. #ifndef PNG_NO_WRITE_FILTER
  199713. case PNG_FILTER_VALUE_SUB:
  199714. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199715. case PNG_FILTER_VALUE_UP:
  199716. png_ptr->do_filter=PNG_FILTER_UP; break;
  199717. case PNG_FILTER_VALUE_AVG:
  199718. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199719. case PNG_FILTER_VALUE_PAETH:
  199720. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199721. default: png_ptr->do_filter = (png_byte)filters; break;
  199722. #else
  199723. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199724. #endif /* PNG_NO_WRITE_FILTER */
  199725. }
  199726. /* If we have allocated the row_buf, this means we have already started
  199727. * with the image and we should have allocated all of the filter buffers
  199728. * that have been selected. If prev_row isn't already allocated, then
  199729. * it is too late to start using the filters that need it, since we
  199730. * will be missing the data in the previous row. If an application
  199731. * wants to start and stop using particular filters during compression,
  199732. * it should start out with all of the filters, and then add and
  199733. * remove them after the start of compression.
  199734. */
  199735. if (png_ptr->row_buf != NULL)
  199736. {
  199737. #ifndef PNG_NO_WRITE_FILTER
  199738. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199739. {
  199740. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199741. (png_ptr->rowbytes + 1));
  199742. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199743. }
  199744. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199745. {
  199746. if (png_ptr->prev_row == NULL)
  199747. {
  199748. png_warning(png_ptr, "Can't add Up filter after starting");
  199749. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199750. }
  199751. else
  199752. {
  199753. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199754. (png_ptr->rowbytes + 1));
  199755. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199756. }
  199757. }
  199758. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199759. {
  199760. if (png_ptr->prev_row == NULL)
  199761. {
  199762. png_warning(png_ptr, "Can't add Average filter after starting");
  199763. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199764. }
  199765. else
  199766. {
  199767. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199768. (png_ptr->rowbytes + 1));
  199769. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199770. }
  199771. }
  199772. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199773. png_ptr->paeth_row == NULL)
  199774. {
  199775. if (png_ptr->prev_row == NULL)
  199776. {
  199777. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199778. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199779. }
  199780. else
  199781. {
  199782. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199783. (png_ptr->rowbytes + 1));
  199784. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199785. }
  199786. }
  199787. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199788. #endif /* PNG_NO_WRITE_FILTER */
  199789. png_ptr->do_filter = PNG_FILTER_NONE;
  199790. }
  199791. }
  199792. else
  199793. png_error(png_ptr, "Unknown custom filter method");
  199794. }
  199795. /* This allows us to influence the way in which libpng chooses the "best"
  199796. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199797. * differences metric is relatively fast and effective, there is some
  199798. * question as to whether it can be improved upon by trying to keep the
  199799. * filtered data going to zlib more consistent, hopefully resulting in
  199800. * better compression.
  199801. */
  199802. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199803. void PNGAPI
  199804. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199805. int num_weights, png_doublep filter_weights,
  199806. png_doublep filter_costs)
  199807. {
  199808. int i;
  199809. png_debug(1, "in png_set_filter_heuristics\n");
  199810. if (png_ptr == NULL)
  199811. return;
  199812. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199813. {
  199814. png_warning(png_ptr, "Unknown filter heuristic method");
  199815. return;
  199816. }
  199817. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199818. {
  199819. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199820. }
  199821. if (num_weights < 0 || filter_weights == NULL ||
  199822. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199823. {
  199824. num_weights = 0;
  199825. }
  199826. png_ptr->num_prev_filters = (png_byte)num_weights;
  199827. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199828. if (num_weights > 0)
  199829. {
  199830. if (png_ptr->prev_filters == NULL)
  199831. {
  199832. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199833. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199834. /* To make sure that the weighting starts out fairly */
  199835. for (i = 0; i < num_weights; i++)
  199836. {
  199837. png_ptr->prev_filters[i] = 255;
  199838. }
  199839. }
  199840. if (png_ptr->filter_weights == NULL)
  199841. {
  199842. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199843. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199844. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199845. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199846. for (i = 0; i < num_weights; i++)
  199847. {
  199848. png_ptr->inv_filter_weights[i] =
  199849. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199850. }
  199851. }
  199852. for (i = 0; i < num_weights; i++)
  199853. {
  199854. if (filter_weights[i] < 0.0)
  199855. {
  199856. png_ptr->inv_filter_weights[i] =
  199857. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199858. }
  199859. else
  199860. {
  199861. png_ptr->inv_filter_weights[i] =
  199862. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199863. png_ptr->filter_weights[i] =
  199864. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199865. }
  199866. }
  199867. }
  199868. /* If, in the future, there are other filter methods, this would
  199869. * need to be based on png_ptr->filter.
  199870. */
  199871. if (png_ptr->filter_costs == NULL)
  199872. {
  199873. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199874. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199875. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199876. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199877. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199878. {
  199879. png_ptr->inv_filter_costs[i] =
  199880. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199881. }
  199882. }
  199883. /* Here is where we set the relative costs of the different filters. We
  199884. * should take the desired compression level into account when setting
  199885. * the costs, so that Paeth, for instance, has a high relative cost at low
  199886. * compression levels, while it has a lower relative cost at higher
  199887. * compression settings. The filter types are in order of increasing
  199888. * relative cost, so it would be possible to do this with an algorithm.
  199889. */
  199890. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199891. {
  199892. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199893. {
  199894. png_ptr->inv_filter_costs[i] =
  199895. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199896. }
  199897. else if (filter_costs[i] >= 1.0)
  199898. {
  199899. png_ptr->inv_filter_costs[i] =
  199900. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199901. png_ptr->filter_costs[i] =
  199902. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199903. }
  199904. }
  199905. }
  199906. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199907. void PNGAPI
  199908. png_set_compression_level(png_structp png_ptr, int level)
  199909. {
  199910. png_debug(1, "in png_set_compression_level\n");
  199911. if (png_ptr == NULL)
  199912. return;
  199913. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199914. png_ptr->zlib_level = level;
  199915. }
  199916. void PNGAPI
  199917. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199918. {
  199919. png_debug(1, "in png_set_compression_mem_level\n");
  199920. if (png_ptr == NULL)
  199921. return;
  199922. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199923. png_ptr->zlib_mem_level = mem_level;
  199924. }
  199925. void PNGAPI
  199926. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199927. {
  199928. png_debug(1, "in png_set_compression_strategy\n");
  199929. if (png_ptr == NULL)
  199930. return;
  199931. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199932. png_ptr->zlib_strategy = strategy;
  199933. }
  199934. void PNGAPI
  199935. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199936. {
  199937. if (png_ptr == NULL)
  199938. return;
  199939. if (window_bits > 15)
  199940. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199941. else if (window_bits < 8)
  199942. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199943. #ifndef WBITS_8_OK
  199944. /* avoid libpng bug with 256-byte windows */
  199945. if (window_bits == 8)
  199946. {
  199947. png_warning(png_ptr, "Compression window is being reset to 512");
  199948. window_bits=9;
  199949. }
  199950. #endif
  199951. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199952. png_ptr->zlib_window_bits = window_bits;
  199953. }
  199954. void PNGAPI
  199955. png_set_compression_method(png_structp png_ptr, int method)
  199956. {
  199957. png_debug(1, "in png_set_compression_method\n");
  199958. if (png_ptr == NULL)
  199959. return;
  199960. if (method != 8)
  199961. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199962. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199963. png_ptr->zlib_method = method;
  199964. }
  199965. void PNGAPI
  199966. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199967. {
  199968. if (png_ptr == NULL)
  199969. return;
  199970. png_ptr->write_row_fn = write_row_fn;
  199971. }
  199972. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199973. void PNGAPI
  199974. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199975. write_user_transform_fn)
  199976. {
  199977. png_debug(1, "in png_set_write_user_transform_fn\n");
  199978. if (png_ptr == NULL)
  199979. return;
  199980. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199981. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199982. }
  199983. #endif
  199984. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199985. void PNGAPI
  199986. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199987. int transforms, voidp params)
  199988. {
  199989. if (png_ptr == NULL || info_ptr == NULL)
  199990. return;
  199991. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199992. /* invert the alpha channel from opacity to transparency */
  199993. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199994. png_set_invert_alpha(png_ptr);
  199995. #endif
  199996. /* Write the file header information. */
  199997. png_write_info(png_ptr, info_ptr);
  199998. /* ------ these transformations don't touch the info structure ------- */
  199999. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200000. /* invert monochrome pixels */
  200001. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200002. png_set_invert_mono(png_ptr);
  200003. #endif
  200004. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200005. /* Shift the pixels up to a legal bit depth and fill in
  200006. * as appropriate to correctly scale the image.
  200007. */
  200008. if ((transforms & PNG_TRANSFORM_SHIFT)
  200009. && (info_ptr->valid & PNG_INFO_sBIT))
  200010. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200011. #endif
  200012. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200013. /* pack pixels into bytes */
  200014. if (transforms & PNG_TRANSFORM_PACKING)
  200015. png_set_packing(png_ptr);
  200016. #endif
  200017. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200018. /* swap location of alpha bytes from ARGB to RGBA */
  200019. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200020. png_set_swap_alpha(png_ptr);
  200021. #endif
  200022. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200023. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200024. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200025. */
  200026. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200027. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200028. #endif
  200029. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200030. /* flip BGR pixels to RGB */
  200031. if (transforms & PNG_TRANSFORM_BGR)
  200032. png_set_bgr(png_ptr);
  200033. #endif
  200034. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200035. /* swap bytes of 16-bit files to most significant byte first */
  200036. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200037. png_set_swap(png_ptr);
  200038. #endif
  200039. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200040. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200041. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200042. png_set_packswap(png_ptr);
  200043. #endif
  200044. /* ----------------------- end of transformations ------------------- */
  200045. /* write the bits */
  200046. if (info_ptr->valid & PNG_INFO_IDAT)
  200047. png_write_image(png_ptr, info_ptr->row_pointers);
  200048. /* It is REQUIRED to call this to finish writing the rest of the file */
  200049. png_write_end(png_ptr, info_ptr);
  200050. transforms = transforms; /* quiet compiler warnings */
  200051. params = params;
  200052. }
  200053. #endif
  200054. #endif /* PNG_WRITE_SUPPORTED */
  200055. /*** End of inlined file: pngwrite.c ***/
  200056. /*** Start of inlined file: pngwtran.c ***/
  200057. /* pngwtran.c - transforms the data in a row for PNG writers
  200058. *
  200059. * Last changed in libpng 1.2.9 April 14, 2006
  200060. * For conditions of distribution and use, see copyright notice in png.h
  200061. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200062. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200063. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200064. */
  200065. #define PNG_INTERNAL
  200066. #ifdef PNG_WRITE_SUPPORTED
  200067. /* Transform the data according to the user's wishes. The order of
  200068. * transformations is significant.
  200069. */
  200070. void /* PRIVATE */
  200071. png_do_write_transformations(png_structp png_ptr)
  200072. {
  200073. png_debug(1, "in png_do_write_transformations\n");
  200074. if (png_ptr == NULL)
  200075. return;
  200076. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200077. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200078. if(png_ptr->write_user_transform_fn != NULL)
  200079. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200080. (png_ptr, /* png_ptr */
  200081. &(png_ptr->row_info), /* row_info: */
  200082. /* png_uint_32 width; width of row */
  200083. /* png_uint_32 rowbytes; number of bytes in row */
  200084. /* png_byte color_type; color type of pixels */
  200085. /* png_byte bit_depth; bit depth of samples */
  200086. /* png_byte channels; number of channels (1-4) */
  200087. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200088. png_ptr->row_buf + 1); /* start of pixel data for row */
  200089. #endif
  200090. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200091. if (png_ptr->transformations & PNG_FILLER)
  200092. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200093. png_ptr->flags);
  200094. #endif
  200095. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200096. if (png_ptr->transformations & PNG_PACKSWAP)
  200097. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200098. #endif
  200099. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200100. if (png_ptr->transformations & PNG_PACK)
  200101. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200102. (png_uint_32)png_ptr->bit_depth);
  200103. #endif
  200104. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200105. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200106. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200107. #endif
  200108. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200109. if (png_ptr->transformations & PNG_SHIFT)
  200110. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200111. &(png_ptr->shift));
  200112. #endif
  200113. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200114. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200115. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200116. #endif
  200117. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200118. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200119. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200120. #endif
  200121. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200122. if (png_ptr->transformations & PNG_BGR)
  200123. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200124. #endif
  200125. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200126. if (png_ptr->transformations & PNG_INVERT_MONO)
  200127. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200128. #endif
  200129. }
  200130. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200131. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200132. * row_info bit depth should be 8 (one pixel per byte). The channels
  200133. * should be 1 (this only happens on grayscale and paletted images).
  200134. */
  200135. void /* PRIVATE */
  200136. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200137. {
  200138. png_debug(1, "in png_do_pack\n");
  200139. if (row_info->bit_depth == 8 &&
  200140. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200141. row != NULL && row_info != NULL &&
  200142. #endif
  200143. row_info->channels == 1)
  200144. {
  200145. switch ((int)bit_depth)
  200146. {
  200147. case 1:
  200148. {
  200149. png_bytep sp, dp;
  200150. int mask, v;
  200151. png_uint_32 i;
  200152. png_uint_32 row_width = row_info->width;
  200153. sp = row;
  200154. dp = row;
  200155. mask = 0x80;
  200156. v = 0;
  200157. for (i = 0; i < row_width; i++)
  200158. {
  200159. if (*sp != 0)
  200160. v |= mask;
  200161. sp++;
  200162. if (mask > 1)
  200163. mask >>= 1;
  200164. else
  200165. {
  200166. mask = 0x80;
  200167. *dp = (png_byte)v;
  200168. dp++;
  200169. v = 0;
  200170. }
  200171. }
  200172. if (mask != 0x80)
  200173. *dp = (png_byte)v;
  200174. break;
  200175. }
  200176. case 2:
  200177. {
  200178. png_bytep sp, dp;
  200179. int shift, v;
  200180. png_uint_32 i;
  200181. png_uint_32 row_width = row_info->width;
  200182. sp = row;
  200183. dp = row;
  200184. shift = 6;
  200185. v = 0;
  200186. for (i = 0; i < row_width; i++)
  200187. {
  200188. png_byte value;
  200189. value = (png_byte)(*sp & 0x03);
  200190. v |= (value << shift);
  200191. if (shift == 0)
  200192. {
  200193. shift = 6;
  200194. *dp = (png_byte)v;
  200195. dp++;
  200196. v = 0;
  200197. }
  200198. else
  200199. shift -= 2;
  200200. sp++;
  200201. }
  200202. if (shift != 6)
  200203. *dp = (png_byte)v;
  200204. break;
  200205. }
  200206. case 4:
  200207. {
  200208. png_bytep sp, dp;
  200209. int shift, v;
  200210. png_uint_32 i;
  200211. png_uint_32 row_width = row_info->width;
  200212. sp = row;
  200213. dp = row;
  200214. shift = 4;
  200215. v = 0;
  200216. for (i = 0; i < row_width; i++)
  200217. {
  200218. png_byte value;
  200219. value = (png_byte)(*sp & 0x0f);
  200220. v |= (value << shift);
  200221. if (shift == 0)
  200222. {
  200223. shift = 4;
  200224. *dp = (png_byte)v;
  200225. dp++;
  200226. v = 0;
  200227. }
  200228. else
  200229. shift -= 4;
  200230. sp++;
  200231. }
  200232. if (shift != 4)
  200233. *dp = (png_byte)v;
  200234. break;
  200235. }
  200236. }
  200237. row_info->bit_depth = (png_byte)bit_depth;
  200238. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200239. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200240. row_info->width);
  200241. }
  200242. }
  200243. #endif
  200244. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200245. /* Shift pixel values to take advantage of whole range. Pass the
  200246. * true number of bits in bit_depth. The row should be packed
  200247. * according to row_info->bit_depth. Thus, if you had a row of
  200248. * bit depth 4, but the pixels only had values from 0 to 7, you
  200249. * would pass 3 as bit_depth, and this routine would translate the
  200250. * data to 0 to 15.
  200251. */
  200252. void /* PRIVATE */
  200253. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200254. {
  200255. png_debug(1, "in png_do_shift\n");
  200256. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200257. if (row != NULL && row_info != NULL &&
  200258. #else
  200259. if (
  200260. #endif
  200261. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200262. {
  200263. int shift_start[4], shift_dec[4];
  200264. int channels = 0;
  200265. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200266. {
  200267. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200268. shift_dec[channels] = bit_depth->red;
  200269. channels++;
  200270. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200271. shift_dec[channels] = bit_depth->green;
  200272. channels++;
  200273. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200274. shift_dec[channels] = bit_depth->blue;
  200275. channels++;
  200276. }
  200277. else
  200278. {
  200279. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200280. shift_dec[channels] = bit_depth->gray;
  200281. channels++;
  200282. }
  200283. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200284. {
  200285. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200286. shift_dec[channels] = bit_depth->alpha;
  200287. channels++;
  200288. }
  200289. /* with low row depths, could only be grayscale, so one channel */
  200290. if (row_info->bit_depth < 8)
  200291. {
  200292. png_bytep bp = row;
  200293. png_uint_32 i;
  200294. png_byte mask;
  200295. png_uint_32 row_bytes = row_info->rowbytes;
  200296. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200297. mask = 0x55;
  200298. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200299. mask = 0x11;
  200300. else
  200301. mask = 0xff;
  200302. for (i = 0; i < row_bytes; i++, bp++)
  200303. {
  200304. png_uint_16 v;
  200305. int j;
  200306. v = *bp;
  200307. *bp = 0;
  200308. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200309. {
  200310. if (j > 0)
  200311. *bp |= (png_byte)((v << j) & 0xff);
  200312. else
  200313. *bp |= (png_byte)((v >> (-j)) & mask);
  200314. }
  200315. }
  200316. }
  200317. else if (row_info->bit_depth == 8)
  200318. {
  200319. png_bytep bp = row;
  200320. png_uint_32 i;
  200321. png_uint_32 istop = channels * row_info->width;
  200322. for (i = 0; i < istop; i++, bp++)
  200323. {
  200324. png_uint_16 v;
  200325. int j;
  200326. int c = (int)(i%channels);
  200327. v = *bp;
  200328. *bp = 0;
  200329. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200330. {
  200331. if (j > 0)
  200332. *bp |= (png_byte)((v << j) & 0xff);
  200333. else
  200334. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200335. }
  200336. }
  200337. }
  200338. else
  200339. {
  200340. png_bytep bp;
  200341. png_uint_32 i;
  200342. png_uint_32 istop = channels * row_info->width;
  200343. for (bp = row, i = 0; i < istop; i++)
  200344. {
  200345. int c = (int)(i%channels);
  200346. png_uint_16 value, v;
  200347. int j;
  200348. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200349. value = 0;
  200350. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200351. {
  200352. if (j > 0)
  200353. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200354. else
  200355. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200356. }
  200357. *bp++ = (png_byte)(value >> 8);
  200358. *bp++ = (png_byte)(value & 0xff);
  200359. }
  200360. }
  200361. }
  200362. }
  200363. #endif
  200364. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200365. void /* PRIVATE */
  200366. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200367. {
  200368. png_debug(1, "in png_do_write_swap_alpha\n");
  200369. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200370. if (row != NULL && row_info != NULL)
  200371. #endif
  200372. {
  200373. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200374. {
  200375. /* This converts from ARGB to RGBA */
  200376. if (row_info->bit_depth == 8)
  200377. {
  200378. png_bytep sp, dp;
  200379. png_uint_32 i;
  200380. png_uint_32 row_width = row_info->width;
  200381. for (i = 0, sp = dp = row; i < row_width; i++)
  200382. {
  200383. png_byte save = *(sp++);
  200384. *(dp++) = *(sp++);
  200385. *(dp++) = *(sp++);
  200386. *(dp++) = *(sp++);
  200387. *(dp++) = save;
  200388. }
  200389. }
  200390. /* This converts from AARRGGBB to RRGGBBAA */
  200391. else
  200392. {
  200393. png_bytep sp, dp;
  200394. png_uint_32 i;
  200395. png_uint_32 row_width = row_info->width;
  200396. for (i = 0, sp = dp = row; i < row_width; i++)
  200397. {
  200398. png_byte save[2];
  200399. save[0] = *(sp++);
  200400. save[1] = *(sp++);
  200401. *(dp++) = *(sp++);
  200402. *(dp++) = *(sp++);
  200403. *(dp++) = *(sp++);
  200404. *(dp++) = *(sp++);
  200405. *(dp++) = *(sp++);
  200406. *(dp++) = *(sp++);
  200407. *(dp++) = save[0];
  200408. *(dp++) = save[1];
  200409. }
  200410. }
  200411. }
  200412. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200413. {
  200414. /* This converts from AG to GA */
  200415. if (row_info->bit_depth == 8)
  200416. {
  200417. png_bytep sp, dp;
  200418. png_uint_32 i;
  200419. png_uint_32 row_width = row_info->width;
  200420. for (i = 0, sp = dp = row; i < row_width; i++)
  200421. {
  200422. png_byte save = *(sp++);
  200423. *(dp++) = *(sp++);
  200424. *(dp++) = save;
  200425. }
  200426. }
  200427. /* This converts from AAGG to GGAA */
  200428. else
  200429. {
  200430. png_bytep sp, dp;
  200431. png_uint_32 i;
  200432. png_uint_32 row_width = row_info->width;
  200433. for (i = 0, sp = dp = row; i < row_width; i++)
  200434. {
  200435. png_byte save[2];
  200436. save[0] = *(sp++);
  200437. save[1] = *(sp++);
  200438. *(dp++) = *(sp++);
  200439. *(dp++) = *(sp++);
  200440. *(dp++) = save[0];
  200441. *(dp++) = save[1];
  200442. }
  200443. }
  200444. }
  200445. }
  200446. }
  200447. #endif
  200448. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200449. void /* PRIVATE */
  200450. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200451. {
  200452. png_debug(1, "in png_do_write_invert_alpha\n");
  200453. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200454. if (row != NULL && row_info != NULL)
  200455. #endif
  200456. {
  200457. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200458. {
  200459. /* This inverts the alpha channel in RGBA */
  200460. if (row_info->bit_depth == 8)
  200461. {
  200462. png_bytep sp, dp;
  200463. png_uint_32 i;
  200464. png_uint_32 row_width = row_info->width;
  200465. for (i = 0, sp = dp = row; i < row_width; i++)
  200466. {
  200467. /* does nothing
  200468. *(dp++) = *(sp++);
  200469. *(dp++) = *(sp++);
  200470. *(dp++) = *(sp++);
  200471. */
  200472. sp+=3; dp = sp;
  200473. *(dp++) = (png_byte)(255 - *(sp++));
  200474. }
  200475. }
  200476. /* This inverts the alpha channel in RRGGBBAA */
  200477. else
  200478. {
  200479. png_bytep sp, dp;
  200480. png_uint_32 i;
  200481. png_uint_32 row_width = row_info->width;
  200482. for (i = 0, sp = dp = row; i < row_width; i++)
  200483. {
  200484. /* does nothing
  200485. *(dp++) = *(sp++);
  200486. *(dp++) = *(sp++);
  200487. *(dp++) = *(sp++);
  200488. *(dp++) = *(sp++);
  200489. *(dp++) = *(sp++);
  200490. *(dp++) = *(sp++);
  200491. */
  200492. sp+=6; dp = sp;
  200493. *(dp++) = (png_byte)(255 - *(sp++));
  200494. *(dp++) = (png_byte)(255 - *(sp++));
  200495. }
  200496. }
  200497. }
  200498. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200499. {
  200500. /* This inverts the alpha channel in GA */
  200501. if (row_info->bit_depth == 8)
  200502. {
  200503. png_bytep sp, dp;
  200504. png_uint_32 i;
  200505. png_uint_32 row_width = row_info->width;
  200506. for (i = 0, sp = dp = row; i < row_width; i++)
  200507. {
  200508. *(dp++) = *(sp++);
  200509. *(dp++) = (png_byte)(255 - *(sp++));
  200510. }
  200511. }
  200512. /* This inverts the alpha channel in GGAA */
  200513. else
  200514. {
  200515. png_bytep sp, dp;
  200516. png_uint_32 i;
  200517. png_uint_32 row_width = row_info->width;
  200518. for (i = 0, sp = dp = row; i < row_width; i++)
  200519. {
  200520. /* does nothing
  200521. *(dp++) = *(sp++);
  200522. *(dp++) = *(sp++);
  200523. */
  200524. sp+=2; dp = sp;
  200525. *(dp++) = (png_byte)(255 - *(sp++));
  200526. *(dp++) = (png_byte)(255 - *(sp++));
  200527. }
  200528. }
  200529. }
  200530. }
  200531. }
  200532. #endif
  200533. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200534. /* undoes intrapixel differencing */
  200535. void /* PRIVATE */
  200536. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200537. {
  200538. png_debug(1, "in png_do_write_intrapixel\n");
  200539. if (
  200540. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200541. row != NULL && row_info != NULL &&
  200542. #endif
  200543. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200544. {
  200545. int bytes_per_pixel;
  200546. png_uint_32 row_width = row_info->width;
  200547. if (row_info->bit_depth == 8)
  200548. {
  200549. png_bytep rp;
  200550. png_uint_32 i;
  200551. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200552. bytes_per_pixel = 3;
  200553. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200554. bytes_per_pixel = 4;
  200555. else
  200556. return;
  200557. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200558. {
  200559. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200560. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200561. }
  200562. }
  200563. else if (row_info->bit_depth == 16)
  200564. {
  200565. png_bytep rp;
  200566. png_uint_32 i;
  200567. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200568. bytes_per_pixel = 6;
  200569. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200570. bytes_per_pixel = 8;
  200571. else
  200572. return;
  200573. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200574. {
  200575. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200576. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200577. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200578. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200579. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200580. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200581. *(rp+1) = (png_byte)(red & 0xff);
  200582. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200583. *(rp+5) = (png_byte)(blue & 0xff);
  200584. }
  200585. }
  200586. }
  200587. }
  200588. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200589. #endif /* PNG_WRITE_SUPPORTED */
  200590. /*** End of inlined file: pngwtran.c ***/
  200591. /*** Start of inlined file: pngwutil.c ***/
  200592. /* pngwutil.c - utilities to write a PNG file
  200593. *
  200594. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200595. * For conditions of distribution and use, see copyright notice in png.h
  200596. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200597. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200598. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200599. */
  200600. #define PNG_INTERNAL
  200601. #ifdef PNG_WRITE_SUPPORTED
  200602. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200603. * with unsigned numbers for convenience, although one supported
  200604. * ancillary chunk uses signed (two's complement) numbers.
  200605. */
  200606. void PNGAPI
  200607. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200608. {
  200609. buf[0] = (png_byte)((i >> 24) & 0xff);
  200610. buf[1] = (png_byte)((i >> 16) & 0xff);
  200611. buf[2] = (png_byte)((i >> 8) & 0xff);
  200612. buf[3] = (png_byte)(i & 0xff);
  200613. }
  200614. /* The png_save_int_32 function assumes integers are stored in two's
  200615. * complement format. If this isn't the case, then this routine needs to
  200616. * be modified to write data in two's complement format.
  200617. */
  200618. void PNGAPI
  200619. png_save_int_32(png_bytep buf, png_int_32 i)
  200620. {
  200621. buf[0] = (png_byte)((i >> 24) & 0xff);
  200622. buf[1] = (png_byte)((i >> 16) & 0xff);
  200623. buf[2] = (png_byte)((i >> 8) & 0xff);
  200624. buf[3] = (png_byte)(i & 0xff);
  200625. }
  200626. /* Place a 16-bit number into a buffer in PNG byte order.
  200627. * The parameter is declared unsigned int, not png_uint_16,
  200628. * just to avoid potential problems on pre-ANSI C compilers.
  200629. */
  200630. void PNGAPI
  200631. png_save_uint_16(png_bytep buf, unsigned int i)
  200632. {
  200633. buf[0] = (png_byte)((i >> 8) & 0xff);
  200634. buf[1] = (png_byte)(i & 0xff);
  200635. }
  200636. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200637. * representing the chunk name. The array must be at least 4 bytes in
  200638. * length, and does not need to be null terminated. To be safe, pass the
  200639. * pre-defined chunk names here, and if you need a new one, define it
  200640. * where the others are defined. The length is the length of the data.
  200641. * All the data must be present. If that is not possible, use the
  200642. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200643. * functions instead.
  200644. */
  200645. void PNGAPI
  200646. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200647. png_bytep data, png_size_t length)
  200648. {
  200649. if(png_ptr == NULL) return;
  200650. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200651. png_write_chunk_data(png_ptr, data, length);
  200652. png_write_chunk_end(png_ptr);
  200653. }
  200654. /* Write the start of a PNG chunk. The type is the chunk type.
  200655. * The total_length is the sum of the lengths of all the data you will be
  200656. * passing in png_write_chunk_data().
  200657. */
  200658. void PNGAPI
  200659. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200660. png_uint_32 length)
  200661. {
  200662. png_byte buf[4];
  200663. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200664. if(png_ptr == NULL) return;
  200665. /* write the length */
  200666. png_save_uint_32(buf, length);
  200667. png_write_data(png_ptr, buf, (png_size_t)4);
  200668. /* write the chunk name */
  200669. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200670. /* reset the crc and run it over the chunk name */
  200671. png_reset_crc(png_ptr);
  200672. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200673. }
  200674. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200675. * Note that multiple calls to this function are allowed, and that the
  200676. * sum of the lengths from these calls *must* add up to the total_length
  200677. * given to png_write_chunk_start().
  200678. */
  200679. void PNGAPI
  200680. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200681. {
  200682. /* write the data, and run the CRC over it */
  200683. if(png_ptr == NULL) return;
  200684. if (data != NULL && length > 0)
  200685. {
  200686. png_calculate_crc(png_ptr, data, length);
  200687. png_write_data(png_ptr, data, length);
  200688. }
  200689. }
  200690. /* Finish a chunk started with png_write_chunk_start(). */
  200691. void PNGAPI
  200692. png_write_chunk_end(png_structp png_ptr)
  200693. {
  200694. png_byte buf[4];
  200695. if(png_ptr == NULL) return;
  200696. /* write the crc */
  200697. png_save_uint_32(buf, png_ptr->crc);
  200698. png_write_data(png_ptr, buf, (png_size_t)4);
  200699. }
  200700. /* Simple function to write the signature. If we have already written
  200701. * the magic bytes of the signature, or more likely, the PNG stream is
  200702. * being embedded into another stream and doesn't need its own signature,
  200703. * we should call png_set_sig_bytes() to tell libpng how many of the
  200704. * bytes have already been written.
  200705. */
  200706. void /* PRIVATE */
  200707. png_write_sig(png_structp png_ptr)
  200708. {
  200709. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200710. /* write the rest of the 8 byte signature */
  200711. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200712. (png_size_t)8 - png_ptr->sig_bytes);
  200713. if(png_ptr->sig_bytes < 3)
  200714. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200715. }
  200716. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200717. /*
  200718. * This pair of functions encapsulates the operation of (a) compressing a
  200719. * text string, and (b) issuing it later as a series of chunk data writes.
  200720. * The compression_state structure is shared context for these functions
  200721. * set up by the caller in order to make the whole mess thread-safe.
  200722. */
  200723. typedef struct
  200724. {
  200725. char *input; /* the uncompressed input data */
  200726. int input_len; /* its length */
  200727. int num_output_ptr; /* number of output pointers used */
  200728. int max_output_ptr; /* size of output_ptr */
  200729. png_charpp output_ptr; /* array of pointers to output */
  200730. } compression_state;
  200731. /* compress given text into storage in the png_ptr structure */
  200732. static int /* PRIVATE */
  200733. png_text_compress(png_structp png_ptr,
  200734. png_charp text, png_size_t text_len, int compression,
  200735. compression_state *comp)
  200736. {
  200737. int ret;
  200738. comp->num_output_ptr = 0;
  200739. comp->max_output_ptr = 0;
  200740. comp->output_ptr = NULL;
  200741. comp->input = NULL;
  200742. comp->input_len = 0;
  200743. /* we may just want to pass the text right through */
  200744. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200745. {
  200746. comp->input = text;
  200747. comp->input_len = text_len;
  200748. return((int)text_len);
  200749. }
  200750. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200751. {
  200752. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200753. char msg[50];
  200754. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200755. png_warning(png_ptr, msg);
  200756. #else
  200757. png_warning(png_ptr, "Unknown compression type");
  200758. #endif
  200759. }
  200760. /* We can't write the chunk until we find out how much data we have,
  200761. * which means we need to run the compressor first and save the
  200762. * output. This shouldn't be a problem, as the vast majority of
  200763. * comments should be reasonable, but we will set up an array of
  200764. * malloc'd pointers to be sure.
  200765. *
  200766. * If we knew the application was well behaved, we could simplify this
  200767. * greatly by assuming we can always malloc an output buffer large
  200768. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200769. * and malloc this directly. The only time this would be a bad idea is
  200770. * if we can't malloc more than 64K and we have 64K of random input
  200771. * data, or if the input string is incredibly large (although this
  200772. * wouldn't cause a failure, just a slowdown due to swapping).
  200773. */
  200774. /* set up the compression buffers */
  200775. png_ptr->zstream.avail_in = (uInt)text_len;
  200776. png_ptr->zstream.next_in = (Bytef *)text;
  200777. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200778. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200779. /* this is the same compression loop as in png_write_row() */
  200780. do
  200781. {
  200782. /* compress the data */
  200783. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200784. if (ret != Z_OK)
  200785. {
  200786. /* error */
  200787. if (png_ptr->zstream.msg != NULL)
  200788. png_error(png_ptr, png_ptr->zstream.msg);
  200789. else
  200790. png_error(png_ptr, "zlib error");
  200791. }
  200792. /* check to see if we need more room */
  200793. if (!(png_ptr->zstream.avail_out))
  200794. {
  200795. /* make sure the output array has room */
  200796. if (comp->num_output_ptr >= comp->max_output_ptr)
  200797. {
  200798. int old_max;
  200799. old_max = comp->max_output_ptr;
  200800. comp->max_output_ptr = comp->num_output_ptr + 4;
  200801. if (comp->output_ptr != NULL)
  200802. {
  200803. png_charpp old_ptr;
  200804. old_ptr = comp->output_ptr;
  200805. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200806. (png_uint_32)(comp->max_output_ptr *
  200807. png_sizeof (png_charpp)));
  200808. png_memcpy(comp->output_ptr, old_ptr, old_max
  200809. * png_sizeof (png_charp));
  200810. png_free(png_ptr, old_ptr);
  200811. }
  200812. else
  200813. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200814. (png_uint_32)(comp->max_output_ptr *
  200815. png_sizeof (png_charp)));
  200816. }
  200817. /* save the data */
  200818. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200819. (png_uint_32)png_ptr->zbuf_size);
  200820. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200821. png_ptr->zbuf_size);
  200822. comp->num_output_ptr++;
  200823. /* and reset the buffer */
  200824. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200825. png_ptr->zstream.next_out = png_ptr->zbuf;
  200826. }
  200827. /* continue until we don't have any more to compress */
  200828. } while (png_ptr->zstream.avail_in);
  200829. /* finish the compression */
  200830. do
  200831. {
  200832. /* tell zlib we are finished */
  200833. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200834. if (ret == Z_OK)
  200835. {
  200836. /* check to see if we need more room */
  200837. if (!(png_ptr->zstream.avail_out))
  200838. {
  200839. /* check to make sure our output array has room */
  200840. if (comp->num_output_ptr >= comp->max_output_ptr)
  200841. {
  200842. int old_max;
  200843. old_max = comp->max_output_ptr;
  200844. comp->max_output_ptr = comp->num_output_ptr + 4;
  200845. if (comp->output_ptr != NULL)
  200846. {
  200847. png_charpp old_ptr;
  200848. old_ptr = comp->output_ptr;
  200849. /* This could be optimized to realloc() */
  200850. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200851. (png_uint_32)(comp->max_output_ptr *
  200852. png_sizeof (png_charpp)));
  200853. png_memcpy(comp->output_ptr, old_ptr,
  200854. old_max * png_sizeof (png_charp));
  200855. png_free(png_ptr, old_ptr);
  200856. }
  200857. else
  200858. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200859. (png_uint_32)(comp->max_output_ptr *
  200860. png_sizeof (png_charp)));
  200861. }
  200862. /* save off the data */
  200863. comp->output_ptr[comp->num_output_ptr] =
  200864. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200865. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200866. png_ptr->zbuf_size);
  200867. comp->num_output_ptr++;
  200868. /* and reset the buffer pointers */
  200869. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200870. png_ptr->zstream.next_out = png_ptr->zbuf;
  200871. }
  200872. }
  200873. else if (ret != Z_STREAM_END)
  200874. {
  200875. /* we got an error */
  200876. if (png_ptr->zstream.msg != NULL)
  200877. png_error(png_ptr, png_ptr->zstream.msg);
  200878. else
  200879. png_error(png_ptr, "zlib error");
  200880. }
  200881. } while (ret != Z_STREAM_END);
  200882. /* text length is number of buffers plus last buffer */
  200883. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200884. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200885. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200886. return((int)text_len);
  200887. }
  200888. /* ship the compressed text out via chunk writes */
  200889. static void /* PRIVATE */
  200890. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200891. {
  200892. int i;
  200893. /* handle the no-compression case */
  200894. if (comp->input)
  200895. {
  200896. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200897. (png_size_t)comp->input_len);
  200898. return;
  200899. }
  200900. /* write saved output buffers, if any */
  200901. for (i = 0; i < comp->num_output_ptr; i++)
  200902. {
  200903. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200904. png_ptr->zbuf_size);
  200905. png_free(png_ptr, comp->output_ptr[i]);
  200906. comp->output_ptr[i]=NULL;
  200907. }
  200908. if (comp->max_output_ptr != 0)
  200909. png_free(png_ptr, comp->output_ptr);
  200910. comp->output_ptr=NULL;
  200911. /* write anything left in zbuf */
  200912. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200913. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200914. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200915. /* reset zlib for another zTXt/iTXt or image data */
  200916. deflateReset(&png_ptr->zstream);
  200917. png_ptr->zstream.data_type = Z_BINARY;
  200918. }
  200919. #endif
  200920. /* Write the IHDR chunk, and update the png_struct with the necessary
  200921. * information. Note that the rest of this code depends upon this
  200922. * information being correct.
  200923. */
  200924. void /* PRIVATE */
  200925. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200926. int bit_depth, int color_type, int compression_type, int filter_type,
  200927. int interlace_type)
  200928. {
  200929. #ifdef PNG_USE_LOCAL_ARRAYS
  200930. PNG_IHDR;
  200931. #endif
  200932. png_byte buf[13]; /* buffer to store the IHDR info */
  200933. png_debug(1, "in png_write_IHDR\n");
  200934. /* Check that we have valid input data from the application info */
  200935. switch (color_type)
  200936. {
  200937. case PNG_COLOR_TYPE_GRAY:
  200938. switch (bit_depth)
  200939. {
  200940. case 1:
  200941. case 2:
  200942. case 4:
  200943. case 8:
  200944. case 16: png_ptr->channels = 1; break;
  200945. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200946. }
  200947. break;
  200948. case PNG_COLOR_TYPE_RGB:
  200949. if (bit_depth != 8 && bit_depth != 16)
  200950. png_error(png_ptr, "Invalid bit depth for RGB image");
  200951. png_ptr->channels = 3;
  200952. break;
  200953. case PNG_COLOR_TYPE_PALETTE:
  200954. switch (bit_depth)
  200955. {
  200956. case 1:
  200957. case 2:
  200958. case 4:
  200959. case 8: png_ptr->channels = 1; break;
  200960. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200961. }
  200962. break;
  200963. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200964. if (bit_depth != 8 && bit_depth != 16)
  200965. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200966. png_ptr->channels = 2;
  200967. break;
  200968. case PNG_COLOR_TYPE_RGB_ALPHA:
  200969. if (bit_depth != 8 && bit_depth != 16)
  200970. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200971. png_ptr->channels = 4;
  200972. break;
  200973. default:
  200974. png_error(png_ptr, "Invalid image color type specified");
  200975. }
  200976. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200977. {
  200978. png_warning(png_ptr, "Invalid compression type specified");
  200979. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200980. }
  200981. /* Write filter_method 64 (intrapixel differencing) only if
  200982. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200983. * 2. Libpng did not write a PNG signature (this filter_method is only
  200984. * used in PNG datastreams that are embedded in MNG datastreams) and
  200985. * 3. The application called png_permit_mng_features with a mask that
  200986. * included PNG_FLAG_MNG_FILTER_64 and
  200987. * 4. The filter_method is 64 and
  200988. * 5. The color_type is RGB or RGBA
  200989. */
  200990. if (
  200991. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200992. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200993. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200994. (color_type == PNG_COLOR_TYPE_RGB ||
  200995. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200996. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200997. #endif
  200998. filter_type != PNG_FILTER_TYPE_BASE)
  200999. {
  201000. png_warning(png_ptr, "Invalid filter type specified");
  201001. filter_type = PNG_FILTER_TYPE_BASE;
  201002. }
  201003. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201004. if (interlace_type != PNG_INTERLACE_NONE &&
  201005. interlace_type != PNG_INTERLACE_ADAM7)
  201006. {
  201007. png_warning(png_ptr, "Invalid interlace type specified");
  201008. interlace_type = PNG_INTERLACE_ADAM7;
  201009. }
  201010. #else
  201011. interlace_type=PNG_INTERLACE_NONE;
  201012. #endif
  201013. /* save off the relevent information */
  201014. png_ptr->bit_depth = (png_byte)bit_depth;
  201015. png_ptr->color_type = (png_byte)color_type;
  201016. png_ptr->interlaced = (png_byte)interlace_type;
  201017. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201018. png_ptr->filter_type = (png_byte)filter_type;
  201019. #endif
  201020. png_ptr->compression_type = (png_byte)compression_type;
  201021. png_ptr->width = width;
  201022. png_ptr->height = height;
  201023. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201024. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201025. /* set the usr info, so any transformations can modify it */
  201026. png_ptr->usr_width = png_ptr->width;
  201027. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201028. png_ptr->usr_channels = png_ptr->channels;
  201029. /* pack the header information into the buffer */
  201030. png_save_uint_32(buf, width);
  201031. png_save_uint_32(buf + 4, height);
  201032. buf[8] = (png_byte)bit_depth;
  201033. buf[9] = (png_byte)color_type;
  201034. buf[10] = (png_byte)compression_type;
  201035. buf[11] = (png_byte)filter_type;
  201036. buf[12] = (png_byte)interlace_type;
  201037. /* write the chunk */
  201038. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201039. /* initialize zlib with PNG info */
  201040. png_ptr->zstream.zalloc = png_zalloc;
  201041. png_ptr->zstream.zfree = png_zfree;
  201042. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201043. if (!(png_ptr->do_filter))
  201044. {
  201045. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201046. png_ptr->bit_depth < 8)
  201047. png_ptr->do_filter = PNG_FILTER_NONE;
  201048. else
  201049. png_ptr->do_filter = PNG_ALL_FILTERS;
  201050. }
  201051. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201052. {
  201053. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201054. png_ptr->zlib_strategy = Z_FILTERED;
  201055. else
  201056. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201057. }
  201058. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201059. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201060. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201061. png_ptr->zlib_mem_level = 8;
  201062. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201063. png_ptr->zlib_window_bits = 15;
  201064. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201065. png_ptr->zlib_method = 8;
  201066. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201067. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201068. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201069. png_error(png_ptr, "zlib failed to initialize compressor");
  201070. png_ptr->zstream.next_out = png_ptr->zbuf;
  201071. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201072. /* libpng is not interested in zstream.data_type */
  201073. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201074. png_ptr->zstream.data_type = Z_BINARY;
  201075. png_ptr->mode = PNG_HAVE_IHDR;
  201076. }
  201077. /* write the palette. We are careful not to trust png_color to be in the
  201078. * correct order for PNG, so people can redefine it to any convenient
  201079. * structure.
  201080. */
  201081. void /* PRIVATE */
  201082. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201083. {
  201084. #ifdef PNG_USE_LOCAL_ARRAYS
  201085. PNG_PLTE;
  201086. #endif
  201087. png_uint_32 i;
  201088. png_colorp pal_ptr;
  201089. png_byte buf[3];
  201090. png_debug(1, "in png_write_PLTE\n");
  201091. if ((
  201092. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201093. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201094. #endif
  201095. num_pal == 0) || num_pal > 256)
  201096. {
  201097. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201098. {
  201099. png_error(png_ptr, "Invalid number of colors in palette");
  201100. }
  201101. else
  201102. {
  201103. png_warning(png_ptr, "Invalid number of colors in palette");
  201104. return;
  201105. }
  201106. }
  201107. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201108. {
  201109. png_warning(png_ptr,
  201110. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201111. return;
  201112. }
  201113. png_ptr->num_palette = (png_uint_16)num_pal;
  201114. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201115. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201116. #ifndef PNG_NO_POINTER_INDEXING
  201117. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201118. {
  201119. buf[0] = pal_ptr->red;
  201120. buf[1] = pal_ptr->green;
  201121. buf[2] = pal_ptr->blue;
  201122. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201123. }
  201124. #else
  201125. /* This is a little slower but some buggy compilers need to do this instead */
  201126. pal_ptr=palette;
  201127. for (i = 0; i < num_pal; i++)
  201128. {
  201129. buf[0] = pal_ptr[i].red;
  201130. buf[1] = pal_ptr[i].green;
  201131. buf[2] = pal_ptr[i].blue;
  201132. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201133. }
  201134. #endif
  201135. png_write_chunk_end(png_ptr);
  201136. png_ptr->mode |= PNG_HAVE_PLTE;
  201137. }
  201138. /* write an IDAT chunk */
  201139. void /* PRIVATE */
  201140. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201141. {
  201142. #ifdef PNG_USE_LOCAL_ARRAYS
  201143. PNG_IDAT;
  201144. #endif
  201145. png_debug(1, "in png_write_IDAT\n");
  201146. /* Optimize the CMF field in the zlib stream. */
  201147. /* This hack of the zlib stream is compliant to the stream specification. */
  201148. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201149. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201150. {
  201151. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201152. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201153. {
  201154. /* Avoid memory underflows and multiplication overflows. */
  201155. /* The conditions below are practically always satisfied;
  201156. however, they still must be checked. */
  201157. if (length >= 2 &&
  201158. png_ptr->height < 16384 && png_ptr->width < 16384)
  201159. {
  201160. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201161. ((png_ptr->width *
  201162. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201163. unsigned int z_cinfo = z_cmf >> 4;
  201164. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201165. while (uncompressed_idat_size <= half_z_window_size &&
  201166. half_z_window_size >= 256)
  201167. {
  201168. z_cinfo--;
  201169. half_z_window_size >>= 1;
  201170. }
  201171. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201172. if (data[0] != (png_byte)z_cmf)
  201173. {
  201174. data[0] = (png_byte)z_cmf;
  201175. data[1] &= 0xe0;
  201176. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201177. }
  201178. }
  201179. }
  201180. else
  201181. png_error(png_ptr,
  201182. "Invalid zlib compression method or flags in IDAT");
  201183. }
  201184. png_write_chunk(png_ptr, png_IDAT, data, length);
  201185. png_ptr->mode |= PNG_HAVE_IDAT;
  201186. }
  201187. /* write an IEND chunk */
  201188. void /* PRIVATE */
  201189. png_write_IEND(png_structp png_ptr)
  201190. {
  201191. #ifdef PNG_USE_LOCAL_ARRAYS
  201192. PNG_IEND;
  201193. #endif
  201194. png_debug(1, "in png_write_IEND\n");
  201195. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201196. (png_size_t)0);
  201197. png_ptr->mode |= PNG_HAVE_IEND;
  201198. }
  201199. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201200. /* write a gAMA chunk */
  201201. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201202. void /* PRIVATE */
  201203. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201204. {
  201205. #ifdef PNG_USE_LOCAL_ARRAYS
  201206. PNG_gAMA;
  201207. #endif
  201208. png_uint_32 igamma;
  201209. png_byte buf[4];
  201210. png_debug(1, "in png_write_gAMA\n");
  201211. /* file_gamma is saved in 1/100,000ths */
  201212. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201213. png_save_uint_32(buf, igamma);
  201214. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201215. }
  201216. #endif
  201217. #ifdef PNG_FIXED_POINT_SUPPORTED
  201218. void /* PRIVATE */
  201219. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201220. {
  201221. #ifdef PNG_USE_LOCAL_ARRAYS
  201222. PNG_gAMA;
  201223. #endif
  201224. png_byte buf[4];
  201225. png_debug(1, "in png_write_gAMA\n");
  201226. /* file_gamma is saved in 1/100,000ths */
  201227. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201228. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201229. }
  201230. #endif
  201231. #endif
  201232. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201233. /* write a sRGB chunk */
  201234. void /* PRIVATE */
  201235. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201236. {
  201237. #ifdef PNG_USE_LOCAL_ARRAYS
  201238. PNG_sRGB;
  201239. #endif
  201240. png_byte buf[1];
  201241. png_debug(1, "in png_write_sRGB\n");
  201242. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201243. png_warning(png_ptr,
  201244. "Invalid sRGB rendering intent specified");
  201245. buf[0]=(png_byte)srgb_intent;
  201246. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201247. }
  201248. #endif
  201249. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201250. /* write an iCCP chunk */
  201251. void /* PRIVATE */
  201252. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201253. png_charp profile, int profile_len)
  201254. {
  201255. #ifdef PNG_USE_LOCAL_ARRAYS
  201256. PNG_iCCP;
  201257. #endif
  201258. png_size_t name_len;
  201259. png_charp new_name;
  201260. compression_state comp;
  201261. int embedded_profile_len = 0;
  201262. png_debug(1, "in png_write_iCCP\n");
  201263. comp.num_output_ptr = 0;
  201264. comp.max_output_ptr = 0;
  201265. comp.output_ptr = NULL;
  201266. comp.input = NULL;
  201267. comp.input_len = 0;
  201268. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201269. &new_name)) == 0)
  201270. {
  201271. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201272. return;
  201273. }
  201274. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201275. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201276. if (profile == NULL)
  201277. profile_len = 0;
  201278. if (profile_len > 3)
  201279. embedded_profile_len =
  201280. ((*( (png_bytep)profile ))<<24) |
  201281. ((*( (png_bytep)profile+1))<<16) |
  201282. ((*( (png_bytep)profile+2))<< 8) |
  201283. ((*( (png_bytep)profile+3)) );
  201284. if (profile_len < embedded_profile_len)
  201285. {
  201286. png_warning(png_ptr,
  201287. "Embedded profile length too large in iCCP chunk");
  201288. return;
  201289. }
  201290. if (profile_len > embedded_profile_len)
  201291. {
  201292. png_warning(png_ptr,
  201293. "Truncating profile to actual length in iCCP chunk");
  201294. profile_len = embedded_profile_len;
  201295. }
  201296. if (profile_len)
  201297. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201298. PNG_COMPRESSION_TYPE_BASE, &comp);
  201299. /* make sure we include the NULL after the name and the compression type */
  201300. png_write_chunk_start(png_ptr, png_iCCP,
  201301. (png_uint_32)name_len+profile_len+2);
  201302. new_name[name_len+1]=0x00;
  201303. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201304. if (profile_len)
  201305. png_write_compressed_data_out(png_ptr, &comp);
  201306. png_write_chunk_end(png_ptr);
  201307. png_free(png_ptr, new_name);
  201308. }
  201309. #endif
  201310. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201311. /* write a sPLT chunk */
  201312. void /* PRIVATE */
  201313. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201314. {
  201315. #ifdef PNG_USE_LOCAL_ARRAYS
  201316. PNG_sPLT;
  201317. #endif
  201318. png_size_t name_len;
  201319. png_charp new_name;
  201320. png_byte entrybuf[10];
  201321. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201322. int palette_size = entry_size * spalette->nentries;
  201323. png_sPLT_entryp ep;
  201324. #ifdef PNG_NO_POINTER_INDEXING
  201325. int i;
  201326. #endif
  201327. png_debug(1, "in png_write_sPLT\n");
  201328. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201329. spalette->name, &new_name))==0)
  201330. {
  201331. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201332. return;
  201333. }
  201334. /* make sure we include the NULL after the name */
  201335. png_write_chunk_start(png_ptr, png_sPLT,
  201336. (png_uint_32)(name_len + 2 + palette_size));
  201337. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201338. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201339. /* loop through each palette entry, writing appropriately */
  201340. #ifndef PNG_NO_POINTER_INDEXING
  201341. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201342. {
  201343. if (spalette->depth == 8)
  201344. {
  201345. entrybuf[0] = (png_byte)ep->red;
  201346. entrybuf[1] = (png_byte)ep->green;
  201347. entrybuf[2] = (png_byte)ep->blue;
  201348. entrybuf[3] = (png_byte)ep->alpha;
  201349. png_save_uint_16(entrybuf + 4, ep->frequency);
  201350. }
  201351. else
  201352. {
  201353. png_save_uint_16(entrybuf + 0, ep->red);
  201354. png_save_uint_16(entrybuf + 2, ep->green);
  201355. png_save_uint_16(entrybuf + 4, ep->blue);
  201356. png_save_uint_16(entrybuf + 6, ep->alpha);
  201357. png_save_uint_16(entrybuf + 8, ep->frequency);
  201358. }
  201359. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201360. }
  201361. #else
  201362. ep=spalette->entries;
  201363. for (i=0; i>spalette->nentries; i++)
  201364. {
  201365. if (spalette->depth == 8)
  201366. {
  201367. entrybuf[0] = (png_byte)ep[i].red;
  201368. entrybuf[1] = (png_byte)ep[i].green;
  201369. entrybuf[2] = (png_byte)ep[i].blue;
  201370. entrybuf[3] = (png_byte)ep[i].alpha;
  201371. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201372. }
  201373. else
  201374. {
  201375. png_save_uint_16(entrybuf + 0, ep[i].red);
  201376. png_save_uint_16(entrybuf + 2, ep[i].green);
  201377. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201378. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201379. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201380. }
  201381. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201382. }
  201383. #endif
  201384. png_write_chunk_end(png_ptr);
  201385. png_free(png_ptr, new_name);
  201386. }
  201387. #endif
  201388. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201389. /* write the sBIT chunk */
  201390. void /* PRIVATE */
  201391. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201392. {
  201393. #ifdef PNG_USE_LOCAL_ARRAYS
  201394. PNG_sBIT;
  201395. #endif
  201396. png_byte buf[4];
  201397. png_size_t size;
  201398. png_debug(1, "in png_write_sBIT\n");
  201399. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201400. if (color_type & PNG_COLOR_MASK_COLOR)
  201401. {
  201402. png_byte maxbits;
  201403. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201404. png_ptr->usr_bit_depth);
  201405. if (sbit->red == 0 || sbit->red > maxbits ||
  201406. sbit->green == 0 || sbit->green > maxbits ||
  201407. sbit->blue == 0 || sbit->blue > maxbits)
  201408. {
  201409. png_warning(png_ptr, "Invalid sBIT depth specified");
  201410. return;
  201411. }
  201412. buf[0] = sbit->red;
  201413. buf[1] = sbit->green;
  201414. buf[2] = sbit->blue;
  201415. size = 3;
  201416. }
  201417. else
  201418. {
  201419. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201420. {
  201421. png_warning(png_ptr, "Invalid sBIT depth specified");
  201422. return;
  201423. }
  201424. buf[0] = sbit->gray;
  201425. size = 1;
  201426. }
  201427. if (color_type & PNG_COLOR_MASK_ALPHA)
  201428. {
  201429. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201430. {
  201431. png_warning(png_ptr, "Invalid sBIT depth specified");
  201432. return;
  201433. }
  201434. buf[size++] = sbit->alpha;
  201435. }
  201436. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201437. }
  201438. #endif
  201439. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201440. /* write the cHRM chunk */
  201441. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201442. void /* PRIVATE */
  201443. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201444. double red_x, double red_y, double green_x, double green_y,
  201445. double blue_x, double blue_y)
  201446. {
  201447. #ifdef PNG_USE_LOCAL_ARRAYS
  201448. PNG_cHRM;
  201449. #endif
  201450. png_byte buf[32];
  201451. png_uint_32 itemp;
  201452. png_debug(1, "in png_write_cHRM\n");
  201453. /* each value is saved in 1/100,000ths */
  201454. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201455. white_x + white_y > 1.0)
  201456. {
  201457. png_warning(png_ptr, "Invalid cHRM white point specified");
  201458. #if !defined(PNG_NO_CONSOLE_IO)
  201459. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201460. #endif
  201461. return;
  201462. }
  201463. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201464. png_save_uint_32(buf, itemp);
  201465. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201466. png_save_uint_32(buf + 4, itemp);
  201467. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201468. {
  201469. png_warning(png_ptr, "Invalid cHRM red point specified");
  201470. return;
  201471. }
  201472. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201473. png_save_uint_32(buf + 8, itemp);
  201474. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201475. png_save_uint_32(buf + 12, itemp);
  201476. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201477. {
  201478. png_warning(png_ptr, "Invalid cHRM green point specified");
  201479. return;
  201480. }
  201481. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201482. png_save_uint_32(buf + 16, itemp);
  201483. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201484. png_save_uint_32(buf + 20, itemp);
  201485. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201486. {
  201487. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201488. return;
  201489. }
  201490. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201491. png_save_uint_32(buf + 24, itemp);
  201492. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201493. png_save_uint_32(buf + 28, itemp);
  201494. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201495. }
  201496. #endif
  201497. #ifdef PNG_FIXED_POINT_SUPPORTED
  201498. void /* PRIVATE */
  201499. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201500. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201501. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201502. png_fixed_point blue_y)
  201503. {
  201504. #ifdef PNG_USE_LOCAL_ARRAYS
  201505. PNG_cHRM;
  201506. #endif
  201507. png_byte buf[32];
  201508. png_debug(1, "in png_write_cHRM\n");
  201509. /* each value is saved in 1/100,000ths */
  201510. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201511. {
  201512. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201513. #if !defined(PNG_NO_CONSOLE_IO)
  201514. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201515. #endif
  201516. return;
  201517. }
  201518. png_save_uint_32(buf, (png_uint_32)white_x);
  201519. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201520. if (red_x + red_y > 100000L)
  201521. {
  201522. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201523. return;
  201524. }
  201525. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201526. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201527. if (green_x + green_y > 100000L)
  201528. {
  201529. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201530. return;
  201531. }
  201532. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201533. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201534. if (blue_x + blue_y > 100000L)
  201535. {
  201536. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201537. return;
  201538. }
  201539. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201540. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201541. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201542. }
  201543. #endif
  201544. #endif
  201545. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201546. /* write the tRNS chunk */
  201547. void /* PRIVATE */
  201548. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201549. int num_trans, int color_type)
  201550. {
  201551. #ifdef PNG_USE_LOCAL_ARRAYS
  201552. PNG_tRNS;
  201553. #endif
  201554. png_byte buf[6];
  201555. png_debug(1, "in png_write_tRNS\n");
  201556. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201557. {
  201558. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201559. {
  201560. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201561. return;
  201562. }
  201563. /* write the chunk out as it is */
  201564. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201565. }
  201566. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201567. {
  201568. /* one 16 bit value */
  201569. if(tran->gray >= (1 << png_ptr->bit_depth))
  201570. {
  201571. png_warning(png_ptr,
  201572. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201573. return;
  201574. }
  201575. png_save_uint_16(buf, tran->gray);
  201576. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201577. }
  201578. else if (color_type == PNG_COLOR_TYPE_RGB)
  201579. {
  201580. /* three 16 bit values */
  201581. png_save_uint_16(buf, tran->red);
  201582. png_save_uint_16(buf + 2, tran->green);
  201583. png_save_uint_16(buf + 4, tran->blue);
  201584. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201585. {
  201586. png_warning(png_ptr,
  201587. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201588. return;
  201589. }
  201590. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201591. }
  201592. else
  201593. {
  201594. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201595. }
  201596. }
  201597. #endif
  201598. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201599. /* write the background chunk */
  201600. void /* PRIVATE */
  201601. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201602. {
  201603. #ifdef PNG_USE_LOCAL_ARRAYS
  201604. PNG_bKGD;
  201605. #endif
  201606. png_byte buf[6];
  201607. png_debug(1, "in png_write_bKGD\n");
  201608. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201609. {
  201610. if (
  201611. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201612. (png_ptr->num_palette ||
  201613. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201614. #endif
  201615. back->index > png_ptr->num_palette)
  201616. {
  201617. png_warning(png_ptr, "Invalid background palette index");
  201618. return;
  201619. }
  201620. buf[0] = back->index;
  201621. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201622. }
  201623. else if (color_type & PNG_COLOR_MASK_COLOR)
  201624. {
  201625. png_save_uint_16(buf, back->red);
  201626. png_save_uint_16(buf + 2, back->green);
  201627. png_save_uint_16(buf + 4, back->blue);
  201628. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201629. {
  201630. png_warning(png_ptr,
  201631. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201632. return;
  201633. }
  201634. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201635. }
  201636. else
  201637. {
  201638. if(back->gray >= (1 << png_ptr->bit_depth))
  201639. {
  201640. png_warning(png_ptr,
  201641. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201642. return;
  201643. }
  201644. png_save_uint_16(buf, back->gray);
  201645. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201646. }
  201647. }
  201648. #endif
  201649. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201650. /* write the histogram */
  201651. void /* PRIVATE */
  201652. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201653. {
  201654. #ifdef PNG_USE_LOCAL_ARRAYS
  201655. PNG_hIST;
  201656. #endif
  201657. int i;
  201658. png_byte buf[3];
  201659. png_debug(1, "in png_write_hIST\n");
  201660. if (num_hist > (int)png_ptr->num_palette)
  201661. {
  201662. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201663. png_ptr->num_palette);
  201664. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201665. return;
  201666. }
  201667. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201668. for (i = 0; i < num_hist; i++)
  201669. {
  201670. png_save_uint_16(buf, hist[i]);
  201671. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201672. }
  201673. png_write_chunk_end(png_ptr);
  201674. }
  201675. #endif
  201676. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201677. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201678. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201679. * and if invalid, correct the keyword rather than discarding the entire
  201680. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201681. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201682. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201683. *
  201684. * The new_key is allocated to hold the corrected keyword and must be freed
  201685. * by the calling routine. This avoids problems with trying to write to
  201686. * static keywords without having to have duplicate copies of the strings.
  201687. */
  201688. png_size_t /* PRIVATE */
  201689. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201690. {
  201691. png_size_t key_len;
  201692. png_charp kp, dp;
  201693. int kflag;
  201694. int kwarn=0;
  201695. png_debug(1, "in png_check_keyword\n");
  201696. *new_key = NULL;
  201697. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201698. {
  201699. png_warning(png_ptr, "zero length keyword");
  201700. return ((png_size_t)0);
  201701. }
  201702. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201703. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201704. if (*new_key == NULL)
  201705. {
  201706. png_warning(png_ptr, "Out of memory while procesing keyword");
  201707. return ((png_size_t)0);
  201708. }
  201709. /* Replace non-printing characters with a blank and print a warning */
  201710. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201711. {
  201712. if ((png_byte)*kp < 0x20 ||
  201713. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201714. {
  201715. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201716. char msg[40];
  201717. png_snprintf(msg, 40,
  201718. "invalid keyword character 0x%02X", (png_byte)*kp);
  201719. png_warning(png_ptr, msg);
  201720. #else
  201721. png_warning(png_ptr, "invalid character in keyword");
  201722. #endif
  201723. *dp = ' ';
  201724. }
  201725. else
  201726. {
  201727. *dp = *kp;
  201728. }
  201729. }
  201730. *dp = '\0';
  201731. /* Remove any trailing white space. */
  201732. kp = *new_key + key_len - 1;
  201733. if (*kp == ' ')
  201734. {
  201735. png_warning(png_ptr, "trailing spaces removed from keyword");
  201736. while (*kp == ' ')
  201737. {
  201738. *(kp--) = '\0';
  201739. key_len--;
  201740. }
  201741. }
  201742. /* Remove any leading white space. */
  201743. kp = *new_key;
  201744. if (*kp == ' ')
  201745. {
  201746. png_warning(png_ptr, "leading spaces removed from keyword");
  201747. while (*kp == ' ')
  201748. {
  201749. kp++;
  201750. key_len--;
  201751. }
  201752. }
  201753. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201754. /* Remove multiple internal spaces. */
  201755. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201756. {
  201757. if (*kp == ' ' && kflag == 0)
  201758. {
  201759. *(dp++) = *kp;
  201760. kflag = 1;
  201761. }
  201762. else if (*kp == ' ')
  201763. {
  201764. key_len--;
  201765. kwarn=1;
  201766. }
  201767. else
  201768. {
  201769. *(dp++) = *kp;
  201770. kflag = 0;
  201771. }
  201772. }
  201773. *dp = '\0';
  201774. if(kwarn)
  201775. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201776. if (key_len == 0)
  201777. {
  201778. png_free(png_ptr, *new_key);
  201779. *new_key=NULL;
  201780. png_warning(png_ptr, "Zero length keyword");
  201781. }
  201782. if (key_len > 79)
  201783. {
  201784. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201785. new_key[79] = '\0';
  201786. key_len = 79;
  201787. }
  201788. return (key_len);
  201789. }
  201790. #endif
  201791. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201792. /* write a tEXt chunk */
  201793. void /* PRIVATE */
  201794. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201795. png_size_t text_len)
  201796. {
  201797. #ifdef PNG_USE_LOCAL_ARRAYS
  201798. PNG_tEXt;
  201799. #endif
  201800. png_size_t key_len;
  201801. png_charp new_key;
  201802. png_debug(1, "in png_write_tEXt\n");
  201803. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201804. {
  201805. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201806. return;
  201807. }
  201808. if (text == NULL || *text == '\0')
  201809. text_len = 0;
  201810. else
  201811. text_len = png_strlen(text);
  201812. /* make sure we include the 0 after the key */
  201813. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201814. /*
  201815. * We leave it to the application to meet PNG-1.0 requirements on the
  201816. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201817. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201818. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201819. */
  201820. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201821. if (text_len)
  201822. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201823. png_write_chunk_end(png_ptr);
  201824. png_free(png_ptr, new_key);
  201825. }
  201826. #endif
  201827. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201828. /* write a compressed text chunk */
  201829. void /* PRIVATE */
  201830. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201831. png_size_t text_len, int compression)
  201832. {
  201833. #ifdef PNG_USE_LOCAL_ARRAYS
  201834. PNG_zTXt;
  201835. #endif
  201836. png_size_t key_len;
  201837. char buf[1];
  201838. png_charp new_key;
  201839. compression_state comp;
  201840. png_debug(1, "in png_write_zTXt\n");
  201841. comp.num_output_ptr = 0;
  201842. comp.max_output_ptr = 0;
  201843. comp.output_ptr = NULL;
  201844. comp.input = NULL;
  201845. comp.input_len = 0;
  201846. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201847. {
  201848. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201849. return;
  201850. }
  201851. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201852. {
  201853. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201854. png_free(png_ptr, new_key);
  201855. return;
  201856. }
  201857. text_len = png_strlen(text);
  201858. /* compute the compressed data; do it now for the length */
  201859. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201860. &comp);
  201861. /* write start of chunk */
  201862. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201863. (key_len+text_len+2));
  201864. /* write key */
  201865. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201866. png_free(png_ptr, new_key);
  201867. buf[0] = (png_byte)compression;
  201868. /* write compression */
  201869. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201870. /* write the compressed data */
  201871. png_write_compressed_data_out(png_ptr, &comp);
  201872. /* close the chunk */
  201873. png_write_chunk_end(png_ptr);
  201874. }
  201875. #endif
  201876. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201877. /* write an iTXt chunk */
  201878. void /* PRIVATE */
  201879. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201880. png_charp lang, png_charp lang_key, png_charp text)
  201881. {
  201882. #ifdef PNG_USE_LOCAL_ARRAYS
  201883. PNG_iTXt;
  201884. #endif
  201885. png_size_t lang_len, key_len, lang_key_len, text_len;
  201886. png_charp new_lang, new_key;
  201887. png_byte cbuf[2];
  201888. compression_state comp;
  201889. png_debug(1, "in png_write_iTXt\n");
  201890. comp.num_output_ptr = 0;
  201891. comp.max_output_ptr = 0;
  201892. comp.output_ptr = NULL;
  201893. comp.input = NULL;
  201894. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201895. {
  201896. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201897. return;
  201898. }
  201899. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201900. {
  201901. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201902. new_lang = NULL;
  201903. lang_len = 0;
  201904. }
  201905. if (lang_key == NULL)
  201906. lang_key_len = 0;
  201907. else
  201908. lang_key_len = png_strlen(lang_key);
  201909. if (text == NULL)
  201910. text_len = 0;
  201911. else
  201912. text_len = png_strlen(text);
  201913. /* compute the compressed data; do it now for the length */
  201914. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201915. &comp);
  201916. /* make sure we include the compression flag, the compression byte,
  201917. * and the NULs after the key, lang, and lang_key parts */
  201918. png_write_chunk_start(png_ptr, png_iTXt,
  201919. (png_uint_32)(
  201920. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201921. + key_len
  201922. + lang_len
  201923. + lang_key_len
  201924. + text_len));
  201925. /*
  201926. * We leave it to the application to meet PNG-1.0 requirements on the
  201927. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201928. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201929. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201930. */
  201931. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201932. /* set the compression flag */
  201933. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201934. compression == PNG_TEXT_COMPRESSION_NONE)
  201935. cbuf[0] = 0;
  201936. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201937. cbuf[0] = 1;
  201938. /* set the compression method */
  201939. cbuf[1] = 0;
  201940. png_write_chunk_data(png_ptr, cbuf, 2);
  201941. cbuf[0] = 0;
  201942. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201943. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201944. png_write_compressed_data_out(png_ptr, &comp);
  201945. png_write_chunk_end(png_ptr);
  201946. png_free(png_ptr, new_key);
  201947. if (new_lang)
  201948. png_free(png_ptr, new_lang);
  201949. }
  201950. #endif
  201951. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201952. /* write the oFFs chunk */
  201953. void /* PRIVATE */
  201954. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201955. int unit_type)
  201956. {
  201957. #ifdef PNG_USE_LOCAL_ARRAYS
  201958. PNG_oFFs;
  201959. #endif
  201960. png_byte buf[9];
  201961. png_debug(1, "in png_write_oFFs\n");
  201962. if (unit_type >= PNG_OFFSET_LAST)
  201963. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201964. png_save_int_32(buf, x_offset);
  201965. png_save_int_32(buf + 4, y_offset);
  201966. buf[8] = (png_byte)unit_type;
  201967. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201968. }
  201969. #endif
  201970. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201971. /* write the pCAL chunk (described in the PNG extensions document) */
  201972. void /* PRIVATE */
  201973. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201974. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201975. {
  201976. #ifdef PNG_USE_LOCAL_ARRAYS
  201977. PNG_pCAL;
  201978. #endif
  201979. png_size_t purpose_len, units_len, total_len;
  201980. png_uint_32p params_len;
  201981. png_byte buf[10];
  201982. png_charp new_purpose;
  201983. int i;
  201984. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201985. if (type >= PNG_EQUATION_LAST)
  201986. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201987. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201988. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201989. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201990. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201991. total_len = purpose_len + units_len + 10;
  201992. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201993. *png_sizeof(png_uint_32)));
  201994. /* Find the length of each parameter, making sure we don't count the
  201995. null terminator for the last parameter. */
  201996. for (i = 0; i < nparams; i++)
  201997. {
  201998. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201999. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202000. total_len += (png_size_t)params_len[i];
  202001. }
  202002. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202003. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202004. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202005. png_save_int_32(buf, X0);
  202006. png_save_int_32(buf + 4, X1);
  202007. buf[8] = (png_byte)type;
  202008. buf[9] = (png_byte)nparams;
  202009. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202010. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202011. png_free(png_ptr, new_purpose);
  202012. for (i = 0; i < nparams; i++)
  202013. {
  202014. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202015. (png_size_t)params_len[i]);
  202016. }
  202017. png_free(png_ptr, params_len);
  202018. png_write_chunk_end(png_ptr);
  202019. }
  202020. #endif
  202021. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202022. /* write the sCAL chunk */
  202023. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202024. void /* PRIVATE */
  202025. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202026. {
  202027. #ifdef PNG_USE_LOCAL_ARRAYS
  202028. PNG_sCAL;
  202029. #endif
  202030. char buf[64];
  202031. png_size_t total_len;
  202032. png_debug(1, "in png_write_sCAL\n");
  202033. buf[0] = (char)unit;
  202034. #if defined(_WIN32_WCE)
  202035. /* sprintf() function is not supported on WindowsCE */
  202036. {
  202037. wchar_t wc_buf[32];
  202038. size_t wc_len;
  202039. swprintf(wc_buf, TEXT("%12.12e"), width);
  202040. wc_len = wcslen(wc_buf);
  202041. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202042. total_len = wc_len + 2;
  202043. swprintf(wc_buf, TEXT("%12.12e"), height);
  202044. wc_len = wcslen(wc_buf);
  202045. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202046. NULL, NULL);
  202047. total_len += wc_len;
  202048. }
  202049. #else
  202050. png_snprintf(buf + 1, 63, "%12.12e", width);
  202051. total_len = 1 + png_strlen(buf + 1) + 1;
  202052. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202053. total_len += png_strlen(buf + total_len);
  202054. #endif
  202055. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202056. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202057. }
  202058. #else
  202059. #ifdef PNG_FIXED_POINT_SUPPORTED
  202060. void /* PRIVATE */
  202061. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202062. png_charp height)
  202063. {
  202064. #ifdef PNG_USE_LOCAL_ARRAYS
  202065. PNG_sCAL;
  202066. #endif
  202067. png_byte buf[64];
  202068. png_size_t wlen, hlen, total_len;
  202069. png_debug(1, "in png_write_sCAL_s\n");
  202070. wlen = png_strlen(width);
  202071. hlen = png_strlen(height);
  202072. total_len = wlen + hlen + 2;
  202073. if (total_len > 64)
  202074. {
  202075. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202076. return;
  202077. }
  202078. buf[0] = (png_byte)unit;
  202079. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202080. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202081. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202082. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202083. }
  202084. #endif
  202085. #endif
  202086. #endif
  202087. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202088. /* write the pHYs chunk */
  202089. void /* PRIVATE */
  202090. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202091. png_uint_32 y_pixels_per_unit,
  202092. int unit_type)
  202093. {
  202094. #ifdef PNG_USE_LOCAL_ARRAYS
  202095. PNG_pHYs;
  202096. #endif
  202097. png_byte buf[9];
  202098. png_debug(1, "in png_write_pHYs\n");
  202099. if (unit_type >= PNG_RESOLUTION_LAST)
  202100. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202101. png_save_uint_32(buf, x_pixels_per_unit);
  202102. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202103. buf[8] = (png_byte)unit_type;
  202104. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202105. }
  202106. #endif
  202107. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202108. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202109. * or png_convert_from_time_t(), or fill in the structure yourself.
  202110. */
  202111. void /* PRIVATE */
  202112. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202113. {
  202114. #ifdef PNG_USE_LOCAL_ARRAYS
  202115. PNG_tIME;
  202116. #endif
  202117. png_byte buf[7];
  202118. png_debug(1, "in png_write_tIME\n");
  202119. if (mod_time->month > 12 || mod_time->month < 1 ||
  202120. mod_time->day > 31 || mod_time->day < 1 ||
  202121. mod_time->hour > 23 || mod_time->second > 60)
  202122. {
  202123. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202124. return;
  202125. }
  202126. png_save_uint_16(buf, mod_time->year);
  202127. buf[2] = mod_time->month;
  202128. buf[3] = mod_time->day;
  202129. buf[4] = mod_time->hour;
  202130. buf[5] = mod_time->minute;
  202131. buf[6] = mod_time->second;
  202132. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202133. }
  202134. #endif
  202135. /* initializes the row writing capability of libpng */
  202136. void /* PRIVATE */
  202137. png_write_start_row(png_structp png_ptr)
  202138. {
  202139. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202140. #ifdef PNG_USE_LOCAL_ARRAYS
  202141. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202142. /* start of interlace block */
  202143. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202144. /* offset to next interlace block */
  202145. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202146. /* start of interlace block in the y direction */
  202147. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202148. /* offset to next interlace block in the y direction */
  202149. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202150. #endif
  202151. #endif
  202152. png_size_t buf_size;
  202153. png_debug(1, "in png_write_start_row\n");
  202154. buf_size = (png_size_t)(PNG_ROWBYTES(
  202155. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202156. /* set up row buffer */
  202157. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202158. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202159. #ifndef PNG_NO_WRITE_FILTERING
  202160. /* set up filtering buffer, if using this filter */
  202161. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202162. {
  202163. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202164. (png_ptr->rowbytes + 1));
  202165. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202166. }
  202167. /* We only need to keep the previous row if we are using one of these. */
  202168. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202169. {
  202170. /* set up previous row buffer */
  202171. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202172. png_memset(png_ptr->prev_row, 0, buf_size);
  202173. if (png_ptr->do_filter & PNG_FILTER_UP)
  202174. {
  202175. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202176. (png_ptr->rowbytes + 1));
  202177. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202178. }
  202179. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202180. {
  202181. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202182. (png_ptr->rowbytes + 1));
  202183. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202184. }
  202185. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202186. {
  202187. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202188. (png_ptr->rowbytes + 1));
  202189. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202190. }
  202191. #endif /* PNG_NO_WRITE_FILTERING */
  202192. }
  202193. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202194. /* if interlaced, we need to set up width and height of pass */
  202195. if (png_ptr->interlaced)
  202196. {
  202197. if (!(png_ptr->transformations & PNG_INTERLACE))
  202198. {
  202199. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202200. png_pass_ystart[0]) / png_pass_yinc[0];
  202201. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202202. png_pass_start[0]) / png_pass_inc[0];
  202203. }
  202204. else
  202205. {
  202206. png_ptr->num_rows = png_ptr->height;
  202207. png_ptr->usr_width = png_ptr->width;
  202208. }
  202209. }
  202210. else
  202211. #endif
  202212. {
  202213. png_ptr->num_rows = png_ptr->height;
  202214. png_ptr->usr_width = png_ptr->width;
  202215. }
  202216. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202217. png_ptr->zstream.next_out = png_ptr->zbuf;
  202218. }
  202219. /* Internal use only. Called when finished processing a row of data. */
  202220. void /* PRIVATE */
  202221. png_write_finish_row(png_structp png_ptr)
  202222. {
  202223. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202224. #ifdef PNG_USE_LOCAL_ARRAYS
  202225. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202226. /* start of interlace block */
  202227. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202228. /* offset to next interlace block */
  202229. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202230. /* start of interlace block in the y direction */
  202231. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202232. /* offset to next interlace block in the y direction */
  202233. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202234. #endif
  202235. #endif
  202236. int ret;
  202237. png_debug(1, "in png_write_finish_row\n");
  202238. /* next row */
  202239. png_ptr->row_number++;
  202240. /* see if we are done */
  202241. if (png_ptr->row_number < png_ptr->num_rows)
  202242. return;
  202243. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202244. /* if interlaced, go to next pass */
  202245. if (png_ptr->interlaced)
  202246. {
  202247. png_ptr->row_number = 0;
  202248. if (png_ptr->transformations & PNG_INTERLACE)
  202249. {
  202250. png_ptr->pass++;
  202251. }
  202252. else
  202253. {
  202254. /* loop until we find a non-zero width or height pass */
  202255. do
  202256. {
  202257. png_ptr->pass++;
  202258. if (png_ptr->pass >= 7)
  202259. break;
  202260. png_ptr->usr_width = (png_ptr->width +
  202261. png_pass_inc[png_ptr->pass] - 1 -
  202262. png_pass_start[png_ptr->pass]) /
  202263. png_pass_inc[png_ptr->pass];
  202264. png_ptr->num_rows = (png_ptr->height +
  202265. png_pass_yinc[png_ptr->pass] - 1 -
  202266. png_pass_ystart[png_ptr->pass]) /
  202267. png_pass_yinc[png_ptr->pass];
  202268. if (png_ptr->transformations & PNG_INTERLACE)
  202269. break;
  202270. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202271. }
  202272. /* reset the row above the image for the next pass */
  202273. if (png_ptr->pass < 7)
  202274. {
  202275. if (png_ptr->prev_row != NULL)
  202276. png_memset(png_ptr->prev_row, 0,
  202277. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202278. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202279. return;
  202280. }
  202281. }
  202282. #endif
  202283. /* if we get here, we've just written the last row, so we need
  202284. to flush the compressor */
  202285. do
  202286. {
  202287. /* tell the compressor we are done */
  202288. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202289. /* check for an error */
  202290. if (ret == Z_OK)
  202291. {
  202292. /* check to see if we need more room */
  202293. if (!(png_ptr->zstream.avail_out))
  202294. {
  202295. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202296. png_ptr->zstream.next_out = png_ptr->zbuf;
  202297. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202298. }
  202299. }
  202300. else if (ret != Z_STREAM_END)
  202301. {
  202302. if (png_ptr->zstream.msg != NULL)
  202303. png_error(png_ptr, png_ptr->zstream.msg);
  202304. else
  202305. png_error(png_ptr, "zlib error");
  202306. }
  202307. } while (ret != Z_STREAM_END);
  202308. /* write any extra space */
  202309. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202310. {
  202311. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202312. png_ptr->zstream.avail_out);
  202313. }
  202314. deflateReset(&png_ptr->zstream);
  202315. png_ptr->zstream.data_type = Z_BINARY;
  202316. }
  202317. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202318. /* Pick out the correct pixels for the interlace pass.
  202319. * The basic idea here is to go through the row with a source
  202320. * pointer and a destination pointer (sp and dp), and copy the
  202321. * correct pixels for the pass. As the row gets compacted,
  202322. * sp will always be >= dp, so we should never overwrite anything.
  202323. * See the default: case for the easiest code to understand.
  202324. */
  202325. void /* PRIVATE */
  202326. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202327. {
  202328. #ifdef PNG_USE_LOCAL_ARRAYS
  202329. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202330. /* start of interlace block */
  202331. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202332. /* offset to next interlace block */
  202333. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202334. #endif
  202335. png_debug(1, "in png_do_write_interlace\n");
  202336. /* we don't have to do anything on the last pass (6) */
  202337. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202338. if (row != NULL && row_info != NULL && pass < 6)
  202339. #else
  202340. if (pass < 6)
  202341. #endif
  202342. {
  202343. /* each pixel depth is handled separately */
  202344. switch (row_info->pixel_depth)
  202345. {
  202346. case 1:
  202347. {
  202348. png_bytep sp;
  202349. png_bytep dp;
  202350. int shift;
  202351. int d;
  202352. int value;
  202353. png_uint_32 i;
  202354. png_uint_32 row_width = row_info->width;
  202355. dp = row;
  202356. d = 0;
  202357. shift = 7;
  202358. for (i = png_pass_start[pass]; i < row_width;
  202359. i += png_pass_inc[pass])
  202360. {
  202361. sp = row + (png_size_t)(i >> 3);
  202362. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202363. d |= (value << shift);
  202364. if (shift == 0)
  202365. {
  202366. shift = 7;
  202367. *dp++ = (png_byte)d;
  202368. d = 0;
  202369. }
  202370. else
  202371. shift--;
  202372. }
  202373. if (shift != 7)
  202374. *dp = (png_byte)d;
  202375. break;
  202376. }
  202377. case 2:
  202378. {
  202379. png_bytep sp;
  202380. png_bytep dp;
  202381. int shift;
  202382. int d;
  202383. int value;
  202384. png_uint_32 i;
  202385. png_uint_32 row_width = row_info->width;
  202386. dp = row;
  202387. shift = 6;
  202388. d = 0;
  202389. for (i = png_pass_start[pass]; i < row_width;
  202390. i += png_pass_inc[pass])
  202391. {
  202392. sp = row + (png_size_t)(i >> 2);
  202393. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202394. d |= (value << shift);
  202395. if (shift == 0)
  202396. {
  202397. shift = 6;
  202398. *dp++ = (png_byte)d;
  202399. d = 0;
  202400. }
  202401. else
  202402. shift -= 2;
  202403. }
  202404. if (shift != 6)
  202405. *dp = (png_byte)d;
  202406. break;
  202407. }
  202408. case 4:
  202409. {
  202410. png_bytep sp;
  202411. png_bytep dp;
  202412. int shift;
  202413. int d;
  202414. int value;
  202415. png_uint_32 i;
  202416. png_uint_32 row_width = row_info->width;
  202417. dp = row;
  202418. shift = 4;
  202419. d = 0;
  202420. for (i = png_pass_start[pass]; i < row_width;
  202421. i += png_pass_inc[pass])
  202422. {
  202423. sp = row + (png_size_t)(i >> 1);
  202424. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202425. d |= (value << shift);
  202426. if (shift == 0)
  202427. {
  202428. shift = 4;
  202429. *dp++ = (png_byte)d;
  202430. d = 0;
  202431. }
  202432. else
  202433. shift -= 4;
  202434. }
  202435. if (shift != 4)
  202436. *dp = (png_byte)d;
  202437. break;
  202438. }
  202439. default:
  202440. {
  202441. png_bytep sp;
  202442. png_bytep dp;
  202443. png_uint_32 i;
  202444. png_uint_32 row_width = row_info->width;
  202445. png_size_t pixel_bytes;
  202446. /* start at the beginning */
  202447. dp = row;
  202448. /* find out how many bytes each pixel takes up */
  202449. pixel_bytes = (row_info->pixel_depth >> 3);
  202450. /* loop through the row, only looking at the pixels that
  202451. matter */
  202452. for (i = png_pass_start[pass]; i < row_width;
  202453. i += png_pass_inc[pass])
  202454. {
  202455. /* find out where the original pixel is */
  202456. sp = row + (png_size_t)i * pixel_bytes;
  202457. /* move the pixel */
  202458. if (dp != sp)
  202459. png_memcpy(dp, sp, pixel_bytes);
  202460. /* next pixel */
  202461. dp += pixel_bytes;
  202462. }
  202463. break;
  202464. }
  202465. }
  202466. /* set new row width */
  202467. row_info->width = (row_info->width +
  202468. png_pass_inc[pass] - 1 -
  202469. png_pass_start[pass]) /
  202470. png_pass_inc[pass];
  202471. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202472. row_info->width);
  202473. }
  202474. }
  202475. #endif
  202476. /* This filters the row, chooses which filter to use, if it has not already
  202477. * been specified by the application, and then writes the row out with the
  202478. * chosen filter.
  202479. */
  202480. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202481. #define PNG_HISHIFT 10
  202482. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202483. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202484. void /* PRIVATE */
  202485. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202486. {
  202487. png_bytep best_row;
  202488. #ifndef PNG_NO_WRITE_FILTER
  202489. png_bytep prev_row, row_buf;
  202490. png_uint_32 mins, bpp;
  202491. png_byte filter_to_do = png_ptr->do_filter;
  202492. png_uint_32 row_bytes = row_info->rowbytes;
  202493. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202494. int num_p_filters = (int)png_ptr->num_prev_filters;
  202495. #endif
  202496. png_debug(1, "in png_write_find_filter\n");
  202497. /* find out how many bytes offset each pixel is */
  202498. bpp = (row_info->pixel_depth + 7) >> 3;
  202499. prev_row = png_ptr->prev_row;
  202500. #endif
  202501. best_row = png_ptr->row_buf;
  202502. #ifndef PNG_NO_WRITE_FILTER
  202503. row_buf = best_row;
  202504. mins = PNG_MAXSUM;
  202505. /* The prediction method we use is to find which method provides the
  202506. * smallest value when summing the absolute values of the distances
  202507. * from zero, using anything >= 128 as negative numbers. This is known
  202508. * as the "minimum sum of absolute differences" heuristic. Other
  202509. * heuristics are the "weighted minimum sum of absolute differences"
  202510. * (experimental and can in theory improve compression), and the "zlib
  202511. * predictive" method (not implemented yet), which does test compressions
  202512. * of lines using different filter methods, and then chooses the
  202513. * (series of) filter(s) that give minimum compressed data size (VERY
  202514. * computationally expensive).
  202515. *
  202516. * GRR 980525: consider also
  202517. * (1) minimum sum of absolute differences from running average (i.e.,
  202518. * keep running sum of non-absolute differences & count of bytes)
  202519. * [track dispersion, too? restart average if dispersion too large?]
  202520. * (1b) minimum sum of absolute differences from sliding average, probably
  202521. * with window size <= deflate window (usually 32K)
  202522. * (2) minimum sum of squared differences from zero or running average
  202523. * (i.e., ~ root-mean-square approach)
  202524. */
  202525. /* We don't need to test the 'no filter' case if this is the only filter
  202526. * that has been chosen, as it doesn't actually do anything to the data.
  202527. */
  202528. if ((filter_to_do & PNG_FILTER_NONE) &&
  202529. filter_to_do != PNG_FILTER_NONE)
  202530. {
  202531. png_bytep rp;
  202532. png_uint_32 sum = 0;
  202533. png_uint_32 i;
  202534. int v;
  202535. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202536. {
  202537. v = *rp;
  202538. sum += (v < 128) ? v : 256 - v;
  202539. }
  202540. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202541. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202542. {
  202543. png_uint_32 sumhi, sumlo;
  202544. int j;
  202545. sumlo = sum & PNG_LOMASK;
  202546. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202547. /* Reduce the sum if we match any of the previous rows */
  202548. for (j = 0; j < num_p_filters; j++)
  202549. {
  202550. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202551. {
  202552. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202553. PNG_WEIGHT_SHIFT;
  202554. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202555. PNG_WEIGHT_SHIFT;
  202556. }
  202557. }
  202558. /* Factor in the cost of this filter (this is here for completeness,
  202559. * but it makes no sense to have a "cost" for the NONE filter, as
  202560. * it has the minimum possible computational cost - none).
  202561. */
  202562. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202563. PNG_COST_SHIFT;
  202564. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202565. PNG_COST_SHIFT;
  202566. if (sumhi > PNG_HIMASK)
  202567. sum = PNG_MAXSUM;
  202568. else
  202569. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202570. }
  202571. #endif
  202572. mins = sum;
  202573. }
  202574. /* sub filter */
  202575. if (filter_to_do == PNG_FILTER_SUB)
  202576. /* it's the only filter so no testing is needed */
  202577. {
  202578. png_bytep rp, lp, dp;
  202579. png_uint_32 i;
  202580. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202581. i++, rp++, dp++)
  202582. {
  202583. *dp = *rp;
  202584. }
  202585. for (lp = row_buf + 1; i < row_bytes;
  202586. i++, rp++, lp++, dp++)
  202587. {
  202588. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202589. }
  202590. best_row = png_ptr->sub_row;
  202591. }
  202592. else if (filter_to_do & PNG_FILTER_SUB)
  202593. {
  202594. png_bytep rp, dp, lp;
  202595. png_uint_32 sum = 0, lmins = mins;
  202596. png_uint_32 i;
  202597. int v;
  202598. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202599. /* We temporarily increase the "minimum sum" by the factor we
  202600. * would reduce the sum of this filter, so that we can do the
  202601. * early exit comparison without scaling the sum each time.
  202602. */
  202603. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202604. {
  202605. int j;
  202606. png_uint_32 lmhi, lmlo;
  202607. lmlo = lmins & PNG_LOMASK;
  202608. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202609. for (j = 0; j < num_p_filters; j++)
  202610. {
  202611. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202612. {
  202613. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202614. PNG_WEIGHT_SHIFT;
  202615. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202616. PNG_WEIGHT_SHIFT;
  202617. }
  202618. }
  202619. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202620. PNG_COST_SHIFT;
  202621. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202622. PNG_COST_SHIFT;
  202623. if (lmhi > PNG_HIMASK)
  202624. lmins = PNG_MAXSUM;
  202625. else
  202626. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202627. }
  202628. #endif
  202629. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202630. i++, rp++, dp++)
  202631. {
  202632. v = *dp = *rp;
  202633. sum += (v < 128) ? v : 256 - v;
  202634. }
  202635. for (lp = row_buf + 1; i < row_bytes;
  202636. i++, rp++, lp++, dp++)
  202637. {
  202638. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202639. sum += (v < 128) ? v : 256 - v;
  202640. if (sum > lmins) /* We are already worse, don't continue. */
  202641. break;
  202642. }
  202643. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202644. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202645. {
  202646. int j;
  202647. png_uint_32 sumhi, sumlo;
  202648. sumlo = sum & PNG_LOMASK;
  202649. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202650. for (j = 0; j < num_p_filters; j++)
  202651. {
  202652. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202653. {
  202654. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202655. PNG_WEIGHT_SHIFT;
  202656. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202657. PNG_WEIGHT_SHIFT;
  202658. }
  202659. }
  202660. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202661. PNG_COST_SHIFT;
  202662. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202663. PNG_COST_SHIFT;
  202664. if (sumhi > PNG_HIMASK)
  202665. sum = PNG_MAXSUM;
  202666. else
  202667. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202668. }
  202669. #endif
  202670. if (sum < mins)
  202671. {
  202672. mins = sum;
  202673. best_row = png_ptr->sub_row;
  202674. }
  202675. }
  202676. /* up filter */
  202677. if (filter_to_do == PNG_FILTER_UP)
  202678. {
  202679. png_bytep rp, dp, pp;
  202680. png_uint_32 i;
  202681. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202682. pp = prev_row + 1; i < row_bytes;
  202683. i++, rp++, pp++, dp++)
  202684. {
  202685. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202686. }
  202687. best_row = png_ptr->up_row;
  202688. }
  202689. else if (filter_to_do & PNG_FILTER_UP)
  202690. {
  202691. png_bytep rp, dp, pp;
  202692. png_uint_32 sum = 0, lmins = mins;
  202693. png_uint_32 i;
  202694. int v;
  202695. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202696. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202697. {
  202698. int j;
  202699. png_uint_32 lmhi, lmlo;
  202700. lmlo = lmins & PNG_LOMASK;
  202701. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202702. for (j = 0; j < num_p_filters; j++)
  202703. {
  202704. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202705. {
  202706. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202707. PNG_WEIGHT_SHIFT;
  202708. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202709. PNG_WEIGHT_SHIFT;
  202710. }
  202711. }
  202712. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202713. PNG_COST_SHIFT;
  202714. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202715. PNG_COST_SHIFT;
  202716. if (lmhi > PNG_HIMASK)
  202717. lmins = PNG_MAXSUM;
  202718. else
  202719. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202720. }
  202721. #endif
  202722. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202723. pp = prev_row + 1; i < row_bytes; i++)
  202724. {
  202725. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202726. sum += (v < 128) ? v : 256 - v;
  202727. if (sum > lmins) /* We are already worse, don't continue. */
  202728. break;
  202729. }
  202730. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202731. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202732. {
  202733. int j;
  202734. png_uint_32 sumhi, sumlo;
  202735. sumlo = sum & PNG_LOMASK;
  202736. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202737. for (j = 0; j < num_p_filters; j++)
  202738. {
  202739. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202740. {
  202741. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202742. PNG_WEIGHT_SHIFT;
  202743. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202744. PNG_WEIGHT_SHIFT;
  202745. }
  202746. }
  202747. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202748. PNG_COST_SHIFT;
  202749. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202750. PNG_COST_SHIFT;
  202751. if (sumhi > PNG_HIMASK)
  202752. sum = PNG_MAXSUM;
  202753. else
  202754. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202755. }
  202756. #endif
  202757. if (sum < mins)
  202758. {
  202759. mins = sum;
  202760. best_row = png_ptr->up_row;
  202761. }
  202762. }
  202763. /* avg filter */
  202764. if (filter_to_do == PNG_FILTER_AVG)
  202765. {
  202766. png_bytep rp, dp, pp, lp;
  202767. png_uint_32 i;
  202768. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202769. pp = prev_row + 1; i < bpp; i++)
  202770. {
  202771. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202772. }
  202773. for (lp = row_buf + 1; i < row_bytes; i++)
  202774. {
  202775. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202776. & 0xff);
  202777. }
  202778. best_row = png_ptr->avg_row;
  202779. }
  202780. else if (filter_to_do & PNG_FILTER_AVG)
  202781. {
  202782. png_bytep rp, dp, pp, lp;
  202783. png_uint_32 sum = 0, lmins = mins;
  202784. png_uint_32 i;
  202785. int v;
  202786. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202787. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202788. {
  202789. int j;
  202790. png_uint_32 lmhi, lmlo;
  202791. lmlo = lmins & PNG_LOMASK;
  202792. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202793. for (j = 0; j < num_p_filters; j++)
  202794. {
  202795. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202796. {
  202797. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202798. PNG_WEIGHT_SHIFT;
  202799. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202800. PNG_WEIGHT_SHIFT;
  202801. }
  202802. }
  202803. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202804. PNG_COST_SHIFT;
  202805. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202806. PNG_COST_SHIFT;
  202807. if (lmhi > PNG_HIMASK)
  202808. lmins = PNG_MAXSUM;
  202809. else
  202810. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202811. }
  202812. #endif
  202813. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202814. pp = prev_row + 1; i < bpp; i++)
  202815. {
  202816. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202817. sum += (v < 128) ? v : 256 - v;
  202818. }
  202819. for (lp = row_buf + 1; i < row_bytes; i++)
  202820. {
  202821. v = *dp++ =
  202822. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202823. sum += (v < 128) ? v : 256 - v;
  202824. if (sum > lmins) /* We are already worse, don't continue. */
  202825. break;
  202826. }
  202827. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202828. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202829. {
  202830. int j;
  202831. png_uint_32 sumhi, sumlo;
  202832. sumlo = sum & PNG_LOMASK;
  202833. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202834. for (j = 0; j < num_p_filters; j++)
  202835. {
  202836. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202837. {
  202838. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202839. PNG_WEIGHT_SHIFT;
  202840. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202841. PNG_WEIGHT_SHIFT;
  202842. }
  202843. }
  202844. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202845. PNG_COST_SHIFT;
  202846. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202847. PNG_COST_SHIFT;
  202848. if (sumhi > PNG_HIMASK)
  202849. sum = PNG_MAXSUM;
  202850. else
  202851. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202852. }
  202853. #endif
  202854. if (sum < mins)
  202855. {
  202856. mins = sum;
  202857. best_row = png_ptr->avg_row;
  202858. }
  202859. }
  202860. /* Paeth filter */
  202861. if (filter_to_do == PNG_FILTER_PAETH)
  202862. {
  202863. png_bytep rp, dp, pp, cp, lp;
  202864. png_uint_32 i;
  202865. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202866. pp = prev_row + 1; i < bpp; i++)
  202867. {
  202868. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202869. }
  202870. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202871. {
  202872. int a, b, c, pa, pb, pc, p;
  202873. b = *pp++;
  202874. c = *cp++;
  202875. a = *lp++;
  202876. p = b - c;
  202877. pc = a - c;
  202878. #ifdef PNG_USE_ABS
  202879. pa = abs(p);
  202880. pb = abs(pc);
  202881. pc = abs(p + pc);
  202882. #else
  202883. pa = p < 0 ? -p : p;
  202884. pb = pc < 0 ? -pc : pc;
  202885. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202886. #endif
  202887. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202888. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202889. }
  202890. best_row = png_ptr->paeth_row;
  202891. }
  202892. else if (filter_to_do & PNG_FILTER_PAETH)
  202893. {
  202894. png_bytep rp, dp, pp, cp, lp;
  202895. png_uint_32 sum = 0, lmins = mins;
  202896. png_uint_32 i;
  202897. int v;
  202898. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202899. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202900. {
  202901. int j;
  202902. png_uint_32 lmhi, lmlo;
  202903. lmlo = lmins & PNG_LOMASK;
  202904. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202905. for (j = 0; j < num_p_filters; j++)
  202906. {
  202907. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202908. {
  202909. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202910. PNG_WEIGHT_SHIFT;
  202911. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202912. PNG_WEIGHT_SHIFT;
  202913. }
  202914. }
  202915. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202916. PNG_COST_SHIFT;
  202917. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202918. PNG_COST_SHIFT;
  202919. if (lmhi > PNG_HIMASK)
  202920. lmins = PNG_MAXSUM;
  202921. else
  202922. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202923. }
  202924. #endif
  202925. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202926. pp = prev_row + 1; i < bpp; i++)
  202927. {
  202928. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202929. sum += (v < 128) ? v : 256 - v;
  202930. }
  202931. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202932. {
  202933. int a, b, c, pa, pb, pc, p;
  202934. b = *pp++;
  202935. c = *cp++;
  202936. a = *lp++;
  202937. #ifndef PNG_SLOW_PAETH
  202938. p = b - c;
  202939. pc = a - c;
  202940. #ifdef PNG_USE_ABS
  202941. pa = abs(p);
  202942. pb = abs(pc);
  202943. pc = abs(p + pc);
  202944. #else
  202945. pa = p < 0 ? -p : p;
  202946. pb = pc < 0 ? -pc : pc;
  202947. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202948. #endif
  202949. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202950. #else /* PNG_SLOW_PAETH */
  202951. p = a + b - c;
  202952. pa = abs(p - a);
  202953. pb = abs(p - b);
  202954. pc = abs(p - c);
  202955. if (pa <= pb && pa <= pc)
  202956. p = a;
  202957. else if (pb <= pc)
  202958. p = b;
  202959. else
  202960. p = c;
  202961. #endif /* PNG_SLOW_PAETH */
  202962. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202963. sum += (v < 128) ? v : 256 - v;
  202964. if (sum > lmins) /* We are already worse, don't continue. */
  202965. break;
  202966. }
  202967. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202968. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202969. {
  202970. int j;
  202971. png_uint_32 sumhi, sumlo;
  202972. sumlo = sum & PNG_LOMASK;
  202973. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202974. for (j = 0; j < num_p_filters; j++)
  202975. {
  202976. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202977. {
  202978. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202979. PNG_WEIGHT_SHIFT;
  202980. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202981. PNG_WEIGHT_SHIFT;
  202982. }
  202983. }
  202984. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202985. PNG_COST_SHIFT;
  202986. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202987. PNG_COST_SHIFT;
  202988. if (sumhi > PNG_HIMASK)
  202989. sum = PNG_MAXSUM;
  202990. else
  202991. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202992. }
  202993. #endif
  202994. if (sum < mins)
  202995. {
  202996. best_row = png_ptr->paeth_row;
  202997. }
  202998. }
  202999. #endif /* PNG_NO_WRITE_FILTER */
  203000. /* Do the actual writing of the filtered row data from the chosen filter. */
  203001. png_write_filtered_row(png_ptr, best_row);
  203002. #ifndef PNG_NO_WRITE_FILTER
  203003. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203004. /* Save the type of filter we picked this time for future calculations */
  203005. if (png_ptr->num_prev_filters > 0)
  203006. {
  203007. int j;
  203008. for (j = 1; j < num_p_filters; j++)
  203009. {
  203010. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203011. }
  203012. png_ptr->prev_filters[j] = best_row[0];
  203013. }
  203014. #endif
  203015. #endif /* PNG_NO_WRITE_FILTER */
  203016. }
  203017. /* Do the actual writing of a previously filtered row. */
  203018. void /* PRIVATE */
  203019. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203020. {
  203021. png_debug(1, "in png_write_filtered_row\n");
  203022. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203023. /* set up the zlib input buffer */
  203024. png_ptr->zstream.next_in = filtered_row;
  203025. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203026. /* repeat until we have compressed all the data */
  203027. do
  203028. {
  203029. int ret; /* return of zlib */
  203030. /* compress the data */
  203031. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203032. /* check for compression errors */
  203033. if (ret != Z_OK)
  203034. {
  203035. if (png_ptr->zstream.msg != NULL)
  203036. png_error(png_ptr, png_ptr->zstream.msg);
  203037. else
  203038. png_error(png_ptr, "zlib error");
  203039. }
  203040. /* see if it is time to write another IDAT */
  203041. if (!(png_ptr->zstream.avail_out))
  203042. {
  203043. /* write the IDAT and reset the zlib output buffer */
  203044. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203045. png_ptr->zstream.next_out = png_ptr->zbuf;
  203046. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203047. }
  203048. /* repeat until all data has been compressed */
  203049. } while (png_ptr->zstream.avail_in);
  203050. /* swap the current and previous rows */
  203051. if (png_ptr->prev_row != NULL)
  203052. {
  203053. png_bytep tptr;
  203054. tptr = png_ptr->prev_row;
  203055. png_ptr->prev_row = png_ptr->row_buf;
  203056. png_ptr->row_buf = tptr;
  203057. }
  203058. /* finish row - updates counters and flushes zlib if last row */
  203059. png_write_finish_row(png_ptr);
  203060. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203061. png_ptr->flush_rows++;
  203062. if (png_ptr->flush_dist > 0 &&
  203063. png_ptr->flush_rows >= png_ptr->flush_dist)
  203064. {
  203065. png_write_flush(png_ptr);
  203066. }
  203067. #endif
  203068. }
  203069. #endif /* PNG_WRITE_SUPPORTED */
  203070. /*** End of inlined file: pngwutil.c ***/
  203071. #else
  203072. extern "C"
  203073. {
  203074. #include <png.h>
  203075. #include <pngconf.h>
  203076. }
  203077. #endif
  203078. }
  203079. #undef max
  203080. #undef min
  203081. #if JUCE_MSVC
  203082. #pragma warning (pop)
  203083. #endif
  203084. BEGIN_JUCE_NAMESPACE
  203085. using ::calloc;
  203086. using ::malloc;
  203087. using ::free;
  203088. namespace PNGHelpers
  203089. {
  203090. using namespace pnglibNamespace;
  203091. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203092. {
  203093. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203094. }
  203095. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203096. {
  203097. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203098. }
  203099. struct PNGErrorStruct {};
  203100. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203101. {
  203102. throw PNGErrorStruct();
  203103. }
  203104. }
  203105. PNGImageFormat::PNGImageFormat() {}
  203106. PNGImageFormat::~PNGImageFormat() {}
  203107. const String PNGImageFormat::getFormatName()
  203108. {
  203109. return "PNG";
  203110. }
  203111. bool PNGImageFormat::canUnderstand (InputStream& in)
  203112. {
  203113. const int bytesNeeded = 4;
  203114. char header [bytesNeeded];
  203115. return in.read (header, bytesNeeded) == bytesNeeded
  203116. && header[1] == 'P'
  203117. && header[2] == 'N'
  203118. && header[3] == 'G';
  203119. }
  203120. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203121. const Image juce_loadWithCoreImage (InputStream& input);
  203122. #endif
  203123. const Image PNGImageFormat::decodeImage (InputStream& in)
  203124. {
  203125. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203126. return juce_loadWithCoreImage (in);
  203127. #else
  203128. using namespace pnglibNamespace;
  203129. Image image;
  203130. png_structp pngReadStruct;
  203131. png_infop pngInfoStruct;
  203132. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203133. if (pngReadStruct != 0)
  203134. {
  203135. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203136. if (pngInfoStruct == 0)
  203137. {
  203138. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203139. return Image::null;
  203140. }
  203141. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203142. // read the header..
  203143. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203144. png_uint_32 width, height;
  203145. int bitDepth, colorType, interlaceType;
  203146. png_read_info (pngReadStruct, pngInfoStruct);
  203147. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203148. &width, &height,
  203149. &bitDepth, &colorType,
  203150. &interlaceType, 0, 0);
  203151. if (bitDepth == 16)
  203152. png_set_strip_16 (pngReadStruct);
  203153. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203154. png_set_expand (pngReadStruct);
  203155. if (bitDepth < 8)
  203156. png_set_expand (pngReadStruct);
  203157. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203158. png_set_expand (pngReadStruct);
  203159. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203160. png_set_gray_to_rgb (pngReadStruct);
  203161. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203162. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203163. || pngInfoStruct->num_trans > 0;
  203164. // Load the image into a temp buffer in the pnglib format..
  203165. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203166. {
  203167. HeapBlock <png_bytep> rows (height);
  203168. for (int y = (int) height; --y >= 0;)
  203169. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203170. png_read_image (pngReadStruct, rows);
  203171. png_read_end (pngReadStruct, pngInfoStruct);
  203172. }
  203173. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203174. // now convert the data to a juce image format..
  203175. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203176. (int) width, (int) height, hasAlphaChan);
  203177. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203178. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203179. const Image::BitmapData destData (image, true);
  203180. uint8* srcRow = tempBuffer;
  203181. uint8* destRow = destData.data;
  203182. for (int y = 0; y < (int) height; ++y)
  203183. {
  203184. const uint8* src = srcRow;
  203185. srcRow += (width << 2);
  203186. uint8* dest = destRow;
  203187. destRow += destData.lineStride;
  203188. if (hasAlphaChan)
  203189. {
  203190. for (int i = (int) width; --i >= 0;)
  203191. {
  203192. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203193. ((PixelARGB*) dest)->premultiply();
  203194. dest += destData.pixelStride;
  203195. src += 4;
  203196. }
  203197. }
  203198. else
  203199. {
  203200. for (int i = (int) width; --i >= 0;)
  203201. {
  203202. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203203. dest += destData.pixelStride;
  203204. src += 4;
  203205. }
  203206. }
  203207. }
  203208. }
  203209. return image;
  203210. #endif
  203211. }
  203212. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203213. {
  203214. using namespace pnglibNamespace;
  203215. const int width = image.getWidth();
  203216. const int height = image.getHeight();
  203217. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203218. if (pngWriteStruct == 0)
  203219. return false;
  203220. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203221. if (pngInfoStruct == 0)
  203222. {
  203223. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203224. return false;
  203225. }
  203226. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203227. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203228. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203229. : PNG_COLOR_TYPE_RGB,
  203230. PNG_INTERLACE_NONE,
  203231. PNG_COMPRESSION_TYPE_BASE,
  203232. PNG_FILTER_TYPE_BASE);
  203233. HeapBlock <uint8> rowData (width * 4);
  203234. png_color_8 sig_bit;
  203235. sig_bit.red = 8;
  203236. sig_bit.green = 8;
  203237. sig_bit.blue = 8;
  203238. sig_bit.alpha = 8;
  203239. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203240. png_write_info (pngWriteStruct, pngInfoStruct);
  203241. png_set_shift (pngWriteStruct, &sig_bit);
  203242. png_set_packing (pngWriteStruct);
  203243. const Image::BitmapData srcData (image, false);
  203244. for (int y = 0; y < height; ++y)
  203245. {
  203246. uint8* dst = rowData;
  203247. const uint8* src = srcData.getLinePointer (y);
  203248. if (image.hasAlphaChannel())
  203249. {
  203250. for (int i = width; --i >= 0;)
  203251. {
  203252. PixelARGB p (*(const PixelARGB*) src);
  203253. p.unpremultiply();
  203254. *dst++ = p.getRed();
  203255. *dst++ = p.getGreen();
  203256. *dst++ = p.getBlue();
  203257. *dst++ = p.getAlpha();
  203258. src += srcData.pixelStride;
  203259. }
  203260. }
  203261. else
  203262. {
  203263. for (int i = width; --i >= 0;)
  203264. {
  203265. *dst++ = ((const PixelRGB*) src)->getRed();
  203266. *dst++ = ((const PixelRGB*) src)->getGreen();
  203267. *dst++ = ((const PixelRGB*) src)->getBlue();
  203268. src += srcData.pixelStride;
  203269. }
  203270. }
  203271. png_bytep rowPtr = rowData;
  203272. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203273. }
  203274. png_write_end (pngWriteStruct, pngInfoStruct);
  203275. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203276. out.flush();
  203277. return true;
  203278. }
  203279. END_JUCE_NAMESPACE
  203280. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203281. #endif
  203282. //==============================================================================
  203283. #if JUCE_BUILD_NATIVE
  203284. // Non-public headers that are needed by more than one platform must be included
  203285. // before the platform-specific sections..
  203286. BEGIN_JUCE_NAMESPACE
  203287. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203288. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203289. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203290. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203291. /**
  203292. Helper class that takes chunks of incoming midi bytes, packages them into
  203293. messages, and dispatches them to a midi callback.
  203294. */
  203295. class MidiDataConcatenator
  203296. {
  203297. public:
  203298. MidiDataConcatenator (const int initialBufferSize)
  203299. : pendingData (initialBufferSize),
  203300. pendingBytes (0), pendingDataTime (0)
  203301. {
  203302. }
  203303. void reset()
  203304. {
  203305. pendingBytes = 0;
  203306. pendingDataTime = 0;
  203307. }
  203308. void pushMidiData (const void* data, int numBytes, double time,
  203309. MidiInput* input, MidiInputCallback& callback)
  203310. {
  203311. const uint8* d = static_cast <const uint8*> (data);
  203312. while (numBytes > 0)
  203313. {
  203314. if (pendingBytes > 0 || d[0] == 0xf0)
  203315. {
  203316. processSysex (d, numBytes, time, input, callback);
  203317. }
  203318. else
  203319. {
  203320. int used = 0;
  203321. const MidiMessage m (d, numBytes, used, 0, time);
  203322. if (used <= 0)
  203323. break; // malformed message..
  203324. callback.handleIncomingMidiMessage (input, m);
  203325. numBytes -= used;
  203326. d += used;
  203327. }
  203328. }
  203329. }
  203330. private:
  203331. void processSysex (const uint8*& d, int& numBytes, double time,
  203332. MidiInput* input, MidiInputCallback& callback)
  203333. {
  203334. if (*d == 0xf0)
  203335. {
  203336. pendingBytes = 0;
  203337. pendingDataTime = time;
  203338. }
  203339. pendingData.ensureSize (pendingBytes + numBytes, false);
  203340. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203341. uint8* dest = totalMessage + pendingBytes;
  203342. do
  203343. {
  203344. if (pendingBytes > 0 && *d >= 0x80)
  203345. {
  203346. if (*d >= 0xfa || *d == 0xf8)
  203347. {
  203348. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203349. ++d;
  203350. --numBytes;
  203351. }
  203352. else
  203353. {
  203354. if (*d == 0xf7)
  203355. {
  203356. *dest++ = *d++;
  203357. pendingBytes++;
  203358. --numBytes;
  203359. }
  203360. break;
  203361. }
  203362. }
  203363. else
  203364. {
  203365. *dest++ = *d++;
  203366. pendingBytes++;
  203367. --numBytes;
  203368. }
  203369. }
  203370. while (numBytes > 0);
  203371. if (pendingBytes > 0)
  203372. {
  203373. if (totalMessage [pendingBytes - 1] == 0xf7)
  203374. {
  203375. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203376. pendingBytes = 0;
  203377. }
  203378. else
  203379. {
  203380. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203381. }
  203382. }
  203383. }
  203384. MemoryBlock pendingData;
  203385. int pendingBytes;
  203386. double pendingDataTime;
  203387. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203388. };
  203389. #endif
  203390. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203391. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203392. END_JUCE_NAMESPACE
  203393. #if JUCE_WINDOWS
  203394. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203395. /*
  203396. This file wraps together all the win32-specific code, so that
  203397. we can include all the native headers just once, and compile all our
  203398. platform-specific stuff in one big lump, keeping it out of the way of
  203399. the rest of the codebase.
  203400. */
  203401. #if JUCE_WINDOWS
  203402. #undef JUCE_BUILD_NATIVE
  203403. #define JUCE_BUILD_NATIVE 1
  203404. BEGIN_JUCE_NAMESPACE
  203405. #define JUCE_INCLUDED_FILE 1
  203406. // Now include the actual code files..
  203407. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203408. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203409. // compiled on its own).
  203410. #if JUCE_INCLUDED_FILE
  203411. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203412. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203413. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203414. #ifndef DOXYGEN
  203415. // use with DynamicLibraryLoader to simplify importing functions
  203416. //
  203417. // functionName: function to import
  203418. // localFunctionName: name you want to use to actually call it (must be different)
  203419. // returnType: the return type
  203420. // object: the DynamicLibraryLoader to use
  203421. // params: list of params (bracketed)
  203422. //
  203423. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203424. typedef returnType (WINAPI *type##localFunctionName) params; \
  203425. type##localFunctionName localFunctionName \
  203426. = (type##localFunctionName)object.findProcAddress (#functionName);
  203427. // loads and unloads a DLL automatically
  203428. class JUCE_API DynamicLibraryLoader
  203429. {
  203430. public:
  203431. DynamicLibraryLoader (const String& name = String::empty);
  203432. ~DynamicLibraryLoader();
  203433. bool load (const String& libraryName);
  203434. void* findProcAddress (const String& functionName);
  203435. private:
  203436. void* libHandle;
  203437. };
  203438. #endif
  203439. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203440. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203441. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203442. : libHandle (0)
  203443. {
  203444. load (name);
  203445. }
  203446. DynamicLibraryLoader::~DynamicLibraryLoader()
  203447. {
  203448. load (String::empty);
  203449. }
  203450. bool DynamicLibraryLoader::load (const String& name)
  203451. {
  203452. FreeLibrary ((HMODULE) libHandle);
  203453. libHandle = name.isNotEmpty() ? LoadLibrary (name) : 0;
  203454. return libHandle != 0;
  203455. }
  203456. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203457. {
  203458. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203459. }
  203460. #endif
  203461. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203462. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203463. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203464. // compiled on its own).
  203465. #if JUCE_INCLUDED_FILE
  203466. void Logger::outputDebugString (const String& text)
  203467. {
  203468. OutputDebugString (text + "\n");
  203469. }
  203470. static int64 hiResTicksPerSecond;
  203471. static double hiResTicksScaleFactor;
  203472. #if JUCE_USE_INTRINSICS
  203473. // CPU info functions using intrinsics...
  203474. #pragma intrinsic (__cpuid)
  203475. #pragma intrinsic (__rdtsc)
  203476. const String SystemStats::getCpuVendor()
  203477. {
  203478. int info [4];
  203479. __cpuid (info, 0);
  203480. char v [12];
  203481. memcpy (v, info + 1, 4);
  203482. memcpy (v + 4, info + 3, 4);
  203483. memcpy (v + 8, info + 2, 4);
  203484. return String (v, 12);
  203485. }
  203486. #else
  203487. // CPU info functions using old fashioned inline asm...
  203488. static void juce_getCpuVendor (char* const v)
  203489. {
  203490. int vendor[4];
  203491. zeromem (vendor, 16);
  203492. #ifdef JUCE_64BIT
  203493. #else
  203494. #ifndef __MINGW32__
  203495. __try
  203496. #endif
  203497. {
  203498. #if JUCE_GCC
  203499. unsigned int dummy = 0;
  203500. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203501. #else
  203502. __asm
  203503. {
  203504. mov eax, 0
  203505. cpuid
  203506. mov [vendor], ebx
  203507. mov [vendor + 4], edx
  203508. mov [vendor + 8], ecx
  203509. }
  203510. #endif
  203511. }
  203512. #ifndef __MINGW32__
  203513. __except (EXCEPTION_EXECUTE_HANDLER)
  203514. {
  203515. *v = 0;
  203516. }
  203517. #endif
  203518. #endif
  203519. memcpy (v, vendor, 16);
  203520. }
  203521. const String SystemStats::getCpuVendor()
  203522. {
  203523. char v [16];
  203524. juce_getCpuVendor (v);
  203525. return String (v, 16);
  203526. }
  203527. #endif
  203528. void SystemStats::initialiseStats()
  203529. {
  203530. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203531. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203532. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203533. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203534. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203535. #else
  203536. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203537. #endif
  203538. {
  203539. SYSTEM_INFO systemInfo;
  203540. GetSystemInfo (&systemInfo);
  203541. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203542. }
  203543. LARGE_INTEGER f;
  203544. QueryPerformanceFrequency (&f);
  203545. hiResTicksPerSecond = f.QuadPart;
  203546. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203547. String s (SystemStats::getJUCEVersion());
  203548. const MMRESULT res = timeBeginPeriod (1);
  203549. (void) res;
  203550. jassert (res == TIMERR_NOERROR);
  203551. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203552. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203553. #endif
  203554. }
  203555. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203556. {
  203557. OSVERSIONINFO info;
  203558. info.dwOSVersionInfoSize = sizeof (info);
  203559. GetVersionEx (&info);
  203560. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203561. {
  203562. switch (info.dwMajorVersion)
  203563. {
  203564. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203565. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203566. default: jassertfalse; break; // !! not a supported OS!
  203567. }
  203568. }
  203569. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203570. {
  203571. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203572. return Win98;
  203573. }
  203574. return UnknownOS;
  203575. }
  203576. const String SystemStats::getOperatingSystemName()
  203577. {
  203578. const char* name = "Unknown OS";
  203579. switch (getOperatingSystemType())
  203580. {
  203581. case Windows7: name = "Windows 7"; break;
  203582. case WinVista: name = "Windows Vista"; break;
  203583. case WinXP: name = "Windows XP"; break;
  203584. case Win2000: name = "Windows 2000"; break;
  203585. case Win98: name = "Windows 98"; break;
  203586. default: jassertfalse; break; // !! new type of OS?
  203587. }
  203588. return name;
  203589. }
  203590. bool SystemStats::isOperatingSystem64Bit()
  203591. {
  203592. #ifdef _WIN64
  203593. return true;
  203594. #else
  203595. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203596. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203597. BOOL isWow64 = FALSE;
  203598. return (fnIsWow64Process != 0)
  203599. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203600. && (isWow64 != FALSE);
  203601. #endif
  203602. }
  203603. int SystemStats::getMemorySizeInMegabytes()
  203604. {
  203605. MEMORYSTATUSEX mem;
  203606. mem.dwLength = sizeof (mem);
  203607. GlobalMemoryStatusEx (&mem);
  203608. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203609. }
  203610. uint32 juce_millisecondsSinceStartup() throw()
  203611. {
  203612. return (uint32) timeGetTime();
  203613. }
  203614. int64 Time::getHighResolutionTicks() throw()
  203615. {
  203616. LARGE_INTEGER ticks;
  203617. QueryPerformanceCounter (&ticks);
  203618. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203619. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203620. // fix for a very obscure PCI hardware bug that can make the counter
  203621. // sometimes jump forwards by a few seconds..
  203622. static int64 hiResTicksOffset = 0;
  203623. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203624. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203625. hiResTicksOffset = newOffset;
  203626. return ticks.QuadPart + hiResTicksOffset;
  203627. }
  203628. double Time::getMillisecondCounterHiRes() throw()
  203629. {
  203630. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203631. }
  203632. int64 Time::getHighResolutionTicksPerSecond() throw()
  203633. {
  203634. return hiResTicksPerSecond;
  203635. }
  203636. static int64 juce_getClockCycleCounter() throw()
  203637. {
  203638. #if JUCE_USE_INTRINSICS
  203639. // MS intrinsics version...
  203640. return __rdtsc();
  203641. #elif JUCE_GCC
  203642. // GNU inline asm version...
  203643. unsigned int hi = 0, lo = 0;
  203644. __asm__ __volatile__ (
  203645. "xor %%eax, %%eax \n\
  203646. xor %%edx, %%edx \n\
  203647. rdtsc \n\
  203648. movl %%eax, %[lo] \n\
  203649. movl %%edx, %[hi]"
  203650. :
  203651. : [hi] "m" (hi),
  203652. [lo] "m" (lo)
  203653. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203654. return (int64) ((((uint64) hi) << 32) | lo);
  203655. #else
  203656. // MSVC inline asm version...
  203657. unsigned int hi = 0, lo = 0;
  203658. __asm
  203659. {
  203660. xor eax, eax
  203661. xor edx, edx
  203662. rdtsc
  203663. mov lo, eax
  203664. mov hi, edx
  203665. }
  203666. return (int64) ((((uint64) hi) << 32) | lo);
  203667. #endif
  203668. }
  203669. int SystemStats::getCpuSpeedInMegaherz()
  203670. {
  203671. const int64 cycles = juce_getClockCycleCounter();
  203672. const uint32 millis = Time::getMillisecondCounter();
  203673. int lastResult = 0;
  203674. for (;;)
  203675. {
  203676. int n = 1000000;
  203677. while (--n > 0) {}
  203678. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203679. const int64 cyclesNow = juce_getClockCycleCounter();
  203680. if (millisElapsed > 80)
  203681. {
  203682. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203683. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203684. return newResult;
  203685. lastResult = newResult;
  203686. }
  203687. }
  203688. }
  203689. bool Time::setSystemTimeToThisTime() const
  203690. {
  203691. SYSTEMTIME st;
  203692. st.wDayOfWeek = 0;
  203693. st.wYear = (WORD) getYear();
  203694. st.wMonth = (WORD) (getMonth() + 1);
  203695. st.wDay = (WORD) getDayOfMonth();
  203696. st.wHour = (WORD) getHours();
  203697. st.wMinute = (WORD) getMinutes();
  203698. st.wSecond = (WORD) getSeconds();
  203699. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203700. // do this twice because of daylight saving conversion problems - the
  203701. // first one sets it up, the second one kicks it in.
  203702. return SetLocalTime (&st) != 0
  203703. && SetLocalTime (&st) != 0;
  203704. }
  203705. int SystemStats::getPageSize()
  203706. {
  203707. SYSTEM_INFO systemInfo;
  203708. GetSystemInfo (&systemInfo);
  203709. return systemInfo.dwPageSize;
  203710. }
  203711. const String SystemStats::getLogonName()
  203712. {
  203713. TCHAR text [256];
  203714. DWORD len = numElementsInArray (text) - 2;
  203715. zerostruct (text);
  203716. GetUserName (text, &len);
  203717. return String (text, len);
  203718. }
  203719. const String SystemStats::getFullUserName()
  203720. {
  203721. return getLogonName();
  203722. }
  203723. #endif
  203724. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203725. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203726. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203727. // compiled on its own).
  203728. #if JUCE_INCLUDED_FILE
  203729. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203730. extern HWND juce_messageWindowHandle;
  203731. #endif
  203732. #if ! JUCE_USE_INTRINSICS
  203733. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203734. // older ones we have to actually call the ops as win32 functions..
  203735. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203736. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203737. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203738. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203739. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203740. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203741. {
  203742. jassertfalse; // This operation isn't available in old MS compiler versions!
  203743. __int64 oldValue = *value;
  203744. if (oldValue == valueToCompare)
  203745. *value = newValue;
  203746. return oldValue;
  203747. }
  203748. #endif
  203749. CriticalSection::CriticalSection() throw()
  203750. {
  203751. // (just to check the MS haven't changed this structure and broken things...)
  203752. #if JUCE_VC7_OR_EARLIER
  203753. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203754. #else
  203755. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203756. #endif
  203757. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203758. }
  203759. CriticalSection::~CriticalSection() throw()
  203760. {
  203761. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203762. }
  203763. void CriticalSection::enter() const throw()
  203764. {
  203765. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203766. }
  203767. bool CriticalSection::tryEnter() const throw()
  203768. {
  203769. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203770. }
  203771. void CriticalSection::exit() const throw()
  203772. {
  203773. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203774. }
  203775. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203776. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203777. {
  203778. }
  203779. WaitableEvent::~WaitableEvent() throw()
  203780. {
  203781. CloseHandle (internal);
  203782. }
  203783. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203784. {
  203785. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203786. }
  203787. void WaitableEvent::signal() const throw()
  203788. {
  203789. SetEvent (internal);
  203790. }
  203791. void WaitableEvent::reset() const throw()
  203792. {
  203793. ResetEvent (internal);
  203794. }
  203795. void JUCE_API juce_threadEntryPoint (void*);
  203796. static unsigned int __stdcall threadEntryProc (void* userData)
  203797. {
  203798. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203799. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203800. GetCurrentThreadId(), TRUE);
  203801. #endif
  203802. juce_threadEntryPoint (userData);
  203803. _endthreadex (0);
  203804. return 0;
  203805. }
  203806. void Thread::launchThread()
  203807. {
  203808. unsigned int newThreadId;
  203809. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203810. threadId_ = (ThreadID) newThreadId;
  203811. }
  203812. void Thread::closeThreadHandle()
  203813. {
  203814. CloseHandle ((HANDLE) threadHandle_);
  203815. threadId_ = 0;
  203816. threadHandle_ = 0;
  203817. }
  203818. void Thread::killThread()
  203819. {
  203820. if (threadHandle_ != 0)
  203821. {
  203822. #if JUCE_DEBUG
  203823. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203824. #endif
  203825. TerminateThread (threadHandle_, 0);
  203826. }
  203827. }
  203828. void Thread::setCurrentThreadName (const String& name)
  203829. {
  203830. #if JUCE_DEBUG && JUCE_MSVC
  203831. struct
  203832. {
  203833. DWORD dwType;
  203834. LPCSTR szName;
  203835. DWORD dwThreadID;
  203836. DWORD dwFlags;
  203837. } info;
  203838. info.dwType = 0x1000;
  203839. info.szName = name.toCString();
  203840. info.dwThreadID = GetCurrentThreadId();
  203841. info.dwFlags = 0;
  203842. __try
  203843. {
  203844. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203845. }
  203846. __except (EXCEPTION_CONTINUE_EXECUTION)
  203847. {}
  203848. #else
  203849. (void) name;
  203850. #endif
  203851. }
  203852. Thread::ThreadID Thread::getCurrentThreadId()
  203853. {
  203854. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203855. }
  203856. bool Thread::setThreadPriority (void* handle, int priority)
  203857. {
  203858. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203859. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203860. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203861. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203862. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203863. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203864. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203865. if (handle == 0)
  203866. handle = GetCurrentThread();
  203867. return SetThreadPriority (handle, pri) != FALSE;
  203868. }
  203869. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203870. {
  203871. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203872. }
  203873. struct SleepEvent
  203874. {
  203875. SleepEvent()
  203876. : handle (CreateEvent (0, 0, 0,
  203877. #if JUCE_DEBUG
  203878. _T("Juce Sleep Event")))
  203879. #else
  203880. 0))
  203881. #endif
  203882. {
  203883. }
  203884. HANDLE handle;
  203885. };
  203886. static SleepEvent sleepEvent;
  203887. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203888. {
  203889. if (millisecs >= 10)
  203890. {
  203891. Sleep (millisecs);
  203892. }
  203893. else
  203894. {
  203895. // unlike Sleep() this is guaranteed to return to the current thread after
  203896. // the time expires, so we'll use this for short waits, which are more likely
  203897. // to need to be accurate
  203898. WaitForSingleObject (sleepEvent.handle, millisecs);
  203899. }
  203900. }
  203901. void Thread::yield()
  203902. {
  203903. Sleep (0);
  203904. }
  203905. static int lastProcessPriority = -1;
  203906. // called by WindowDriver because Windows does wierd things to process priority
  203907. // when you swap apps, and this forces an update when the app is brought to the front.
  203908. void juce_repeatLastProcessPriority()
  203909. {
  203910. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203911. {
  203912. DWORD p;
  203913. switch (lastProcessPriority)
  203914. {
  203915. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203916. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203917. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203918. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203919. default: jassertfalse; return; // bad priority value
  203920. }
  203921. SetPriorityClass (GetCurrentProcess(), p);
  203922. }
  203923. }
  203924. void Process::setPriority (ProcessPriority prior)
  203925. {
  203926. if (lastProcessPriority != (int) prior)
  203927. {
  203928. lastProcessPriority = (int) prior;
  203929. juce_repeatLastProcessPriority();
  203930. }
  203931. }
  203932. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203933. {
  203934. return IsDebuggerPresent() != FALSE;
  203935. }
  203936. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203937. {
  203938. return juce_isRunningUnderDebugger();
  203939. }
  203940. void Process::raisePrivilege()
  203941. {
  203942. jassertfalse; // xxx not implemented
  203943. }
  203944. void Process::lowerPrivilege()
  203945. {
  203946. jassertfalse; // xxx not implemented
  203947. }
  203948. void Process::terminate()
  203949. {
  203950. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203951. _CrtDumpMemoryLeaks();
  203952. #endif
  203953. // bullet in the head in case there's a problem shutting down..
  203954. ExitProcess (0);
  203955. }
  203956. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203957. {
  203958. void* result = 0;
  203959. JUCE_TRY
  203960. {
  203961. result = LoadLibrary (name);
  203962. }
  203963. JUCE_CATCH_ALL
  203964. return result;
  203965. }
  203966. void PlatformUtilities::freeDynamicLibrary (void* h)
  203967. {
  203968. JUCE_TRY
  203969. {
  203970. if (h != 0)
  203971. FreeLibrary ((HMODULE) h);
  203972. }
  203973. JUCE_CATCH_ALL
  203974. }
  203975. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203976. {
  203977. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203978. }
  203979. class InterProcessLock::Pimpl
  203980. {
  203981. public:
  203982. Pimpl (const String& name, const int timeOutMillisecs)
  203983. : handle (0), refCount (1)
  203984. {
  203985. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203986. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203987. {
  203988. if (timeOutMillisecs == 0)
  203989. {
  203990. close();
  203991. return;
  203992. }
  203993. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203994. {
  203995. case WAIT_OBJECT_0:
  203996. case WAIT_ABANDONED:
  203997. break;
  203998. case WAIT_TIMEOUT:
  203999. default:
  204000. close();
  204001. break;
  204002. }
  204003. }
  204004. }
  204005. ~Pimpl()
  204006. {
  204007. close();
  204008. }
  204009. void close()
  204010. {
  204011. if (handle != 0)
  204012. {
  204013. ReleaseMutex (handle);
  204014. CloseHandle (handle);
  204015. handle = 0;
  204016. }
  204017. }
  204018. HANDLE handle;
  204019. int refCount;
  204020. };
  204021. InterProcessLock::InterProcessLock (const String& name_)
  204022. : name (name_)
  204023. {
  204024. }
  204025. InterProcessLock::~InterProcessLock()
  204026. {
  204027. }
  204028. bool InterProcessLock::enter (const int timeOutMillisecs)
  204029. {
  204030. const ScopedLock sl (lock);
  204031. if (pimpl == 0)
  204032. {
  204033. pimpl = new Pimpl (name, timeOutMillisecs);
  204034. if (pimpl->handle == 0)
  204035. pimpl = 0;
  204036. }
  204037. else
  204038. {
  204039. pimpl->refCount++;
  204040. }
  204041. return pimpl != 0;
  204042. }
  204043. void InterProcessLock::exit()
  204044. {
  204045. const ScopedLock sl (lock);
  204046. // Trying to release the lock too many times!
  204047. jassert (pimpl != 0);
  204048. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204049. pimpl = 0;
  204050. }
  204051. #endif
  204052. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204053. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204054. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204055. // compiled on its own).
  204056. #if JUCE_INCLUDED_FILE
  204057. #ifndef CSIDL_MYMUSIC
  204058. #define CSIDL_MYMUSIC 0x000d
  204059. #endif
  204060. #ifndef CSIDL_MYVIDEO
  204061. #define CSIDL_MYVIDEO 0x000e
  204062. #endif
  204063. #ifndef INVALID_FILE_ATTRIBUTES
  204064. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204065. #endif
  204066. namespace WindowsFileHelpers
  204067. {
  204068. int64 fileTimeToTime (const FILETIME* const ft)
  204069. {
  204070. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204071. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204072. }
  204073. void timeToFileTime (const int64 time, FILETIME* const ft)
  204074. {
  204075. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204076. }
  204077. const String getDriveFromPath (const String& path)
  204078. {
  204079. if (path.isNotEmpty() && path[1] == ':')
  204080. return path.substring (0, 2) + '\\';
  204081. return path;
  204082. }
  204083. int64 getDiskSpaceInfo (const String& path, const bool total)
  204084. {
  204085. ULARGE_INTEGER spc, tot, totFree;
  204086. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204087. return total ? (int64) tot.QuadPart
  204088. : (int64) spc.QuadPart;
  204089. return 0;
  204090. }
  204091. unsigned int getWindowsDriveType (const String& path)
  204092. {
  204093. return GetDriveType (getDriveFromPath (path));
  204094. }
  204095. const File getSpecialFolderPath (int type)
  204096. {
  204097. WCHAR path [MAX_PATH + 256];
  204098. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204099. return File (String (path));
  204100. return File::nonexistent;
  204101. }
  204102. }
  204103. const juce_wchar File::separator = '\\';
  204104. const String File::separatorString ("\\");
  204105. bool File::exists() const
  204106. {
  204107. return fullPath.isNotEmpty()
  204108. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204109. }
  204110. bool File::existsAsFile() const
  204111. {
  204112. return fullPath.isNotEmpty()
  204113. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204114. }
  204115. bool File::isDirectory() const
  204116. {
  204117. const DWORD attr = GetFileAttributes (fullPath);
  204118. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204119. }
  204120. bool File::hasWriteAccess() const
  204121. {
  204122. if (exists())
  204123. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204124. // on windows, it seems that even read-only directories can still be written into,
  204125. // so checking the parent directory's permissions would return the wrong result..
  204126. return true;
  204127. }
  204128. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204129. {
  204130. DWORD attr = GetFileAttributes (fullPath);
  204131. if (attr == INVALID_FILE_ATTRIBUTES)
  204132. return false;
  204133. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204134. return true;
  204135. if (shouldBeReadOnly)
  204136. attr |= FILE_ATTRIBUTE_READONLY;
  204137. else
  204138. attr &= ~FILE_ATTRIBUTE_READONLY;
  204139. return SetFileAttributes (fullPath, attr) != FALSE;
  204140. }
  204141. bool File::isHidden() const
  204142. {
  204143. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204144. }
  204145. bool File::deleteFile() const
  204146. {
  204147. if (! exists())
  204148. return true;
  204149. else if (isDirectory())
  204150. return RemoveDirectory (fullPath) != 0;
  204151. else
  204152. return DeleteFile (fullPath) != 0;
  204153. }
  204154. bool File::moveToTrash() const
  204155. {
  204156. if (! exists())
  204157. return true;
  204158. SHFILEOPSTRUCT fos;
  204159. zerostruct (fos);
  204160. // The string we pass in must be double null terminated..
  204161. String doubleNullTermPath (getFullPathName() + " ");
  204162. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204163. p [getFullPathName().length()] = 0;
  204164. fos.wFunc = FO_DELETE;
  204165. fos.pFrom = p;
  204166. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204167. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204168. return SHFileOperation (&fos) == 0;
  204169. }
  204170. bool File::copyInternal (const File& dest) const
  204171. {
  204172. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204173. }
  204174. bool File::moveInternal (const File& dest) const
  204175. {
  204176. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204177. }
  204178. void File::createDirectoryInternal (const String& fileName) const
  204179. {
  204180. CreateDirectory (fileName, 0);
  204181. }
  204182. int64 juce_fileSetPosition (void* handle, int64 pos)
  204183. {
  204184. LARGE_INTEGER li;
  204185. li.QuadPart = pos;
  204186. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204187. return li.QuadPart;
  204188. }
  204189. void FileInputStream::openHandle()
  204190. {
  204191. totalSize = file.getSize();
  204192. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204193. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204194. if (h != INVALID_HANDLE_VALUE)
  204195. fileHandle = (void*) h;
  204196. }
  204197. void FileInputStream::closeHandle()
  204198. {
  204199. CloseHandle ((HANDLE) fileHandle);
  204200. }
  204201. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204202. {
  204203. if (fileHandle != 0)
  204204. {
  204205. DWORD actualNum = 0;
  204206. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204207. return (size_t) actualNum;
  204208. }
  204209. return 0;
  204210. }
  204211. void FileOutputStream::openHandle()
  204212. {
  204213. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204214. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204215. if (h != INVALID_HANDLE_VALUE)
  204216. {
  204217. LARGE_INTEGER li;
  204218. li.QuadPart = 0;
  204219. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204220. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204221. {
  204222. fileHandle = (void*) h;
  204223. currentPosition = li.QuadPart;
  204224. }
  204225. }
  204226. }
  204227. void FileOutputStream::closeHandle()
  204228. {
  204229. CloseHandle ((HANDLE) fileHandle);
  204230. }
  204231. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204232. {
  204233. if (fileHandle != 0)
  204234. {
  204235. DWORD actualNum = 0;
  204236. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204237. return (int) actualNum;
  204238. }
  204239. return 0;
  204240. }
  204241. void FileOutputStream::flushInternal()
  204242. {
  204243. if (fileHandle != 0)
  204244. FlushFileBuffers ((HANDLE) fileHandle);
  204245. }
  204246. int64 File::getSize() const
  204247. {
  204248. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204249. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204250. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204251. return 0;
  204252. }
  204253. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204254. {
  204255. using namespace WindowsFileHelpers;
  204256. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204257. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204258. {
  204259. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204260. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204261. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204262. }
  204263. else
  204264. {
  204265. creationTime = accessTime = modificationTime = 0;
  204266. }
  204267. }
  204268. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204269. {
  204270. using namespace WindowsFileHelpers;
  204271. bool ok = false;
  204272. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204273. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204274. if (h != INVALID_HANDLE_VALUE)
  204275. {
  204276. FILETIME m, a, c;
  204277. timeToFileTime (modificationTime, &m);
  204278. timeToFileTime (accessTime, &a);
  204279. timeToFileTime (creationTime, &c);
  204280. ok = SetFileTime (h,
  204281. creationTime > 0 ? &c : 0,
  204282. accessTime > 0 ? &a : 0,
  204283. modificationTime > 0 ? &m : 0) != 0;
  204284. CloseHandle (h);
  204285. }
  204286. return ok;
  204287. }
  204288. void File::findFileSystemRoots (Array<File>& destArray)
  204289. {
  204290. TCHAR buffer [2048];
  204291. buffer[0] = 0;
  204292. buffer[1] = 0;
  204293. GetLogicalDriveStrings (2048, buffer);
  204294. const TCHAR* n = buffer;
  204295. StringArray roots;
  204296. while (*n != 0)
  204297. {
  204298. roots.add (String (n));
  204299. while (*n++ != 0)
  204300. {}
  204301. }
  204302. roots.sort (true);
  204303. for (int i = 0; i < roots.size(); ++i)
  204304. destArray.add (roots [i]);
  204305. }
  204306. const String File::getVolumeLabel() const
  204307. {
  204308. TCHAR dest[64];
  204309. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204310. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204311. dest[0] = 0;
  204312. return dest;
  204313. }
  204314. int File::getVolumeSerialNumber() const
  204315. {
  204316. TCHAR dest[64];
  204317. DWORD serialNum;
  204318. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204319. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204320. return 0;
  204321. return (int) serialNum;
  204322. }
  204323. int64 File::getBytesFreeOnVolume() const
  204324. {
  204325. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204326. }
  204327. int64 File::getVolumeTotalSize() const
  204328. {
  204329. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204330. }
  204331. bool File::isOnCDRomDrive() const
  204332. {
  204333. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204334. }
  204335. bool File::isOnHardDisk() const
  204336. {
  204337. if (fullPath.isEmpty())
  204338. return false;
  204339. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204340. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204341. return n != DRIVE_REMOVABLE;
  204342. else
  204343. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204344. }
  204345. bool File::isOnRemovableDrive() const
  204346. {
  204347. if (fullPath.isEmpty())
  204348. return false;
  204349. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204350. return n == DRIVE_CDROM
  204351. || n == DRIVE_REMOTE
  204352. || n == DRIVE_REMOVABLE
  204353. || n == DRIVE_RAMDISK;
  204354. }
  204355. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204356. {
  204357. int csidlType = 0;
  204358. switch (type)
  204359. {
  204360. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204361. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204362. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204363. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204364. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204365. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204366. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204367. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204368. case tempDirectory:
  204369. {
  204370. WCHAR dest [2048];
  204371. dest[0] = 0;
  204372. GetTempPath (numElementsInArray (dest), dest);
  204373. return File (String (dest));
  204374. }
  204375. case invokedExecutableFile:
  204376. case currentExecutableFile:
  204377. case currentApplicationFile:
  204378. {
  204379. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204380. WCHAR dest [MAX_PATH + 256];
  204381. dest[0] = 0;
  204382. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204383. return File (String (dest));
  204384. }
  204385. case hostApplicationPath:
  204386. {
  204387. WCHAR dest [MAX_PATH + 256];
  204388. dest[0] = 0;
  204389. GetModuleFileName (0, dest, numElementsInArray (dest));
  204390. return File (String (dest));
  204391. }
  204392. default:
  204393. jassertfalse; // unknown type?
  204394. return File::nonexistent;
  204395. }
  204396. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204397. }
  204398. const File File::getCurrentWorkingDirectory()
  204399. {
  204400. WCHAR dest [MAX_PATH + 256];
  204401. dest[0] = 0;
  204402. GetCurrentDirectory (numElementsInArray (dest), dest);
  204403. return File (String (dest));
  204404. }
  204405. bool File::setAsCurrentWorkingDirectory() const
  204406. {
  204407. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204408. }
  204409. const String File::getVersion() const
  204410. {
  204411. String result;
  204412. DWORD handle = 0;
  204413. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204414. HeapBlock<char> buffer;
  204415. buffer.calloc (bufferSize);
  204416. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204417. {
  204418. VS_FIXEDFILEINFO* vffi;
  204419. UINT len = 0;
  204420. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204421. {
  204422. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204423. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204424. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204425. << (int) LOWORD (vffi->dwFileVersionLS);
  204426. }
  204427. }
  204428. return result;
  204429. }
  204430. const File File::getLinkedTarget() const
  204431. {
  204432. File result (*this);
  204433. String p (getFullPathName());
  204434. if (! exists())
  204435. p += ".lnk";
  204436. else if (getFileExtension() != ".lnk")
  204437. return result;
  204438. ComSmartPtr <IShellLink> shellLink;
  204439. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204440. {
  204441. ComSmartPtr <IPersistFile> persistFile;
  204442. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204443. {
  204444. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204445. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204446. {
  204447. WIN32_FIND_DATA winFindData;
  204448. WCHAR resolvedPath [MAX_PATH];
  204449. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204450. result = File (resolvedPath);
  204451. }
  204452. }
  204453. }
  204454. return result;
  204455. }
  204456. class DirectoryIterator::NativeIterator::Pimpl
  204457. {
  204458. public:
  204459. Pimpl (const File& directory, const String& wildCard)
  204460. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204461. handle (INVALID_HANDLE_VALUE)
  204462. {
  204463. }
  204464. ~Pimpl()
  204465. {
  204466. if (handle != INVALID_HANDLE_VALUE)
  204467. FindClose (handle);
  204468. }
  204469. bool next (String& filenameFound,
  204470. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204471. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204472. {
  204473. using namespace WindowsFileHelpers;
  204474. WIN32_FIND_DATA findData;
  204475. if (handle == INVALID_HANDLE_VALUE)
  204476. {
  204477. handle = FindFirstFile (directoryWithWildCard, &findData);
  204478. if (handle == INVALID_HANDLE_VALUE)
  204479. return false;
  204480. }
  204481. else
  204482. {
  204483. if (FindNextFile (handle, &findData) == 0)
  204484. return false;
  204485. }
  204486. filenameFound = findData.cFileName;
  204487. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204488. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204489. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204490. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204491. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204492. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204493. return true;
  204494. }
  204495. private:
  204496. const String directoryWithWildCard;
  204497. HANDLE handle;
  204498. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204499. };
  204500. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204501. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204502. {
  204503. }
  204504. DirectoryIterator::NativeIterator::~NativeIterator()
  204505. {
  204506. }
  204507. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204508. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204509. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204510. {
  204511. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204512. }
  204513. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204514. {
  204515. HINSTANCE hInstance = 0;
  204516. JUCE_TRY
  204517. {
  204518. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204519. }
  204520. JUCE_CATCH_ALL
  204521. return hInstance > (HINSTANCE) 32;
  204522. }
  204523. void File::revealToUser() const
  204524. {
  204525. if (isDirectory())
  204526. startAsProcess();
  204527. else if (getParentDirectory().exists())
  204528. getParentDirectory().startAsProcess();
  204529. }
  204530. class NamedPipeInternal
  204531. {
  204532. public:
  204533. NamedPipeInternal (const String& file, const bool isPipe_)
  204534. : pipeH (0),
  204535. cancelEvent (0),
  204536. connected (false),
  204537. isPipe (isPipe_)
  204538. {
  204539. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204540. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204541. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204542. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204543. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204544. }
  204545. ~NamedPipeInternal()
  204546. {
  204547. disconnectPipe();
  204548. if (pipeH != 0)
  204549. CloseHandle (pipeH);
  204550. CloseHandle (cancelEvent);
  204551. }
  204552. bool connect (const int timeOutMs)
  204553. {
  204554. if (! isPipe)
  204555. return true;
  204556. if (! connected)
  204557. {
  204558. OVERLAPPED over;
  204559. zerostruct (over);
  204560. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204561. if (ConnectNamedPipe (pipeH, &over))
  204562. {
  204563. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204564. }
  204565. else
  204566. {
  204567. const int err = GetLastError();
  204568. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204569. {
  204570. HANDLE handles[] = { over.hEvent, cancelEvent };
  204571. if (WaitForMultipleObjects (2, handles, FALSE,
  204572. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204573. connected = true;
  204574. }
  204575. else if (err == ERROR_PIPE_CONNECTED)
  204576. {
  204577. connected = true;
  204578. }
  204579. }
  204580. CloseHandle (over.hEvent);
  204581. }
  204582. return connected;
  204583. }
  204584. void disconnectPipe()
  204585. {
  204586. if (connected)
  204587. {
  204588. DisconnectNamedPipe (pipeH);
  204589. connected = false;
  204590. }
  204591. }
  204592. HANDLE pipeH;
  204593. HANDLE cancelEvent;
  204594. bool connected, isPipe;
  204595. };
  204596. void NamedPipe::close()
  204597. {
  204598. cancelPendingReads();
  204599. const ScopedLock sl (lock);
  204600. delete static_cast<NamedPipeInternal*> (internal);
  204601. internal = 0;
  204602. }
  204603. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204604. {
  204605. close();
  204606. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204607. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204608. {
  204609. internal = intern.release();
  204610. return true;
  204611. }
  204612. return false;
  204613. }
  204614. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204615. {
  204616. const ScopedLock sl (lock);
  204617. int bytesRead = -1;
  204618. bool waitAgain = true;
  204619. while (waitAgain && internal != 0)
  204620. {
  204621. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204622. waitAgain = false;
  204623. if (! intern->connect (timeOutMilliseconds))
  204624. break;
  204625. if (maxBytesToRead <= 0)
  204626. return 0;
  204627. OVERLAPPED over;
  204628. zerostruct (over);
  204629. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204630. unsigned long numRead;
  204631. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204632. {
  204633. bytesRead = (int) numRead;
  204634. }
  204635. else if (GetLastError() == ERROR_IO_PENDING)
  204636. {
  204637. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204638. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204639. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204640. : INFINITE);
  204641. if (waitResult != WAIT_OBJECT_0)
  204642. {
  204643. // if the operation timed out, let's cancel it...
  204644. CancelIo (intern->pipeH);
  204645. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204646. }
  204647. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204648. {
  204649. bytesRead = (int) numRead;
  204650. }
  204651. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204652. {
  204653. intern->disconnectPipe();
  204654. waitAgain = true;
  204655. }
  204656. }
  204657. else
  204658. {
  204659. waitAgain = internal != 0;
  204660. Sleep (5);
  204661. }
  204662. CloseHandle (over.hEvent);
  204663. }
  204664. return bytesRead;
  204665. }
  204666. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204667. {
  204668. int bytesWritten = -1;
  204669. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204670. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204671. {
  204672. if (numBytesToWrite <= 0)
  204673. return 0;
  204674. OVERLAPPED over;
  204675. zerostruct (over);
  204676. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204677. unsigned long numWritten;
  204678. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204679. {
  204680. bytesWritten = (int) numWritten;
  204681. }
  204682. else if (GetLastError() == ERROR_IO_PENDING)
  204683. {
  204684. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204685. DWORD waitResult;
  204686. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204687. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204688. : INFINITE);
  204689. if (waitResult != WAIT_OBJECT_0)
  204690. {
  204691. CancelIo (intern->pipeH);
  204692. WaitForSingleObject (over.hEvent, INFINITE);
  204693. }
  204694. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204695. {
  204696. bytesWritten = (int) numWritten;
  204697. }
  204698. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204699. {
  204700. intern->disconnectPipe();
  204701. }
  204702. }
  204703. CloseHandle (over.hEvent);
  204704. }
  204705. return bytesWritten;
  204706. }
  204707. void NamedPipe::cancelPendingReads()
  204708. {
  204709. if (internal != 0)
  204710. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204711. }
  204712. #endif
  204713. /*** End of inlined file: juce_win32_Files.cpp ***/
  204714. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204715. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204716. // compiled on its own).
  204717. #if JUCE_INCLUDED_FILE
  204718. #ifndef INTERNET_FLAG_NEED_FILE
  204719. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204720. #endif
  204721. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204722. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204723. #endif
  204724. struct ConnectionAndRequestStruct
  204725. {
  204726. HINTERNET connection, request;
  204727. };
  204728. static HINTERNET sessionHandle = 0;
  204729. #ifndef WORKAROUND_TIMEOUT_BUG
  204730. //#define WORKAROUND_TIMEOUT_BUG 1
  204731. #endif
  204732. #if WORKAROUND_TIMEOUT_BUG
  204733. // Required because of a Microsoft bug in setting a timeout
  204734. class InternetConnectThread : public Thread
  204735. {
  204736. public:
  204737. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204738. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204739. {
  204740. startThread();
  204741. }
  204742. ~InternetConnectThread()
  204743. {
  204744. stopThread (60000);
  204745. }
  204746. void run()
  204747. {
  204748. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204749. uc.nPort, _T(""), _T(""),
  204750. isFtp ? INTERNET_SERVICE_FTP
  204751. : INTERNET_SERVICE_HTTP,
  204752. 0, 0);
  204753. notify();
  204754. }
  204755. private:
  204756. URL_COMPONENTS& uc;
  204757. HINTERNET& connection;
  204758. const bool isFtp;
  204759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204760. };
  204761. #endif
  204762. class WebInputStream : public InputStream
  204763. {
  204764. public:
  204765. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204766. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204767. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204768. : connection (0), request (0),
  204769. address (address_), headers (headers_), postData (postData_), position (0),
  204770. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204771. {
  204772. createConnection (progressCallback, progressCallbackContext);
  204773. if (responseHeaders != 0 && ! isError())
  204774. {
  204775. DWORD bufferSizeBytes = 4096;
  204776. for (;;)
  204777. {
  204778. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204779. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204780. {
  204781. StringArray headersArray;
  204782. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204783. for (int i = 0; i < headersArray.size(); ++i)
  204784. {
  204785. const String& header = headersArray[i];
  204786. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204787. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204788. const String previousValue ((*responseHeaders) [key]);
  204789. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204790. }
  204791. break;
  204792. }
  204793. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204794. break;
  204795. }
  204796. }
  204797. }
  204798. ~WebInputStream()
  204799. {
  204800. close();
  204801. }
  204802. bool isError() const { return request == 0; }
  204803. bool isExhausted() { return finished; }
  204804. int64 getPosition() { return position; }
  204805. int64 getTotalLength()
  204806. {
  204807. if (! isError())
  204808. {
  204809. DWORD index = 0, result = 0, size = sizeof (result);
  204810. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204811. return (int64) result;
  204812. }
  204813. return -1;
  204814. }
  204815. int read (void* buffer, int bytesToRead)
  204816. {
  204817. DWORD bytesRead = 0;
  204818. if (! (finished || isError()))
  204819. {
  204820. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204821. position += bytesRead;
  204822. if (bytesRead == 0)
  204823. finished = true;
  204824. }
  204825. return (int) bytesRead;
  204826. }
  204827. bool setPosition (int64 wantedPos)
  204828. {
  204829. if (isError())
  204830. return false;
  204831. if (wantedPos != position)
  204832. {
  204833. finished = false;
  204834. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204835. if (position == wantedPos)
  204836. return true;
  204837. if (wantedPos < position)
  204838. {
  204839. close();
  204840. position = 0;
  204841. createConnection (0, 0);
  204842. }
  204843. skipNextBytes (wantedPos - position);
  204844. }
  204845. return true;
  204846. }
  204847. private:
  204848. HINTERNET connection, request;
  204849. String address, headers;
  204850. MemoryBlock postData;
  204851. int64 position;
  204852. bool finished;
  204853. const bool isPost;
  204854. int timeOutMs;
  204855. void close()
  204856. {
  204857. if (request != 0)
  204858. {
  204859. InternetCloseHandle (request);
  204860. request = 0;
  204861. }
  204862. if (connection != 0)
  204863. {
  204864. InternetCloseHandle (connection);
  204865. connection = 0;
  204866. }
  204867. }
  204868. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204869. void* progressCallbackContext)
  204870. {
  204871. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204872. close();
  204873. if (sessionHandle != 0)
  204874. {
  204875. // break up the url..
  204876. TCHAR file[1024], server[1024];
  204877. URL_COMPONENTS uc;
  204878. zerostruct (uc);
  204879. uc.dwStructSize = sizeof (uc);
  204880. uc.dwUrlPathLength = sizeof (file);
  204881. uc.dwHostNameLength = sizeof (server);
  204882. uc.lpszUrlPath = file;
  204883. uc.lpszHostName = server;
  204884. if (InternetCrackUrl (address, 0, 0, &uc))
  204885. {
  204886. int disable = 1;
  204887. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204888. if (timeOutMs == 0)
  204889. timeOutMs = 30000;
  204890. else if (timeOutMs < 0)
  204891. timeOutMs = -1;
  204892. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204893. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204894. #if WORKAROUND_TIMEOUT_BUG
  204895. connection = 0;
  204896. {
  204897. InternetConnectThread connectThread (uc, connection, isFtp);
  204898. connectThread.wait (timeOutMs);
  204899. if (connection == 0)
  204900. {
  204901. InternetCloseHandle (sessionHandle);
  204902. sessionHandle = 0;
  204903. }
  204904. }
  204905. #else
  204906. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204907. _T(""), _T(""),
  204908. isFtp ? INTERNET_SERVICE_FTP
  204909. : INTERNET_SERVICE_HTTP,
  204910. 0, 0);
  204911. #endif
  204912. if (connection != 0)
  204913. {
  204914. if (isFtp)
  204915. {
  204916. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204917. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204918. }
  204919. else
  204920. {
  204921. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204922. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204923. if (address.startsWithIgnoreCase ("https:"))
  204924. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204925. // IE7 seems to automatically work out when it's https)
  204926. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204927. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204928. if (request != 0)
  204929. {
  204930. INTERNET_BUFFERS buffers;
  204931. zerostruct (buffers);
  204932. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204933. buffers.lpcszHeader = static_cast <LPCTSTR> (headers);
  204934. buffers.dwHeadersLength = headers.length();
  204935. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204936. ConnectionAndRequestStruct* result = 0;
  204937. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204938. {
  204939. int bytesSent = 0;
  204940. for (;;)
  204941. {
  204942. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204943. DWORD bytesDone = 0;
  204944. if (bytesToDo > 0
  204945. && ! InternetWriteFile (request,
  204946. static_cast <const char*> (postData.getData()) + bytesSent,
  204947. bytesToDo, &bytesDone))
  204948. {
  204949. break;
  204950. }
  204951. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204952. {
  204953. if (HttpEndRequest (request, 0, 0, 0))
  204954. return;
  204955. break;
  204956. }
  204957. bytesSent += bytesDone;
  204958. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204959. break;
  204960. }
  204961. }
  204962. }
  204963. close();
  204964. }
  204965. }
  204966. }
  204967. }
  204968. }
  204969. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204970. };
  204971. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204972. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204973. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204974. {
  204975. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204976. progressCallback, progressCallbackContext,
  204977. headers, timeOutMs, responseHeaders));
  204978. return wi->isError() ? 0 : wi.release();
  204979. }
  204980. namespace MACAddressHelpers
  204981. {
  204982. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204983. {
  204984. DynamicLibraryLoader dll ("iphlpapi.dll");
  204985. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204986. if (getAdaptersInfo != 0)
  204987. {
  204988. ULONG len = sizeof (IP_ADAPTER_INFO);
  204989. MemoryBlock mb;
  204990. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204991. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204992. {
  204993. mb.setSize (len);
  204994. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204995. }
  204996. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204997. {
  204998. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204999. {
  205000. if (adapter->AddressLength >= 6)
  205001. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205002. }
  205003. }
  205004. }
  205005. }
  205006. void getViaNetBios (Array<MACAddress>& result)
  205007. {
  205008. DynamicLibraryLoader dll ("netapi32.dll");
  205009. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205010. if (NetbiosCall != 0)
  205011. {
  205012. NCB ncb;
  205013. zerostruct (ncb);
  205014. struct ASTAT
  205015. {
  205016. ADAPTER_STATUS adapt;
  205017. NAME_BUFFER NameBuff [30];
  205018. };
  205019. ASTAT astat;
  205020. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205021. LANA_ENUM enums;
  205022. zerostruct (enums);
  205023. ncb.ncb_command = NCBENUM;
  205024. ncb.ncb_buffer = (unsigned char*) &enums;
  205025. ncb.ncb_length = sizeof (LANA_ENUM);
  205026. NetbiosCall (&ncb);
  205027. for (int i = 0; i < enums.length; ++i)
  205028. {
  205029. zerostruct (ncb);
  205030. ncb.ncb_command = NCBRESET;
  205031. ncb.ncb_lana_num = enums.lana[i];
  205032. if (NetbiosCall (&ncb) == 0)
  205033. {
  205034. zerostruct (ncb);
  205035. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205036. ncb.ncb_command = NCBASTAT;
  205037. ncb.ncb_lana_num = enums.lana[i];
  205038. ncb.ncb_buffer = (unsigned char*) &astat;
  205039. ncb.ncb_length = sizeof (ASTAT);
  205040. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205041. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205042. }
  205043. }
  205044. }
  205045. }
  205046. }
  205047. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205048. {
  205049. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205050. MACAddressHelpers::getViaNetBios (result);
  205051. }
  205052. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205053. const String& emailSubject,
  205054. const String& bodyText,
  205055. const StringArray& filesToAttach)
  205056. {
  205057. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205058. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205059. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205060. bool ok = false;
  205061. if (mapiSendMail != 0)
  205062. {
  205063. MapiMessage message;
  205064. zerostruct (message);
  205065. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205066. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205067. MapiRecipDesc recip;
  205068. zerostruct (recip);
  205069. recip.ulRecipClass = MAPI_TO;
  205070. String targetEmailAddress_ (targetEmailAddress);
  205071. if (targetEmailAddress_.isEmpty())
  205072. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205073. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205074. message.nRecipCount = 1;
  205075. message.lpRecips = &recip;
  205076. HeapBlock <MapiFileDesc> files;
  205077. files.calloc (filesToAttach.size());
  205078. message.nFileCount = filesToAttach.size();
  205079. message.lpFiles = files;
  205080. for (int i = 0; i < filesToAttach.size(); ++i)
  205081. {
  205082. files[i].nPosition = (ULONG) -1;
  205083. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205084. }
  205085. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205086. }
  205087. FreeLibrary (h);
  205088. return ok;
  205089. }
  205090. #endif
  205091. /*** End of inlined file: juce_win32_Network.cpp ***/
  205092. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205093. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205094. // compiled on its own).
  205095. #if JUCE_INCLUDED_FILE
  205096. namespace
  205097. {
  205098. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205099. {
  205100. HKEY rootKey = 0;
  205101. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205102. rootKey = HKEY_CURRENT_USER;
  205103. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205104. rootKey = HKEY_LOCAL_MACHINE;
  205105. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205106. rootKey = HKEY_CLASSES_ROOT;
  205107. if (rootKey != 0)
  205108. {
  205109. name = name.substring (name.indexOfChar ('\\') + 1);
  205110. const int lastSlash = name.lastIndexOfChar ('\\');
  205111. valueName = name.substring (lastSlash + 1);
  205112. name = name.substring (0, lastSlash);
  205113. HKEY key;
  205114. DWORD result;
  205115. if (createForWriting)
  205116. {
  205117. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205118. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205119. return key;
  205120. }
  205121. else
  205122. {
  205123. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205124. return key;
  205125. }
  205126. }
  205127. return 0;
  205128. }
  205129. }
  205130. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205131. const String& defaultValue)
  205132. {
  205133. String valueName, result (defaultValue);
  205134. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205135. if (k != 0)
  205136. {
  205137. WCHAR buffer [2048];
  205138. unsigned long bufferSize = sizeof (buffer);
  205139. DWORD type = REG_SZ;
  205140. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205141. {
  205142. if (type == REG_SZ)
  205143. result = buffer;
  205144. else if (type == REG_DWORD)
  205145. result = String ((int) *(DWORD*) buffer);
  205146. }
  205147. RegCloseKey (k);
  205148. }
  205149. return result;
  205150. }
  205151. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205152. const String& value)
  205153. {
  205154. String valueName;
  205155. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205156. if (k != 0)
  205157. {
  205158. RegSetValueEx (k, valueName, 0, REG_SZ,
  205159. (const BYTE*) (const WCHAR*) value,
  205160. sizeof (WCHAR) * (value.length() + 1));
  205161. RegCloseKey (k);
  205162. }
  205163. }
  205164. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205165. {
  205166. bool exists = false;
  205167. String valueName;
  205168. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205169. if (k != 0)
  205170. {
  205171. unsigned char buffer [2048];
  205172. unsigned long bufferSize = sizeof (buffer);
  205173. DWORD type = 0;
  205174. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205175. exists = true;
  205176. RegCloseKey (k);
  205177. }
  205178. return exists;
  205179. }
  205180. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205181. {
  205182. String valueName;
  205183. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205184. if (k != 0)
  205185. {
  205186. RegDeleteValue (k, valueName);
  205187. RegCloseKey (k);
  205188. }
  205189. }
  205190. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205191. {
  205192. String valueName;
  205193. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205194. if (k != 0)
  205195. {
  205196. RegDeleteKey (k, valueName);
  205197. RegCloseKey (k);
  205198. }
  205199. }
  205200. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205201. const String& symbolicDescription,
  205202. const String& fullDescription,
  205203. const File& targetExecutable,
  205204. int iconResourceNumber)
  205205. {
  205206. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205207. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205208. if (iconResourceNumber != 0)
  205209. setRegistryValue (key + "\\DefaultIcon\\",
  205210. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205211. setRegistryValue (key + "\\", fullDescription);
  205212. setRegistryValue (key + "\\shell\\open\\command\\",
  205213. targetExecutable.getFullPathName() + " %1");
  205214. }
  205215. bool juce_IsRunningInWine()
  205216. {
  205217. HKEY key;
  205218. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205219. {
  205220. RegCloseKey (key);
  205221. return true;
  205222. }
  205223. return false;
  205224. }
  205225. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205226. {
  205227. String s (::GetCommandLineW());
  205228. StringArray tokens;
  205229. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205230. return tokens.joinIntoString (" ", 1);
  205231. }
  205232. static void* currentModuleHandle = 0;
  205233. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205234. {
  205235. if (currentModuleHandle == 0)
  205236. currentModuleHandle = GetModuleHandle (0);
  205237. return currentModuleHandle;
  205238. }
  205239. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205240. {
  205241. currentModuleHandle = newHandle;
  205242. }
  205243. void PlatformUtilities::fpuReset()
  205244. {
  205245. #if JUCE_MSVC
  205246. _clearfp();
  205247. #endif
  205248. }
  205249. void PlatformUtilities::beep()
  205250. {
  205251. MessageBeep (MB_OK);
  205252. }
  205253. #endif
  205254. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205255. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205256. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205257. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205258. // compiled on its own).
  205259. #if JUCE_INCLUDED_FILE
  205260. static const unsigned int specialId = WM_APP + 0x4400;
  205261. static const unsigned int broadcastId = WM_APP + 0x4403;
  205262. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205263. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205264. HWND juce_messageWindowHandle = 0;
  205265. extern long improbableWindowNumber; // defined in windowing.cpp
  205266. #ifndef WM_APPCOMMAND
  205267. #define WM_APPCOMMAND 0x0319
  205268. #endif
  205269. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205270. const UINT message,
  205271. const WPARAM wParam,
  205272. const LPARAM lParam) throw()
  205273. {
  205274. JUCE_TRY
  205275. {
  205276. if (h == juce_messageWindowHandle)
  205277. {
  205278. if (message == specialCallbackId)
  205279. {
  205280. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205281. return (LRESULT) (*func) ((void*) lParam);
  205282. }
  205283. else if (message == specialId)
  205284. {
  205285. // these are trapped early in the dispatch call, but must also be checked
  205286. // here in case there are windows modal dialog boxes doing their own
  205287. // dispatch loop and not calling our version
  205288. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205289. return 0;
  205290. }
  205291. else if (message == broadcastId)
  205292. {
  205293. const ScopedPointer <String> messageString ((String*) lParam);
  205294. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205295. return 0;
  205296. }
  205297. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205298. {
  205299. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205300. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205301. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205302. return 0;
  205303. }
  205304. }
  205305. }
  205306. JUCE_CATCH_EXCEPTION
  205307. return DefWindowProc (h, message, wParam, lParam);
  205308. }
  205309. static bool isEventBlockedByModalComps (MSG& m)
  205310. {
  205311. if (Component::getNumCurrentlyModalComponents() == 0
  205312. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205313. return false;
  205314. switch (m.message)
  205315. {
  205316. case WM_MOUSEMOVE:
  205317. case WM_NCMOUSEMOVE:
  205318. case 0x020A: /* WM_MOUSEWHEEL */
  205319. case 0x020E: /* WM_MOUSEHWHEEL */
  205320. case WM_KEYUP:
  205321. case WM_SYSKEYUP:
  205322. case WM_CHAR:
  205323. case WM_APPCOMMAND:
  205324. case WM_LBUTTONUP:
  205325. case WM_MBUTTONUP:
  205326. case WM_RBUTTONUP:
  205327. case WM_MOUSEACTIVATE:
  205328. case WM_NCMOUSEHOVER:
  205329. case WM_MOUSEHOVER:
  205330. return true;
  205331. case WM_NCLBUTTONDOWN:
  205332. case WM_NCLBUTTONDBLCLK:
  205333. case WM_NCRBUTTONDOWN:
  205334. case WM_NCRBUTTONDBLCLK:
  205335. case WM_NCMBUTTONDOWN:
  205336. case WM_NCMBUTTONDBLCLK:
  205337. case WM_LBUTTONDOWN:
  205338. case WM_LBUTTONDBLCLK:
  205339. case WM_MBUTTONDOWN:
  205340. case WM_MBUTTONDBLCLK:
  205341. case WM_RBUTTONDOWN:
  205342. case WM_RBUTTONDBLCLK:
  205343. case WM_KEYDOWN:
  205344. case WM_SYSKEYDOWN:
  205345. {
  205346. Component* const modal = Component::getCurrentlyModalComponent (0);
  205347. if (modal != 0)
  205348. modal->inputAttemptWhenModal();
  205349. return true;
  205350. }
  205351. default:
  205352. break;
  205353. }
  205354. return false;
  205355. }
  205356. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205357. {
  205358. MSG m;
  205359. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205360. return false;
  205361. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205362. {
  205363. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205364. {
  205365. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205366. }
  205367. else if (m.message == WM_QUIT)
  205368. {
  205369. if (JUCEApplication::getInstance() != 0)
  205370. JUCEApplication::getInstance()->systemRequestedQuit();
  205371. }
  205372. else if (! isEventBlockedByModalComps (m))
  205373. {
  205374. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205375. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205376. {
  205377. // if it's someone else's window being clicked on, and the focus is
  205378. // currently on a juce window, pass the kb focus over..
  205379. HWND currentFocus = GetFocus();
  205380. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205381. SetFocus (m.hwnd);
  205382. }
  205383. TranslateMessage (&m);
  205384. DispatchMessage (&m);
  205385. }
  205386. }
  205387. return true;
  205388. }
  205389. bool juce_postMessageToSystemQueue (Message* message)
  205390. {
  205391. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205392. }
  205393. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205394. void* userData)
  205395. {
  205396. if (MessageManager::getInstance()->isThisTheMessageThread())
  205397. {
  205398. return (*callback) (userData);
  205399. }
  205400. else
  205401. {
  205402. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205403. // deadlock because the message manager is blocked from running, and can't
  205404. // call your function..
  205405. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205406. return (void*) SendMessage (juce_messageWindowHandle,
  205407. specialCallbackId,
  205408. (WPARAM) callback,
  205409. (LPARAM) userData);
  205410. }
  205411. }
  205412. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205413. {
  205414. if (hwnd != juce_messageWindowHandle)
  205415. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205416. return TRUE;
  205417. }
  205418. void MessageManager::broadcastMessage (const String& value)
  205419. {
  205420. Array<void*> windows;
  205421. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205422. const String localCopy (value);
  205423. COPYDATASTRUCT data;
  205424. data.dwData = broadcastId;
  205425. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205426. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205427. for (int i = windows.size(); --i >= 0;)
  205428. {
  205429. HWND hwnd = (HWND) windows.getUnchecked(i);
  205430. TCHAR windowName [64]; // no need to read longer strings than this
  205431. GetWindowText (hwnd, windowName, 64);
  205432. windowName [63] = 0;
  205433. if (String (windowName) == messageWindowName)
  205434. {
  205435. DWORD_PTR result;
  205436. SendMessageTimeout (hwnd, WM_COPYDATA,
  205437. (WPARAM) juce_messageWindowHandle,
  205438. (LPARAM) &data,
  205439. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205440. 8000,
  205441. &result);
  205442. }
  205443. }
  205444. }
  205445. static const String getMessageWindowClassName()
  205446. {
  205447. // this name has to be different for each app/dll instance because otherwise
  205448. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205449. // window class).
  205450. static int number = 0;
  205451. if (number == 0)
  205452. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205453. return "JUCEcs_" + String (number);
  205454. }
  205455. void MessageManager::doPlatformSpecificInitialisation()
  205456. {
  205457. OleInitialize (0);
  205458. const String className (getMessageWindowClassName());
  205459. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205460. WNDCLASSEX wc;
  205461. zerostruct (wc);
  205462. wc.cbSize = sizeof (wc);
  205463. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205464. wc.cbWndExtra = 4;
  205465. wc.hInstance = hmod;
  205466. wc.lpszClassName = className;
  205467. RegisterClassEx (&wc);
  205468. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205469. messageWindowName,
  205470. 0, 0, 0, 0, 0, 0, 0,
  205471. hmod, 0);
  205472. }
  205473. void MessageManager::doPlatformSpecificShutdown()
  205474. {
  205475. DestroyWindow (juce_messageWindowHandle);
  205476. UnregisterClass (getMessageWindowClassName(), 0);
  205477. OleUninitialize();
  205478. }
  205479. #endif
  205480. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205481. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205482. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205483. // compiled on its own).
  205484. #if JUCE_INCLUDED_FILE
  205485. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205486. NEWTEXTMETRICEXW*,
  205487. int type,
  205488. LPARAM lParam)
  205489. {
  205490. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205491. {
  205492. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205493. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205494. }
  205495. return 1;
  205496. }
  205497. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205498. NEWTEXTMETRICEXW*,
  205499. int type,
  205500. LPARAM lParam)
  205501. {
  205502. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205503. {
  205504. LOGFONTW lf;
  205505. zerostruct (lf);
  205506. lf.lfWeight = FW_DONTCARE;
  205507. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205508. lf.lfQuality = DEFAULT_QUALITY;
  205509. lf.lfCharSet = DEFAULT_CHARSET;
  205510. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205511. lf.lfPitchAndFamily = FF_DONTCARE;
  205512. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205513. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205514. HDC dc = CreateCompatibleDC (0);
  205515. EnumFontFamiliesEx (dc, &lf,
  205516. (FONTENUMPROCW) &wfontEnum2,
  205517. lParam, 0);
  205518. DeleteDC (dc);
  205519. }
  205520. return 1;
  205521. }
  205522. const StringArray Font::findAllTypefaceNames()
  205523. {
  205524. StringArray results;
  205525. HDC dc = CreateCompatibleDC (0);
  205526. {
  205527. LOGFONTW lf;
  205528. zerostruct (lf);
  205529. lf.lfWeight = FW_DONTCARE;
  205530. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205531. lf.lfQuality = DEFAULT_QUALITY;
  205532. lf.lfCharSet = DEFAULT_CHARSET;
  205533. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205534. lf.lfPitchAndFamily = FF_DONTCARE;
  205535. lf.lfFaceName[0] = 0;
  205536. EnumFontFamiliesEx (dc, &lf,
  205537. (FONTENUMPROCW) &wfontEnum1,
  205538. (LPARAM) &results, 0);
  205539. }
  205540. DeleteDC (dc);
  205541. results.sort (true);
  205542. return results;
  205543. }
  205544. extern bool juce_IsRunningInWine();
  205545. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205546. {
  205547. if (juce_IsRunningInWine())
  205548. {
  205549. // If we're running in Wine, then use fonts that might be available on Linux..
  205550. defaultSans = "Bitstream Vera Sans";
  205551. defaultSerif = "Bitstream Vera Serif";
  205552. defaultFixed = "Bitstream Vera Sans Mono";
  205553. }
  205554. else
  205555. {
  205556. defaultSans = "Verdana";
  205557. defaultSerif = "Times";
  205558. defaultFixed = "Lucida Console";
  205559. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205560. }
  205561. }
  205562. class FontDCHolder : private DeletedAtShutdown
  205563. {
  205564. public:
  205565. FontDCHolder()
  205566. : dc (0), numKPs (0), size (0),
  205567. bold (false), italic (false)
  205568. {
  205569. }
  205570. ~FontDCHolder()
  205571. {
  205572. if (dc != 0)
  205573. {
  205574. DeleteDC (dc);
  205575. DeleteObject (fontH);
  205576. }
  205577. clearSingletonInstance();
  205578. }
  205579. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205580. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205581. {
  205582. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205583. {
  205584. fontName = fontName_;
  205585. bold = bold_;
  205586. italic = italic_;
  205587. size = size_;
  205588. if (dc != 0)
  205589. {
  205590. DeleteDC (dc);
  205591. DeleteObject (fontH);
  205592. kps.free();
  205593. }
  205594. fontH = 0;
  205595. dc = CreateCompatibleDC (0);
  205596. SetMapperFlags (dc, 0);
  205597. SetMapMode (dc, MM_TEXT);
  205598. LOGFONTW lfw;
  205599. zerostruct (lfw);
  205600. lfw.lfCharSet = DEFAULT_CHARSET;
  205601. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205602. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205603. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205604. lfw.lfQuality = PROOF_QUALITY;
  205605. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205606. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205607. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205608. lfw.lfHeight = size > 0 ? size : -256;
  205609. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205610. if (standardSizedFont != 0)
  205611. {
  205612. if (SelectObject (dc, standardSizedFont) != 0)
  205613. {
  205614. fontH = standardSizedFont;
  205615. if (size == 0)
  205616. {
  205617. OUTLINETEXTMETRIC otm;
  205618. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205619. {
  205620. lfw.lfHeight = -(int) otm.otmEMSquare;
  205621. fontH = CreateFontIndirect (&lfw);
  205622. SelectObject (dc, fontH);
  205623. DeleteObject (standardSizedFont);
  205624. }
  205625. }
  205626. }
  205627. else
  205628. {
  205629. jassertfalse;
  205630. }
  205631. }
  205632. else
  205633. {
  205634. jassertfalse;
  205635. }
  205636. }
  205637. return dc;
  205638. }
  205639. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205640. {
  205641. if (kps == 0)
  205642. {
  205643. numKPs = GetKerningPairs (dc, 0, 0);
  205644. kps.calloc (numKPs);
  205645. GetKerningPairs (dc, numKPs, kps);
  205646. }
  205647. numKPs_ = numKPs;
  205648. return kps;
  205649. }
  205650. private:
  205651. HFONT fontH;
  205652. HDC dc;
  205653. String fontName;
  205654. HeapBlock <KERNINGPAIR> kps;
  205655. int numKPs, size;
  205656. bool bold, italic;
  205657. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205658. };
  205659. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205660. class WindowsTypeface : public CustomTypeface
  205661. {
  205662. public:
  205663. WindowsTypeface (const Font& font)
  205664. {
  205665. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205666. font.isBold(), font.isItalic(), 0);
  205667. TEXTMETRIC tm;
  205668. tm.tmAscent = tm.tmHeight = 1;
  205669. tm.tmDefaultChar = 0;
  205670. GetTextMetrics (dc, &tm);
  205671. setCharacteristics (font.getTypefaceName(),
  205672. tm.tmAscent / (float) tm.tmHeight,
  205673. font.isBold(), font.isItalic(),
  205674. tm.tmDefaultChar);
  205675. }
  205676. bool loadGlyphIfPossible (juce_wchar character)
  205677. {
  205678. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205679. GLYPHMETRICS gm;
  205680. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205681. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205682. // gets correctly created later on.
  205683. if (! isFallbackFont)
  205684. {
  205685. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205686. WORD index = 0;
  205687. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205688. && index == 0xffff)
  205689. {
  205690. return false;
  205691. }
  205692. }
  205693. Path glyphPath;
  205694. TEXTMETRIC tm;
  205695. if (! GetTextMetrics (dc, &tm))
  205696. {
  205697. addGlyph (character, glyphPath, 0);
  205698. return true;
  205699. }
  205700. const float height = (float) tm.tmHeight;
  205701. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205702. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205703. &gm, 0, 0, &identityMatrix);
  205704. if (bufSize > 0)
  205705. {
  205706. HeapBlock<char> data (bufSize);
  205707. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205708. bufSize, data, &identityMatrix);
  205709. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205710. const float scaleX = 1.0f / height;
  205711. const float scaleY = -1.0f / height;
  205712. while ((char*) pheader < data + bufSize)
  205713. {
  205714. float x = scaleX * pheader->pfxStart.x.value;
  205715. float y = scaleY * pheader->pfxStart.y.value;
  205716. glyphPath.startNewSubPath (x, y);
  205717. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205718. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205719. while ((const char*) curve < curveEnd)
  205720. {
  205721. if (curve->wType == TT_PRIM_LINE)
  205722. {
  205723. for (int i = 0; i < curve->cpfx; ++i)
  205724. {
  205725. x = scaleX * curve->apfx[i].x.value;
  205726. y = scaleY * curve->apfx[i].y.value;
  205727. glyphPath.lineTo (x, y);
  205728. }
  205729. }
  205730. else if (curve->wType == TT_PRIM_QSPLINE)
  205731. {
  205732. for (int i = 0; i < curve->cpfx - 1; ++i)
  205733. {
  205734. const float x2 = scaleX * curve->apfx[i].x.value;
  205735. const float y2 = scaleY * curve->apfx[i].y.value;
  205736. float x3, y3;
  205737. if (i < curve->cpfx - 2)
  205738. {
  205739. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205740. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205741. }
  205742. else
  205743. {
  205744. x3 = scaleX * curve->apfx[i + 1].x.value;
  205745. y3 = scaleY * curve->apfx[i + 1].y.value;
  205746. }
  205747. glyphPath.quadraticTo (x2, y2, x3, y3);
  205748. x = x3;
  205749. y = y3;
  205750. }
  205751. }
  205752. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205753. }
  205754. pheader = (const TTPOLYGONHEADER*) curve;
  205755. glyphPath.closeSubPath();
  205756. }
  205757. }
  205758. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205759. int numKPs;
  205760. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205761. for (int i = 0; i < numKPs; ++i)
  205762. {
  205763. if (kps[i].wFirst == character)
  205764. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205765. kps[i].iKernAmount / height);
  205766. }
  205767. return true;
  205768. }
  205769. private:
  205770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205771. };
  205772. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205773. {
  205774. return new WindowsTypeface (font);
  205775. }
  205776. #endif
  205777. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205778. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205779. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205780. // compiled on its own).
  205781. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205782. class SharedD2DFactory : public DeletedAtShutdown
  205783. {
  205784. public:
  205785. SharedD2DFactory()
  205786. {
  205787. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205788. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205789. if (directWriteFactory != 0)
  205790. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205791. }
  205792. ~SharedD2DFactory()
  205793. {
  205794. clearSingletonInstance();
  205795. }
  205796. juce_DeclareSingleton (SharedD2DFactory, false);
  205797. ComSmartPtr <ID2D1Factory> d2dFactory;
  205798. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205799. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205800. };
  205801. juce_ImplementSingleton (SharedD2DFactory)
  205802. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205803. {
  205804. public:
  205805. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205806. : hwnd (hwnd_),
  205807. currentState (0)
  205808. {
  205809. RECT windowRect;
  205810. GetClientRect (hwnd, &windowRect);
  205811. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205812. bounds.setSize (size.width, size.height);
  205813. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205814. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205815. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205816. // xxx check for error
  205817. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205818. }
  205819. ~Direct2DLowLevelGraphicsContext()
  205820. {
  205821. states.clear();
  205822. }
  205823. void resized()
  205824. {
  205825. RECT windowRect;
  205826. GetClientRect (hwnd, &windowRect);
  205827. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205828. renderingTarget->Resize (size);
  205829. bounds.setSize (size.width, size.height);
  205830. }
  205831. void clear()
  205832. {
  205833. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205834. }
  205835. void start()
  205836. {
  205837. renderingTarget->BeginDraw();
  205838. saveState();
  205839. }
  205840. void end()
  205841. {
  205842. states.clear();
  205843. currentState = 0;
  205844. renderingTarget->EndDraw();
  205845. renderingTarget->CheckWindowState();
  205846. }
  205847. bool isVectorDevice() const { return false; }
  205848. void setOrigin (int x, int y)
  205849. {
  205850. currentState->origin.addXY (x, y);
  205851. }
  205852. void addTransform (const AffineTransform& transform)
  205853. {
  205854. //xxx todo
  205855. jassertfalse;
  205856. }
  205857. float getScaleFactor()
  205858. {
  205859. jassertfalse; //xxx
  205860. return 1.0f;
  205861. }
  205862. bool clipToRectangle (const Rectangle<int>& r)
  205863. {
  205864. currentState->clipToRectangle (r);
  205865. return ! isClipEmpty();
  205866. }
  205867. bool clipToRectangleList (const RectangleList& clipRegion)
  205868. {
  205869. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205870. return ! isClipEmpty();
  205871. }
  205872. void excludeClipRectangle (const Rectangle<int>&)
  205873. {
  205874. //xxx
  205875. }
  205876. void clipToPath (const Path& path, const AffineTransform& transform)
  205877. {
  205878. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205879. }
  205880. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205881. {
  205882. currentState->clipToImage (sourceImage,transform);
  205883. }
  205884. bool clipRegionIntersects (const Rectangle<int>& r)
  205885. {
  205886. const Rectangle<int> r2 (r + currentState->origin);
  205887. return currentState->clipRect.intersects (r2);
  205888. }
  205889. const Rectangle<int> getClipBounds() const
  205890. {
  205891. // xxx could this take into account complex clip regions?
  205892. return currentState->clipRect - currentState->origin;
  205893. }
  205894. bool isClipEmpty() const
  205895. {
  205896. return currentState->clipRect.isEmpty();
  205897. }
  205898. void saveState()
  205899. {
  205900. states.add (new SavedState (*this));
  205901. currentState = states.getLast();
  205902. }
  205903. void restoreState()
  205904. {
  205905. jassert (states.size() > 1) //you should never pop the last state!
  205906. states.removeLast (1);
  205907. currentState = states.getLast();
  205908. }
  205909. void beginTransparencyLayer (float opacity)
  205910. {
  205911. jassertfalse; //xxx todo
  205912. }
  205913. void endTransparencyLayer()
  205914. {
  205915. jassertfalse; //xxx todo
  205916. }
  205917. void setFill (const FillType& fillType)
  205918. {
  205919. currentState->setFill (fillType);
  205920. }
  205921. void setOpacity (float newOpacity)
  205922. {
  205923. currentState->setOpacity (newOpacity);
  205924. }
  205925. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205926. {
  205927. }
  205928. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205929. {
  205930. currentState->createBrush();
  205931. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205932. }
  205933. void fillPath (const Path& p, const AffineTransform& transform)
  205934. {
  205935. currentState->createBrush();
  205936. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205937. if (renderingTarget != 0)
  205938. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205939. }
  205940. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205941. {
  205942. const int x = currentState->origin.getX();
  205943. const int y = currentState->origin.getY();
  205944. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205945. D2D1_SIZE_U size;
  205946. size.width = image.getWidth();
  205947. size.height = image.getHeight();
  205948. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205949. Image img (image.convertedToFormat (Image::ARGB));
  205950. Image::BitmapData bd (img, false);
  205951. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205952. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205953. {
  205954. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205955. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205956. if (tempBitmap != 0)
  205957. renderingTarget->DrawBitmap (tempBitmap);
  205958. }
  205959. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205960. }
  205961. void drawLine (const Line <float>& line)
  205962. {
  205963. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205964. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205965. line.getEnd() + currentState->origin.toFloat());
  205966. currentState->createBrush();
  205967. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205968. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205969. currentState->currentBrush);
  205970. }
  205971. void drawVerticalLine (int x, float top, float bottom)
  205972. {
  205973. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205974. currentState->createBrush();
  205975. x += currentState->origin.getX();
  205976. const int y = currentState->origin.getY();
  205977. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205978. D2D1::Point2F (x, y + bottom),
  205979. currentState->currentBrush);
  205980. }
  205981. void drawHorizontalLine (int y, float left, float right)
  205982. {
  205983. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205984. currentState->createBrush();
  205985. y += currentState->origin.getY();
  205986. const int x = currentState->origin.getX();
  205987. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205988. D2D1::Point2F (x + right, y),
  205989. currentState->currentBrush);
  205990. }
  205991. void setFont (const Font& newFont)
  205992. {
  205993. currentState->setFont (newFont);
  205994. }
  205995. const Font getFont()
  205996. {
  205997. return currentState->font;
  205998. }
  205999. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206000. {
  206001. const float x = currentState->origin.getX();
  206002. const float y = currentState->origin.getY();
  206003. currentState->createBrush();
  206004. currentState->createFont();
  206005. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206006. float hScale = currentState->font.getHorizontalScale();
  206007. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206008. float dpiX = 0, dpiY = 0;
  206009. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206010. UINT32 glyphNum = glyphNumber;
  206011. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206012. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206013. DWRITE_GLYPH_OFFSET offset;
  206014. offset.advanceOffset = 0;
  206015. offset.ascenderOffset = 0;
  206016. float glyphAdvances = 0;
  206017. DWRITE_GLYPH_RUN glyph;
  206018. glyph.fontFace = currentState->currentFontFace;
  206019. glyph.glyphCount = 1;
  206020. glyph.glyphIndices = &glyphNum1;
  206021. glyph.isSideways = FALSE;
  206022. glyph.glyphAdvances = &glyphAdvances;
  206023. glyph.glyphOffsets = &offset;
  206024. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206025. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206026. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206027. }
  206028. class SavedState
  206029. {
  206030. public:
  206031. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206032. : owner (owner_), currentBrush (0),
  206033. fontScaling (1.0f), currentFontFace (0),
  206034. clipsRect (false), shouldClipRect (false),
  206035. clipsRectList (false), shouldClipRectList (false),
  206036. clipsComplex (false), shouldClipComplex (false),
  206037. clipsBitmap (false), shouldClipBitmap (false)
  206038. {
  206039. if (owner.currentState != 0)
  206040. {
  206041. // xxx seems like a very slow way to create one of these, and this is a performance
  206042. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206043. setFill (owner.currentState->fillType);
  206044. currentBrush = owner.currentState->currentBrush;
  206045. origin = owner.currentState->origin;
  206046. clipRect = owner.currentState->clipRect;
  206047. font = owner.currentState->font;
  206048. currentFontFace = owner.currentState->currentFontFace;
  206049. }
  206050. else
  206051. {
  206052. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206053. clipRect.setSize (size.width, size.height);
  206054. setFill (FillType (Colours::black));
  206055. }
  206056. }
  206057. ~SavedState()
  206058. {
  206059. clearClip();
  206060. clearFont();
  206061. clearFill();
  206062. clearPathClip();
  206063. clearImageClip();
  206064. complexClipLayer = 0;
  206065. bitmapMaskLayer = 0;
  206066. }
  206067. void clearClip()
  206068. {
  206069. popClips();
  206070. shouldClipRect = false;
  206071. }
  206072. void clipToRectangle (const Rectangle<int>& r)
  206073. {
  206074. clearClip();
  206075. clipRect = r + origin;
  206076. shouldClipRect = true;
  206077. pushClips();
  206078. }
  206079. void clearPathClip()
  206080. {
  206081. popClips();
  206082. if (shouldClipComplex)
  206083. {
  206084. complexClipGeometry = 0;
  206085. shouldClipComplex = false;
  206086. }
  206087. }
  206088. void clipToPath (ID2D1Geometry* geometry)
  206089. {
  206090. clearPathClip();
  206091. if (complexClipLayer == 0)
  206092. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206093. complexClipGeometry = geometry;
  206094. shouldClipComplex = true;
  206095. pushClips();
  206096. }
  206097. void clearRectListClip()
  206098. {
  206099. popClips();
  206100. if (shouldClipRectList)
  206101. {
  206102. rectListGeometry = 0;
  206103. shouldClipRectList = false;
  206104. }
  206105. }
  206106. void clipToRectList (ID2D1Geometry* geometry)
  206107. {
  206108. clearRectListClip();
  206109. if (rectListLayer == 0)
  206110. owner.renderingTarget->CreateLayer (&rectListLayer);
  206111. rectListGeometry = geometry;
  206112. shouldClipRectList = true;
  206113. pushClips();
  206114. }
  206115. void clearImageClip()
  206116. {
  206117. popClips();
  206118. if (shouldClipBitmap)
  206119. {
  206120. maskBitmap = 0;
  206121. bitmapMaskBrush = 0;
  206122. shouldClipBitmap = false;
  206123. }
  206124. }
  206125. void clipToImage (const Image& image, const AffineTransform& transform)
  206126. {
  206127. clearImageClip();
  206128. if (bitmapMaskLayer == 0)
  206129. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206130. D2D1_BRUSH_PROPERTIES brushProps;
  206131. brushProps.opacity = 1;
  206132. brushProps.transform = transfromToMatrix (transform);
  206133. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206134. D2D1_SIZE_U size;
  206135. size.width = image.getWidth();
  206136. size.height = image.getHeight();
  206137. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206138. maskImage = image.convertedToFormat (Image::ARGB);
  206139. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206140. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206141. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206142. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206143. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206144. imageMaskLayerParams = D2D1::LayerParameters();
  206145. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206146. shouldClipBitmap = true;
  206147. pushClips();
  206148. }
  206149. void popClips()
  206150. {
  206151. if (clipsBitmap)
  206152. {
  206153. owner.renderingTarget->PopLayer();
  206154. clipsBitmap = false;
  206155. }
  206156. if (clipsComplex)
  206157. {
  206158. owner.renderingTarget->PopLayer();
  206159. clipsComplex = false;
  206160. }
  206161. if (clipsRectList)
  206162. {
  206163. owner.renderingTarget->PopLayer();
  206164. clipsRectList = false;
  206165. }
  206166. if (clipsRect)
  206167. {
  206168. owner.renderingTarget->PopAxisAlignedClip();
  206169. clipsRect = false;
  206170. }
  206171. }
  206172. void pushClips()
  206173. {
  206174. if (shouldClipRect && ! clipsRect)
  206175. {
  206176. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206177. clipsRect = true;
  206178. }
  206179. if (shouldClipRectList && ! clipsRectList)
  206180. {
  206181. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206182. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206183. layerParams.geometricMask = rectListGeometry;
  206184. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206185. clipsRectList = true;
  206186. }
  206187. if (shouldClipComplex && ! clipsComplex)
  206188. {
  206189. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206190. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206191. layerParams.geometricMask = complexClipGeometry;
  206192. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206193. clipsComplex = true;
  206194. }
  206195. if (shouldClipBitmap && ! clipsBitmap)
  206196. {
  206197. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206198. clipsBitmap = true;
  206199. }
  206200. }
  206201. void setFill (const FillType& newFillType)
  206202. {
  206203. if (fillType != newFillType)
  206204. {
  206205. fillType = newFillType;
  206206. clearFill();
  206207. }
  206208. }
  206209. void clearFont()
  206210. {
  206211. currentFontFace = localFontFace = 0;
  206212. }
  206213. void setFont (const Font& newFont)
  206214. {
  206215. if (font != newFont)
  206216. {
  206217. font = newFont;
  206218. clearFont();
  206219. }
  206220. }
  206221. void createFont()
  206222. {
  206223. // xxx The font shouldn't be managed by the graphics context.
  206224. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206225. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206226. // WindowsTypeface class.
  206227. if (currentFontFace == 0)
  206228. {
  206229. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206230. fontScaling = systemType->getAscent();
  206231. BOOL fontFound;
  206232. uint32 fontIndex;
  206233. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206234. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206235. if (! fontFound)
  206236. fontIndex = 0;
  206237. ComSmartPtr <IDWriteFontFamily> fontFam;
  206238. fonts->GetFontFamily (fontIndex, &fontFam);
  206239. ComSmartPtr <IDWriteFont> font;
  206240. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206241. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206242. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206243. font->CreateFontFace (&localFontFace);
  206244. currentFontFace = localFontFace;
  206245. }
  206246. }
  206247. void setOpacity (float newOpacity)
  206248. {
  206249. fillType.setOpacity (newOpacity);
  206250. if (currentBrush != 0)
  206251. currentBrush->SetOpacity (newOpacity);
  206252. }
  206253. void clearFill()
  206254. {
  206255. gradientStops = 0;
  206256. linearGradient = 0;
  206257. radialGradient = 0;
  206258. bitmap = 0;
  206259. bitmapBrush = 0;
  206260. currentBrush = 0;
  206261. }
  206262. void createBrush()
  206263. {
  206264. if (currentBrush == 0)
  206265. {
  206266. const int x = origin.getX();
  206267. const int y = origin.getY();
  206268. if (fillType.isColour())
  206269. {
  206270. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206271. owner.colourBrush->SetColor (colour);
  206272. currentBrush = owner.colourBrush;
  206273. }
  206274. else if (fillType.isTiledImage())
  206275. {
  206276. D2D1_BRUSH_PROPERTIES brushProps;
  206277. brushProps.opacity = fillType.getOpacity();
  206278. brushProps.transform = transfromToMatrix (fillType.transform);
  206279. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206280. image = fillType.image;
  206281. D2D1_SIZE_U size;
  206282. size.width = image.getWidth();
  206283. size.height = image.getHeight();
  206284. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206285. this->image = image.convertedToFormat (Image::ARGB);
  206286. Image::BitmapData bd (this->image, false);
  206287. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206288. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206289. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206290. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206291. currentBrush = bitmapBrush;
  206292. }
  206293. else if (fillType.isGradient())
  206294. {
  206295. gradientStops = 0;
  206296. D2D1_BRUSH_PROPERTIES brushProps;
  206297. brushProps.opacity = fillType.getOpacity();
  206298. brushProps.transform = transfromToMatrix (fillType.transform);
  206299. const int numColors = fillType.gradient->getNumColours();
  206300. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206301. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206302. {
  206303. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206304. stops[i].position = fillType.gradient->getColourPosition(i);
  206305. }
  206306. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206307. if (fillType.gradient->isRadial)
  206308. {
  206309. radialGradient = 0;
  206310. const Point<float>& p1 = fillType.gradient->point1;
  206311. const Point<float>& p2 = fillType.gradient->point2;
  206312. float r = p1.getDistanceFrom (p2);
  206313. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206314. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206315. D2D1::Point2F (0, 0),
  206316. r, r);
  206317. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206318. currentBrush = radialGradient;
  206319. }
  206320. else
  206321. {
  206322. linearGradient = 0;
  206323. const Point<float>& p1 = fillType.gradient->point1;
  206324. const Point<float>& p2 = fillType.gradient->point2;
  206325. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206326. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206327. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206328. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206329. currentBrush = linearGradient;
  206330. }
  206331. }
  206332. }
  206333. }
  206334. //xxx most of these members should probably be private...
  206335. Direct2DLowLevelGraphicsContext& owner;
  206336. Point<int> origin;
  206337. Font font;
  206338. float fontScaling;
  206339. IDWriteFontFace* currentFontFace;
  206340. ComSmartPtr <IDWriteFontFace> localFontFace;
  206341. FillType fillType;
  206342. Image image;
  206343. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206344. Rectangle<int> clipRect;
  206345. bool clipsRect, shouldClipRect;
  206346. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206347. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206348. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206349. bool clipsComplex, shouldClipComplex;
  206350. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206351. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206352. ComSmartPtr <ID2D1Layer> rectListLayer;
  206353. bool clipsRectList, shouldClipRectList;
  206354. Image maskImage;
  206355. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206356. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206357. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206358. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206359. bool clipsBitmap, shouldClipBitmap;
  206360. ID2D1Brush* currentBrush;
  206361. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206362. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206363. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206364. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206365. private:
  206366. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206367. };
  206368. private:
  206369. HWND hwnd;
  206370. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206371. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206372. Rectangle<int> bounds;
  206373. SavedState* currentState;
  206374. OwnedArray<SavedState> states;
  206375. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206376. {
  206377. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206378. }
  206379. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206380. {
  206381. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206382. }
  206383. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206384. {
  206385. transform.transformPoint (x, y);
  206386. return D2D1::Point2F (x, y);
  206387. }
  206388. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206389. {
  206390. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206391. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206392. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206393. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206394. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206395. }
  206396. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206397. {
  206398. ID2D1PathGeometry* p = 0;
  206399. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206400. ComSmartPtr <ID2D1GeometrySink> sink;
  206401. HRESULT hr = p->Open (&sink); // xxx handle error
  206402. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206403. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206404. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206405. hr = sink->Close();
  206406. return p;
  206407. }
  206408. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206409. {
  206410. Path::Iterator it (path);
  206411. while (it.next())
  206412. {
  206413. switch (it.elementType)
  206414. {
  206415. case Path::Iterator::cubicTo:
  206416. {
  206417. D2D1_BEZIER_SEGMENT seg;
  206418. transform.transformPoint (it.x1, it.y1);
  206419. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206420. transform.transformPoint (it.x2, it.y2);
  206421. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206422. transform.transformPoint(it.x3, it.y3);
  206423. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206424. sink->AddBezier (seg);
  206425. break;
  206426. }
  206427. case Path::Iterator::lineTo:
  206428. {
  206429. transform.transformPoint (it.x1, it.y1);
  206430. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206431. break;
  206432. }
  206433. case Path::Iterator::quadraticTo:
  206434. {
  206435. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206436. transform.transformPoint (it.x1, it.y1);
  206437. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206438. transform.transformPoint (it.x2, it.y2);
  206439. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206440. sink->AddQuadraticBezier (seg);
  206441. break;
  206442. }
  206443. case Path::Iterator::closePath:
  206444. {
  206445. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206446. break;
  206447. }
  206448. case Path::Iterator::startNewSubPath:
  206449. {
  206450. transform.transformPoint (it.x1, it.y1);
  206451. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206452. break;
  206453. }
  206454. }
  206455. }
  206456. }
  206457. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206458. {
  206459. ID2D1PathGeometry* p = 0;
  206460. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206461. ComSmartPtr <ID2D1GeometrySink> sink;
  206462. HRESULT hr = p->Open (&sink);
  206463. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206464. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206465. hr = sink->Close();
  206466. return p;
  206467. }
  206468. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206469. {
  206470. D2D1::Matrix3x2F matrix;
  206471. matrix._11 = transform.mat00;
  206472. matrix._12 = transform.mat10;
  206473. matrix._21 = transform.mat01;
  206474. matrix._22 = transform.mat11;
  206475. matrix._31 = transform.mat02;
  206476. matrix._32 = transform.mat12;
  206477. return matrix;
  206478. }
  206479. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206480. };
  206481. #endif
  206482. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206483. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206484. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206485. // compiled on its own).
  206486. #if JUCE_INCLUDED_FILE
  206487. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206488. // these are in the windows SDK, but need to be repeated here for GCC..
  206489. #ifndef GET_APPCOMMAND_LPARAM
  206490. #define FAPPCOMMAND_MASK 0xF000
  206491. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206492. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206493. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206494. #define APPCOMMAND_MEDIA_STOP 13
  206495. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206496. #define WM_APPCOMMAND 0x0319
  206497. #endif
  206498. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206499. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206500. extern bool juce_IsRunningInWine();
  206501. #ifndef ULW_ALPHA
  206502. #define ULW_ALPHA 0x00000002
  206503. #endif
  206504. #ifndef AC_SRC_ALPHA
  206505. #define AC_SRC_ALPHA 0x01
  206506. #endif
  206507. static HPALETTE palette = 0;
  206508. static bool createPaletteIfNeeded = true;
  206509. static bool shouldDeactivateTitleBar = true;
  206510. #define WM_TRAYNOTIFY WM_USER + 100
  206511. using ::abs;
  206512. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206513. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206514. bool Desktop::canUseSemiTransparentWindows() throw()
  206515. {
  206516. if (updateLayeredWindow == 0)
  206517. {
  206518. if (! juce_IsRunningInWine())
  206519. {
  206520. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206521. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206522. }
  206523. }
  206524. return updateLayeredWindow != 0;
  206525. }
  206526. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206527. {
  206528. return upright;
  206529. }
  206530. const int extendedKeyModifier = 0x10000;
  206531. const int KeyPress::spaceKey = VK_SPACE;
  206532. const int KeyPress::returnKey = VK_RETURN;
  206533. const int KeyPress::escapeKey = VK_ESCAPE;
  206534. const int KeyPress::backspaceKey = VK_BACK;
  206535. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206536. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206537. const int KeyPress::tabKey = VK_TAB;
  206538. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206539. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206540. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206541. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206542. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206543. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206544. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206545. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206546. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206547. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206548. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206549. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206550. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206551. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206552. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206553. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206554. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206555. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206556. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206557. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206558. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206559. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206560. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206561. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206562. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206563. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206564. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206565. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206566. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206567. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206568. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206569. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206570. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206571. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206572. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206573. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206574. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206575. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206576. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206577. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206578. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206579. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206580. const int KeyPress::playKey = 0x30000;
  206581. const int KeyPress::stopKey = 0x30001;
  206582. const int KeyPress::fastForwardKey = 0x30002;
  206583. const int KeyPress::rewindKey = 0x30003;
  206584. class WindowsBitmapImage : public Image::SharedImage
  206585. {
  206586. public:
  206587. HBITMAP hBitmap;
  206588. BITMAPV4HEADER bitmapInfo;
  206589. HDC hdc;
  206590. unsigned char* bitmapData;
  206591. WindowsBitmapImage (const Image::PixelFormat format_,
  206592. const int w, const int h, const bool clearImage)
  206593. : Image::SharedImage (format_, w, h)
  206594. {
  206595. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206596. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206597. zerostruct (bitmapInfo);
  206598. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206599. bitmapInfo.bV4Width = w;
  206600. bitmapInfo.bV4Height = h;
  206601. bitmapInfo.bV4Planes = 1;
  206602. bitmapInfo.bV4CSType = 1;
  206603. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206604. if (format_ == Image::ARGB)
  206605. {
  206606. bitmapInfo.bV4AlphaMask = 0xff000000;
  206607. bitmapInfo.bV4RedMask = 0xff0000;
  206608. bitmapInfo.bV4GreenMask = 0xff00;
  206609. bitmapInfo.bV4BlueMask = 0xff;
  206610. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206611. }
  206612. else
  206613. {
  206614. bitmapInfo.bV4V4Compression = BI_RGB;
  206615. }
  206616. lineStride = -((w * pixelStride + 3) & ~3);
  206617. HDC dc = GetDC (0);
  206618. hdc = CreateCompatibleDC (dc);
  206619. ReleaseDC (0, dc);
  206620. SetMapMode (hdc, MM_TEXT);
  206621. hBitmap = CreateDIBSection (hdc,
  206622. (BITMAPINFO*) &(bitmapInfo),
  206623. DIB_RGB_COLORS,
  206624. (void**) &bitmapData,
  206625. 0, 0);
  206626. SelectObject (hdc, hBitmap);
  206627. if (format_ == Image::ARGB && clearImage)
  206628. zeromem (bitmapData, abs (h * lineStride));
  206629. imageData = bitmapData - (lineStride * (h - 1));
  206630. }
  206631. ~WindowsBitmapImage()
  206632. {
  206633. DeleteDC (hdc);
  206634. DeleteObject (hBitmap);
  206635. }
  206636. Image::ImageType getType() const { return Image::NativeImage; }
  206637. LowLevelGraphicsContext* createLowLevelContext()
  206638. {
  206639. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206640. }
  206641. Image::SharedImage* clone()
  206642. {
  206643. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206644. for (int i = 0; i < height; ++i)
  206645. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206646. return im;
  206647. }
  206648. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206649. const int x, const int y,
  206650. const RectangleList& maskedRegion,
  206651. const uint8 updateLayeredWindowAlpha) throw()
  206652. {
  206653. static HDRAWDIB hdd = 0;
  206654. static bool needToCreateDrawDib = true;
  206655. if (needToCreateDrawDib)
  206656. {
  206657. needToCreateDrawDib = false;
  206658. HDC dc = GetDC (0);
  206659. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206660. ReleaseDC (0, dc);
  206661. // only open if we're not palettised
  206662. if (n > 8)
  206663. hdd = DrawDibOpen();
  206664. }
  206665. if (createPaletteIfNeeded)
  206666. {
  206667. HDC dc = GetDC (0);
  206668. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206669. ReleaseDC (0, dc);
  206670. if (n <= 8)
  206671. palette = CreateHalftonePalette (dc);
  206672. createPaletteIfNeeded = false;
  206673. }
  206674. if (palette != 0)
  206675. {
  206676. SelectPalette (dc, palette, FALSE);
  206677. RealizePalette (dc);
  206678. SetStretchBltMode (dc, HALFTONE);
  206679. }
  206680. SetMapMode (dc, MM_TEXT);
  206681. if (transparent)
  206682. {
  206683. POINT p, pos;
  206684. SIZE size;
  206685. RECT windowBounds;
  206686. GetWindowRect (hwnd, &windowBounds);
  206687. p.x = -x;
  206688. p.y = -y;
  206689. pos.x = windowBounds.left;
  206690. pos.y = windowBounds.top;
  206691. size.cx = windowBounds.right - windowBounds.left;
  206692. size.cy = windowBounds.bottom - windowBounds.top;
  206693. BLENDFUNCTION bf;
  206694. bf.AlphaFormat = AC_SRC_ALPHA;
  206695. bf.BlendFlags = 0;
  206696. bf.BlendOp = AC_SRC_OVER;
  206697. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206698. if (! maskedRegion.isEmpty())
  206699. {
  206700. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206701. {
  206702. const Rectangle<int>& r = *i.getRectangle();
  206703. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206704. }
  206705. }
  206706. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206707. }
  206708. else
  206709. {
  206710. int savedDC = 0;
  206711. if (! maskedRegion.isEmpty())
  206712. {
  206713. savedDC = SaveDC (dc);
  206714. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206715. {
  206716. const Rectangle<int>& r = *i.getRectangle();
  206717. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206718. }
  206719. }
  206720. if (hdd == 0)
  206721. {
  206722. StretchDIBits (dc,
  206723. x, y, width, height,
  206724. 0, 0, width, height,
  206725. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206726. DIB_RGB_COLORS, SRCCOPY);
  206727. }
  206728. else
  206729. {
  206730. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206731. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206732. 0, 0, width, height, 0);
  206733. }
  206734. if (! maskedRegion.isEmpty())
  206735. RestoreDC (dc, savedDC);
  206736. }
  206737. }
  206738. private:
  206739. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206740. };
  206741. namespace IconConverters
  206742. {
  206743. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206744. {
  206745. Image im;
  206746. if (bitmap != 0)
  206747. {
  206748. BITMAP bm;
  206749. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206750. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206751. {
  206752. HDC tempDC = GetDC (0);
  206753. HDC dc = CreateCompatibleDC (tempDC);
  206754. ReleaseDC (0, tempDC);
  206755. SelectObject (dc, bitmap);
  206756. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206757. Image::BitmapData imageData (im, true);
  206758. for (int y = bm.bmHeight; --y >= 0;)
  206759. {
  206760. for (int x = bm.bmWidth; --x >= 0;)
  206761. {
  206762. COLORREF col = GetPixel (dc, x, y);
  206763. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206764. (uint8) GetGValue (col),
  206765. (uint8) GetBValue (col)));
  206766. }
  206767. }
  206768. DeleteDC (dc);
  206769. }
  206770. }
  206771. return im;
  206772. }
  206773. const Image createImageFromHICON (HICON icon)
  206774. {
  206775. ICONINFO info;
  206776. if (GetIconInfo (icon, &info))
  206777. {
  206778. Image mask (createImageFromHBITMAP (info.hbmMask));
  206779. Image image (createImageFromHBITMAP (info.hbmColor));
  206780. if (mask.isValid() && image.isValid())
  206781. {
  206782. for (int y = image.getHeight(); --y >= 0;)
  206783. {
  206784. for (int x = image.getWidth(); --x >= 0;)
  206785. {
  206786. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206787. if (brightness > 0.0f)
  206788. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206789. }
  206790. }
  206791. return image;
  206792. }
  206793. }
  206794. return Image::null;
  206795. }
  206796. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206797. {
  206798. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206799. Image bitmap (nativeBitmap);
  206800. {
  206801. Graphics g (bitmap);
  206802. g.drawImageAt (image, 0, 0);
  206803. }
  206804. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206805. ICONINFO info;
  206806. info.fIcon = isIcon;
  206807. info.xHotspot = hotspotX;
  206808. info.yHotspot = hotspotY;
  206809. info.hbmMask = mask;
  206810. info.hbmColor = nativeBitmap->hBitmap;
  206811. HICON hi = CreateIconIndirect (&info);
  206812. DeleteObject (mask);
  206813. return hi;
  206814. }
  206815. }
  206816. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206817. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206818. {
  206819. SHORT k = (SHORT) keyCode;
  206820. if ((keyCode & extendedKeyModifier) == 0
  206821. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206822. k += (SHORT) 'A' - (SHORT) 'a';
  206823. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206824. (SHORT) '+', VK_OEM_PLUS,
  206825. (SHORT) '-', VK_OEM_MINUS,
  206826. (SHORT) '.', VK_OEM_PERIOD,
  206827. (SHORT) ';', VK_OEM_1,
  206828. (SHORT) ':', VK_OEM_1,
  206829. (SHORT) '/', VK_OEM_2,
  206830. (SHORT) '?', VK_OEM_2,
  206831. (SHORT) '[', VK_OEM_4,
  206832. (SHORT) ']', VK_OEM_6 };
  206833. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206834. if (k == translatedValues [i])
  206835. k = translatedValues [i + 1];
  206836. return (GetKeyState (k) & 0x8000) != 0;
  206837. }
  206838. class Win32ComponentPeer : public ComponentPeer
  206839. {
  206840. public:
  206841. enum RenderingEngineType
  206842. {
  206843. softwareRenderingEngine = 0,
  206844. direct2DRenderingEngine
  206845. };
  206846. Win32ComponentPeer (Component* const component,
  206847. const int windowStyleFlags,
  206848. HWND parentToAddTo_)
  206849. : ComponentPeer (component, windowStyleFlags),
  206850. dontRepaint (false),
  206851. #if JUCE_DIRECT2D
  206852. currentRenderingEngine (direct2DRenderingEngine),
  206853. #else
  206854. currentRenderingEngine (softwareRenderingEngine),
  206855. #endif
  206856. fullScreen (false),
  206857. isDragging (false),
  206858. isMouseOver (false),
  206859. hasCreatedCaret (false),
  206860. currentWindowIcon (0),
  206861. dropTarget (0),
  206862. updateLayeredWindowAlpha (255),
  206863. parentToAddTo (parentToAddTo_)
  206864. {
  206865. callFunctionIfNotLocked (&createWindowCallback, this);
  206866. setTitle (component->getName());
  206867. if ((windowStyleFlags & windowHasDropShadow) != 0
  206868. && Desktop::canUseSemiTransparentWindows())
  206869. {
  206870. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206871. if (shadower != 0)
  206872. shadower->setOwner (component);
  206873. }
  206874. }
  206875. ~Win32ComponentPeer()
  206876. {
  206877. setTaskBarIcon (Image());
  206878. shadower = 0;
  206879. // do this before the next bit to avoid messages arriving for this window
  206880. // before it's destroyed
  206881. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206882. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206883. if (currentWindowIcon != 0)
  206884. DestroyIcon (currentWindowIcon);
  206885. if (dropTarget != 0)
  206886. {
  206887. dropTarget->Release();
  206888. dropTarget = 0;
  206889. }
  206890. #if JUCE_DIRECT2D
  206891. direct2DContext = 0;
  206892. #endif
  206893. }
  206894. void* getNativeHandle() const
  206895. {
  206896. return hwnd;
  206897. }
  206898. void setVisible (bool shouldBeVisible)
  206899. {
  206900. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206901. if (shouldBeVisible)
  206902. InvalidateRect (hwnd, 0, 0);
  206903. else
  206904. lastPaintTime = 0;
  206905. }
  206906. void setTitle (const String& title)
  206907. {
  206908. SetWindowText (hwnd, title);
  206909. }
  206910. void setPosition (int x, int y)
  206911. {
  206912. offsetWithinParent (x, y);
  206913. SetWindowPos (hwnd, 0,
  206914. x - windowBorder.getLeft(),
  206915. y - windowBorder.getTop(),
  206916. 0, 0,
  206917. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206918. }
  206919. void repaintNowIfTransparent()
  206920. {
  206921. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206922. handlePaintMessage();
  206923. }
  206924. void updateBorderSize()
  206925. {
  206926. WINDOWINFO info;
  206927. info.cbSize = sizeof (info);
  206928. if (GetWindowInfo (hwnd, &info))
  206929. {
  206930. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206931. info.rcClient.left - info.rcWindow.left,
  206932. info.rcWindow.bottom - info.rcClient.bottom,
  206933. info.rcWindow.right - info.rcClient.right);
  206934. }
  206935. #if JUCE_DIRECT2D
  206936. if (direct2DContext != 0)
  206937. direct2DContext->resized();
  206938. #endif
  206939. }
  206940. void setSize (int w, int h)
  206941. {
  206942. SetWindowPos (hwnd, 0, 0, 0,
  206943. w + windowBorder.getLeftAndRight(),
  206944. h + windowBorder.getTopAndBottom(),
  206945. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206946. updateBorderSize();
  206947. repaintNowIfTransparent();
  206948. }
  206949. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206950. {
  206951. fullScreen = isNowFullScreen;
  206952. offsetWithinParent (x, y);
  206953. SetWindowPos (hwnd, 0,
  206954. x - windowBorder.getLeft(),
  206955. y - windowBorder.getTop(),
  206956. w + windowBorder.getLeftAndRight(),
  206957. h + windowBorder.getTopAndBottom(),
  206958. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206959. updateBorderSize();
  206960. repaintNowIfTransparent();
  206961. }
  206962. const Rectangle<int> getBounds() const
  206963. {
  206964. RECT r;
  206965. GetWindowRect (hwnd, &r);
  206966. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206967. HWND parentH = GetParent (hwnd);
  206968. if (parentH != 0)
  206969. {
  206970. GetWindowRect (parentH, &r);
  206971. bounds.translate (-r.left, -r.top);
  206972. }
  206973. return windowBorder.subtractedFrom (bounds);
  206974. }
  206975. const Point<int> getScreenPosition() const
  206976. {
  206977. RECT r;
  206978. GetWindowRect (hwnd, &r);
  206979. return Point<int> (r.left + windowBorder.getLeft(),
  206980. r.top + windowBorder.getTop());
  206981. }
  206982. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206983. {
  206984. return relativePosition + getScreenPosition();
  206985. }
  206986. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206987. {
  206988. return screenPosition - getScreenPosition();
  206989. }
  206990. void setAlpha (float newAlpha)
  206991. {
  206992. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206993. if (component->isOpaque())
  206994. {
  206995. if (newAlpha < 1.0f)
  206996. {
  206997. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206998. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206999. }
  207000. else
  207001. {
  207002. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207003. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207004. }
  207005. }
  207006. else
  207007. {
  207008. updateLayeredWindowAlpha = intAlpha;
  207009. component->repaint();
  207010. }
  207011. }
  207012. void setMinimised (bool shouldBeMinimised)
  207013. {
  207014. if (shouldBeMinimised != isMinimised())
  207015. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207016. }
  207017. bool isMinimised() const
  207018. {
  207019. WINDOWPLACEMENT wp;
  207020. wp.length = sizeof (WINDOWPLACEMENT);
  207021. GetWindowPlacement (hwnd, &wp);
  207022. return wp.showCmd == SW_SHOWMINIMIZED;
  207023. }
  207024. void setFullScreen (bool shouldBeFullScreen)
  207025. {
  207026. setMinimised (false);
  207027. if (fullScreen != shouldBeFullScreen)
  207028. {
  207029. fullScreen = shouldBeFullScreen;
  207030. const Component::SafePointer<Component> deletionChecker (component);
  207031. if (! fullScreen)
  207032. {
  207033. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207034. if (hasTitleBar())
  207035. ShowWindow (hwnd, SW_SHOWNORMAL);
  207036. if (! boundsCopy.isEmpty())
  207037. {
  207038. setBounds (boundsCopy.getX(),
  207039. boundsCopy.getY(),
  207040. boundsCopy.getWidth(),
  207041. boundsCopy.getHeight(),
  207042. false);
  207043. }
  207044. }
  207045. else
  207046. {
  207047. if (hasTitleBar())
  207048. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207049. else
  207050. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207051. }
  207052. if (deletionChecker != 0)
  207053. handleMovedOrResized();
  207054. }
  207055. }
  207056. bool isFullScreen() const
  207057. {
  207058. if (! hasTitleBar())
  207059. return fullScreen;
  207060. WINDOWPLACEMENT wp;
  207061. wp.length = sizeof (wp);
  207062. GetWindowPlacement (hwnd, &wp);
  207063. return wp.showCmd == SW_SHOWMAXIMIZED;
  207064. }
  207065. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207066. {
  207067. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207068. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207069. return false;
  207070. RECT r;
  207071. GetWindowRect (hwnd, &r);
  207072. POINT p;
  207073. p.x = position.getX() + r.left + windowBorder.getLeft();
  207074. p.y = position.getY() + r.top + windowBorder.getTop();
  207075. HWND w = WindowFromPoint (p);
  207076. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207077. }
  207078. const BorderSize getFrameSize() const
  207079. {
  207080. return windowBorder;
  207081. }
  207082. bool setAlwaysOnTop (bool alwaysOnTop)
  207083. {
  207084. const bool oldDeactivate = shouldDeactivateTitleBar;
  207085. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207086. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207087. 0, 0, 0, 0,
  207088. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207089. shouldDeactivateTitleBar = oldDeactivate;
  207090. if (shadower != 0)
  207091. shadower->componentBroughtToFront (*component);
  207092. return true;
  207093. }
  207094. void toFront (bool makeActive)
  207095. {
  207096. setMinimised (false);
  207097. const bool oldDeactivate = shouldDeactivateTitleBar;
  207098. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207099. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207100. shouldDeactivateTitleBar = oldDeactivate;
  207101. if (! makeActive)
  207102. {
  207103. // in this case a broughttofront call won't have occured, so do it now..
  207104. handleBroughtToFront();
  207105. }
  207106. }
  207107. void toBehind (ComponentPeer* other)
  207108. {
  207109. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207110. jassert (otherPeer != 0); // wrong type of window?
  207111. if (otherPeer != 0)
  207112. {
  207113. setMinimised (false);
  207114. // must be careful not to try to put a topmost window behind a normal one, or win32
  207115. // promotes the normal one to be topmost!
  207116. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207117. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207118. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207119. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207120. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207121. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207122. }
  207123. }
  207124. bool isFocused() const
  207125. {
  207126. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207127. }
  207128. void grabFocus()
  207129. {
  207130. const bool oldDeactivate = shouldDeactivateTitleBar;
  207131. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207132. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207133. shouldDeactivateTitleBar = oldDeactivate;
  207134. }
  207135. void textInputRequired (const Point<int>&)
  207136. {
  207137. if (! hasCreatedCaret)
  207138. {
  207139. hasCreatedCaret = true;
  207140. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207141. }
  207142. ShowCaret (hwnd);
  207143. SetCaretPos (0, 0);
  207144. }
  207145. void repaint (const Rectangle<int>& area)
  207146. {
  207147. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207148. InvalidateRect (hwnd, &r, FALSE);
  207149. }
  207150. void performAnyPendingRepaintsNow()
  207151. {
  207152. MSG m;
  207153. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207154. DispatchMessage (&m);
  207155. }
  207156. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207157. {
  207158. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207159. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207160. return 0;
  207161. }
  207162. void setTaskBarIcon (const Image& image)
  207163. {
  207164. if (image.isValid())
  207165. {
  207166. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207167. if (taskBarIcon == 0)
  207168. {
  207169. taskBarIcon = new NOTIFYICONDATA();
  207170. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207171. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207172. taskBarIcon->hWnd = (HWND) hwnd;
  207173. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207174. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207175. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207176. taskBarIcon->hIcon = hicon;
  207177. taskBarIcon->szTip[0] = 0;
  207178. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207179. }
  207180. else
  207181. {
  207182. HICON oldIcon = taskBarIcon->hIcon;
  207183. taskBarIcon->hIcon = hicon;
  207184. taskBarIcon->uFlags = NIF_ICON;
  207185. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207186. DestroyIcon (oldIcon);
  207187. }
  207188. }
  207189. else if (taskBarIcon != 0)
  207190. {
  207191. taskBarIcon->uFlags = 0;
  207192. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207193. DestroyIcon (taskBarIcon->hIcon);
  207194. taskBarIcon = 0;
  207195. }
  207196. }
  207197. void setTaskBarIconToolTip (const String& toolTip) const
  207198. {
  207199. if (taskBarIcon != 0)
  207200. {
  207201. taskBarIcon->uFlags = NIF_TIP;
  207202. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207203. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207204. }
  207205. }
  207206. void handleTaskBarEvent (const LPARAM lParam, const WPARAM wParam)
  207207. {
  207208. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207209. {
  207210. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207211. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207212. {
  207213. Component* const current = Component::getCurrentlyModalComponent();
  207214. if (current != 0)
  207215. current->inputAttemptWhenModal();
  207216. }
  207217. }
  207218. else
  207219. {
  207220. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207221. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207222. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207223. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207224. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207225. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207226. eventMods = eventMods.withoutMouseButtons();
  207227. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207228. Point<int>(), eventMods, component, component, getMouseEventTime(),
  207229. Point<int>(), getMouseEventTime(), 1, false);
  207230. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207231. {
  207232. SetFocus (hwnd);
  207233. SetForegroundWindow (hwnd);
  207234. component->mouseDown (e);
  207235. }
  207236. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207237. {
  207238. component->mouseUp (e);
  207239. }
  207240. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207241. {
  207242. component->mouseDoubleClick (e);
  207243. }
  207244. else if (lParam == WM_MOUSEMOVE)
  207245. {
  207246. component->mouseMove (e);
  207247. }
  207248. }
  207249. }
  207250. bool isInside (HWND h) const
  207251. {
  207252. return GetAncestor (hwnd, GA_ROOT) == h;
  207253. }
  207254. static void updateKeyModifiers() throw()
  207255. {
  207256. int keyMods = 0;
  207257. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207258. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207259. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207260. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207261. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207262. }
  207263. static void updateModifiersFromWParam (const WPARAM wParam)
  207264. {
  207265. int mouseMods = 0;
  207266. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207267. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207268. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207269. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207270. updateKeyModifiers();
  207271. }
  207272. static int64 getMouseEventTime()
  207273. {
  207274. static int64 eventTimeOffset = 0;
  207275. static DWORD lastMessageTime = 0;
  207276. const DWORD thisMessageTime = GetMessageTime();
  207277. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207278. {
  207279. lastMessageTime = thisMessageTime;
  207280. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207281. }
  207282. return eventTimeOffset + thisMessageTime;
  207283. }
  207284. bool dontRepaint;
  207285. static ModifierKeys currentModifiers;
  207286. static ModifierKeys modifiersAtLastCallback;
  207287. private:
  207288. HWND hwnd, parentToAddTo;
  207289. ScopedPointer<DropShadower> shadower;
  207290. RenderingEngineType currentRenderingEngine;
  207291. #if JUCE_DIRECT2D
  207292. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207293. #endif
  207294. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207295. BorderSize windowBorder;
  207296. HICON currentWindowIcon;
  207297. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207298. IDropTarget* dropTarget;
  207299. uint8 updateLayeredWindowAlpha;
  207300. class TemporaryImage : public Timer
  207301. {
  207302. public:
  207303. TemporaryImage() {}
  207304. ~TemporaryImage() {}
  207305. const Image& getImage (const bool transparent, const int w, const int h)
  207306. {
  207307. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207308. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207309. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207310. startTimer (3000);
  207311. return image;
  207312. }
  207313. void timerCallback()
  207314. {
  207315. stopTimer();
  207316. image = Image::null;
  207317. }
  207318. private:
  207319. Image image;
  207320. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207321. };
  207322. TemporaryImage offscreenImageGenerator;
  207323. class WindowClassHolder : public DeletedAtShutdown
  207324. {
  207325. public:
  207326. WindowClassHolder()
  207327. : windowClassName ("JUCE_")
  207328. {
  207329. // this name has to be different for each app/dll instance because otherwise
  207330. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207331. // window class).
  207332. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207333. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207334. TCHAR moduleFile [1024];
  207335. moduleFile[0] = 0;
  207336. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207337. WORD iconNum = 0;
  207338. WNDCLASSEX wcex;
  207339. wcex.cbSize = sizeof (wcex);
  207340. wcex.style = CS_OWNDC;
  207341. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207342. wcex.lpszClassName = windowClassName;
  207343. wcex.cbClsExtra = 0;
  207344. wcex.cbWndExtra = 32;
  207345. wcex.hInstance = moduleHandle;
  207346. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207347. iconNum = 1;
  207348. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207349. wcex.hCursor = 0;
  207350. wcex.hbrBackground = 0;
  207351. wcex.lpszMenuName = 0;
  207352. RegisterClassEx (&wcex);
  207353. }
  207354. ~WindowClassHolder()
  207355. {
  207356. if (ComponentPeer::getNumPeers() == 0)
  207357. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207358. clearSingletonInstance();
  207359. }
  207360. String windowClassName;
  207361. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207362. };
  207363. static void* createWindowCallback (void* userData)
  207364. {
  207365. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207366. return 0;
  207367. }
  207368. void createWindow()
  207369. {
  207370. DWORD exstyle = WS_EX_ACCEPTFILES;
  207371. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207372. if (hasTitleBar())
  207373. {
  207374. type |= WS_OVERLAPPED;
  207375. if ((styleFlags & windowHasCloseButton) != 0)
  207376. {
  207377. type |= WS_SYSMENU;
  207378. }
  207379. else
  207380. {
  207381. // annoyingly, windows won't let you have a min/max button without a close button
  207382. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207383. }
  207384. if ((styleFlags & windowIsResizable) != 0)
  207385. type |= WS_THICKFRAME;
  207386. }
  207387. else if (parentToAddTo != 0)
  207388. {
  207389. type |= WS_CHILD;
  207390. }
  207391. else
  207392. {
  207393. type |= WS_POPUP | WS_SYSMENU;
  207394. }
  207395. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207396. exstyle |= WS_EX_TOOLWINDOW;
  207397. else
  207398. exstyle |= WS_EX_APPWINDOW;
  207399. if ((styleFlags & windowHasMinimiseButton) != 0)
  207400. type |= WS_MINIMIZEBOX;
  207401. if ((styleFlags & windowHasMaximiseButton) != 0)
  207402. type |= WS_MAXIMIZEBOX;
  207403. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207404. exstyle |= WS_EX_TRANSPARENT;
  207405. if ((styleFlags & windowIsSemiTransparent) != 0
  207406. && Desktop::canUseSemiTransparentWindows())
  207407. exstyle |= WS_EX_LAYERED;
  207408. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207409. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207410. #if JUCE_DIRECT2D
  207411. updateDirect2DContext();
  207412. #endif
  207413. if (hwnd != 0)
  207414. {
  207415. SetWindowLongPtr (hwnd, 0, 0);
  207416. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207417. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207418. if (dropTarget == 0)
  207419. dropTarget = new JuceDropTarget (this);
  207420. RegisterDragDrop (hwnd, dropTarget);
  207421. updateBorderSize();
  207422. // Calling this function here is (for some reason) necessary to make Windows
  207423. // correctly enable the menu items that we specify in the wm_initmenu message.
  207424. GetSystemMenu (hwnd, false);
  207425. const float alpha = component->getAlpha();
  207426. if (alpha < 1.0f)
  207427. setAlpha (alpha);
  207428. }
  207429. else
  207430. {
  207431. jassertfalse;
  207432. }
  207433. }
  207434. static void* destroyWindowCallback (void* handle)
  207435. {
  207436. RevokeDragDrop ((HWND) handle);
  207437. DestroyWindow ((HWND) handle);
  207438. return 0;
  207439. }
  207440. static void* toFrontCallback1 (void* h)
  207441. {
  207442. SetForegroundWindow ((HWND) h);
  207443. return 0;
  207444. }
  207445. static void* toFrontCallback2 (void* h)
  207446. {
  207447. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207448. return 0;
  207449. }
  207450. static void* setFocusCallback (void* h)
  207451. {
  207452. SetFocus ((HWND) h);
  207453. return 0;
  207454. }
  207455. static void* getFocusCallback (void*)
  207456. {
  207457. return GetFocus();
  207458. }
  207459. void offsetWithinParent (int& x, int& y) const
  207460. {
  207461. if (isUsingUpdateLayeredWindow())
  207462. {
  207463. HWND parentHwnd = GetParent (hwnd);
  207464. if (parentHwnd != 0)
  207465. {
  207466. RECT parentRect;
  207467. GetWindowRect (parentHwnd, &parentRect);
  207468. x += parentRect.left;
  207469. y += parentRect.top;
  207470. }
  207471. }
  207472. }
  207473. bool isUsingUpdateLayeredWindow() const
  207474. {
  207475. return ! component->isOpaque();
  207476. }
  207477. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207478. void setIcon (const Image& newIcon)
  207479. {
  207480. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207481. if (hicon != 0)
  207482. {
  207483. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207484. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207485. if (currentWindowIcon != 0)
  207486. DestroyIcon (currentWindowIcon);
  207487. currentWindowIcon = hicon;
  207488. }
  207489. }
  207490. void handlePaintMessage()
  207491. {
  207492. #if JUCE_DIRECT2D
  207493. if (direct2DContext != 0)
  207494. {
  207495. RECT r;
  207496. if (GetUpdateRect (hwnd, &r, false))
  207497. {
  207498. direct2DContext->start();
  207499. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207500. handlePaint (*direct2DContext);
  207501. direct2DContext->end();
  207502. }
  207503. }
  207504. else
  207505. #endif
  207506. {
  207507. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207508. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207509. PAINTSTRUCT paintStruct;
  207510. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207511. // message and become re-entrant, but that's OK
  207512. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207513. // corrupt the image it's using to paint into, so do a check here.
  207514. static bool reentrant = false;
  207515. if (reentrant)
  207516. {
  207517. DeleteObject (rgn);
  207518. EndPaint (hwnd, &paintStruct);
  207519. return;
  207520. }
  207521. reentrant = true;
  207522. // this is the rectangle to update..
  207523. int x = paintStruct.rcPaint.left;
  207524. int y = paintStruct.rcPaint.top;
  207525. int w = paintStruct.rcPaint.right - x;
  207526. int h = paintStruct.rcPaint.bottom - y;
  207527. const bool transparent = isUsingUpdateLayeredWindow();
  207528. if (transparent)
  207529. {
  207530. // it's not possible to have a transparent window with a title bar at the moment!
  207531. jassert (! hasTitleBar());
  207532. RECT r;
  207533. GetWindowRect (hwnd, &r);
  207534. x = y = 0;
  207535. w = r.right - r.left;
  207536. h = r.bottom - r.top;
  207537. }
  207538. if (w > 0 && h > 0)
  207539. {
  207540. clearMaskedRegion();
  207541. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207542. RectangleList contextClip;
  207543. const Rectangle<int> clipBounds (0, 0, w, h);
  207544. bool needToPaintAll = true;
  207545. if (regionType == COMPLEXREGION && ! transparent)
  207546. {
  207547. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207548. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207549. DeleteObject (clipRgn);
  207550. char rgnData [8192];
  207551. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207552. if (res > 0 && res <= sizeof (rgnData))
  207553. {
  207554. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207555. if (hdr->iType == RDH_RECTANGLES
  207556. && hdr->rcBound.right - hdr->rcBound.left >= w
  207557. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207558. {
  207559. needToPaintAll = false;
  207560. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207561. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207562. while (--num >= 0)
  207563. {
  207564. if (rects->right <= x + w && rects->bottom <= y + h)
  207565. {
  207566. const int cx = jmax (x, (int) rects->left);
  207567. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207568. .getIntersection (clipBounds));
  207569. }
  207570. else
  207571. {
  207572. needToPaintAll = true;
  207573. break;
  207574. }
  207575. ++rects;
  207576. }
  207577. }
  207578. }
  207579. }
  207580. if (needToPaintAll)
  207581. {
  207582. contextClip.clear();
  207583. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207584. }
  207585. if (transparent)
  207586. {
  207587. RectangleList::Iterator i (contextClip);
  207588. while (i.next())
  207589. offscreenImage.clear (*i.getRectangle());
  207590. }
  207591. // if the component's not opaque, this won't draw properly unless the platform can support this
  207592. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207593. updateCurrentModifiers();
  207594. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207595. handlePaint (context);
  207596. if (! dontRepaint)
  207597. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207598. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207599. }
  207600. DeleteObject (rgn);
  207601. EndPaint (hwnd, &paintStruct);
  207602. reentrant = false;
  207603. }
  207604. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207605. _fpreset(); // because some graphics cards can unmask FP exceptions
  207606. #endif
  207607. lastPaintTime = Time::getMillisecondCounter();
  207608. }
  207609. void doMouseEvent (const Point<int>& position)
  207610. {
  207611. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207612. }
  207613. const StringArray getAvailableRenderingEngines()
  207614. {
  207615. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207616. #if JUCE_DIRECT2D
  207617. // xxx is this correct? Seems to enable it on Vista too??
  207618. OSVERSIONINFO info;
  207619. zerostruct (info);
  207620. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207621. GetVersionEx (&info);
  207622. if (info.dwMajorVersion >= 6)
  207623. s.add ("Direct2D");
  207624. #endif
  207625. return s;
  207626. }
  207627. int getCurrentRenderingEngine() throw()
  207628. {
  207629. return currentRenderingEngine;
  207630. }
  207631. #if JUCE_DIRECT2D
  207632. void updateDirect2DContext()
  207633. {
  207634. if (currentRenderingEngine != direct2DRenderingEngine)
  207635. direct2DContext = 0;
  207636. else if (direct2DContext == 0)
  207637. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207638. }
  207639. #endif
  207640. void setCurrentRenderingEngine (int index)
  207641. {
  207642. (void) index;
  207643. #if JUCE_DIRECT2D
  207644. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207645. updateDirect2DContext();
  207646. repaint (component->getLocalBounds());
  207647. #endif
  207648. }
  207649. void doMouseMove (const Point<int>& position)
  207650. {
  207651. if (! isMouseOver)
  207652. {
  207653. isMouseOver = true;
  207654. updateKeyModifiers();
  207655. TRACKMOUSEEVENT tme;
  207656. tme.cbSize = sizeof (tme);
  207657. tme.dwFlags = TME_LEAVE;
  207658. tme.hwndTrack = hwnd;
  207659. tme.dwHoverTime = 0;
  207660. if (! TrackMouseEvent (&tme))
  207661. jassertfalse;
  207662. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207663. }
  207664. else if (! isDragging)
  207665. {
  207666. if (! contains (position, false))
  207667. return;
  207668. }
  207669. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207670. static uint32 lastMouseTime = 0;
  207671. const uint32 now = Time::getMillisecondCounter();
  207672. const int maxMouseMovesPerSecond = 60;
  207673. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207674. {
  207675. lastMouseTime = now;
  207676. doMouseEvent (position);
  207677. }
  207678. }
  207679. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207680. {
  207681. if (GetCapture() != hwnd)
  207682. SetCapture (hwnd);
  207683. doMouseMove (position);
  207684. updateModifiersFromWParam (wParam);
  207685. isDragging = true;
  207686. doMouseEvent (position);
  207687. }
  207688. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207689. {
  207690. updateModifiersFromWParam (wParam);
  207691. isDragging = false;
  207692. // release the mouse capture if the user has released all buttons
  207693. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207694. ReleaseCapture();
  207695. doMouseEvent (position);
  207696. }
  207697. void doCaptureChanged()
  207698. {
  207699. if (isDragging)
  207700. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207701. }
  207702. void doMouseExit()
  207703. {
  207704. isMouseOver = false;
  207705. doMouseEvent (getCurrentMousePos());
  207706. }
  207707. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207708. {
  207709. updateKeyModifiers();
  207710. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207711. handleMouseWheel (0, position, getMouseEventTime(),
  207712. isVertical ? 0.0f : amount,
  207713. isVertical ? amount : 0.0f);
  207714. }
  207715. void sendModifierKeyChangeIfNeeded()
  207716. {
  207717. if (modifiersAtLastCallback != currentModifiers)
  207718. {
  207719. modifiersAtLastCallback = currentModifiers;
  207720. handleModifierKeysChange();
  207721. }
  207722. }
  207723. bool doKeyUp (const WPARAM key)
  207724. {
  207725. updateKeyModifiers();
  207726. switch (key)
  207727. {
  207728. case VK_SHIFT:
  207729. case VK_CONTROL:
  207730. case VK_MENU:
  207731. case VK_CAPITAL:
  207732. case VK_LWIN:
  207733. case VK_RWIN:
  207734. case VK_APPS:
  207735. case VK_NUMLOCK:
  207736. case VK_SCROLL:
  207737. case VK_LSHIFT:
  207738. case VK_RSHIFT:
  207739. case VK_LCONTROL:
  207740. case VK_LMENU:
  207741. case VK_RCONTROL:
  207742. case VK_RMENU:
  207743. sendModifierKeyChangeIfNeeded();
  207744. }
  207745. return handleKeyUpOrDown (false)
  207746. || Component::getCurrentlyModalComponent() != 0;
  207747. }
  207748. bool doKeyDown (const WPARAM key)
  207749. {
  207750. updateKeyModifiers();
  207751. bool used = false;
  207752. switch (key)
  207753. {
  207754. case VK_SHIFT:
  207755. case VK_LSHIFT:
  207756. case VK_RSHIFT:
  207757. case VK_CONTROL:
  207758. case VK_LCONTROL:
  207759. case VK_RCONTROL:
  207760. case VK_MENU:
  207761. case VK_LMENU:
  207762. case VK_RMENU:
  207763. case VK_LWIN:
  207764. case VK_RWIN:
  207765. case VK_CAPITAL:
  207766. case VK_NUMLOCK:
  207767. case VK_SCROLL:
  207768. case VK_APPS:
  207769. sendModifierKeyChangeIfNeeded();
  207770. break;
  207771. case VK_LEFT:
  207772. case VK_RIGHT:
  207773. case VK_UP:
  207774. case VK_DOWN:
  207775. case VK_PRIOR:
  207776. case VK_NEXT:
  207777. case VK_HOME:
  207778. case VK_END:
  207779. case VK_DELETE:
  207780. case VK_INSERT:
  207781. case VK_F1:
  207782. case VK_F2:
  207783. case VK_F3:
  207784. case VK_F4:
  207785. case VK_F5:
  207786. case VK_F6:
  207787. case VK_F7:
  207788. case VK_F8:
  207789. case VK_F9:
  207790. case VK_F10:
  207791. case VK_F11:
  207792. case VK_F12:
  207793. case VK_F13:
  207794. case VK_F14:
  207795. case VK_F15:
  207796. case VK_F16:
  207797. used = handleKeyUpOrDown (true);
  207798. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207799. break;
  207800. case VK_ADD:
  207801. case VK_SUBTRACT:
  207802. case VK_MULTIPLY:
  207803. case VK_DIVIDE:
  207804. case VK_SEPARATOR:
  207805. case VK_DECIMAL:
  207806. used = handleKeyUpOrDown (true);
  207807. break;
  207808. default:
  207809. used = handleKeyUpOrDown (true);
  207810. {
  207811. MSG msg;
  207812. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207813. {
  207814. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207815. // manually generate the key-press event that matches this key-down.
  207816. const UINT keyChar = MapVirtualKey (key, 2);
  207817. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207818. }
  207819. }
  207820. break;
  207821. }
  207822. if (Component::getCurrentlyModalComponent() != 0)
  207823. used = true;
  207824. return used;
  207825. }
  207826. bool doKeyChar (int key, const LPARAM flags)
  207827. {
  207828. updateKeyModifiers();
  207829. juce_wchar textChar = (juce_wchar) key;
  207830. const int virtualScanCode = (flags >> 16) & 0xff;
  207831. if (key >= '0' && key <= '9')
  207832. {
  207833. switch (virtualScanCode) // check for a numeric keypad scan-code
  207834. {
  207835. case 0x52:
  207836. case 0x4f:
  207837. case 0x50:
  207838. case 0x51:
  207839. case 0x4b:
  207840. case 0x4c:
  207841. case 0x4d:
  207842. case 0x47:
  207843. case 0x48:
  207844. case 0x49:
  207845. key = (key - '0') + KeyPress::numberPad0;
  207846. break;
  207847. default:
  207848. break;
  207849. }
  207850. }
  207851. else
  207852. {
  207853. // convert the scan code to an unmodified character code..
  207854. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207855. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207856. keyChar = LOWORD (keyChar);
  207857. if (keyChar != 0)
  207858. key = (int) keyChar;
  207859. // avoid sending junk text characters for some control-key combinations
  207860. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207861. textChar = 0;
  207862. }
  207863. return handleKeyPress (key, textChar);
  207864. }
  207865. bool doAppCommand (const LPARAM lParam)
  207866. {
  207867. int key = 0;
  207868. switch (GET_APPCOMMAND_LPARAM (lParam))
  207869. {
  207870. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207871. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207872. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207873. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207874. default: break;
  207875. }
  207876. if (key != 0)
  207877. {
  207878. updateKeyModifiers();
  207879. if (hwnd == GetActiveWindow())
  207880. {
  207881. handleKeyPress (key, 0);
  207882. return true;
  207883. }
  207884. }
  207885. return false;
  207886. }
  207887. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207888. {
  207889. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207890. {
  207891. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207892. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207893. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207894. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207895. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207896. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207897. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207898. r->left = pos.getX();
  207899. r->top = pos.getY();
  207900. r->right = pos.getRight();
  207901. r->bottom = pos.getBottom();
  207902. }
  207903. return TRUE;
  207904. }
  207905. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207906. {
  207907. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207908. {
  207909. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207910. && ! Component::isMouseButtonDownAnywhere())
  207911. {
  207912. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207913. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207914. constrainer->checkBounds (pos, current,
  207915. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207916. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207917. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207918. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207919. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207920. wp->x = pos.getX();
  207921. wp->y = pos.getY();
  207922. wp->cx = pos.getWidth();
  207923. wp->cy = pos.getHeight();
  207924. }
  207925. }
  207926. return 0;
  207927. }
  207928. void handleAppActivation (const WPARAM wParam)
  207929. {
  207930. modifiersAtLastCallback = -1;
  207931. updateKeyModifiers();
  207932. if (isMinimised())
  207933. {
  207934. component->repaint();
  207935. handleMovedOrResized();
  207936. if (! ComponentPeer::isValidPeer (this))
  207937. return;
  207938. }
  207939. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207940. {
  207941. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207942. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207943. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207944. }
  207945. else
  207946. {
  207947. handleBroughtToFront();
  207948. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207949. Component::getCurrentlyModalComponent()->toFront (true);
  207950. }
  207951. }
  207952. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207953. {
  207954. public:
  207955. JuceDropTarget (Win32ComponentPeer* const owner_)
  207956. : owner (owner_)
  207957. {
  207958. }
  207959. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207960. {
  207961. updateFileList (pDataObject);
  207962. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207963. *pdwEffect = DROPEFFECT_COPY;
  207964. return S_OK;
  207965. }
  207966. HRESULT __stdcall DragLeave()
  207967. {
  207968. owner->handleFileDragExit (files);
  207969. return S_OK;
  207970. }
  207971. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207972. {
  207973. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207974. *pdwEffect = DROPEFFECT_COPY;
  207975. return S_OK;
  207976. }
  207977. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207978. {
  207979. updateFileList (pDataObject);
  207980. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207981. *pdwEffect = DROPEFFECT_COPY;
  207982. return S_OK;
  207983. }
  207984. private:
  207985. Win32ComponentPeer* const owner;
  207986. StringArray files;
  207987. void updateFileList (IDataObject* const pDataObject)
  207988. {
  207989. files.clear();
  207990. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207991. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207992. if (pDataObject->GetData (&format, &medium) == S_OK)
  207993. {
  207994. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207995. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207996. unsigned int i = 0;
  207997. if (pDropFiles->fWide)
  207998. {
  207999. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208000. for (;;)
  208001. {
  208002. unsigned int len = 0;
  208003. while (i + len < totalLen && fname [i + len] != 0)
  208004. ++len;
  208005. if (len == 0)
  208006. break;
  208007. files.add (String (fname + i, len));
  208008. i += len + 1;
  208009. }
  208010. }
  208011. else
  208012. {
  208013. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208014. for (;;)
  208015. {
  208016. unsigned int len = 0;
  208017. while (i + len < totalLen && fname [i + len] != 0)
  208018. ++len;
  208019. if (len == 0)
  208020. break;
  208021. files.add (String (fname + i, len));
  208022. i += len + 1;
  208023. }
  208024. }
  208025. GlobalUnlock (medium.hGlobal);
  208026. }
  208027. }
  208028. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  208029. };
  208030. void doSettingChange()
  208031. {
  208032. Desktop::getInstance().refreshMonitorSizes();
  208033. if (fullScreen && ! isMinimised())
  208034. {
  208035. const Rectangle<int> r (component->getParentMonitorArea());
  208036. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208037. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208038. }
  208039. }
  208040. public:
  208041. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208042. {
  208043. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208044. if (peer != 0)
  208045. {
  208046. jassert (isValidPeer (peer));
  208047. return peer->peerWindowProc (h, message, wParam, lParam);
  208048. }
  208049. return DefWindowProcW (h, message, wParam, lParam);
  208050. }
  208051. private:
  208052. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208053. {
  208054. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208055. return callback (userData);
  208056. else
  208057. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208058. }
  208059. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208060. {
  208061. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208062. }
  208063. const Point<int> getCurrentMousePos() throw()
  208064. {
  208065. RECT wr;
  208066. GetWindowRect (hwnd, &wr);
  208067. const DWORD mp = GetMessagePos();
  208068. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208069. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208070. }
  208071. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208072. {
  208073. switch (message)
  208074. {
  208075. case WM_NCHITTEST:
  208076. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208077. return HTTRANSPARENT;
  208078. else if (! hasTitleBar())
  208079. return HTCLIENT;
  208080. break;
  208081. case WM_PAINT:
  208082. handlePaintMessage();
  208083. return 0;
  208084. case WM_NCPAINT:
  208085. if (wParam != 1)
  208086. handlePaintMessage();
  208087. if (hasTitleBar())
  208088. break;
  208089. return 0;
  208090. case WM_ERASEBKGND:
  208091. case WM_NCCALCSIZE:
  208092. if (hasTitleBar())
  208093. break;
  208094. return 1;
  208095. case WM_MOUSEMOVE:
  208096. doMouseMove (getPointFromLParam (lParam));
  208097. return 0;
  208098. case WM_MOUSELEAVE:
  208099. doMouseExit();
  208100. return 0;
  208101. case WM_LBUTTONDOWN:
  208102. case WM_MBUTTONDOWN:
  208103. case WM_RBUTTONDOWN:
  208104. doMouseDown (getPointFromLParam (lParam), wParam);
  208105. return 0;
  208106. case WM_LBUTTONUP:
  208107. case WM_MBUTTONUP:
  208108. case WM_RBUTTONUP:
  208109. doMouseUp (getPointFromLParam (lParam), wParam);
  208110. return 0;
  208111. case WM_CAPTURECHANGED:
  208112. doCaptureChanged();
  208113. return 0;
  208114. case WM_NCMOUSEMOVE:
  208115. if (hasTitleBar())
  208116. break;
  208117. return 0;
  208118. case 0x020A: /* WM_MOUSEWHEEL */
  208119. case 0x020E: /* WM_MOUSEHWHEEL */
  208120. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208121. return 0;
  208122. case WM_SIZING:
  208123. return handleSizeConstraining ((RECT*) lParam, wParam);
  208124. case WM_WINDOWPOSCHANGING:
  208125. return handlePositionChanging ((WINDOWPOS*) lParam);
  208126. case WM_WINDOWPOSCHANGED:
  208127. {
  208128. const Point<int> pos (getCurrentMousePos());
  208129. if (contains (pos, false))
  208130. doMouseEvent (pos);
  208131. }
  208132. handleMovedOrResized();
  208133. if (dontRepaint)
  208134. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208135. return 0;
  208136. case WM_KEYDOWN:
  208137. case WM_SYSKEYDOWN:
  208138. if (doKeyDown (wParam))
  208139. return 0;
  208140. break;
  208141. case WM_KEYUP:
  208142. case WM_SYSKEYUP:
  208143. if (doKeyUp (wParam))
  208144. return 0;
  208145. break;
  208146. case WM_CHAR:
  208147. if (doKeyChar ((int) wParam, lParam))
  208148. return 0;
  208149. break;
  208150. case WM_APPCOMMAND:
  208151. if (doAppCommand (lParam))
  208152. return TRUE;
  208153. break;
  208154. case WM_SETFOCUS:
  208155. updateKeyModifiers();
  208156. handleFocusGain();
  208157. break;
  208158. case WM_KILLFOCUS:
  208159. if (hasCreatedCaret)
  208160. {
  208161. hasCreatedCaret = false;
  208162. DestroyCaret();
  208163. }
  208164. handleFocusLoss();
  208165. break;
  208166. case WM_ACTIVATEAPP:
  208167. // Windows does weird things to process priority when you swap apps,
  208168. // so this forces an update when the app is brought to the front
  208169. if (wParam != FALSE)
  208170. juce_repeatLastProcessPriority();
  208171. else
  208172. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208173. juce_CheckCurrentlyFocusedTopLevelWindow();
  208174. modifiersAtLastCallback = -1;
  208175. return 0;
  208176. case WM_ACTIVATE:
  208177. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208178. {
  208179. handleAppActivation (wParam);
  208180. return 0;
  208181. }
  208182. break;
  208183. case WM_NCACTIVATE:
  208184. // while a temporary window is being shown, prevent Windows from deactivating the
  208185. // title bars of our main windows.
  208186. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208187. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208188. break;
  208189. case WM_MOUSEACTIVATE:
  208190. if (! component->getMouseClickGrabsKeyboardFocus())
  208191. return MA_NOACTIVATE;
  208192. break;
  208193. case WM_SHOWWINDOW:
  208194. if (wParam != 0)
  208195. handleBroughtToFront();
  208196. break;
  208197. case WM_CLOSE:
  208198. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208199. handleUserClosingWindow();
  208200. return 0;
  208201. case WM_QUERYENDSESSION:
  208202. if (JUCEApplication::getInstance() != 0)
  208203. {
  208204. JUCEApplication::getInstance()->systemRequestedQuit();
  208205. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208206. }
  208207. return TRUE;
  208208. case WM_TRAYNOTIFY:
  208209. handleTaskBarEvent (lParam, wParam);
  208210. break;
  208211. case WM_SYNCPAINT:
  208212. return 0;
  208213. case WM_PALETTECHANGED:
  208214. InvalidateRect (h, 0, 0);
  208215. break;
  208216. case WM_DISPLAYCHANGE:
  208217. InvalidateRect (h, 0, 0);
  208218. createPaletteIfNeeded = true;
  208219. // intentional fall-through...
  208220. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208221. doSettingChange();
  208222. break;
  208223. case WM_INITMENU:
  208224. if (! hasTitleBar())
  208225. {
  208226. if (isFullScreen())
  208227. {
  208228. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208229. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208230. }
  208231. else if (! isMinimised())
  208232. {
  208233. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208234. }
  208235. }
  208236. break;
  208237. case WM_SYSCOMMAND:
  208238. switch (wParam & 0xfff0)
  208239. {
  208240. case SC_CLOSE:
  208241. if (sendInputAttemptWhenModalMessage())
  208242. return 0;
  208243. if (hasTitleBar())
  208244. {
  208245. PostMessage (h, WM_CLOSE, 0, 0);
  208246. return 0;
  208247. }
  208248. break;
  208249. case SC_KEYMENU:
  208250. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208251. // situations that can arise if a modal loop is started from an alt-key keypress).
  208252. if (hasTitleBar() && h == GetCapture())
  208253. ReleaseCapture();
  208254. break;
  208255. case SC_MAXIMIZE:
  208256. if (! sendInputAttemptWhenModalMessage())
  208257. return 0;
  208258. setFullScreen (true);
  208259. return 0;
  208260. case SC_MINIMIZE:
  208261. if (sendInputAttemptWhenModalMessage())
  208262. return 0;
  208263. if (! hasTitleBar())
  208264. {
  208265. setMinimised (true);
  208266. return 0;
  208267. }
  208268. break;
  208269. case SC_RESTORE:
  208270. if (sendInputAttemptWhenModalMessage())
  208271. return 0;
  208272. if (hasTitleBar())
  208273. {
  208274. if (isFullScreen())
  208275. {
  208276. setFullScreen (false);
  208277. return 0;
  208278. }
  208279. }
  208280. else
  208281. {
  208282. if (isMinimised())
  208283. setMinimised (false);
  208284. else if (isFullScreen())
  208285. setFullScreen (false);
  208286. return 0;
  208287. }
  208288. break;
  208289. }
  208290. break;
  208291. case WM_NCLBUTTONDOWN:
  208292. case WM_NCRBUTTONDOWN:
  208293. case WM_NCMBUTTONDOWN:
  208294. sendInputAttemptWhenModalMessage();
  208295. break;
  208296. //case WM_IME_STARTCOMPOSITION;
  208297. // return 0;
  208298. case WM_GETDLGCODE:
  208299. return DLGC_WANTALLKEYS;
  208300. default:
  208301. if (taskBarIcon != 0)
  208302. {
  208303. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208304. if (message == taskbarCreatedMessage)
  208305. {
  208306. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208307. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208308. }
  208309. }
  208310. break;
  208311. }
  208312. return DefWindowProcW (h, message, wParam, lParam);
  208313. }
  208314. bool sendInputAttemptWhenModalMessage()
  208315. {
  208316. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208317. {
  208318. Component* const current = Component::getCurrentlyModalComponent();
  208319. if (current != 0)
  208320. current->inputAttemptWhenModal();
  208321. return true;
  208322. }
  208323. return false;
  208324. }
  208325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208326. };
  208327. ModifierKeys Win32ComponentPeer::currentModifiers;
  208328. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208329. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208330. {
  208331. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208332. }
  208333. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208334. void ModifierKeys::updateCurrentModifiers() throw()
  208335. {
  208336. currentModifiers = Win32ComponentPeer::currentModifiers;
  208337. }
  208338. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208339. {
  208340. Win32ComponentPeer::updateKeyModifiers();
  208341. int mouseMods = 0;
  208342. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208343. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208344. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208345. Win32ComponentPeer::currentModifiers
  208346. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208347. return Win32ComponentPeer::currentModifiers;
  208348. }
  208349. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208350. {
  208351. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208352. if (wp != 0)
  208353. wp->setTaskBarIcon (newImage);
  208354. }
  208355. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208356. {
  208357. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208358. if (wp != 0)
  208359. wp->setTaskBarIconToolTip (tooltip);
  208360. }
  208361. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208362. {
  208363. DWORD val = GetWindowLong (h, styleType);
  208364. if (bitIsSet)
  208365. val |= feature;
  208366. else
  208367. val &= ~feature;
  208368. SetWindowLongPtr (h, styleType, val);
  208369. SetWindowPos (h, 0, 0, 0, 0, 0,
  208370. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208371. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208372. }
  208373. bool Process::isForegroundProcess()
  208374. {
  208375. HWND fg = GetForegroundWindow();
  208376. if (fg == 0)
  208377. return true;
  208378. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208379. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208380. // have to see if any of our windows are children of the foreground window
  208381. fg = GetAncestor (fg, GA_ROOT);
  208382. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208383. {
  208384. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208385. if (wp != 0 && wp->isInside (fg))
  208386. return true;
  208387. }
  208388. return false;
  208389. }
  208390. bool AlertWindow::showNativeDialogBox (const String& title,
  208391. const String& bodyText,
  208392. bool isOkCancel)
  208393. {
  208394. return MessageBox (0, bodyText, title,
  208395. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208396. : MB_OK)) == IDOK;
  208397. }
  208398. void Desktop::createMouseInputSources()
  208399. {
  208400. mouseSources.add (new MouseInputSource (0, true));
  208401. }
  208402. const Point<int> MouseInputSource::getCurrentMousePosition()
  208403. {
  208404. POINT mousePos;
  208405. GetCursorPos (&mousePos);
  208406. return Point<int> (mousePos.x, mousePos.y);
  208407. }
  208408. void Desktop::setMousePosition (const Point<int>& newPosition)
  208409. {
  208410. SetCursorPos (newPosition.getX(), newPosition.getY());
  208411. }
  208412. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208413. {
  208414. return createSoftwareImage (format, width, height, clearImage);
  208415. }
  208416. class ScreenSaverDefeater : public Timer,
  208417. public DeletedAtShutdown
  208418. {
  208419. public:
  208420. ScreenSaverDefeater()
  208421. {
  208422. startTimer (10000);
  208423. timerCallback();
  208424. }
  208425. ~ScreenSaverDefeater() {}
  208426. void timerCallback()
  208427. {
  208428. if (Process::isForegroundProcess())
  208429. {
  208430. // simulate a shift key getting pressed..
  208431. INPUT input[2];
  208432. input[0].type = INPUT_KEYBOARD;
  208433. input[0].ki.wVk = VK_SHIFT;
  208434. input[0].ki.dwFlags = 0;
  208435. input[0].ki.dwExtraInfo = 0;
  208436. input[1].type = INPUT_KEYBOARD;
  208437. input[1].ki.wVk = VK_SHIFT;
  208438. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208439. input[1].ki.dwExtraInfo = 0;
  208440. SendInput (2, input, sizeof (INPUT));
  208441. }
  208442. }
  208443. };
  208444. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208445. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208446. {
  208447. if (isEnabled)
  208448. deleteAndZero (screenSaverDefeater);
  208449. else if (screenSaverDefeater == 0)
  208450. screenSaverDefeater = new ScreenSaverDefeater();
  208451. }
  208452. bool Desktop::isScreenSaverEnabled()
  208453. {
  208454. return screenSaverDefeater == 0;
  208455. }
  208456. /* (The code below is the "correct" way to disable the screen saver, but it
  208457. completely fails on winXP when the saver is password-protected...)
  208458. static bool juce_screenSaverEnabled = true;
  208459. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208460. {
  208461. juce_screenSaverEnabled = isEnabled;
  208462. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208463. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208464. }
  208465. bool Desktop::isScreenSaverEnabled() throw()
  208466. {
  208467. return juce_screenSaverEnabled;
  208468. }
  208469. */
  208470. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208471. {
  208472. if (enableOrDisable)
  208473. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208474. }
  208475. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208476. {
  208477. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208478. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208479. return TRUE;
  208480. }
  208481. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208482. {
  208483. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208484. // make sure the first in the list is the main monitor
  208485. for (int i = 1; i < monitorCoords.size(); ++i)
  208486. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208487. monitorCoords.swap (i, 0);
  208488. if (monitorCoords.size() == 0)
  208489. {
  208490. RECT r;
  208491. GetWindowRect (GetDesktopWindow(), &r);
  208492. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208493. }
  208494. if (clipToWorkArea)
  208495. {
  208496. // clip the main monitor to the active non-taskbar area
  208497. RECT r;
  208498. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208499. Rectangle<int>& screen = monitorCoords.getReference (0);
  208500. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208501. jmax (screen.getY(), (int) r.top));
  208502. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208503. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208504. }
  208505. }
  208506. const Image juce_createIconForFile (const File& file)
  208507. {
  208508. Image image;
  208509. WCHAR filename [1024];
  208510. file.getFullPathName().copyToUnicode (filename, 1023);
  208511. WORD iconNum = 0;
  208512. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208513. filename, &iconNum);
  208514. if (icon != 0)
  208515. {
  208516. image = IconConverters::createImageFromHICON (icon);
  208517. DestroyIcon (icon);
  208518. }
  208519. return image;
  208520. }
  208521. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208522. {
  208523. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208524. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208525. Image im (image);
  208526. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208527. {
  208528. im = im.rescaled (maxW, maxH);
  208529. hotspotX = (hotspotX * maxW) / image.getWidth();
  208530. hotspotY = (hotspotY * maxH) / image.getHeight();
  208531. }
  208532. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208533. }
  208534. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208535. {
  208536. if (cursorHandle != 0 && ! isStandard)
  208537. DestroyCursor ((HCURSOR) cursorHandle);
  208538. }
  208539. enum
  208540. {
  208541. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208542. };
  208543. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208544. {
  208545. LPCTSTR cursorName = IDC_ARROW;
  208546. switch (type)
  208547. {
  208548. case NormalCursor: break;
  208549. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208550. case WaitCursor: cursorName = IDC_WAIT; break;
  208551. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208552. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208553. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208554. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208555. case LeftRightResizeCursor:
  208556. case LeftEdgeResizeCursor:
  208557. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208558. case UpDownResizeCursor:
  208559. case TopEdgeResizeCursor:
  208560. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208561. case TopLeftCornerResizeCursor:
  208562. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208563. case TopRightCornerResizeCursor:
  208564. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208565. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208566. case DraggingHandCursor:
  208567. {
  208568. static void* dragHandCursor = 0;
  208569. if (dragHandCursor == 0)
  208570. {
  208571. static const unsigned char dragHandData[] =
  208572. { 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,
  208573. 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,
  208574. 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 };
  208575. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208576. }
  208577. return dragHandCursor;
  208578. }
  208579. default:
  208580. jassertfalse; break;
  208581. }
  208582. HCURSOR cursorH = LoadCursor (0, cursorName);
  208583. if (cursorH == 0)
  208584. cursorH = LoadCursor (0, IDC_ARROW);
  208585. return cursorH;
  208586. }
  208587. void MouseCursor::showInWindow (ComponentPeer*) const
  208588. {
  208589. HCURSOR c = (HCURSOR) getHandle();
  208590. if (c == 0)
  208591. c = LoadCursor (0, IDC_ARROW);
  208592. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208593. c = 0;
  208594. SetCursor (c);
  208595. }
  208596. void MouseCursor::showInAllWindows() const
  208597. {
  208598. showInWindow (0);
  208599. }
  208600. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208601. {
  208602. public:
  208603. JuceDropSource() {}
  208604. ~JuceDropSource() {}
  208605. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208606. {
  208607. if (escapePressed)
  208608. return DRAGDROP_S_CANCEL;
  208609. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208610. return DRAGDROP_S_DROP;
  208611. return S_OK;
  208612. }
  208613. HRESULT __stdcall GiveFeedback (DWORD)
  208614. {
  208615. return DRAGDROP_S_USEDEFAULTCURSORS;
  208616. }
  208617. };
  208618. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208619. {
  208620. public:
  208621. JuceEnumFormatEtc (const FORMATETC* const format_)
  208622. : format (format_),
  208623. index (0)
  208624. {
  208625. }
  208626. ~JuceEnumFormatEtc() {}
  208627. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208628. {
  208629. if (result == 0)
  208630. return E_POINTER;
  208631. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208632. newOne->index = index;
  208633. *result = newOne;
  208634. return S_OK;
  208635. }
  208636. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208637. {
  208638. if (pceltFetched != 0)
  208639. *pceltFetched = 0;
  208640. else if (celt != 1)
  208641. return S_FALSE;
  208642. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208643. {
  208644. copyFormatEtc (lpFormatEtc [0], *format);
  208645. ++index;
  208646. if (pceltFetched != 0)
  208647. *pceltFetched = 1;
  208648. return S_OK;
  208649. }
  208650. return S_FALSE;
  208651. }
  208652. HRESULT __stdcall Skip (ULONG celt)
  208653. {
  208654. if (index + (int) celt >= 1)
  208655. return S_FALSE;
  208656. index += celt;
  208657. return S_OK;
  208658. }
  208659. HRESULT __stdcall Reset()
  208660. {
  208661. index = 0;
  208662. return S_OK;
  208663. }
  208664. private:
  208665. const FORMATETC* const format;
  208666. int index;
  208667. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208668. {
  208669. dest = source;
  208670. if (source.ptd != 0)
  208671. {
  208672. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208673. *(dest.ptd) = *(source.ptd);
  208674. }
  208675. }
  208676. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208677. };
  208678. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208679. {
  208680. public:
  208681. JuceDataObject (JuceDropSource* const dropSource_,
  208682. const FORMATETC* const format_,
  208683. const STGMEDIUM* const medium_)
  208684. : dropSource (dropSource_),
  208685. format (format_),
  208686. medium (medium_)
  208687. {
  208688. }
  208689. ~JuceDataObject()
  208690. {
  208691. jassert (refCount == 0);
  208692. }
  208693. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208694. {
  208695. if ((pFormatEtc->tymed & format->tymed) != 0
  208696. && pFormatEtc->cfFormat == format->cfFormat
  208697. && pFormatEtc->dwAspect == format->dwAspect)
  208698. {
  208699. pMedium->tymed = format->tymed;
  208700. pMedium->pUnkForRelease = 0;
  208701. if (format->tymed == TYMED_HGLOBAL)
  208702. {
  208703. const SIZE_T len = GlobalSize (medium->hGlobal);
  208704. void* const src = GlobalLock (medium->hGlobal);
  208705. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208706. memcpy (dst, src, len);
  208707. GlobalUnlock (medium->hGlobal);
  208708. pMedium->hGlobal = dst;
  208709. return S_OK;
  208710. }
  208711. }
  208712. return DV_E_FORMATETC;
  208713. }
  208714. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208715. {
  208716. if (f == 0)
  208717. return E_INVALIDARG;
  208718. if (f->tymed == format->tymed
  208719. && f->cfFormat == format->cfFormat
  208720. && f->dwAspect == format->dwAspect)
  208721. return S_OK;
  208722. return DV_E_FORMATETC;
  208723. }
  208724. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208725. {
  208726. pFormatEtcOut->ptd = 0;
  208727. return E_NOTIMPL;
  208728. }
  208729. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208730. {
  208731. if (result == 0)
  208732. return E_POINTER;
  208733. if (direction == DATADIR_GET)
  208734. {
  208735. *result = new JuceEnumFormatEtc (format);
  208736. return S_OK;
  208737. }
  208738. *result = 0;
  208739. return E_NOTIMPL;
  208740. }
  208741. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208742. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208743. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208744. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208745. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208746. private:
  208747. JuceDropSource* const dropSource;
  208748. const FORMATETC* const format;
  208749. const STGMEDIUM* const medium;
  208750. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208751. };
  208752. static HDROP createHDrop (const StringArray& fileNames)
  208753. {
  208754. int totalChars = 0;
  208755. for (int i = fileNames.size(); --i >= 0;)
  208756. totalChars += fileNames[i].length() + 1;
  208757. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208758. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208759. if (hDrop != 0)
  208760. {
  208761. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208762. pDropFiles->pFiles = sizeof (DROPFILES);
  208763. pDropFiles->fWide = true;
  208764. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208765. for (int i = 0; i < fileNames.size(); ++i)
  208766. {
  208767. fileNames[i].copyToUnicode (fname, 2048);
  208768. fname += fileNames[i].length() + 1;
  208769. }
  208770. *fname = 0;
  208771. GlobalUnlock (hDrop);
  208772. }
  208773. return hDrop;
  208774. }
  208775. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208776. {
  208777. JuceDropSource* const source = new JuceDropSource();
  208778. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208779. DWORD effect;
  208780. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208781. data->Release();
  208782. source->Release();
  208783. return res == DRAGDROP_S_DROP;
  208784. }
  208785. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208786. {
  208787. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208788. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208789. medium.hGlobal = createHDrop (files);
  208790. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208791. : DROPEFFECT_COPY);
  208792. }
  208793. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208794. {
  208795. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208796. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208797. const int numChars = text.length();
  208798. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208799. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208800. text.copyToUnicode (data, numChars + 1);
  208801. format.cfFormat = CF_UNICODETEXT;
  208802. GlobalUnlock (medium.hGlobal);
  208803. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208804. }
  208805. #endif
  208806. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208807. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208808. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208809. // compiled on its own).
  208810. #if JUCE_INCLUDED_FILE
  208811. namespace FileChooserHelpers
  208812. {
  208813. static bool areThereAnyAlwaysOnTopWindows()
  208814. {
  208815. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208816. {
  208817. Component* c = Desktop::getInstance().getComponent (i);
  208818. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208819. return true;
  208820. }
  208821. return false;
  208822. }
  208823. struct FileChooserCallbackInfo
  208824. {
  208825. String initialPath;
  208826. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208827. ScopedPointer<Component> customComponent;
  208828. };
  208829. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208830. {
  208831. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208832. if (msg == BFFM_INITIALIZED)
  208833. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208834. else if (msg == BFFM_VALIDATEFAILEDW)
  208835. info->returnedString = (LPCWSTR) lParam;
  208836. else if (msg == BFFM_VALIDATEFAILEDA)
  208837. info->returnedString = (const char*) lParam;
  208838. return 0;
  208839. }
  208840. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208841. {
  208842. if (uiMsg == WM_INITDIALOG)
  208843. {
  208844. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208845. HWND dialogH = GetParent (hdlg);
  208846. jassert (dialogH != 0);
  208847. if (dialogH == 0)
  208848. dialogH = hdlg;
  208849. RECT r, cr;
  208850. GetWindowRect (dialogH, &r);
  208851. GetClientRect (dialogH, &cr);
  208852. SetWindowPos (dialogH, 0,
  208853. r.left, r.top,
  208854. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208855. jmax (150, (int) (r.bottom - r.top)),
  208856. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208857. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208858. customComp->addToDesktop (0, dialogH);
  208859. }
  208860. else if (uiMsg == WM_NOTIFY)
  208861. {
  208862. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208863. if (ofn->hdr.code == CDN_SELCHANGE)
  208864. {
  208865. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208866. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208867. if (comp != 0)
  208868. {
  208869. WCHAR path [MAX_PATH * 2];
  208870. zerostruct (path);
  208871. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208872. comp->selectedFileChanged (File (path));
  208873. }
  208874. }
  208875. }
  208876. return 0;
  208877. }
  208878. class CustomComponentHolder : public Component
  208879. {
  208880. public:
  208881. CustomComponentHolder (Component* customComp)
  208882. {
  208883. setVisible (true);
  208884. setOpaque (true);
  208885. addAndMakeVisible (customComp);
  208886. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208887. }
  208888. void paint (Graphics& g)
  208889. {
  208890. g.fillAll (Colours::lightgrey);
  208891. }
  208892. void resized()
  208893. {
  208894. if (getNumChildComponents() > 0)
  208895. getChildComponent(0)->setBounds (getLocalBounds());
  208896. }
  208897. private:
  208898. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208899. };
  208900. }
  208901. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208902. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208903. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208904. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208905. {
  208906. using namespace FileChooserHelpers;
  208907. HeapBlock<WCHAR> files;
  208908. const int charsAvailableForResult = 32768;
  208909. files.calloc (charsAvailableForResult + 1);
  208910. int filenameOffset = 0;
  208911. FileChooserCallbackInfo info;
  208912. // use a modal window as the parent for this dialog box
  208913. // to block input from other app windows
  208914. Component parentWindow (String::empty);
  208915. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208916. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208917. mainMon.getY() + mainMon.getHeight() / 4,
  208918. 0, 0);
  208919. parentWindow.setOpaque (true);
  208920. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208921. parentWindow.addToDesktop (0);
  208922. if (extraInfoComponent == 0)
  208923. parentWindow.enterModalState();
  208924. if (currentFileOrDirectory.isDirectory())
  208925. {
  208926. info.initialPath = currentFileOrDirectory.getFullPathName();
  208927. }
  208928. else
  208929. {
  208930. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208931. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208932. }
  208933. if (selectsDirectory)
  208934. {
  208935. BROWSEINFO bi;
  208936. zerostruct (bi);
  208937. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208938. bi.pszDisplayName = files;
  208939. bi.lpszTitle = title;
  208940. bi.lParam = (LPARAM) &info;
  208941. bi.lpfn = browseCallbackProc;
  208942. #ifdef BIF_USENEWUI
  208943. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208944. #else
  208945. bi.ulFlags = 0x50;
  208946. #endif
  208947. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208948. if (! SHGetPathFromIDListW (list, files))
  208949. {
  208950. files[0] = 0;
  208951. info.returnedString = String::empty;
  208952. }
  208953. LPMALLOC al;
  208954. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208955. al->Free (list);
  208956. if (info.returnedString.isNotEmpty())
  208957. {
  208958. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208959. return;
  208960. }
  208961. }
  208962. else
  208963. {
  208964. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208965. if (warnAboutOverwritingExistingFiles)
  208966. flags |= OFN_OVERWRITEPROMPT;
  208967. if (selectMultipleFiles)
  208968. flags |= OFN_ALLOWMULTISELECT;
  208969. if (extraInfoComponent != 0)
  208970. {
  208971. flags |= OFN_ENABLEHOOK;
  208972. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208973. info.customComponent->enterModalState();
  208974. }
  208975. WCHAR filters [1024];
  208976. zerostruct (filters);
  208977. filter.copyToUnicode (filters, 1024);
  208978. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208979. OPENFILENAMEW of;
  208980. zerostruct (of);
  208981. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208982. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208983. #else
  208984. of.lStructSize = sizeof (of);
  208985. #endif
  208986. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208987. of.lpstrFilter = filters;
  208988. of.nFilterIndex = 1;
  208989. of.lpstrFile = files;
  208990. of.nMaxFile = charsAvailableForResult;
  208991. of.lpstrInitialDir = info.initialPath;
  208992. of.lpstrTitle = title;
  208993. of.Flags = flags;
  208994. of.lCustData = (LPARAM) &info;
  208995. if (extraInfoComponent != 0)
  208996. of.lpfnHook = &openCallback;
  208997. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208998. : GetOpenFileName (&of)))
  208999. return;
  209000. filenameOffset = of.nFileOffset;
  209001. }
  209002. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209003. {
  209004. const WCHAR* filename = files + filenameOffset;
  209005. while (*filename != 0)
  209006. {
  209007. results.add (File (String (files) + "\\" + String (filename)));
  209008. filename += CharacterFunctions::length (filename) + 1;
  209009. }
  209010. }
  209011. else if (files[0] != 0)
  209012. {
  209013. results.add (File (String (files)));
  209014. }
  209015. }
  209016. #endif
  209017. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209018. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209019. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209020. // compiled on its own).
  209021. #if JUCE_INCLUDED_FILE
  209022. void SystemClipboard::copyTextToClipboard (const String& text)
  209023. {
  209024. if (OpenClipboard (0) != 0)
  209025. {
  209026. if (EmptyClipboard() != 0)
  209027. {
  209028. const int len = text.length();
  209029. if (len > 0)
  209030. {
  209031. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209032. (len + 1) * sizeof (wchar_t));
  209033. if (bufH != 0)
  209034. {
  209035. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209036. text.copyToUnicode (data, len);
  209037. GlobalUnlock (bufH);
  209038. SetClipboardData (CF_UNICODETEXT, bufH);
  209039. }
  209040. }
  209041. }
  209042. CloseClipboard();
  209043. }
  209044. }
  209045. const String SystemClipboard::getTextFromClipboard()
  209046. {
  209047. String result;
  209048. if (OpenClipboard (0) != 0)
  209049. {
  209050. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209051. if (bufH != 0)
  209052. {
  209053. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209054. if (data != 0)
  209055. {
  209056. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209057. GlobalUnlock (bufH);
  209058. }
  209059. }
  209060. CloseClipboard();
  209061. }
  209062. return result;
  209063. }
  209064. #endif
  209065. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209066. /*** Start of inlined file: juce_win32_ActiveXComponent.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 ActiveXHelpers
  209071. {
  209072. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209073. {
  209074. public:
  209075. JuceIStorage() {}
  209076. ~JuceIStorage() {}
  209077. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209078. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209079. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209080. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209081. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209082. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209083. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209084. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209085. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209086. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209087. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209088. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209089. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209090. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209091. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209092. };
  209093. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209094. {
  209095. HWND window;
  209096. public:
  209097. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209098. ~JuceOleInPlaceFrame() {}
  209099. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209100. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209101. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209102. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209103. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209104. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209105. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209106. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209107. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209108. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209109. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209110. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209111. };
  209112. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209113. {
  209114. HWND window;
  209115. JuceOleInPlaceFrame* frame;
  209116. public:
  209117. JuceIOleInPlaceSite (HWND window_)
  209118. : window (window_),
  209119. frame (new JuceOleInPlaceFrame (window))
  209120. {}
  209121. ~JuceIOleInPlaceSite()
  209122. {
  209123. frame->Release();
  209124. }
  209125. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209126. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209127. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209128. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209129. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209130. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209131. {
  209132. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209133. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209134. */
  209135. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209136. if (lplpDoc != 0) *lplpDoc = 0;
  209137. lpFrameInfo->fMDIApp = FALSE;
  209138. lpFrameInfo->hwndFrame = window;
  209139. lpFrameInfo->haccel = 0;
  209140. lpFrameInfo->cAccelEntries = 0;
  209141. return S_OK;
  209142. }
  209143. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209144. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209145. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209146. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209147. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209148. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209149. };
  209150. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209151. {
  209152. JuceIOleInPlaceSite* inplaceSite;
  209153. public:
  209154. JuceIOleClientSite (HWND window)
  209155. : inplaceSite (new JuceIOleInPlaceSite (window))
  209156. {}
  209157. ~JuceIOleClientSite()
  209158. {
  209159. inplaceSite->Release();
  209160. }
  209161. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209162. {
  209163. if (type == IID_IOleInPlaceSite)
  209164. {
  209165. inplaceSite->AddRef();
  209166. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209167. return S_OK;
  209168. }
  209169. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209170. }
  209171. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209172. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209173. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209174. HRESULT __stdcall ShowObject() { return S_OK; }
  209175. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209176. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209177. };
  209178. static Array<ActiveXControlComponent*> activeXComps;
  209179. static HWND getHWND (const ActiveXControlComponent* const component)
  209180. {
  209181. HWND hwnd = 0;
  209182. const IID iid = IID_IOleWindow;
  209183. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209184. if (window != 0)
  209185. {
  209186. window->GetWindow (&hwnd);
  209187. window->Release();
  209188. }
  209189. return hwnd;
  209190. }
  209191. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209192. {
  209193. RECT activeXRect, peerRect;
  209194. GetWindowRect (hwnd, &activeXRect);
  209195. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209196. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209197. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209198. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209199. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209200. switch (message)
  209201. {
  209202. case WM_MOUSEMOVE:
  209203. case WM_LBUTTONDOWN:
  209204. case WM_MBUTTONDOWN:
  209205. case WM_RBUTTONDOWN:
  209206. case WM_LBUTTONUP:
  209207. case WM_MBUTTONUP:
  209208. case WM_RBUTTONUP:
  209209. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209210. break;
  209211. default:
  209212. break;
  209213. }
  209214. }
  209215. }
  209216. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209217. {
  209218. ActiveXControlComponent& owner;
  209219. bool wasShowing;
  209220. public:
  209221. HWND controlHWND;
  209222. IStorage* storage;
  209223. IOleClientSite* clientSite;
  209224. IOleObject* control;
  209225. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209226. : ComponentMovementWatcher (&owner_),
  209227. owner (owner_),
  209228. wasShowing (owner_.isShowing()),
  209229. controlHWND (0),
  209230. storage (new ActiveXHelpers::JuceIStorage()),
  209231. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209232. control (0)
  209233. {
  209234. }
  209235. ~Pimpl()
  209236. {
  209237. if (control != 0)
  209238. {
  209239. control->Close (OLECLOSE_NOSAVE);
  209240. control->Release();
  209241. }
  209242. clientSite->Release();
  209243. storage->Release();
  209244. }
  209245. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209246. {
  209247. Component* const topComp = owner.getTopLevelComponent();
  209248. if (topComp->getPeer() != 0)
  209249. {
  209250. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209251. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209252. }
  209253. }
  209254. void componentPeerChanged()
  209255. {
  209256. const bool isShowingNow = owner.isShowing();
  209257. if (wasShowing != isShowingNow)
  209258. {
  209259. wasShowing = isShowingNow;
  209260. owner.setControlVisible (isShowingNow);
  209261. }
  209262. componentMovedOrResized (true, true);
  209263. }
  209264. void componentVisibilityChanged (Component&)
  209265. {
  209266. componentPeerChanged();
  209267. }
  209268. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209269. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209270. {
  209271. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209272. {
  209273. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209274. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209275. {
  209276. switch (message)
  209277. {
  209278. case WM_MOUSEMOVE:
  209279. case WM_LBUTTONDOWN:
  209280. case WM_MBUTTONDOWN:
  209281. case WM_RBUTTONDOWN:
  209282. case WM_LBUTTONUP:
  209283. case WM_MBUTTONUP:
  209284. case WM_RBUTTONUP:
  209285. case WM_LBUTTONDBLCLK:
  209286. case WM_MBUTTONDBLCLK:
  209287. case WM_RBUTTONDBLCLK:
  209288. if (ax->isShowing())
  209289. {
  209290. ComponentPeer* const peer = ax->getPeer();
  209291. if (peer != 0)
  209292. {
  209293. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209294. if (! ax->areMouseEventsAllowed())
  209295. return 0;
  209296. }
  209297. }
  209298. break;
  209299. default:
  209300. break;
  209301. }
  209302. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209303. }
  209304. }
  209305. return DefWindowProc (hwnd, message, wParam, lParam);
  209306. }
  209307. };
  209308. ActiveXControlComponent::ActiveXControlComponent()
  209309. : originalWndProc (0),
  209310. mouseEventsAllowed (true)
  209311. {
  209312. ActiveXHelpers::activeXComps.add (this);
  209313. }
  209314. ActiveXControlComponent::~ActiveXControlComponent()
  209315. {
  209316. deleteControl();
  209317. ActiveXHelpers::activeXComps.removeValue (this);
  209318. }
  209319. void ActiveXControlComponent::paint (Graphics& g)
  209320. {
  209321. if (control == 0)
  209322. g.fillAll (Colours::lightgrey);
  209323. }
  209324. bool ActiveXControlComponent::createControl (const void* controlIID)
  209325. {
  209326. deleteControl();
  209327. ComponentPeer* const peer = getPeer();
  209328. // the component must have already been added to a real window when you call this!
  209329. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209330. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209331. {
  209332. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209333. HWND hwnd = (HWND) peer->getNativeHandle();
  209334. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209335. HRESULT hr;
  209336. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209337. newControl->clientSite, newControl->storage,
  209338. (void**) &(newControl->control))) == S_OK)
  209339. {
  209340. newControl->control->SetHostNames (L"Juce", 0);
  209341. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209342. {
  209343. RECT rect;
  209344. rect.left = pos.getX();
  209345. rect.top = pos.getY();
  209346. rect.right = pos.getX() + getWidth();
  209347. rect.bottom = pos.getY() + getHeight();
  209348. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209349. {
  209350. control = newControl;
  209351. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209352. control->controlHWND = ActiveXHelpers::getHWND (this);
  209353. if (control->controlHWND != 0)
  209354. {
  209355. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209356. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209357. }
  209358. return true;
  209359. }
  209360. }
  209361. }
  209362. }
  209363. return false;
  209364. }
  209365. void ActiveXControlComponent::deleteControl()
  209366. {
  209367. control = 0;
  209368. originalWndProc = 0;
  209369. }
  209370. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209371. {
  209372. void* result = 0;
  209373. if (control != 0 && control->control != 0
  209374. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209375. return result;
  209376. return 0;
  209377. }
  209378. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209379. {
  209380. if (control->controlHWND != 0)
  209381. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209382. }
  209383. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209384. {
  209385. if (control->controlHWND != 0)
  209386. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209387. }
  209388. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209389. {
  209390. mouseEventsAllowed = eventsCanReachControl;
  209391. }
  209392. #endif
  209393. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209394. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209395. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209396. // compiled on its own).
  209397. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209398. using namespace QTOLibrary;
  209399. using namespace QTOControlLib;
  209400. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209401. static bool isQTAvailable = false;
  209402. class QuickTimeMovieComponent::Pimpl
  209403. {
  209404. public:
  209405. Pimpl() : dataHandle (0)
  209406. {
  209407. }
  209408. ~Pimpl()
  209409. {
  209410. clearHandle();
  209411. }
  209412. void clearHandle()
  209413. {
  209414. if (dataHandle != 0)
  209415. {
  209416. DisposeHandle (dataHandle);
  209417. dataHandle = 0;
  209418. }
  209419. }
  209420. IQTControlPtr qtControl;
  209421. IQTMoviePtr qtMovie;
  209422. Handle dataHandle;
  209423. };
  209424. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209425. : movieLoaded (false),
  209426. controllerVisible (true)
  209427. {
  209428. pimpl = new Pimpl();
  209429. setMouseEventsAllowed (false);
  209430. }
  209431. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209432. {
  209433. closeMovie();
  209434. pimpl->qtControl = 0;
  209435. deleteControl();
  209436. pimpl = 0;
  209437. }
  209438. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209439. {
  209440. if (! isQTAvailable)
  209441. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209442. return isQTAvailable;
  209443. }
  209444. void QuickTimeMovieComponent::createControlIfNeeded()
  209445. {
  209446. if (isShowing() && ! isControlCreated())
  209447. {
  209448. const IID qtIID = __uuidof (QTControl);
  209449. if (createControl (&qtIID))
  209450. {
  209451. const IID qtInterfaceIID = __uuidof (IQTControl);
  209452. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209453. if (pimpl->qtControl != 0)
  209454. {
  209455. pimpl->qtControl->Release(); // it has one ref too many at this point
  209456. pimpl->qtControl->QuickTimeInitialize();
  209457. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209458. if (movieFile != File::nonexistent)
  209459. loadMovie (movieFile, controllerVisible);
  209460. }
  209461. }
  209462. }
  209463. }
  209464. bool QuickTimeMovieComponent::isControlCreated() const
  209465. {
  209466. return isControlOpen();
  209467. }
  209468. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209469. const bool isControllerVisible)
  209470. {
  209471. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209472. movieFile = File::nonexistent;
  209473. movieLoaded = false;
  209474. pimpl->qtMovie = 0;
  209475. controllerVisible = isControllerVisible;
  209476. createControlIfNeeded();
  209477. if (isControlCreated())
  209478. {
  209479. if (pimpl->qtControl != 0)
  209480. {
  209481. pimpl->qtControl->Put_MovieHandle (0);
  209482. pimpl->clearHandle();
  209483. Movie movie;
  209484. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209485. {
  209486. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209487. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209488. if (pimpl->qtMovie != 0)
  209489. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209490. : qtMovieControllerTypeNone);
  209491. }
  209492. if (movie == 0)
  209493. pimpl->clearHandle();
  209494. }
  209495. movieLoaded = (pimpl->qtMovie != 0);
  209496. }
  209497. else
  209498. {
  209499. // You're trying to open a movie when the control hasn't yet been created, probably because
  209500. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209501. jassertfalse;
  209502. }
  209503. return movieLoaded;
  209504. }
  209505. void QuickTimeMovieComponent::closeMovie()
  209506. {
  209507. stop();
  209508. movieFile = File::nonexistent;
  209509. movieLoaded = false;
  209510. pimpl->qtMovie = 0;
  209511. if (pimpl->qtControl != 0)
  209512. pimpl->qtControl->Put_MovieHandle (0);
  209513. pimpl->clearHandle();
  209514. }
  209515. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209516. {
  209517. return movieFile;
  209518. }
  209519. bool QuickTimeMovieComponent::isMovieOpen() const
  209520. {
  209521. return movieLoaded;
  209522. }
  209523. double QuickTimeMovieComponent::getMovieDuration() const
  209524. {
  209525. if (pimpl->qtMovie != 0)
  209526. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209527. return 0.0;
  209528. }
  209529. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209530. {
  209531. if (pimpl->qtMovie != 0)
  209532. {
  209533. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209534. width = r.right - r.left;
  209535. height = r.bottom - r.top;
  209536. }
  209537. else
  209538. {
  209539. width = height = 0;
  209540. }
  209541. }
  209542. void QuickTimeMovieComponent::play()
  209543. {
  209544. if (pimpl->qtMovie != 0)
  209545. pimpl->qtMovie->Play();
  209546. }
  209547. void QuickTimeMovieComponent::stop()
  209548. {
  209549. if (pimpl->qtMovie != 0)
  209550. pimpl->qtMovie->Stop();
  209551. }
  209552. bool QuickTimeMovieComponent::isPlaying() const
  209553. {
  209554. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209555. }
  209556. void QuickTimeMovieComponent::setPosition (const double seconds)
  209557. {
  209558. if (pimpl->qtMovie != 0)
  209559. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209560. }
  209561. double QuickTimeMovieComponent::getPosition() const
  209562. {
  209563. if (pimpl->qtMovie != 0)
  209564. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209565. return 0.0;
  209566. }
  209567. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209568. {
  209569. if (pimpl->qtMovie != 0)
  209570. pimpl->qtMovie->PutRate (newSpeed);
  209571. }
  209572. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209573. {
  209574. if (pimpl->qtMovie != 0)
  209575. {
  209576. pimpl->qtMovie->PutAudioVolume (newVolume);
  209577. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209578. }
  209579. }
  209580. float QuickTimeMovieComponent::getMovieVolume() const
  209581. {
  209582. if (pimpl->qtMovie != 0)
  209583. return pimpl->qtMovie->GetAudioVolume();
  209584. return 0.0f;
  209585. }
  209586. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209587. {
  209588. if (pimpl->qtMovie != 0)
  209589. pimpl->qtMovie->PutLoop (shouldLoop);
  209590. }
  209591. bool QuickTimeMovieComponent::isLooping() const
  209592. {
  209593. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209594. }
  209595. bool QuickTimeMovieComponent::isControllerVisible() const
  209596. {
  209597. return controllerVisible;
  209598. }
  209599. void QuickTimeMovieComponent::parentHierarchyChanged()
  209600. {
  209601. createControlIfNeeded();
  209602. QTCompBaseClass::parentHierarchyChanged();
  209603. }
  209604. void QuickTimeMovieComponent::visibilityChanged()
  209605. {
  209606. createControlIfNeeded();
  209607. QTCompBaseClass::visibilityChanged();
  209608. }
  209609. void QuickTimeMovieComponent::paint (Graphics& g)
  209610. {
  209611. if (! isControlCreated())
  209612. g.fillAll (Colours::black);
  209613. }
  209614. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209615. {
  209616. Handle dataRef = 0;
  209617. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209618. if (err == noErr)
  209619. {
  209620. Str255 suffix;
  209621. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209622. StringPtr name = suffix;
  209623. err = PtrAndHand (name, dataRef, name[0] + 1);
  209624. if (err == noErr)
  209625. {
  209626. long atoms[3];
  209627. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209628. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209629. atoms[2] = EndianU32_NtoB (MovieFileType);
  209630. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209631. if (err == noErr)
  209632. return dataRef;
  209633. }
  209634. DisposeHandle (dataRef);
  209635. }
  209636. return 0;
  209637. }
  209638. static CFStringRef juceStringToCFString (const String& s)
  209639. {
  209640. const int len = s.length();
  209641. const juce_wchar* const t = s;
  209642. HeapBlock <UniChar> temp (len + 2);
  209643. for (int i = 0; i <= len; ++i)
  209644. temp[i] = t[i];
  209645. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209646. }
  209647. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209648. {
  209649. Boolean trueBool = true;
  209650. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209651. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209652. props[prop].propValueSize = sizeof (trueBool);
  209653. props[prop].propValueAddress = &trueBool;
  209654. ++prop;
  209655. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209656. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209657. props[prop].propValueSize = sizeof (trueBool);
  209658. props[prop].propValueAddress = &trueBool;
  209659. ++prop;
  209660. Boolean isActive = true;
  209661. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209662. props[prop].propID = kQTNewMoviePropertyID_Active;
  209663. props[prop].propValueSize = sizeof (isActive);
  209664. props[prop].propValueAddress = &isActive;
  209665. ++prop;
  209666. MacSetPort (0);
  209667. jassert (prop <= 5);
  209668. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209669. return err == noErr;
  209670. }
  209671. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209672. {
  209673. if (input == 0)
  209674. return false;
  209675. dataHandle = 0;
  209676. bool ok = false;
  209677. QTNewMoviePropertyElement props[5];
  209678. zeromem (props, sizeof (props));
  209679. int prop = 0;
  209680. DataReferenceRecord dr;
  209681. props[prop].propClass = kQTPropertyClass_DataLocation;
  209682. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209683. props[prop].propValueSize = sizeof (dr);
  209684. props[prop].propValueAddress = &dr;
  209685. ++prop;
  209686. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209687. if (fin != 0)
  209688. {
  209689. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209690. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209691. &dr.dataRef, &dr.dataRefType);
  209692. ok = openMovie (props, prop, movie);
  209693. DisposeHandle (dr.dataRef);
  209694. CFRelease (filePath);
  209695. }
  209696. else
  209697. {
  209698. // sanity-check because this currently needs to load the whole stream into memory..
  209699. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209700. dataHandle = NewHandle ((Size) input->getTotalLength());
  209701. HLock (dataHandle);
  209702. // read the entire stream into memory - this is a pain, but can't get it to work
  209703. // properly using a custom callback to supply the data.
  209704. input->read (*dataHandle, (int) input->getTotalLength());
  209705. HUnlock (dataHandle);
  209706. // different types to get QT to try. (We should really be a bit smarter here by
  209707. // working out in advance which one the stream contains, rather than just trying
  209708. // each one)
  209709. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209710. "\04.avi", "\04.m4a" };
  209711. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209712. {
  209713. /* // this fails for some bizarre reason - it can be bodged to work with
  209714. // movies, but can't seem to do it for other file types..
  209715. QTNewMovieUserProcRecord procInfo;
  209716. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209717. procInfo.getMovieUserProcRefcon = this;
  209718. procInfo.defaultDataRef.dataRef = dataRef;
  209719. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209720. props[prop].propClass = kQTPropertyClass_DataLocation;
  209721. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209722. props[prop].propValueSize = sizeof (procInfo);
  209723. props[prop].propValueAddress = (void*) &procInfo;
  209724. ++prop; */
  209725. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209726. dr.dataRefType = HandleDataHandlerSubType;
  209727. ok = openMovie (props, prop, movie);
  209728. DisposeHandle (dr.dataRef);
  209729. }
  209730. }
  209731. return ok;
  209732. }
  209733. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209734. const bool isControllerVisible)
  209735. {
  209736. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209737. movieFile = movieFile_;
  209738. return ok;
  209739. }
  209740. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209741. const bool isControllerVisible)
  209742. {
  209743. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209744. }
  209745. void QuickTimeMovieComponent::goToStart()
  209746. {
  209747. setPosition (0.0);
  209748. }
  209749. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209750. const RectanglePlacement& placement)
  209751. {
  209752. int normalWidth, normalHeight;
  209753. getMovieNormalSize (normalWidth, normalHeight);
  209754. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209755. {
  209756. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209757. placement.applyTo (x, y, w, h,
  209758. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209759. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209760. if (w > 0 && h > 0)
  209761. {
  209762. setBounds (roundToInt (x), roundToInt (y),
  209763. roundToInt (w), roundToInt (h));
  209764. }
  209765. }
  209766. else
  209767. {
  209768. setBounds (spaceToFitWithin);
  209769. }
  209770. }
  209771. #endif
  209772. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209773. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209774. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209775. // compiled on its own).
  209776. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209777. class WebBrowserComponentInternal : public ActiveXControlComponent
  209778. {
  209779. public:
  209780. WebBrowserComponentInternal()
  209781. : browser (0),
  209782. connectionPoint (0),
  209783. adviseCookie (0)
  209784. {
  209785. }
  209786. ~WebBrowserComponentInternal()
  209787. {
  209788. if (connectionPoint != 0)
  209789. connectionPoint->Unadvise (adviseCookie);
  209790. if (browser != 0)
  209791. browser->Release();
  209792. }
  209793. void createBrowser()
  209794. {
  209795. createControl (&CLSID_WebBrowser);
  209796. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209797. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209798. if (connectionPointContainer != 0)
  209799. {
  209800. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209801. &connectionPoint);
  209802. if (connectionPoint != 0)
  209803. {
  209804. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209805. jassert (owner != 0);
  209806. EventHandler* handler = new EventHandler (owner);
  209807. connectionPoint->Advise (handler, &adviseCookie);
  209808. handler->Release();
  209809. }
  209810. }
  209811. }
  209812. void goToURL (const String& url,
  209813. const StringArray* headers,
  209814. const MemoryBlock* postData)
  209815. {
  209816. if (browser != 0)
  209817. {
  209818. LPSAFEARRAY sa = 0;
  209819. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209820. VariantInit (&flags);
  209821. VariantInit (&frame);
  209822. VariantInit (&postDataVar);
  209823. VariantInit (&headersVar);
  209824. if (headers != 0)
  209825. {
  209826. V_VT (&headersVar) = VT_BSTR;
  209827. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209828. }
  209829. if (postData != 0 && postData->getSize() > 0)
  209830. {
  209831. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209832. if (sa != 0)
  209833. {
  209834. void* data = 0;
  209835. SafeArrayAccessData (sa, &data);
  209836. jassert (data != 0);
  209837. if (data != 0)
  209838. {
  209839. postData->copyTo (data, 0, postData->getSize());
  209840. SafeArrayUnaccessData (sa);
  209841. VARIANT postDataVar2;
  209842. VariantInit (&postDataVar2);
  209843. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209844. V_ARRAY (&postDataVar2) = sa;
  209845. postDataVar = postDataVar2;
  209846. }
  209847. }
  209848. }
  209849. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209850. &flags, &frame,
  209851. &postDataVar, &headersVar);
  209852. if (sa != 0)
  209853. SafeArrayDestroy (sa);
  209854. VariantClear (&flags);
  209855. VariantClear (&frame);
  209856. VariantClear (&postDataVar);
  209857. VariantClear (&headersVar);
  209858. }
  209859. }
  209860. IWebBrowser2* browser;
  209861. private:
  209862. IConnectionPoint* connectionPoint;
  209863. DWORD adviseCookie;
  209864. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209865. public ComponentMovementWatcher
  209866. {
  209867. public:
  209868. EventHandler (WebBrowserComponent* const owner_)
  209869. : ComponentMovementWatcher (owner_),
  209870. owner (owner_)
  209871. {
  209872. }
  209873. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209874. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209875. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209876. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209877. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209878. {
  209879. switch (dispIdMember)
  209880. {
  209881. case DISPID_BEFORENAVIGATE2:
  209882. {
  209883. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209884. String url;
  209885. if ((vurl->vt & VT_BYREF) != 0)
  209886. url = *vurl->pbstrVal;
  209887. else
  209888. url = vurl->bstrVal;
  209889. *pDispParams->rgvarg->pboolVal
  209890. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209891. : VARIANT_TRUE;
  209892. return S_OK;
  209893. }
  209894. default:
  209895. break;
  209896. }
  209897. return E_NOTIMPL;
  209898. }
  209899. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209900. void componentPeerChanged() {}
  209901. void componentVisibilityChanged (Component&)
  209902. {
  209903. owner->visibilityChanged();
  209904. }
  209905. private:
  209906. WebBrowserComponent* const owner;
  209907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209908. };
  209909. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209910. };
  209911. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209912. : browser (0),
  209913. blankPageShown (false),
  209914. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209915. {
  209916. setOpaque (true);
  209917. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209918. }
  209919. WebBrowserComponent::~WebBrowserComponent()
  209920. {
  209921. delete browser;
  209922. }
  209923. void WebBrowserComponent::goToURL (const String& url,
  209924. const StringArray* headers,
  209925. const MemoryBlock* postData)
  209926. {
  209927. lastURL = url;
  209928. lastHeaders.clear();
  209929. if (headers != 0)
  209930. lastHeaders = *headers;
  209931. lastPostData.setSize (0);
  209932. if (postData != 0)
  209933. lastPostData = *postData;
  209934. blankPageShown = false;
  209935. browser->goToURL (url, headers, postData);
  209936. }
  209937. void WebBrowserComponent::stop()
  209938. {
  209939. if (browser->browser != 0)
  209940. browser->browser->Stop();
  209941. }
  209942. void WebBrowserComponent::goBack()
  209943. {
  209944. lastURL = String::empty;
  209945. blankPageShown = false;
  209946. if (browser->browser != 0)
  209947. browser->browser->GoBack();
  209948. }
  209949. void WebBrowserComponent::goForward()
  209950. {
  209951. lastURL = String::empty;
  209952. if (browser->browser != 0)
  209953. browser->browser->GoForward();
  209954. }
  209955. void WebBrowserComponent::refresh()
  209956. {
  209957. if (browser->browser != 0)
  209958. browser->browser->Refresh();
  209959. }
  209960. void WebBrowserComponent::paint (Graphics& g)
  209961. {
  209962. if (browser->browser == 0)
  209963. g.fillAll (Colours::white);
  209964. }
  209965. void WebBrowserComponent::checkWindowAssociation()
  209966. {
  209967. if (isShowing())
  209968. {
  209969. if (browser->browser == 0 && getPeer() != 0)
  209970. {
  209971. browser->createBrowser();
  209972. reloadLastURL();
  209973. }
  209974. else
  209975. {
  209976. if (blankPageShown)
  209977. goBack();
  209978. }
  209979. }
  209980. else
  209981. {
  209982. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209983. {
  209984. // when the component becomes invisible, some stuff like flash
  209985. // carries on playing audio, so we need to force it onto a blank
  209986. // page to avoid this..
  209987. blankPageShown = true;
  209988. browser->goToURL ("about:blank", 0, 0);
  209989. }
  209990. }
  209991. }
  209992. void WebBrowserComponent::reloadLastURL()
  209993. {
  209994. if (lastURL.isNotEmpty())
  209995. {
  209996. goToURL (lastURL, &lastHeaders, &lastPostData);
  209997. lastURL = String::empty;
  209998. }
  209999. }
  210000. void WebBrowserComponent::parentHierarchyChanged()
  210001. {
  210002. checkWindowAssociation();
  210003. }
  210004. void WebBrowserComponent::resized()
  210005. {
  210006. browser->setSize (getWidth(), getHeight());
  210007. }
  210008. void WebBrowserComponent::visibilityChanged()
  210009. {
  210010. checkWindowAssociation();
  210011. }
  210012. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210013. {
  210014. return true;
  210015. }
  210016. #endif
  210017. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210018. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210019. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210020. // compiled on its own).
  210021. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210022. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210023. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210024. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210025. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210026. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210027. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210028. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210029. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210030. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210031. #define WGL_ACCELERATION_ARB 0x2003
  210032. #define WGL_SWAP_METHOD_ARB 0x2007
  210033. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210034. #define WGL_PIXEL_TYPE_ARB 0x2013
  210035. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210036. #define WGL_COLOR_BITS_ARB 0x2014
  210037. #define WGL_RED_BITS_ARB 0x2015
  210038. #define WGL_GREEN_BITS_ARB 0x2017
  210039. #define WGL_BLUE_BITS_ARB 0x2019
  210040. #define WGL_ALPHA_BITS_ARB 0x201B
  210041. #define WGL_DEPTH_BITS_ARB 0x2022
  210042. #define WGL_STENCIL_BITS_ARB 0x2023
  210043. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210044. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210045. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210046. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210047. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210048. #define WGL_STEREO_ARB 0x2012
  210049. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210050. #define WGL_SAMPLES_ARB 0x2042
  210051. #define WGL_TYPE_RGBA_ARB 0x202B
  210052. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210053. {
  210054. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210055. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210056. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210057. else
  210058. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210059. }
  210060. class WindowedGLContext : public OpenGLContext
  210061. {
  210062. public:
  210063. WindowedGLContext (Component* const component_,
  210064. HGLRC contextToShareWith,
  210065. const OpenGLPixelFormat& pixelFormat)
  210066. : renderContext (0),
  210067. dc (0),
  210068. component (component_)
  210069. {
  210070. jassert (component != 0);
  210071. createNativeWindow();
  210072. // Use a default pixel format that should be supported everywhere
  210073. PIXELFORMATDESCRIPTOR pfd;
  210074. zerostruct (pfd);
  210075. pfd.nSize = sizeof (pfd);
  210076. pfd.nVersion = 1;
  210077. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210078. pfd.iPixelType = PFD_TYPE_RGBA;
  210079. pfd.cColorBits = 24;
  210080. pfd.cDepthBits = 16;
  210081. const int format = ChoosePixelFormat (dc, &pfd);
  210082. if (format != 0)
  210083. SetPixelFormat (dc, format, &pfd);
  210084. renderContext = wglCreateContext (dc);
  210085. makeActive();
  210086. setPixelFormat (pixelFormat);
  210087. if (contextToShareWith != 0 && renderContext != 0)
  210088. wglShareLists (contextToShareWith, renderContext);
  210089. }
  210090. ~WindowedGLContext()
  210091. {
  210092. deleteContext();
  210093. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210094. nativeWindow = 0;
  210095. }
  210096. void deleteContext()
  210097. {
  210098. makeInactive();
  210099. if (renderContext != 0)
  210100. {
  210101. wglDeleteContext (renderContext);
  210102. renderContext = 0;
  210103. }
  210104. }
  210105. bool makeActive() const throw()
  210106. {
  210107. jassert (renderContext != 0);
  210108. return wglMakeCurrent (dc, renderContext) != 0;
  210109. }
  210110. bool makeInactive() const throw()
  210111. {
  210112. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210113. }
  210114. bool isActive() const throw()
  210115. {
  210116. return wglGetCurrentContext() == renderContext;
  210117. }
  210118. const OpenGLPixelFormat getPixelFormat() const
  210119. {
  210120. OpenGLPixelFormat pf;
  210121. makeActive();
  210122. StringArray availableExtensions;
  210123. getWglExtensions (dc, availableExtensions);
  210124. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210125. return pf;
  210126. }
  210127. void* getRawContext() const throw()
  210128. {
  210129. return renderContext;
  210130. }
  210131. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210132. {
  210133. makeActive();
  210134. PIXELFORMATDESCRIPTOR pfd;
  210135. zerostruct (pfd);
  210136. pfd.nSize = sizeof (pfd);
  210137. pfd.nVersion = 1;
  210138. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210139. pfd.iPixelType = PFD_TYPE_RGBA;
  210140. pfd.iLayerType = PFD_MAIN_PLANE;
  210141. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210142. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210143. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210144. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210145. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210146. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210147. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210148. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210149. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210150. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210151. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210152. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210153. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210154. int format = 0;
  210155. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210156. StringArray availableExtensions;
  210157. getWglExtensions (dc, availableExtensions);
  210158. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210159. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210160. {
  210161. int attributes[64];
  210162. int n = 0;
  210163. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210164. attributes[n++] = GL_TRUE;
  210165. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210166. attributes[n++] = GL_TRUE;
  210167. attributes[n++] = WGL_ACCELERATION_ARB;
  210168. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210169. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210170. attributes[n++] = GL_TRUE;
  210171. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210172. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210173. attributes[n++] = WGL_COLOR_BITS_ARB;
  210174. attributes[n++] = pfd.cColorBits;
  210175. attributes[n++] = WGL_RED_BITS_ARB;
  210176. attributes[n++] = pixelFormat.redBits;
  210177. attributes[n++] = WGL_GREEN_BITS_ARB;
  210178. attributes[n++] = pixelFormat.greenBits;
  210179. attributes[n++] = WGL_BLUE_BITS_ARB;
  210180. attributes[n++] = pixelFormat.blueBits;
  210181. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210182. attributes[n++] = pixelFormat.alphaBits;
  210183. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210184. attributes[n++] = pixelFormat.depthBufferBits;
  210185. if (pixelFormat.stencilBufferBits > 0)
  210186. {
  210187. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210188. attributes[n++] = pixelFormat.stencilBufferBits;
  210189. }
  210190. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210191. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210192. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210193. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210194. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210195. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210196. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210197. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210198. if (availableExtensions.contains ("WGL_ARB_multisample")
  210199. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210200. {
  210201. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210202. attributes[n++] = 1;
  210203. attributes[n++] = WGL_SAMPLES_ARB;
  210204. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210205. }
  210206. attributes[n++] = 0;
  210207. UINT formatsCount;
  210208. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210209. (void) ok;
  210210. jassert (ok);
  210211. }
  210212. else
  210213. {
  210214. format = ChoosePixelFormat (dc, &pfd);
  210215. }
  210216. if (format != 0)
  210217. {
  210218. makeInactive();
  210219. // win32 can't change the pixel format of a window, so need to delete the
  210220. // old one and create a new one..
  210221. jassert (nativeWindow != 0);
  210222. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210223. nativeWindow = 0;
  210224. createNativeWindow();
  210225. if (SetPixelFormat (dc, format, &pfd))
  210226. {
  210227. wglDeleteContext (renderContext);
  210228. renderContext = wglCreateContext (dc);
  210229. jassert (renderContext != 0);
  210230. return renderContext != 0;
  210231. }
  210232. }
  210233. return false;
  210234. }
  210235. void updateWindowPosition (int x, int y, int w, int h, int)
  210236. {
  210237. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210238. x, y, w, h,
  210239. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210240. }
  210241. void repaint()
  210242. {
  210243. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210244. }
  210245. void swapBuffers()
  210246. {
  210247. SwapBuffers (dc);
  210248. }
  210249. bool setSwapInterval (int numFramesPerSwap)
  210250. {
  210251. makeActive();
  210252. StringArray availableExtensions;
  210253. getWglExtensions (dc, availableExtensions);
  210254. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210255. return availableExtensions.contains ("WGL_EXT_swap_control")
  210256. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210257. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210258. }
  210259. int getSwapInterval() const
  210260. {
  210261. makeActive();
  210262. StringArray availableExtensions;
  210263. getWglExtensions (dc, availableExtensions);
  210264. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210265. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210266. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210267. return wglGetSwapIntervalEXT();
  210268. return 0;
  210269. }
  210270. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210271. {
  210272. jassert (isActive());
  210273. StringArray availableExtensions;
  210274. getWglExtensions (dc, availableExtensions);
  210275. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210276. int numTypes = 0;
  210277. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210278. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210279. {
  210280. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210281. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210282. jassertfalse;
  210283. }
  210284. else
  210285. {
  210286. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210287. }
  210288. OpenGLPixelFormat pf;
  210289. for (int i = 0; i < numTypes; ++i)
  210290. {
  210291. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210292. {
  210293. bool alreadyListed = false;
  210294. for (int j = results.size(); --j >= 0;)
  210295. if (pf == *results.getUnchecked(j))
  210296. alreadyListed = true;
  210297. if (! alreadyListed)
  210298. results.add (new OpenGLPixelFormat (pf));
  210299. }
  210300. }
  210301. }
  210302. void* getNativeWindowHandle() const
  210303. {
  210304. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210305. }
  210306. HGLRC renderContext;
  210307. private:
  210308. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210309. Component* const component;
  210310. HDC dc;
  210311. void createNativeWindow()
  210312. {
  210313. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210314. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210315. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210316. nativeWindow->dontRepaint = true;
  210317. nativeWindow->setVisible (true);
  210318. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210319. }
  210320. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210321. OpenGLPixelFormat& result,
  210322. const StringArray& availableExtensions) const throw()
  210323. {
  210324. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210325. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210326. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210327. {
  210328. int attributes[32];
  210329. int numAttributes = 0;
  210330. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210331. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210332. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210333. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210334. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210335. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210336. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210337. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210338. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210339. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210340. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210341. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210342. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210343. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210344. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210345. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210346. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210347. int values[32];
  210348. zeromem (values, sizeof (values));
  210349. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210350. {
  210351. int n = 0;
  210352. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210353. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210354. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210355. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210356. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210357. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210358. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210359. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210360. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210361. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210362. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210363. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210364. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210365. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210366. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210367. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210368. return isValidFormat;
  210369. }
  210370. else
  210371. {
  210372. jassertfalse;
  210373. }
  210374. }
  210375. else
  210376. {
  210377. PIXELFORMATDESCRIPTOR pfd;
  210378. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210379. {
  210380. result.redBits = pfd.cRedBits;
  210381. result.greenBits = pfd.cGreenBits;
  210382. result.blueBits = pfd.cBlueBits;
  210383. result.alphaBits = pfd.cAlphaBits;
  210384. result.depthBufferBits = pfd.cDepthBits;
  210385. result.stencilBufferBits = pfd.cStencilBits;
  210386. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210387. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210388. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210389. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210390. result.fullSceneAntiAliasingNumSamples = 0;
  210391. return true;
  210392. }
  210393. else
  210394. {
  210395. jassertfalse;
  210396. }
  210397. }
  210398. return false;
  210399. }
  210400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210401. };
  210402. OpenGLContext* OpenGLComponent::createContext()
  210403. {
  210404. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210405. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210406. preferredPixelFormat));
  210407. return (c->renderContext != 0) ? c.release() : 0;
  210408. }
  210409. void* OpenGLComponent::getNativeWindowHandle() const
  210410. {
  210411. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210412. }
  210413. void juce_glViewport (const int w, const int h)
  210414. {
  210415. glViewport (0, 0, w, h);
  210416. }
  210417. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210418. OwnedArray <OpenGLPixelFormat>& results)
  210419. {
  210420. Component tempComp;
  210421. {
  210422. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210423. wc.makeActive();
  210424. wc.findAlternativeOpenGLPixelFormats (results);
  210425. }
  210426. }
  210427. #endif
  210428. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210429. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210430. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210431. // compiled on its own).
  210432. #if JUCE_INCLUDED_FILE
  210433. #if JUCE_USE_CDREADER
  210434. namespace CDReaderHelpers
  210435. {
  210436. #define FILE_ANY_ACCESS 0
  210437. #ifndef FILE_READ_ACCESS
  210438. #define FILE_READ_ACCESS 1
  210439. #endif
  210440. #ifndef FILE_WRITE_ACCESS
  210441. #define FILE_WRITE_ACCESS 2
  210442. #endif
  210443. #define METHOD_BUFFERED 0
  210444. #define IOCTL_SCSI_BASE 4
  210445. #define SCSI_IOCTL_DATA_OUT 0
  210446. #define SCSI_IOCTL_DATA_IN 1
  210447. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210448. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210449. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210450. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210451. #define SENSE_LEN 14
  210452. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210453. #define SRB_DIR_IN 0x08
  210454. #define SRB_DIR_OUT 0x10
  210455. #define SRB_EVENT_NOTIFY 0x40
  210456. #define SC_HA_INQUIRY 0x00
  210457. #define SC_GET_DEV_TYPE 0x01
  210458. #define SC_EXEC_SCSI_CMD 0x02
  210459. #define SS_PENDING 0x00
  210460. #define SS_COMP 0x01
  210461. #define SS_ERR 0x04
  210462. enum
  210463. {
  210464. READTYPE_ANY = 0,
  210465. READTYPE_ATAPI1 = 1,
  210466. READTYPE_ATAPI2 = 2,
  210467. READTYPE_READ6 = 3,
  210468. READTYPE_READ10 = 4,
  210469. READTYPE_READ_D8 = 5,
  210470. READTYPE_READ_D4 = 6,
  210471. READTYPE_READ_D4_1 = 7,
  210472. READTYPE_READ10_2 = 8
  210473. };
  210474. struct SCSI_PASS_THROUGH
  210475. {
  210476. USHORT Length;
  210477. UCHAR ScsiStatus;
  210478. UCHAR PathId;
  210479. UCHAR TargetId;
  210480. UCHAR Lun;
  210481. UCHAR CdbLength;
  210482. UCHAR SenseInfoLength;
  210483. UCHAR DataIn;
  210484. ULONG DataTransferLength;
  210485. ULONG TimeOutValue;
  210486. ULONG DataBufferOffset;
  210487. ULONG SenseInfoOffset;
  210488. UCHAR Cdb[16];
  210489. };
  210490. struct SCSI_PASS_THROUGH_DIRECT
  210491. {
  210492. USHORT Length;
  210493. UCHAR ScsiStatus;
  210494. UCHAR PathId;
  210495. UCHAR TargetId;
  210496. UCHAR Lun;
  210497. UCHAR CdbLength;
  210498. UCHAR SenseInfoLength;
  210499. UCHAR DataIn;
  210500. ULONG DataTransferLength;
  210501. ULONG TimeOutValue;
  210502. PVOID DataBuffer;
  210503. ULONG SenseInfoOffset;
  210504. UCHAR Cdb[16];
  210505. };
  210506. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210507. {
  210508. SCSI_PASS_THROUGH_DIRECT spt;
  210509. ULONG Filler;
  210510. UCHAR ucSenseBuf[32];
  210511. };
  210512. struct SCSI_ADDRESS
  210513. {
  210514. ULONG Length;
  210515. UCHAR PortNumber;
  210516. UCHAR PathId;
  210517. UCHAR TargetId;
  210518. UCHAR Lun;
  210519. };
  210520. #pragma pack(1)
  210521. struct SRB_GDEVBlock
  210522. {
  210523. BYTE SRB_Cmd;
  210524. BYTE SRB_Status;
  210525. BYTE SRB_HaID;
  210526. BYTE SRB_Flags;
  210527. DWORD SRB_Hdr_Rsvd;
  210528. BYTE SRB_Target;
  210529. BYTE SRB_Lun;
  210530. BYTE SRB_DeviceType;
  210531. BYTE SRB_Rsvd1;
  210532. BYTE pad[68];
  210533. };
  210534. struct SRB_ExecSCSICmd
  210535. {
  210536. BYTE SRB_Cmd;
  210537. BYTE SRB_Status;
  210538. BYTE SRB_HaID;
  210539. BYTE SRB_Flags;
  210540. DWORD SRB_Hdr_Rsvd;
  210541. BYTE SRB_Target;
  210542. BYTE SRB_Lun;
  210543. WORD SRB_Rsvd1;
  210544. DWORD SRB_BufLen;
  210545. BYTE *SRB_BufPointer;
  210546. BYTE SRB_SenseLen;
  210547. BYTE SRB_CDBLen;
  210548. BYTE SRB_HaStat;
  210549. BYTE SRB_TargStat;
  210550. VOID *SRB_PostProc;
  210551. BYTE SRB_Rsvd2[20];
  210552. BYTE CDBByte[16];
  210553. BYTE SenseArea[SENSE_LEN + 2];
  210554. };
  210555. struct SRB
  210556. {
  210557. BYTE SRB_Cmd;
  210558. BYTE SRB_Status;
  210559. BYTE SRB_HaId;
  210560. BYTE SRB_Flags;
  210561. DWORD SRB_Hdr_Rsvd;
  210562. };
  210563. struct TOCTRACK
  210564. {
  210565. BYTE rsvd;
  210566. BYTE ADR;
  210567. BYTE trackNumber;
  210568. BYTE rsvd2;
  210569. BYTE addr[4];
  210570. };
  210571. struct TOC
  210572. {
  210573. WORD tocLen;
  210574. BYTE firstTrack;
  210575. BYTE lastTrack;
  210576. TOCTRACK tracks[100];
  210577. };
  210578. #pragma pack()
  210579. struct CDDeviceDescription
  210580. {
  210581. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210582. {
  210583. }
  210584. void createDescription (const char* data)
  210585. {
  210586. description << String (data + 8, 8).trim() // vendor
  210587. << ' ' << String (data + 16, 16).trim() // product id
  210588. << ' ' << String (data + 32, 4).trim(); // rev
  210589. }
  210590. String description;
  210591. BYTE ha, tgt, lun;
  210592. char scsiDriveLetter; // will be 0 if not using scsi
  210593. };
  210594. class CDReadBuffer
  210595. {
  210596. public:
  210597. CDReadBuffer (const int numberOfFrames)
  210598. : startFrame (0), numFrames (0), dataStartOffset (0),
  210599. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210600. buffer (bufferSize), wantsIndex (false)
  210601. {
  210602. }
  210603. bool isZero() const throw()
  210604. {
  210605. for (int i = 0; i < dataLength; ++i)
  210606. if (buffer [dataStartOffset + i] != 0)
  210607. return false;
  210608. return true;
  210609. }
  210610. int startFrame, numFrames, dataStartOffset;
  210611. int dataLength, bufferSize, index;
  210612. HeapBlock<BYTE> buffer;
  210613. bool wantsIndex;
  210614. };
  210615. class CDDeviceHandle;
  210616. class CDController
  210617. {
  210618. public:
  210619. CDController() : initialised (false) {}
  210620. virtual ~CDController() {}
  210621. virtual bool read (CDReadBuffer&) = 0;
  210622. virtual void shutDown() {}
  210623. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210624. int getLastIndex();
  210625. public:
  210626. CDDeviceHandle* deviceInfo;
  210627. int framesToCheck, framesOverlap;
  210628. bool initialised;
  210629. void prepare (SRB_ExecSCSICmd& s);
  210630. void perform (SRB_ExecSCSICmd& s);
  210631. void setPaused (bool paused);
  210632. };
  210633. class CDDeviceHandle
  210634. {
  210635. public:
  210636. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210637. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210638. {
  210639. }
  210640. ~CDDeviceHandle()
  210641. {
  210642. if (controller != 0)
  210643. {
  210644. controller->shutDown();
  210645. controller = 0;
  210646. }
  210647. if (scsiHandle != 0)
  210648. CloseHandle (scsiHandle);
  210649. }
  210650. bool readTOC (TOC* lpToc);
  210651. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210652. void openDrawer (bool shouldBeOpen);
  210653. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210654. CDDeviceDescription info;
  210655. HANDLE scsiHandle;
  210656. BYTE readType;
  210657. private:
  210658. ScopedPointer<CDController> controller;
  210659. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210660. };
  210661. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210662. {
  210663. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210664. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210665. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210666. if (h == INVALID_HANDLE_VALUE)
  210667. {
  210668. flags ^= GENERIC_WRITE;
  210669. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210670. }
  210671. return h;
  210672. }
  210673. void findCDDevices (Array<CDDeviceDescription>& list)
  210674. {
  210675. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210676. {
  210677. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210678. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210679. {
  210680. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210681. if (h != INVALID_HANDLE_VALUE)
  210682. {
  210683. char buffer[100];
  210684. zeromem (buffer, sizeof (buffer));
  210685. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210686. zerostruct (p);
  210687. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210688. p.spt.CdbLength = 6;
  210689. p.spt.SenseInfoLength = 24;
  210690. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210691. p.spt.DataTransferLength = sizeof (buffer);
  210692. p.spt.TimeOutValue = 2;
  210693. p.spt.DataBuffer = buffer;
  210694. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210695. p.spt.Cdb[0] = 0x12;
  210696. p.spt.Cdb[4] = 100;
  210697. DWORD bytesReturned = 0;
  210698. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210699. &p, sizeof (p), &p, sizeof (p),
  210700. &bytesReturned, 0) != 0)
  210701. {
  210702. CDDeviceDescription dev;
  210703. dev.scsiDriveLetter = driveLetter;
  210704. dev.createDescription (buffer);
  210705. SCSI_ADDRESS scsiAddr;
  210706. zerostruct (scsiAddr);
  210707. scsiAddr.Length = sizeof (scsiAddr);
  210708. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210709. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210710. &bytesReturned, 0) != 0)
  210711. {
  210712. dev.ha = scsiAddr.PortNumber;
  210713. dev.tgt = scsiAddr.TargetId;
  210714. dev.lun = scsiAddr.Lun;
  210715. list.add (dev);
  210716. }
  210717. }
  210718. CloseHandle (h);
  210719. }
  210720. }
  210721. }
  210722. }
  210723. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210724. HANDLE& deviceHandle, const bool retryOnFailure)
  210725. {
  210726. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210727. zerostruct (s);
  210728. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210729. s.spt.CdbLength = srb->SRB_CDBLen;
  210730. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210731. ? SCSI_IOCTL_DATA_IN
  210732. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210733. ? SCSI_IOCTL_DATA_OUT
  210734. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210735. s.spt.DataTransferLength = srb->SRB_BufLen;
  210736. s.spt.TimeOutValue = 5;
  210737. s.spt.DataBuffer = srb->SRB_BufPointer;
  210738. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210739. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210740. srb->SRB_Status = SS_ERR;
  210741. srb->SRB_TargStat = 0x0004;
  210742. DWORD bytesReturned = 0;
  210743. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210744. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210745. {
  210746. srb->SRB_Status = SS_COMP;
  210747. }
  210748. else if (retryOnFailure)
  210749. {
  210750. const DWORD error = GetLastError();
  210751. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210752. {
  210753. if (error != ERROR_INVALID_HANDLE)
  210754. CloseHandle (deviceHandle);
  210755. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210756. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210757. }
  210758. }
  210759. return srb->SRB_Status;
  210760. }
  210761. // Controller types..
  210762. class ControllerType1 : public CDController
  210763. {
  210764. public:
  210765. ControllerType1() {}
  210766. bool read (CDReadBuffer& rb)
  210767. {
  210768. if (rb.numFrames * 2352 > rb.bufferSize)
  210769. return false;
  210770. SRB_ExecSCSICmd s;
  210771. prepare (s);
  210772. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210773. s.SRB_BufLen = rb.bufferSize;
  210774. s.SRB_BufPointer = rb.buffer;
  210775. s.SRB_CDBLen = 12;
  210776. s.CDBByte[0] = 0xBE;
  210777. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210778. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210779. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210780. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210781. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210782. perform (s);
  210783. if (s.SRB_Status != SS_COMP)
  210784. return false;
  210785. rb.dataLength = rb.numFrames * 2352;
  210786. rb.dataStartOffset = 0;
  210787. return true;
  210788. }
  210789. };
  210790. class ControllerType2 : public CDController
  210791. {
  210792. public:
  210793. ControllerType2() {}
  210794. void shutDown()
  210795. {
  210796. if (initialised)
  210797. {
  210798. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210799. SRB_ExecSCSICmd s;
  210800. prepare (s);
  210801. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210802. s.SRB_BufLen = 0x0C;
  210803. s.SRB_BufPointer = bufPointer;
  210804. s.SRB_CDBLen = 6;
  210805. s.CDBByte[0] = 0x15;
  210806. s.CDBByte[4] = 0x0C;
  210807. perform (s);
  210808. }
  210809. }
  210810. bool init()
  210811. {
  210812. SRB_ExecSCSICmd s;
  210813. s.SRB_Status = SS_ERR;
  210814. if (deviceInfo->readType == READTYPE_READ10_2)
  210815. {
  210816. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210817. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210818. for (int i = 0; i < 2; ++i)
  210819. {
  210820. prepare (s);
  210821. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210822. s.SRB_BufLen = 0x14;
  210823. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210824. s.SRB_CDBLen = 6;
  210825. s.CDBByte[0] = 0x15;
  210826. s.CDBByte[1] = 0x10;
  210827. s.CDBByte[4] = 0x14;
  210828. perform (s);
  210829. if (s.SRB_Status != SS_COMP)
  210830. return false;
  210831. }
  210832. }
  210833. else
  210834. {
  210835. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210836. prepare (s);
  210837. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210838. s.SRB_BufLen = 0x0C;
  210839. s.SRB_BufPointer = bufPointer;
  210840. s.SRB_CDBLen = 6;
  210841. s.CDBByte[0] = 0x15;
  210842. s.CDBByte[4] = 0x0C;
  210843. perform (s);
  210844. }
  210845. return s.SRB_Status == SS_COMP;
  210846. }
  210847. bool read (CDReadBuffer& rb)
  210848. {
  210849. if (rb.numFrames * 2352 > rb.bufferSize)
  210850. return false;
  210851. if (! initialised)
  210852. {
  210853. initialised = init();
  210854. if (! initialised)
  210855. return false;
  210856. }
  210857. SRB_ExecSCSICmd s;
  210858. prepare (s);
  210859. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210860. s.SRB_BufLen = rb.bufferSize;
  210861. s.SRB_BufPointer = rb.buffer;
  210862. s.SRB_CDBLen = 10;
  210863. s.CDBByte[0] = 0x28;
  210864. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210865. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210866. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210867. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210868. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210869. perform (s);
  210870. if (s.SRB_Status != SS_COMP)
  210871. return false;
  210872. rb.dataLength = rb.numFrames * 2352;
  210873. rb.dataStartOffset = 0;
  210874. return true;
  210875. }
  210876. };
  210877. class ControllerType3 : public CDController
  210878. {
  210879. public:
  210880. ControllerType3() {}
  210881. bool read (CDReadBuffer& rb)
  210882. {
  210883. if (rb.numFrames * 2352 > rb.bufferSize)
  210884. return false;
  210885. if (! initialised)
  210886. {
  210887. setPaused (false);
  210888. initialised = true;
  210889. }
  210890. SRB_ExecSCSICmd s;
  210891. prepare (s);
  210892. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210893. s.SRB_BufLen = rb.numFrames * 2352;
  210894. s.SRB_BufPointer = rb.buffer;
  210895. s.SRB_CDBLen = 12;
  210896. s.CDBByte[0] = 0xD8;
  210897. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210898. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210899. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210900. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210901. perform (s);
  210902. if (s.SRB_Status != SS_COMP)
  210903. return false;
  210904. rb.dataLength = rb.numFrames * 2352;
  210905. rb.dataStartOffset = 0;
  210906. return true;
  210907. }
  210908. };
  210909. class ControllerType4 : public CDController
  210910. {
  210911. public:
  210912. ControllerType4() {}
  210913. bool selectD4Mode()
  210914. {
  210915. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210916. SRB_ExecSCSICmd s;
  210917. prepare (s);
  210918. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210919. s.SRB_CDBLen = 6;
  210920. s.SRB_BufLen = 12;
  210921. s.SRB_BufPointer = bufPointer;
  210922. s.CDBByte[0] = 0x15;
  210923. s.CDBByte[1] = 0x10;
  210924. s.CDBByte[4] = 0x08;
  210925. perform (s);
  210926. return s.SRB_Status == SS_COMP;
  210927. }
  210928. bool read (CDReadBuffer& rb)
  210929. {
  210930. if (rb.numFrames * 2352 > rb.bufferSize)
  210931. return false;
  210932. if (! initialised)
  210933. {
  210934. setPaused (true);
  210935. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210936. selectD4Mode();
  210937. initialised = true;
  210938. }
  210939. SRB_ExecSCSICmd s;
  210940. prepare (s);
  210941. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210942. s.SRB_BufLen = rb.bufferSize;
  210943. s.SRB_BufPointer = rb.buffer;
  210944. s.SRB_CDBLen = 10;
  210945. s.CDBByte[0] = 0xD4;
  210946. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210947. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210948. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210949. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210950. perform (s);
  210951. if (s.SRB_Status != SS_COMP)
  210952. return false;
  210953. rb.dataLength = rb.numFrames * 2352;
  210954. rb.dataStartOffset = 0;
  210955. return true;
  210956. }
  210957. };
  210958. void CDController::prepare (SRB_ExecSCSICmd& s)
  210959. {
  210960. zerostruct (s);
  210961. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210962. s.SRB_HaID = deviceInfo->info.ha;
  210963. s.SRB_Target = deviceInfo->info.tgt;
  210964. s.SRB_Lun = deviceInfo->info.lun;
  210965. s.SRB_SenseLen = SENSE_LEN;
  210966. }
  210967. void CDController::perform (SRB_ExecSCSICmd& s)
  210968. {
  210969. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210970. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210971. }
  210972. void CDController::setPaused (bool paused)
  210973. {
  210974. SRB_ExecSCSICmd s;
  210975. prepare (s);
  210976. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210977. s.SRB_CDBLen = 10;
  210978. s.CDBByte[0] = 0x4B;
  210979. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210980. perform (s);
  210981. }
  210982. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210983. {
  210984. if (overlapBuffer != 0)
  210985. {
  210986. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210987. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210988. if (doJitter
  210989. && overlapBuffer->startFrame > 0
  210990. && overlapBuffer->numFrames > 0
  210991. && overlapBuffer->dataLength > 0)
  210992. {
  210993. const int numFrames = rb.numFrames;
  210994. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210995. {
  210996. rb.startFrame -= framesOverlap;
  210997. if (framesToCheck < framesOverlap
  210998. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210999. rb.numFrames += framesOverlap;
  211000. }
  211001. else
  211002. {
  211003. overlapBuffer->dataLength = 0;
  211004. overlapBuffer->startFrame = 0;
  211005. overlapBuffer->numFrames = 0;
  211006. }
  211007. }
  211008. if (! read (rb))
  211009. return false;
  211010. if (doJitter)
  211011. {
  211012. const int checkLen = framesToCheck * 2352;
  211013. const int maxToCheck = rb.dataLength - checkLen;
  211014. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211015. return true;
  211016. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211017. bool found = false;
  211018. for (int i = 0; i < maxToCheck; ++i)
  211019. {
  211020. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  211021. {
  211022. i += checkLen;
  211023. rb.dataStartOffset = i;
  211024. rb.dataLength -= i;
  211025. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  211026. found = true;
  211027. break;
  211028. }
  211029. }
  211030. rb.numFrames = rb.dataLength / 2352;
  211031. rb.dataLength = 2352 * rb.numFrames;
  211032. if (! found)
  211033. return false;
  211034. }
  211035. if (canDoJitter)
  211036. {
  211037. memcpy (overlapBuffer->buffer,
  211038. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  211039. 2352 * framesToCheck);
  211040. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  211041. overlapBuffer->numFrames = framesToCheck;
  211042. overlapBuffer->dataLength = 2352 * framesToCheck;
  211043. overlapBuffer->dataStartOffset = 0;
  211044. }
  211045. else
  211046. {
  211047. overlapBuffer->startFrame = 0;
  211048. overlapBuffer->numFrames = 0;
  211049. overlapBuffer->dataLength = 0;
  211050. }
  211051. return true;
  211052. }
  211053. return read (rb);
  211054. }
  211055. int CDController::getLastIndex()
  211056. {
  211057. char qdata[100];
  211058. SRB_ExecSCSICmd s;
  211059. prepare (s);
  211060. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211061. s.SRB_BufLen = sizeof (qdata);
  211062. s.SRB_BufPointer = (BYTE*) qdata;
  211063. s.SRB_CDBLen = 12;
  211064. s.CDBByte[0] = 0x42;
  211065. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211066. s.CDBByte[2] = 64;
  211067. s.CDBByte[3] = 1; // get current position
  211068. s.CDBByte[7] = 0;
  211069. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211070. perform (s);
  211071. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211072. }
  211073. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211074. {
  211075. SRB_ExecSCSICmd s;
  211076. zerostruct (s);
  211077. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211078. s.SRB_HaID = info.ha;
  211079. s.SRB_Target = info.tgt;
  211080. s.SRB_Lun = info.lun;
  211081. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211082. s.SRB_BufLen = 0x324;
  211083. s.SRB_BufPointer = (BYTE*) lpToc;
  211084. s.SRB_SenseLen = 0x0E;
  211085. s.SRB_CDBLen = 0x0A;
  211086. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211087. s.CDBByte[0] = 0x43;
  211088. s.CDBByte[1] = 0x00;
  211089. s.CDBByte[7] = 0x03;
  211090. s.CDBByte[8] = 0x24;
  211091. performScsiCommand (s.SRB_PostProc, s);
  211092. return (s.SRB_Status == SS_COMP);
  211093. }
  211094. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211095. {
  211096. ResetEvent (event);
  211097. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211098. if (status == SS_PENDING)
  211099. WaitForSingleObject (event, 4000);
  211100. CloseHandle (event);
  211101. }
  211102. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211103. {
  211104. if (controller == 0)
  211105. {
  211106. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211107. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211108. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211109. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211110. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211111. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211112. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211113. }
  211114. buffer.index = 0;
  211115. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211116. {
  211117. if (buffer.wantsIndex)
  211118. buffer.index = controller->getLastIndex();
  211119. return true;
  211120. }
  211121. return false;
  211122. }
  211123. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211124. {
  211125. if (shouldBeOpen)
  211126. {
  211127. if (controller != 0)
  211128. {
  211129. controller->shutDown();
  211130. controller = 0;
  211131. }
  211132. if (scsiHandle != 0)
  211133. {
  211134. CloseHandle (scsiHandle);
  211135. scsiHandle = 0;
  211136. }
  211137. }
  211138. SRB_ExecSCSICmd s;
  211139. zerostruct (s);
  211140. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211141. s.SRB_HaID = info.ha;
  211142. s.SRB_Target = info.tgt;
  211143. s.SRB_Lun = info.lun;
  211144. s.SRB_SenseLen = SENSE_LEN;
  211145. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211146. s.SRB_BufLen = 0;
  211147. s.SRB_BufPointer = 0;
  211148. s.SRB_CDBLen = 12;
  211149. s.CDBByte[0] = 0x1b;
  211150. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211151. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211152. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211153. performScsiCommand (s.SRB_PostProc, s);
  211154. }
  211155. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211156. {
  211157. controller = newController;
  211158. readType = (BYTE) type;
  211159. controller->deviceInfo = this;
  211160. controller->framesToCheck = 1;
  211161. controller->framesOverlap = 3;
  211162. bool passed = false;
  211163. memset (rb.buffer, 0xcd, rb.bufferSize);
  211164. if (controller->read (rb))
  211165. {
  211166. passed = true;
  211167. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211168. int wrong = 0;
  211169. for (int i = rb.dataLength / 4; --i >= 0;)
  211170. {
  211171. if (*p++ == (int) 0xcdcdcdcd)
  211172. {
  211173. if (++wrong == 4)
  211174. {
  211175. passed = false;
  211176. break;
  211177. }
  211178. }
  211179. else
  211180. {
  211181. wrong = 0;
  211182. }
  211183. }
  211184. }
  211185. if (! passed)
  211186. {
  211187. controller->shutDown();
  211188. controller = 0;
  211189. }
  211190. return passed;
  211191. }
  211192. struct CDDeviceWrapper
  211193. {
  211194. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211195. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211196. {
  211197. // xxx jitter never seemed to actually be enabled (??)
  211198. }
  211199. CDDeviceHandle deviceHandle;
  211200. CDReadBuffer overlapBuffer;
  211201. bool jitter;
  211202. };
  211203. int getAddressOfTrack (const TOCTRACK& t) throw()
  211204. {
  211205. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211206. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211207. }
  211208. const int samplesPerFrame = 44100 / 75;
  211209. const int bytesPerFrame = samplesPerFrame * 4;
  211210. const int framesPerIndexRead = 4;
  211211. }
  211212. const StringArray AudioCDReader::getAvailableCDNames()
  211213. {
  211214. using namespace CDReaderHelpers;
  211215. StringArray results;
  211216. Array<CDDeviceDescription> list;
  211217. findCDDevices (list);
  211218. for (int i = 0; i < list.size(); ++i)
  211219. {
  211220. String s;
  211221. if (list[i].scsiDriveLetter > 0)
  211222. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211223. s << list[i].description;
  211224. results.add (s);
  211225. }
  211226. return results;
  211227. }
  211228. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211229. {
  211230. using namespace CDReaderHelpers;
  211231. Array<CDDeviceDescription> list;
  211232. findCDDevices (list);
  211233. if (isPositiveAndBelow (deviceIndex, list.size()))
  211234. {
  211235. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211236. if (h != INVALID_HANDLE_VALUE)
  211237. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211238. }
  211239. return 0;
  211240. }
  211241. AudioCDReader::AudioCDReader (void* handle_)
  211242. : AudioFormatReader (0, "CD Audio"),
  211243. handle (handle_),
  211244. indexingEnabled (false),
  211245. lastIndex (0),
  211246. firstFrameInBuffer (0),
  211247. samplesInBuffer (0)
  211248. {
  211249. using namespace CDReaderHelpers;
  211250. jassert (handle_ != 0);
  211251. refreshTrackLengths();
  211252. sampleRate = 44100.0;
  211253. bitsPerSample = 16;
  211254. numChannels = 2;
  211255. usesFloatingPointData = false;
  211256. buffer.setSize (4 * bytesPerFrame, true);
  211257. }
  211258. AudioCDReader::~AudioCDReader()
  211259. {
  211260. using namespace CDReaderHelpers;
  211261. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211262. delete device;
  211263. }
  211264. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211265. int64 startSampleInFile, int numSamples)
  211266. {
  211267. using namespace CDReaderHelpers;
  211268. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211269. bool ok = true;
  211270. while (numSamples > 0)
  211271. {
  211272. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211273. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211274. if (startSampleInFile >= bufferStartSample
  211275. && startSampleInFile < bufferEndSample)
  211276. {
  211277. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211278. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211279. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211280. const short* src = (const short*) buffer.getData();
  211281. src += 2 * (startSampleInFile - bufferStartSample);
  211282. for (int i = 0; i < toDo; ++i)
  211283. {
  211284. l[i] = src [i << 1] << 16;
  211285. if (r != 0)
  211286. r[i] = src [(i << 1) + 1] << 16;
  211287. }
  211288. startOffsetInDestBuffer += toDo;
  211289. startSampleInFile += toDo;
  211290. numSamples -= toDo;
  211291. }
  211292. else
  211293. {
  211294. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211295. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211296. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211297. {
  211298. device->overlapBuffer.dataLength = 0;
  211299. device->overlapBuffer.startFrame = 0;
  211300. device->overlapBuffer.numFrames = 0;
  211301. device->jitter = false;
  211302. }
  211303. firstFrameInBuffer = frameNeeded;
  211304. lastIndex = 0;
  211305. CDReadBuffer readBuffer (framesInBuffer + 4);
  211306. readBuffer.wantsIndex = indexingEnabled;
  211307. int i;
  211308. for (i = 5; --i >= 0;)
  211309. {
  211310. readBuffer.startFrame = frameNeeded;
  211311. readBuffer.numFrames = framesInBuffer;
  211312. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211313. break;
  211314. else
  211315. device->overlapBuffer.dataLength = 0;
  211316. }
  211317. if (i >= 0)
  211318. {
  211319. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211320. samplesInBuffer = readBuffer.dataLength >> 2;
  211321. lastIndex = readBuffer.index;
  211322. }
  211323. else
  211324. {
  211325. int* l = destSamples[0] + startOffsetInDestBuffer;
  211326. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211327. while (--numSamples >= 0)
  211328. {
  211329. *l++ = 0;
  211330. if (r != 0)
  211331. *r++ = 0;
  211332. }
  211333. // sometimes the read fails for just the very last couple of blocks, so
  211334. // we'll ignore and errors in the last half-second of the disk..
  211335. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211336. break;
  211337. }
  211338. }
  211339. }
  211340. return ok;
  211341. }
  211342. bool AudioCDReader::isCDStillPresent() const
  211343. {
  211344. using namespace CDReaderHelpers;
  211345. TOC toc;
  211346. zerostruct (toc);
  211347. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211348. }
  211349. void AudioCDReader::refreshTrackLengths()
  211350. {
  211351. using namespace CDReaderHelpers;
  211352. trackStartSamples.clear();
  211353. zeromem (audioTracks, sizeof (audioTracks));
  211354. TOC toc;
  211355. zerostruct (toc);
  211356. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211357. {
  211358. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211359. for (int i = 0; i <= numTracks; ++i)
  211360. {
  211361. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211362. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211363. }
  211364. }
  211365. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211366. }
  211367. bool AudioCDReader::isTrackAudio (int trackNum) const
  211368. {
  211369. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211370. }
  211371. void AudioCDReader::enableIndexScanning (bool b)
  211372. {
  211373. indexingEnabled = b;
  211374. }
  211375. int AudioCDReader::getLastIndex() const
  211376. {
  211377. return lastIndex;
  211378. }
  211379. int AudioCDReader::getIndexAt (int samplePos)
  211380. {
  211381. using namespace CDReaderHelpers;
  211382. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211383. const int frameNeeded = samplePos / samplesPerFrame;
  211384. device->overlapBuffer.dataLength = 0;
  211385. device->overlapBuffer.startFrame = 0;
  211386. device->overlapBuffer.numFrames = 0;
  211387. device->jitter = false;
  211388. firstFrameInBuffer = 0;
  211389. lastIndex = 0;
  211390. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211391. readBuffer.wantsIndex = true;
  211392. int i;
  211393. for (i = 5; --i >= 0;)
  211394. {
  211395. readBuffer.startFrame = frameNeeded;
  211396. readBuffer.numFrames = framesPerIndexRead;
  211397. if (device->deviceHandle.readAudio (readBuffer))
  211398. break;
  211399. }
  211400. if (i >= 0)
  211401. return readBuffer.index;
  211402. return -1;
  211403. }
  211404. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211405. {
  211406. using namespace CDReaderHelpers;
  211407. Array <int> indexes;
  211408. const int trackStart = getPositionOfTrackStart (trackNumber);
  211409. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211410. bool needToScan = true;
  211411. if (trackEnd - trackStart > 20 * 44100)
  211412. {
  211413. // check the end of the track for indexes before scanning the whole thing
  211414. needToScan = false;
  211415. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211416. bool seenAnIndex = false;
  211417. while (pos <= trackEnd - samplesPerFrame)
  211418. {
  211419. const int index = getIndexAt (pos);
  211420. if (index == 0)
  211421. {
  211422. // lead-out, so skip back a bit if we've not found any indexes yet..
  211423. if (seenAnIndex)
  211424. break;
  211425. pos -= 44100 * 5;
  211426. if (pos < trackStart)
  211427. break;
  211428. }
  211429. else
  211430. {
  211431. if (index > 0)
  211432. seenAnIndex = true;
  211433. if (index > 1)
  211434. {
  211435. needToScan = true;
  211436. break;
  211437. }
  211438. pos += samplesPerFrame * framesPerIndexRead;
  211439. }
  211440. }
  211441. }
  211442. if (needToScan)
  211443. {
  211444. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211445. int pos = trackStart;
  211446. int last = -1;
  211447. while (pos < trackEnd - samplesPerFrame * 10)
  211448. {
  211449. const int frameNeeded = pos / samplesPerFrame;
  211450. device->overlapBuffer.dataLength = 0;
  211451. device->overlapBuffer.startFrame = 0;
  211452. device->overlapBuffer.numFrames = 0;
  211453. device->jitter = false;
  211454. firstFrameInBuffer = 0;
  211455. CDReadBuffer readBuffer (4);
  211456. readBuffer.wantsIndex = true;
  211457. int i;
  211458. for (i = 5; --i >= 0;)
  211459. {
  211460. readBuffer.startFrame = frameNeeded;
  211461. readBuffer.numFrames = framesPerIndexRead;
  211462. if (device->deviceHandle.readAudio (readBuffer))
  211463. break;
  211464. }
  211465. if (i < 0)
  211466. break;
  211467. if (readBuffer.index > last && readBuffer.index > 1)
  211468. {
  211469. last = readBuffer.index;
  211470. indexes.add (pos);
  211471. }
  211472. pos += samplesPerFrame * framesPerIndexRead;
  211473. }
  211474. indexes.removeValue (trackStart);
  211475. }
  211476. return indexes;
  211477. }
  211478. void AudioCDReader::ejectDisk()
  211479. {
  211480. using namespace CDReaderHelpers;
  211481. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211482. }
  211483. #endif
  211484. #if JUCE_USE_CDBURNER
  211485. namespace CDBurnerHelpers
  211486. {
  211487. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211488. {
  211489. CoInitialize (0);
  211490. IDiscMaster* dm;
  211491. IDiscRecorder* result = 0;
  211492. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211493. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211494. IID_IDiscMaster,
  211495. (void**) &dm)))
  211496. {
  211497. if (SUCCEEDED (dm->Open()))
  211498. {
  211499. IEnumDiscRecorders* drEnum = 0;
  211500. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211501. {
  211502. IDiscRecorder* dr = 0;
  211503. DWORD dummy;
  211504. int index = 0;
  211505. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211506. {
  211507. if (indexToOpen == index)
  211508. {
  211509. result = dr;
  211510. break;
  211511. }
  211512. else if (list != 0)
  211513. {
  211514. BSTR path;
  211515. if (SUCCEEDED (dr->GetPath (&path)))
  211516. list->add ((const WCHAR*) path);
  211517. }
  211518. ++index;
  211519. dr->Release();
  211520. }
  211521. drEnum->Release();
  211522. }
  211523. if (master == 0)
  211524. dm->Close();
  211525. }
  211526. if (master != 0)
  211527. *master = dm;
  211528. else
  211529. dm->Release();
  211530. }
  211531. return result;
  211532. }
  211533. }
  211534. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211535. public Timer
  211536. {
  211537. public:
  211538. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211539. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211540. listener (0), progress (0), shouldCancel (false)
  211541. {
  211542. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211543. jassert (SUCCEEDED (hr));
  211544. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211545. //jassert (SUCCEEDED (hr));
  211546. lastState = getDiskState();
  211547. startTimer (2000);
  211548. }
  211549. ~Pimpl() {}
  211550. void releaseObjects()
  211551. {
  211552. discRecorder->Close();
  211553. if (redbook != 0)
  211554. redbook->Release();
  211555. discRecorder->Release();
  211556. discMaster->Release();
  211557. Release();
  211558. }
  211559. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211560. {
  211561. if (listener != 0 && ! shouldCancel)
  211562. shouldCancel = listener->audioCDBurnProgress (progress);
  211563. *pbCancel = shouldCancel;
  211564. return S_OK;
  211565. }
  211566. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211567. {
  211568. progress = nCompleted / (float) nTotal;
  211569. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211570. return E_NOTIMPL;
  211571. }
  211572. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211573. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211574. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211575. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211576. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211577. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211578. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211579. class ScopedDiscOpener
  211580. {
  211581. public:
  211582. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211583. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211584. private:
  211585. Pimpl& pimpl;
  211586. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211587. };
  211588. DiskState getDiskState()
  211589. {
  211590. const ScopedDiscOpener opener (*this);
  211591. long type, flags;
  211592. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211593. if (FAILED (hr))
  211594. return unknown;
  211595. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211596. return writableDiskPresent;
  211597. if (type == 0)
  211598. return noDisc;
  211599. else
  211600. return readOnlyDiskPresent;
  211601. }
  211602. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211603. {
  211604. ComSmartPtr<IPropertyStorage> prop;
  211605. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211606. return defaultReturn;
  211607. PROPSPEC iPropSpec;
  211608. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211609. iPropSpec.lpwstr = name;
  211610. PROPVARIANT iPropVariant;
  211611. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211612. ? defaultReturn : (int) iPropVariant.lVal;
  211613. }
  211614. bool setIntProperty (const LPOLESTR name, const int value) const
  211615. {
  211616. ComSmartPtr<IPropertyStorage> prop;
  211617. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211618. return false;
  211619. PROPSPEC iPropSpec;
  211620. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211621. iPropSpec.lpwstr = name;
  211622. PROPVARIANT iPropVariant;
  211623. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211624. return false;
  211625. iPropVariant.lVal = (long) value;
  211626. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211627. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211628. }
  211629. void timerCallback()
  211630. {
  211631. const DiskState state = getDiskState();
  211632. if (state != lastState)
  211633. {
  211634. lastState = state;
  211635. owner.sendChangeMessage();
  211636. }
  211637. }
  211638. AudioCDBurner& owner;
  211639. DiskState lastState;
  211640. IDiscMaster* discMaster;
  211641. IDiscRecorder* discRecorder;
  211642. IRedbookDiscMaster* redbook;
  211643. AudioCDBurner::BurnProgressListener* listener;
  211644. float progress;
  211645. bool shouldCancel;
  211646. };
  211647. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211648. {
  211649. IDiscMaster* discMaster = 0;
  211650. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211651. if (discRecorder != 0)
  211652. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211653. }
  211654. AudioCDBurner::~AudioCDBurner()
  211655. {
  211656. if (pimpl != 0)
  211657. pimpl.release()->releaseObjects();
  211658. }
  211659. const StringArray AudioCDBurner::findAvailableDevices()
  211660. {
  211661. StringArray devs;
  211662. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211663. return devs;
  211664. }
  211665. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211666. {
  211667. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211668. if (b->pimpl == 0)
  211669. b = 0;
  211670. return b.release();
  211671. }
  211672. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211673. {
  211674. return pimpl->getDiskState();
  211675. }
  211676. bool AudioCDBurner::isDiskPresent() const
  211677. {
  211678. return getDiskState() == writableDiskPresent;
  211679. }
  211680. bool AudioCDBurner::openTray()
  211681. {
  211682. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211683. return SUCCEEDED (pimpl->discRecorder->Eject());
  211684. }
  211685. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211686. {
  211687. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211688. DiskState oldState = getDiskState();
  211689. DiskState newState = oldState;
  211690. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211691. {
  211692. newState = getDiskState();
  211693. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211694. }
  211695. return newState;
  211696. }
  211697. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211698. {
  211699. Array<int> results;
  211700. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211701. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211702. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211703. if (speeds[i] <= maxSpeed)
  211704. results.add (speeds[i]);
  211705. results.addIfNotAlreadyThere (maxSpeed);
  211706. return results;
  211707. }
  211708. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211709. {
  211710. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211711. return false;
  211712. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211713. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211714. }
  211715. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211716. {
  211717. long blocksFree = 0;
  211718. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211719. return blocksFree;
  211720. }
  211721. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211722. bool performFakeBurnForTesting, int writeSpeed)
  211723. {
  211724. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211725. pimpl->listener = listener;
  211726. pimpl->progress = 0;
  211727. pimpl->shouldCancel = false;
  211728. UINT_PTR cookie;
  211729. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211730. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211731. ejectDiscAfterwards);
  211732. String error;
  211733. if (hr != S_OK)
  211734. {
  211735. const char* e = "Couldn't open or write to the CD device";
  211736. if (hr == IMAPI_E_USERABORT)
  211737. e = "User cancelled the write operation";
  211738. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211739. e = "No Disk present";
  211740. error = e;
  211741. }
  211742. pimpl->discMaster->ProgressUnadvise (cookie);
  211743. pimpl->listener = 0;
  211744. return error;
  211745. }
  211746. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211747. {
  211748. if (audioSource == 0)
  211749. return false;
  211750. ScopedPointer<AudioSource> source (audioSource);
  211751. long bytesPerBlock;
  211752. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211753. const int samplesPerBlock = bytesPerBlock / 4;
  211754. bool ok = true;
  211755. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211756. HeapBlock <byte> buffer (bytesPerBlock);
  211757. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211758. int samplesDone = 0;
  211759. source->prepareToPlay (samplesPerBlock, 44100.0);
  211760. while (ok)
  211761. {
  211762. {
  211763. AudioSourceChannelInfo info;
  211764. info.buffer = &sourceBuffer;
  211765. info.numSamples = samplesPerBlock;
  211766. info.startSample = 0;
  211767. sourceBuffer.clear();
  211768. source->getNextAudioBlock (info);
  211769. }
  211770. zeromem (buffer, bytesPerBlock);
  211771. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211772. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211773. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211774. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211775. CDSampleFormat left (buffer, 2);
  211776. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211777. CDSampleFormat right (buffer + 2, 2);
  211778. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211779. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211780. if (FAILED (hr))
  211781. ok = false;
  211782. samplesDone += samplesPerBlock;
  211783. if (samplesDone >= numSamples)
  211784. break;
  211785. }
  211786. hr = pimpl->redbook->CloseAudioTrack();
  211787. return ok && hr == S_OK;
  211788. }
  211789. #endif
  211790. #endif
  211791. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211792. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211793. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211794. // compiled on its own).
  211795. #if JUCE_INCLUDED_FILE
  211796. class MidiInCollector
  211797. {
  211798. public:
  211799. MidiInCollector (MidiInput* const input_,
  211800. MidiInputCallback& callback_)
  211801. : deviceHandle (0),
  211802. input (input_),
  211803. callback (callback_),
  211804. concatenator (4096),
  211805. isStarted (false),
  211806. startTime (0)
  211807. {
  211808. }
  211809. ~MidiInCollector()
  211810. {
  211811. stop();
  211812. if (deviceHandle != 0)
  211813. {
  211814. int count = 5;
  211815. while (--count >= 0)
  211816. {
  211817. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211818. break;
  211819. Sleep (20);
  211820. }
  211821. }
  211822. }
  211823. void handleMessage (const uint32 message, const uint32 timeStamp)
  211824. {
  211825. if ((message & 0xff) >= 0x80 && isStarted)
  211826. {
  211827. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211828. writeFinishedBlocks();
  211829. }
  211830. }
  211831. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211832. {
  211833. if (isStarted)
  211834. {
  211835. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211836. writeFinishedBlocks();
  211837. }
  211838. }
  211839. void start()
  211840. {
  211841. jassert (deviceHandle != 0);
  211842. if (deviceHandle != 0 && ! isStarted)
  211843. {
  211844. activeMidiCollectors.addIfNotAlreadyThere (this);
  211845. for (int i = 0; i < (int) numHeaders; ++i)
  211846. headers[i].write (deviceHandle);
  211847. startTime = Time::getMillisecondCounter();
  211848. MMRESULT res = midiInStart (deviceHandle);
  211849. if (res == MMSYSERR_NOERROR)
  211850. {
  211851. concatenator.reset();
  211852. isStarted = true;
  211853. }
  211854. else
  211855. {
  211856. unprepareAllHeaders();
  211857. }
  211858. }
  211859. }
  211860. void stop()
  211861. {
  211862. if (isStarted)
  211863. {
  211864. isStarted = false;
  211865. midiInReset (deviceHandle);
  211866. midiInStop (deviceHandle);
  211867. activeMidiCollectors.removeValue (this);
  211868. unprepareAllHeaders();
  211869. concatenator.reset();
  211870. }
  211871. }
  211872. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211873. {
  211874. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211875. if (activeMidiCollectors.contains (collector))
  211876. {
  211877. if (uMsg == MIM_DATA)
  211878. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211879. else if (uMsg == MIM_LONGDATA)
  211880. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211881. }
  211882. }
  211883. HMIDIIN deviceHandle;
  211884. private:
  211885. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211886. MidiInput* input;
  211887. MidiInputCallback& callback;
  211888. MidiDataConcatenator concatenator;
  211889. bool volatile isStarted;
  211890. uint32 startTime;
  211891. class MidiHeader
  211892. {
  211893. public:
  211894. MidiHeader()
  211895. {
  211896. zerostruct (hdr);
  211897. hdr.lpData = data;
  211898. hdr.dwBufferLength = numElementsInArray (data);
  211899. }
  211900. void write (HMIDIIN deviceHandle)
  211901. {
  211902. hdr.dwBytesRecorded = 0;
  211903. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211904. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211905. }
  211906. void writeIfFinished (HMIDIIN deviceHandle)
  211907. {
  211908. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211909. {
  211910. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211911. (void) res;
  211912. write (deviceHandle);
  211913. }
  211914. }
  211915. void unprepare (HMIDIIN deviceHandle)
  211916. {
  211917. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211918. {
  211919. int c = 10;
  211920. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211921. Thread::sleep (20);
  211922. jassert (c >= 0);
  211923. }
  211924. }
  211925. private:
  211926. MIDIHDR hdr;
  211927. char data [256];
  211928. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211929. };
  211930. enum { numHeaders = 32 };
  211931. MidiHeader headers [numHeaders];
  211932. void writeFinishedBlocks()
  211933. {
  211934. for (int i = 0; i < (int) numHeaders; ++i)
  211935. headers[i].writeIfFinished (deviceHandle);
  211936. }
  211937. void unprepareAllHeaders()
  211938. {
  211939. for (int i = 0; i < (int) numHeaders; ++i)
  211940. headers[i].unprepare (deviceHandle);
  211941. }
  211942. double convertTimeStamp (uint32 timeStamp)
  211943. {
  211944. timeStamp += startTime;
  211945. const uint32 now = Time::getMillisecondCounter();
  211946. if (timeStamp > now)
  211947. {
  211948. if (timeStamp > now + 2)
  211949. --startTime;
  211950. timeStamp = now;
  211951. }
  211952. return timeStamp * 0.001;
  211953. }
  211954. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211955. };
  211956. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211957. const StringArray MidiInput::getDevices()
  211958. {
  211959. StringArray s;
  211960. const int num = midiInGetNumDevs();
  211961. for (int i = 0; i < num; ++i)
  211962. {
  211963. MIDIINCAPS mc;
  211964. zerostruct (mc);
  211965. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211966. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211967. }
  211968. return s;
  211969. }
  211970. int MidiInput::getDefaultDeviceIndex()
  211971. {
  211972. return 0;
  211973. }
  211974. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211975. {
  211976. if (callback == 0)
  211977. return 0;
  211978. UINT deviceId = MIDI_MAPPER;
  211979. int n = 0;
  211980. String name;
  211981. const int num = midiInGetNumDevs();
  211982. for (int i = 0; i < num; ++i)
  211983. {
  211984. MIDIINCAPS mc;
  211985. zerostruct (mc);
  211986. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211987. {
  211988. if (index == n)
  211989. {
  211990. deviceId = i;
  211991. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211992. break;
  211993. }
  211994. ++n;
  211995. }
  211996. }
  211997. ScopedPointer <MidiInput> in (new MidiInput (name));
  211998. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211999. HMIDIIN h;
  212000. HRESULT err = midiInOpen (&h, deviceId,
  212001. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212002. (DWORD_PTR) (MidiInCollector*) collector,
  212003. CALLBACK_FUNCTION);
  212004. if (err == MMSYSERR_NOERROR)
  212005. {
  212006. collector->deviceHandle = h;
  212007. in->internal = collector.release();
  212008. return in.release();
  212009. }
  212010. return 0;
  212011. }
  212012. MidiInput::MidiInput (const String& name_)
  212013. : name (name_),
  212014. internal (0)
  212015. {
  212016. }
  212017. MidiInput::~MidiInput()
  212018. {
  212019. delete static_cast <MidiInCollector*> (internal);
  212020. }
  212021. void MidiInput::start()
  212022. {
  212023. static_cast <MidiInCollector*> (internal)->start();
  212024. }
  212025. void MidiInput::stop()
  212026. {
  212027. static_cast <MidiInCollector*> (internal)->stop();
  212028. }
  212029. struct MidiOutHandle
  212030. {
  212031. int refCount;
  212032. UINT deviceId;
  212033. HMIDIOUT handle;
  212034. static Array<MidiOutHandle*> activeHandles;
  212035. private:
  212036. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212037. };
  212038. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212039. const StringArray MidiOutput::getDevices()
  212040. {
  212041. StringArray s;
  212042. const int num = midiOutGetNumDevs();
  212043. for (int i = 0; i < num; ++i)
  212044. {
  212045. MIDIOUTCAPS mc;
  212046. zerostruct (mc);
  212047. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212048. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212049. }
  212050. return s;
  212051. }
  212052. int MidiOutput::getDefaultDeviceIndex()
  212053. {
  212054. const int num = midiOutGetNumDevs();
  212055. int n = 0;
  212056. for (int i = 0; i < num; ++i)
  212057. {
  212058. MIDIOUTCAPS mc;
  212059. zerostruct (mc);
  212060. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212061. {
  212062. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212063. return n;
  212064. ++n;
  212065. }
  212066. }
  212067. return 0;
  212068. }
  212069. MidiOutput* MidiOutput::openDevice (int index)
  212070. {
  212071. UINT deviceId = MIDI_MAPPER;
  212072. const int num = midiOutGetNumDevs();
  212073. int i, n = 0;
  212074. for (i = 0; i < num; ++i)
  212075. {
  212076. MIDIOUTCAPS mc;
  212077. zerostruct (mc);
  212078. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212079. {
  212080. // use the microsoft sw synth as a default - best not to allow deviceId
  212081. // to be MIDI_MAPPER, or else device sharing breaks
  212082. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212083. deviceId = i;
  212084. if (index == n)
  212085. {
  212086. deviceId = i;
  212087. break;
  212088. }
  212089. ++n;
  212090. }
  212091. }
  212092. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212093. {
  212094. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212095. if (han != 0 && han->deviceId == deviceId)
  212096. {
  212097. han->refCount++;
  212098. MidiOutput* const out = new MidiOutput();
  212099. out->internal = han;
  212100. return out;
  212101. }
  212102. }
  212103. for (i = 4; --i >= 0;)
  212104. {
  212105. HMIDIOUT h = 0;
  212106. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212107. if (res == MMSYSERR_NOERROR)
  212108. {
  212109. MidiOutHandle* const han = new MidiOutHandle();
  212110. han->deviceId = deviceId;
  212111. han->refCount = 1;
  212112. han->handle = h;
  212113. MidiOutHandle::activeHandles.add (han);
  212114. MidiOutput* const out = new MidiOutput();
  212115. out->internal = han;
  212116. return out;
  212117. }
  212118. else if (res == MMSYSERR_ALLOCATED)
  212119. {
  212120. Sleep (100);
  212121. }
  212122. else
  212123. {
  212124. break;
  212125. }
  212126. }
  212127. return 0;
  212128. }
  212129. MidiOutput::~MidiOutput()
  212130. {
  212131. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212132. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212133. {
  212134. midiOutClose (h->handle);
  212135. MidiOutHandle::activeHandles.removeValue (h);
  212136. delete h;
  212137. }
  212138. }
  212139. void MidiOutput::reset()
  212140. {
  212141. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212142. midiOutReset (h->handle);
  212143. }
  212144. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212145. {
  212146. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212147. DWORD n;
  212148. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212149. {
  212150. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212151. rightVol = nn[0] / (float) 0xffff;
  212152. leftVol = nn[1] / (float) 0xffff;
  212153. return true;
  212154. }
  212155. else
  212156. {
  212157. rightVol = leftVol = 1.0f;
  212158. return false;
  212159. }
  212160. }
  212161. void MidiOutput::setVolume (float leftVol, float rightVol)
  212162. {
  212163. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212164. DWORD n;
  212165. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212166. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212167. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212168. midiOutSetVolume (handle->handle, n);
  212169. }
  212170. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212171. {
  212172. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212173. if (message.getRawDataSize() > 3
  212174. || message.isSysEx())
  212175. {
  212176. MIDIHDR h;
  212177. zerostruct (h);
  212178. h.lpData = (char*) message.getRawData();
  212179. h.dwBufferLength = message.getRawDataSize();
  212180. h.dwBytesRecorded = message.getRawDataSize();
  212181. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212182. {
  212183. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212184. if (res == MMSYSERR_NOERROR)
  212185. {
  212186. while ((h.dwFlags & MHDR_DONE) == 0)
  212187. Sleep (1);
  212188. int count = 500; // 1 sec timeout
  212189. while (--count >= 0)
  212190. {
  212191. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212192. if (res == MIDIERR_STILLPLAYING)
  212193. Sleep (2);
  212194. else
  212195. break;
  212196. }
  212197. }
  212198. }
  212199. }
  212200. else
  212201. {
  212202. midiOutShortMsg (handle->handle,
  212203. *(unsigned int*) message.getRawData());
  212204. }
  212205. }
  212206. #endif
  212207. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212208. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212209. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212210. // compiled on its own).
  212211. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212212. #undef WINDOWS
  212213. // #define ASIO_DEBUGGING 1
  212214. #undef log
  212215. #if ASIO_DEBUGGING
  212216. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212217. #else
  212218. #define log(a) {}
  212219. #endif
  212220. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212221. to be pretty random about whether or not they do this. If you hit an error using these functions
  212222. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212223. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212224. */
  212225. #define JUCE_ASIOCALLBACK __cdecl
  212226. namespace ASIODebugging
  212227. {
  212228. #if ASIO_DEBUGGING
  212229. static void log (const String& context, long error)
  212230. {
  212231. String err ("unknown error");
  212232. if (error == ASE_NotPresent) err = "Not Present";
  212233. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212234. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212235. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212236. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212237. else if (error == ASE_NoClock) err = "No Clock";
  212238. else if (error == ASE_NoMemory) err = "Out of memory";
  212239. log ("!!error: " + context + " - " + err);
  212240. }
  212241. #define logError(a, b) ASIODebugging::log ((a), (b))
  212242. #else
  212243. #define logError(a, b) {}
  212244. #endif
  212245. }
  212246. class ASIOAudioIODevice;
  212247. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212248. static const int maxASIOChannels = 160;
  212249. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212250. private Timer
  212251. {
  212252. public:
  212253. Component ourWindow;
  212254. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212255. const String& optionalDllForDirectLoading_)
  212256. : AudioIODevice (name_, "ASIO"),
  212257. asioObject (0),
  212258. classId (classId_),
  212259. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212260. currentBitDepth (16),
  212261. currentSampleRate (0),
  212262. isOpen_ (false),
  212263. isStarted (false),
  212264. postOutput (true),
  212265. insideControlPanelModalLoop (false),
  212266. shouldUsePreferredSize (false)
  212267. {
  212268. name = name_;
  212269. ourWindow.addToDesktop (0);
  212270. windowHandle = ourWindow.getWindowHandle();
  212271. jassert (currentASIODev [slotNumber] == 0);
  212272. currentASIODev [slotNumber] = this;
  212273. openDevice();
  212274. }
  212275. ~ASIOAudioIODevice()
  212276. {
  212277. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212278. if (currentASIODev[i] == this)
  212279. currentASIODev[i] = 0;
  212280. close();
  212281. log ("ASIO - exiting");
  212282. removeCurrentDriver();
  212283. }
  212284. void updateSampleRates()
  212285. {
  212286. // find a list of sample rates..
  212287. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212288. sampleRates.clear();
  212289. if (asioObject != 0)
  212290. {
  212291. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212292. {
  212293. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212294. if (err == 0)
  212295. {
  212296. sampleRates.add ((int) possibleSampleRates[index]);
  212297. log ("rate: " + String ((int) possibleSampleRates[index]));
  212298. }
  212299. else if (err != ASE_NoClock)
  212300. {
  212301. logError ("CanSampleRate", err);
  212302. }
  212303. }
  212304. if (sampleRates.size() == 0)
  212305. {
  212306. double cr = 0;
  212307. const long err = asioObject->getSampleRate (&cr);
  212308. log ("No sample rates supported - current rate: " + String ((int) cr));
  212309. if (err == 0)
  212310. sampleRates.add ((int) cr);
  212311. }
  212312. }
  212313. }
  212314. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212315. const StringArray getInputChannelNames() { return inputChannelNames; }
  212316. int getNumSampleRates() { return sampleRates.size(); }
  212317. double getSampleRate (int index) { return sampleRates [index]; }
  212318. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212319. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212320. int getDefaultBufferSize() { return preferredSize; }
  212321. const String open (const BigInteger& inputChannels,
  212322. const BigInteger& outputChannels,
  212323. double sr,
  212324. int bufferSizeSamples)
  212325. {
  212326. close();
  212327. currentCallback = 0;
  212328. if (bufferSizeSamples <= 0)
  212329. shouldUsePreferredSize = true;
  212330. if (asioObject == 0 || ! isASIOOpen)
  212331. {
  212332. log ("Warning: device not open");
  212333. const String err (openDevice());
  212334. if (asioObject == 0 || ! isASIOOpen)
  212335. return err;
  212336. }
  212337. isStarted = false;
  212338. bufferIndex = -1;
  212339. long err = 0;
  212340. long newPreferredSize = 0;
  212341. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212342. minSize = 0;
  212343. maxSize = 0;
  212344. newPreferredSize = 0;
  212345. granularity = 0;
  212346. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212347. {
  212348. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212349. shouldUsePreferredSize = true;
  212350. preferredSize = newPreferredSize;
  212351. }
  212352. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212353. // dynamic changes to the buffer size...
  212354. shouldUsePreferredSize = shouldUsePreferredSize
  212355. || getName().containsIgnoreCase ("Digidesign");
  212356. if (shouldUsePreferredSize)
  212357. {
  212358. log ("Using preferred size for buffer..");
  212359. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212360. {
  212361. bufferSizeSamples = preferredSize;
  212362. }
  212363. else
  212364. {
  212365. bufferSizeSamples = 1024;
  212366. logError ("GetBufferSize1", err);
  212367. }
  212368. shouldUsePreferredSize = false;
  212369. }
  212370. int sampleRate = roundDoubleToInt (sr);
  212371. currentSampleRate = sampleRate;
  212372. currentBlockSizeSamples = bufferSizeSamples;
  212373. currentChansOut.clear();
  212374. currentChansIn.clear();
  212375. zeromem (inBuffers, sizeof (inBuffers));
  212376. zeromem (outBuffers, sizeof (outBuffers));
  212377. updateSampleRates();
  212378. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212379. sampleRate = sampleRates[0];
  212380. jassert (sampleRate != 0);
  212381. if (sampleRate == 0)
  212382. sampleRate = 44100;
  212383. long numSources = 32;
  212384. ASIOClockSource clocks[32];
  212385. zeromem (clocks, sizeof (clocks));
  212386. asioObject->getClockSources (clocks, &numSources);
  212387. bool isSourceSet = false;
  212388. // careful not to remove this loop because it does more than just logging!
  212389. int i;
  212390. for (i = 0; i < numSources; ++i)
  212391. {
  212392. String s ("clock: ");
  212393. s += clocks[i].name;
  212394. if (clocks[i].isCurrentSource)
  212395. {
  212396. isSourceSet = true;
  212397. s << " (cur)";
  212398. }
  212399. log (s);
  212400. }
  212401. if (numSources > 1 && ! isSourceSet)
  212402. {
  212403. log ("setting clock source");
  212404. asioObject->setClockSource (clocks[0].index);
  212405. Thread::sleep (20);
  212406. }
  212407. else
  212408. {
  212409. if (numSources == 0)
  212410. {
  212411. log ("ASIO - no clock sources!");
  212412. }
  212413. }
  212414. double cr = 0;
  212415. err = asioObject->getSampleRate (&cr);
  212416. if (err == 0)
  212417. {
  212418. currentSampleRate = cr;
  212419. }
  212420. else
  212421. {
  212422. logError ("GetSampleRate", err);
  212423. currentSampleRate = 0;
  212424. }
  212425. error = String::empty;
  212426. needToReset = false;
  212427. isReSync = false;
  212428. err = 0;
  212429. bool buffersCreated = false;
  212430. if (currentSampleRate != sampleRate)
  212431. {
  212432. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212433. err = asioObject->setSampleRate (sampleRate);
  212434. if (err == ASE_NoClock && numSources > 0)
  212435. {
  212436. log ("trying to set a clock source..");
  212437. Thread::sleep (10);
  212438. err = asioObject->setClockSource (clocks[0].index);
  212439. if (err != 0)
  212440. {
  212441. logError ("SetClock", err);
  212442. }
  212443. Thread::sleep (10);
  212444. err = asioObject->setSampleRate (sampleRate);
  212445. }
  212446. }
  212447. if (err == 0)
  212448. {
  212449. currentSampleRate = sampleRate;
  212450. if (needToReset)
  212451. {
  212452. if (isReSync)
  212453. {
  212454. log ("Resync request");
  212455. }
  212456. log ("! Resetting ASIO after sample rate change");
  212457. removeCurrentDriver();
  212458. loadDriver();
  212459. const String error (initDriver());
  212460. if (error.isNotEmpty())
  212461. {
  212462. log ("ASIOInit: " + error);
  212463. }
  212464. needToReset = false;
  212465. isReSync = false;
  212466. }
  212467. numActiveInputChans = 0;
  212468. numActiveOutputChans = 0;
  212469. ASIOBufferInfo* info = bufferInfos;
  212470. int i;
  212471. for (i = 0; i < totalNumInputChans; ++i)
  212472. {
  212473. if (inputChannels[i])
  212474. {
  212475. currentChansIn.setBit (i);
  212476. info->isInput = 1;
  212477. info->channelNum = i;
  212478. info->buffers[0] = info->buffers[1] = 0;
  212479. ++info;
  212480. ++numActiveInputChans;
  212481. }
  212482. }
  212483. for (i = 0; i < totalNumOutputChans; ++i)
  212484. {
  212485. if (outputChannels[i])
  212486. {
  212487. currentChansOut.setBit (i);
  212488. info->isInput = 0;
  212489. info->channelNum = i;
  212490. info->buffers[0] = info->buffers[1] = 0;
  212491. ++info;
  212492. ++numActiveOutputChans;
  212493. }
  212494. }
  212495. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212496. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212497. if (currentASIODev[0] == this)
  212498. {
  212499. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212500. callbacks.asioMessage = &asioMessagesCallback0;
  212501. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212502. }
  212503. else if (currentASIODev[1] == this)
  212504. {
  212505. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212506. callbacks.asioMessage = &asioMessagesCallback1;
  212507. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212508. }
  212509. else if (currentASIODev[2] == this)
  212510. {
  212511. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212512. callbacks.asioMessage = &asioMessagesCallback2;
  212513. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212514. }
  212515. else
  212516. {
  212517. jassertfalse;
  212518. }
  212519. log ("disposing buffers");
  212520. err = asioObject->disposeBuffers();
  212521. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212522. err = asioObject->createBuffers (bufferInfos,
  212523. totalBuffers,
  212524. currentBlockSizeSamples,
  212525. &callbacks);
  212526. if (err != 0)
  212527. {
  212528. currentBlockSizeSamples = preferredSize;
  212529. logError ("create buffers 2", err);
  212530. asioObject->disposeBuffers();
  212531. err = asioObject->createBuffers (bufferInfos,
  212532. totalBuffers,
  212533. currentBlockSizeSamples,
  212534. &callbacks);
  212535. }
  212536. if (err == 0)
  212537. {
  212538. buffersCreated = true;
  212539. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212540. int n = 0;
  212541. Array <int> types;
  212542. currentBitDepth = 16;
  212543. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212544. {
  212545. if (inputChannels[i])
  212546. {
  212547. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212548. ASIOChannelInfo channelInfo;
  212549. zerostruct (channelInfo);
  212550. channelInfo.channel = i;
  212551. channelInfo.isInput = 1;
  212552. asioObject->getChannelInfo (&channelInfo);
  212553. types.addIfNotAlreadyThere (channelInfo.type);
  212554. typeToFormatParameters (channelInfo.type,
  212555. inputChannelBitDepths[n],
  212556. inputChannelBytesPerSample[n],
  212557. inputChannelIsFloat[n],
  212558. inputChannelLittleEndian[n]);
  212559. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212560. ++n;
  212561. }
  212562. }
  212563. jassert (numActiveInputChans == n);
  212564. n = 0;
  212565. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212566. {
  212567. if (outputChannels[i])
  212568. {
  212569. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212570. ASIOChannelInfo channelInfo;
  212571. zerostruct (channelInfo);
  212572. channelInfo.channel = i;
  212573. channelInfo.isInput = 0;
  212574. asioObject->getChannelInfo (&channelInfo);
  212575. types.addIfNotAlreadyThere (channelInfo.type);
  212576. typeToFormatParameters (channelInfo.type,
  212577. outputChannelBitDepths[n],
  212578. outputChannelBytesPerSample[n],
  212579. outputChannelIsFloat[n],
  212580. outputChannelLittleEndian[n]);
  212581. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212582. ++n;
  212583. }
  212584. }
  212585. jassert (numActiveOutputChans == n);
  212586. for (i = types.size(); --i >= 0;)
  212587. {
  212588. log ("channel format: " + String (types[i]));
  212589. }
  212590. jassert (n <= totalBuffers);
  212591. for (i = 0; i < numActiveOutputChans; ++i)
  212592. {
  212593. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212594. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212595. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212596. {
  212597. log ("!! Null buffers");
  212598. }
  212599. else
  212600. {
  212601. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212602. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212603. }
  212604. }
  212605. inputLatency = outputLatency = 0;
  212606. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212607. {
  212608. log ("ASIO - no latencies");
  212609. }
  212610. else
  212611. {
  212612. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212613. }
  212614. isOpen_ = true;
  212615. log ("starting ASIO");
  212616. calledback = false;
  212617. err = asioObject->start();
  212618. if (err != 0)
  212619. {
  212620. isOpen_ = false;
  212621. log ("ASIO - stop on failure");
  212622. Thread::sleep (10);
  212623. asioObject->stop();
  212624. error = "Can't start device";
  212625. Thread::sleep (10);
  212626. }
  212627. else
  212628. {
  212629. int count = 300;
  212630. while (--count > 0 && ! calledback)
  212631. Thread::sleep (10);
  212632. isStarted = true;
  212633. if (! calledback)
  212634. {
  212635. error = "Device didn't start correctly";
  212636. log ("ASIO didn't callback - stopping..");
  212637. asioObject->stop();
  212638. }
  212639. }
  212640. }
  212641. else
  212642. {
  212643. error = "Can't create i/o buffers";
  212644. }
  212645. }
  212646. else
  212647. {
  212648. error = "Can't set sample rate: ";
  212649. error << sampleRate;
  212650. }
  212651. if (error.isNotEmpty())
  212652. {
  212653. logError (error, err);
  212654. if (asioObject != 0 && buffersCreated)
  212655. asioObject->disposeBuffers();
  212656. Thread::sleep (20);
  212657. isStarted = false;
  212658. isOpen_ = false;
  212659. const String errorCopy (error);
  212660. close(); // (this resets the error string)
  212661. error = errorCopy;
  212662. }
  212663. needToReset = false;
  212664. isReSync = false;
  212665. return error;
  212666. }
  212667. void close()
  212668. {
  212669. error = String::empty;
  212670. stopTimer();
  212671. stop();
  212672. if (isASIOOpen && isOpen_)
  212673. {
  212674. const ScopedLock sl (callbackLock);
  212675. isOpen_ = false;
  212676. isStarted = false;
  212677. needToReset = false;
  212678. isReSync = false;
  212679. log ("ASIO - stopping");
  212680. if (asioObject != 0)
  212681. {
  212682. Thread::sleep (20);
  212683. asioObject->stop();
  212684. Thread::sleep (10);
  212685. asioObject->disposeBuffers();
  212686. }
  212687. Thread::sleep (10);
  212688. }
  212689. }
  212690. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212691. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212692. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212693. double getCurrentSampleRate() { return currentSampleRate; }
  212694. int getCurrentBitDepth() { return currentBitDepth; }
  212695. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212696. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212697. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212698. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212699. void start (AudioIODeviceCallback* callback)
  212700. {
  212701. if (callback != 0)
  212702. {
  212703. callback->audioDeviceAboutToStart (this);
  212704. const ScopedLock sl (callbackLock);
  212705. currentCallback = callback;
  212706. }
  212707. }
  212708. void stop()
  212709. {
  212710. AudioIODeviceCallback* const lastCallback = currentCallback;
  212711. {
  212712. const ScopedLock sl (callbackLock);
  212713. currentCallback = 0;
  212714. }
  212715. if (lastCallback != 0)
  212716. lastCallback->audioDeviceStopped();
  212717. }
  212718. const String getLastError() { return error; }
  212719. bool hasControlPanel() const { return true; }
  212720. bool showControlPanel()
  212721. {
  212722. log ("ASIO - showing control panel");
  212723. Component modalWindow (String::empty);
  212724. modalWindow.setOpaque (true);
  212725. modalWindow.addToDesktop (0);
  212726. modalWindow.enterModalState();
  212727. bool done = false;
  212728. JUCE_TRY
  212729. {
  212730. // are there are devices that need to be closed before showing their control panel?
  212731. // close();
  212732. insideControlPanelModalLoop = true;
  212733. const uint32 started = Time::getMillisecondCounter();
  212734. if (asioObject != 0)
  212735. {
  212736. asioObject->controlPanel();
  212737. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212738. log ("spent: " + String (spent));
  212739. if (spent > 300)
  212740. {
  212741. shouldUsePreferredSize = true;
  212742. done = true;
  212743. }
  212744. }
  212745. }
  212746. JUCE_CATCH_ALL
  212747. insideControlPanelModalLoop = false;
  212748. return done;
  212749. }
  212750. void resetRequest() throw()
  212751. {
  212752. needToReset = true;
  212753. }
  212754. void resyncRequest() throw()
  212755. {
  212756. needToReset = true;
  212757. isReSync = true;
  212758. }
  212759. void timerCallback()
  212760. {
  212761. if (! insideControlPanelModalLoop)
  212762. {
  212763. stopTimer();
  212764. // used to cause a reset
  212765. log ("! ASIO restart request!");
  212766. if (isOpen_)
  212767. {
  212768. AudioIODeviceCallback* const oldCallback = currentCallback;
  212769. close();
  212770. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212771. currentSampleRate, currentBlockSizeSamples);
  212772. if (oldCallback != 0)
  212773. start (oldCallback);
  212774. }
  212775. }
  212776. else
  212777. {
  212778. startTimer (100);
  212779. }
  212780. }
  212781. private:
  212782. IASIO* volatile asioObject;
  212783. ASIOCallbacks callbacks;
  212784. void* windowHandle;
  212785. CLSID classId;
  212786. const String optionalDllForDirectLoading;
  212787. String error;
  212788. long totalNumInputChans, totalNumOutputChans;
  212789. StringArray inputChannelNames, outputChannelNames;
  212790. Array<int> sampleRates, bufferSizes;
  212791. long inputLatency, outputLatency;
  212792. long minSize, maxSize, preferredSize, granularity;
  212793. int volatile currentBlockSizeSamples;
  212794. int volatile currentBitDepth;
  212795. double volatile currentSampleRate;
  212796. BigInteger currentChansOut, currentChansIn;
  212797. AudioIODeviceCallback* volatile currentCallback;
  212798. CriticalSection callbackLock;
  212799. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212800. float* inBuffers [maxASIOChannels];
  212801. float* outBuffers [maxASIOChannels];
  212802. int inputChannelBitDepths [maxASIOChannels];
  212803. int outputChannelBitDepths [maxASIOChannels];
  212804. int inputChannelBytesPerSample [maxASIOChannels];
  212805. int outputChannelBytesPerSample [maxASIOChannels];
  212806. bool inputChannelIsFloat [maxASIOChannels];
  212807. bool outputChannelIsFloat [maxASIOChannels];
  212808. bool inputChannelLittleEndian [maxASIOChannels];
  212809. bool outputChannelLittleEndian [maxASIOChannels];
  212810. WaitableEvent event1;
  212811. HeapBlock <float> tempBuffer;
  212812. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212813. bool isOpen_, isStarted;
  212814. bool volatile isASIOOpen;
  212815. bool volatile calledback;
  212816. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212817. bool volatile insideControlPanelModalLoop;
  212818. bool volatile shouldUsePreferredSize;
  212819. void removeCurrentDriver()
  212820. {
  212821. if (asioObject != 0)
  212822. {
  212823. asioObject->Release();
  212824. asioObject = 0;
  212825. }
  212826. }
  212827. bool loadDriver()
  212828. {
  212829. removeCurrentDriver();
  212830. JUCE_TRY
  212831. {
  212832. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212833. classId, (void**) &asioObject) == S_OK)
  212834. {
  212835. return true;
  212836. }
  212837. // If a class isn't registered but we have a path for it, we can fallback to
  212838. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212839. if (optionalDllForDirectLoading.isNotEmpty())
  212840. {
  212841. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212842. if (h != 0)
  212843. {
  212844. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212845. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212846. if (dllGetClassObject != 0)
  212847. {
  212848. IClassFactory* classFactory = 0;
  212849. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212850. if (classFactory != 0)
  212851. {
  212852. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212853. classFactory->Release();
  212854. }
  212855. return asioObject != 0;
  212856. }
  212857. }
  212858. }
  212859. }
  212860. JUCE_CATCH_ALL
  212861. asioObject = 0;
  212862. return false;
  212863. }
  212864. const String initDriver()
  212865. {
  212866. if (asioObject != 0)
  212867. {
  212868. char buffer [256];
  212869. zeromem (buffer, sizeof (buffer));
  212870. if (! asioObject->init (windowHandle))
  212871. {
  212872. asioObject->getErrorMessage (buffer);
  212873. return String (buffer, sizeof (buffer) - 1);
  212874. }
  212875. // just in case any daft drivers expect this to be called..
  212876. asioObject->getDriverName (buffer);
  212877. return String::empty;
  212878. }
  212879. return "No Driver";
  212880. }
  212881. const String openDevice()
  212882. {
  212883. // use this in case the driver starts opening dialog boxes..
  212884. Component modalWindow (String::empty);
  212885. modalWindow.setOpaque (true);
  212886. modalWindow.addToDesktop (0);
  212887. modalWindow.enterModalState();
  212888. // open the device and get its info..
  212889. log ("opening ASIO device: " + getName());
  212890. needToReset = false;
  212891. isReSync = false;
  212892. outputChannelNames.clear();
  212893. inputChannelNames.clear();
  212894. bufferSizes.clear();
  212895. sampleRates.clear();
  212896. isASIOOpen = false;
  212897. isOpen_ = false;
  212898. totalNumInputChans = 0;
  212899. totalNumOutputChans = 0;
  212900. numActiveInputChans = 0;
  212901. numActiveOutputChans = 0;
  212902. currentCallback = 0;
  212903. error = String::empty;
  212904. if (getName().isEmpty())
  212905. return error;
  212906. long err = 0;
  212907. if (loadDriver())
  212908. {
  212909. if ((error = initDriver()).isEmpty())
  212910. {
  212911. numActiveInputChans = 0;
  212912. numActiveOutputChans = 0;
  212913. totalNumInputChans = 0;
  212914. totalNumOutputChans = 0;
  212915. if (asioObject != 0
  212916. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212917. {
  212918. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212919. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212920. {
  212921. // find a list of buffer sizes..
  212922. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212923. if (granularity >= 0)
  212924. {
  212925. granularity = jmax (1, (int) granularity);
  212926. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212927. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212928. }
  212929. else if (granularity < 0)
  212930. {
  212931. for (int i = 0; i < 18; ++i)
  212932. {
  212933. const int s = (1 << i);
  212934. if (s >= minSize && s <= maxSize)
  212935. bufferSizes.add (s);
  212936. }
  212937. }
  212938. if (! bufferSizes.contains (preferredSize))
  212939. bufferSizes.insert (0, preferredSize);
  212940. double currentRate = 0;
  212941. asioObject->getSampleRate (&currentRate);
  212942. if (currentRate <= 0.0 || currentRate > 192001.0)
  212943. {
  212944. log ("setting sample rate");
  212945. err = asioObject->setSampleRate (44100.0);
  212946. if (err != 0)
  212947. {
  212948. logError ("setting sample rate", err);
  212949. }
  212950. asioObject->getSampleRate (&currentRate);
  212951. }
  212952. currentSampleRate = currentRate;
  212953. postOutput = (asioObject->outputReady() == 0);
  212954. if (postOutput)
  212955. {
  212956. log ("ASIO outputReady = ok");
  212957. }
  212958. updateSampleRates();
  212959. // ..because cubase does it at this point
  212960. inputLatency = outputLatency = 0;
  212961. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212962. {
  212963. log ("ASIO - no latencies");
  212964. }
  212965. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212966. // create some dummy buffers now.. because cubase does..
  212967. numActiveInputChans = 0;
  212968. numActiveOutputChans = 0;
  212969. ASIOBufferInfo* info = bufferInfos;
  212970. int i, numChans = 0;
  212971. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212972. {
  212973. info->isInput = 1;
  212974. info->channelNum = i;
  212975. info->buffers[0] = info->buffers[1] = 0;
  212976. ++info;
  212977. ++numChans;
  212978. }
  212979. const int outputBufferIndex = numChans;
  212980. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212981. {
  212982. info->isInput = 0;
  212983. info->channelNum = i;
  212984. info->buffers[0] = info->buffers[1] = 0;
  212985. ++info;
  212986. ++numChans;
  212987. }
  212988. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212989. if (currentASIODev[0] == this)
  212990. {
  212991. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212992. callbacks.asioMessage = &asioMessagesCallback0;
  212993. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212994. }
  212995. else if (currentASIODev[1] == this)
  212996. {
  212997. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212998. callbacks.asioMessage = &asioMessagesCallback1;
  212999. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213000. }
  213001. else if (currentASIODev[2] == this)
  213002. {
  213003. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213004. callbacks.asioMessage = &asioMessagesCallback2;
  213005. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213006. }
  213007. else
  213008. {
  213009. jassertfalse;
  213010. }
  213011. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213012. if (preferredSize > 0)
  213013. {
  213014. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213015. if (err != 0)
  213016. {
  213017. logError ("dummy buffers", err);
  213018. }
  213019. }
  213020. long newInps = 0, newOuts = 0;
  213021. asioObject->getChannels (&newInps, &newOuts);
  213022. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213023. {
  213024. totalNumInputChans = newInps;
  213025. totalNumOutputChans = newOuts;
  213026. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213027. }
  213028. updateSampleRates();
  213029. ASIOChannelInfo channelInfo;
  213030. channelInfo.type = 0;
  213031. for (i = 0; i < totalNumInputChans; ++i)
  213032. {
  213033. zerostruct (channelInfo);
  213034. channelInfo.channel = i;
  213035. channelInfo.isInput = 1;
  213036. asioObject->getChannelInfo (&channelInfo);
  213037. inputChannelNames.add (String (channelInfo.name));
  213038. }
  213039. for (i = 0; i < totalNumOutputChans; ++i)
  213040. {
  213041. zerostruct (channelInfo);
  213042. channelInfo.channel = i;
  213043. channelInfo.isInput = 0;
  213044. asioObject->getChannelInfo (&channelInfo);
  213045. outputChannelNames.add (String (channelInfo.name));
  213046. typeToFormatParameters (channelInfo.type,
  213047. outputChannelBitDepths[i],
  213048. outputChannelBytesPerSample[i],
  213049. outputChannelIsFloat[i],
  213050. outputChannelLittleEndian[i]);
  213051. if (i < 2)
  213052. {
  213053. // clear the channels that are used with the dummy stuff
  213054. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213055. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213056. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213057. }
  213058. }
  213059. outputChannelNames.trim();
  213060. inputChannelNames.trim();
  213061. outputChannelNames.appendNumbersToDuplicates (false, true);
  213062. inputChannelNames.appendNumbersToDuplicates (false, true);
  213063. // start and stop because cubase does it..
  213064. asioObject->getLatencies (&inputLatency, &outputLatency);
  213065. if ((err = asioObject->start()) != 0)
  213066. {
  213067. // ignore an error here, as it might start later after setting other stuff up
  213068. logError ("ASIO start", err);
  213069. }
  213070. Thread::sleep (100);
  213071. asioObject->stop();
  213072. }
  213073. else
  213074. {
  213075. error = "Can't detect buffer sizes";
  213076. }
  213077. }
  213078. else
  213079. {
  213080. error = "Can't detect asio channels";
  213081. }
  213082. }
  213083. }
  213084. else
  213085. {
  213086. error = "No such device";
  213087. }
  213088. if (error.isNotEmpty())
  213089. {
  213090. logError (error, err);
  213091. if (asioObject != 0)
  213092. asioObject->disposeBuffers();
  213093. removeCurrentDriver();
  213094. isASIOOpen = false;
  213095. }
  213096. else
  213097. {
  213098. isASIOOpen = true;
  213099. log ("ASIO device open");
  213100. }
  213101. isOpen_ = false;
  213102. needToReset = false;
  213103. isReSync = false;
  213104. return error;
  213105. }
  213106. void JUCE_ASIOCALLBACK callback (const long index)
  213107. {
  213108. if (isStarted)
  213109. {
  213110. bufferIndex = index;
  213111. processBuffer();
  213112. }
  213113. else
  213114. {
  213115. if (postOutput && (asioObject != 0))
  213116. asioObject->outputReady();
  213117. }
  213118. calledback = true;
  213119. }
  213120. void processBuffer()
  213121. {
  213122. const ASIOBufferInfo* const infos = bufferInfos;
  213123. const int bi = bufferIndex;
  213124. const ScopedLock sl (callbackLock);
  213125. if (needToReset)
  213126. {
  213127. needToReset = false;
  213128. if (isReSync)
  213129. {
  213130. log ("! ASIO resync");
  213131. isReSync = false;
  213132. }
  213133. else
  213134. {
  213135. startTimer (20);
  213136. }
  213137. }
  213138. if (bi >= 0)
  213139. {
  213140. const int samps = currentBlockSizeSamples;
  213141. if (currentCallback != 0)
  213142. {
  213143. int i;
  213144. for (i = 0; i < numActiveInputChans; ++i)
  213145. {
  213146. float* const dst = inBuffers[i];
  213147. jassert (dst != 0);
  213148. const char* const src = (const char*) (infos[i].buffers[bi]);
  213149. if (inputChannelIsFloat[i])
  213150. {
  213151. memcpy (dst, src, samps * sizeof (float));
  213152. }
  213153. else
  213154. {
  213155. jassert (dst == tempBuffer + (samps * i));
  213156. switch (inputChannelBitDepths[i])
  213157. {
  213158. case 16:
  213159. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213160. samps, inputChannelLittleEndian[i]);
  213161. break;
  213162. case 24:
  213163. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213164. samps, inputChannelLittleEndian[i]);
  213165. break;
  213166. case 32:
  213167. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213168. samps, inputChannelLittleEndian[i]);
  213169. break;
  213170. case 64:
  213171. jassertfalse;
  213172. break;
  213173. }
  213174. }
  213175. }
  213176. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213177. outBuffers, numActiveOutputChans, samps);
  213178. for (i = 0; i < numActiveOutputChans; ++i)
  213179. {
  213180. float* const src = outBuffers[i];
  213181. jassert (src != 0);
  213182. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213183. if (outputChannelIsFloat[i])
  213184. {
  213185. memcpy (dst, src, samps * sizeof (float));
  213186. }
  213187. else
  213188. {
  213189. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213190. switch (outputChannelBitDepths[i])
  213191. {
  213192. case 16:
  213193. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213194. samps, outputChannelLittleEndian[i]);
  213195. break;
  213196. case 24:
  213197. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213198. samps, outputChannelLittleEndian[i]);
  213199. break;
  213200. case 32:
  213201. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213202. samps, outputChannelLittleEndian[i]);
  213203. break;
  213204. case 64:
  213205. jassertfalse;
  213206. break;
  213207. }
  213208. }
  213209. }
  213210. }
  213211. else
  213212. {
  213213. for (int i = 0; i < numActiveOutputChans; ++i)
  213214. {
  213215. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213216. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213217. }
  213218. }
  213219. }
  213220. if (postOutput)
  213221. asioObject->outputReady();
  213222. }
  213223. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213224. {
  213225. if (currentASIODev[0] != 0)
  213226. currentASIODev[0]->callback (index);
  213227. return 0;
  213228. }
  213229. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213230. {
  213231. if (currentASIODev[1] != 0)
  213232. currentASIODev[1]->callback (index);
  213233. return 0;
  213234. }
  213235. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213236. {
  213237. if (currentASIODev[2] != 0)
  213238. currentASIODev[2]->callback (index);
  213239. return 0;
  213240. }
  213241. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213242. {
  213243. if (currentASIODev[0] != 0)
  213244. currentASIODev[0]->callback (index);
  213245. }
  213246. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213247. {
  213248. if (currentASIODev[1] != 0)
  213249. currentASIODev[1]->callback (index);
  213250. }
  213251. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213252. {
  213253. if (currentASIODev[2] != 0)
  213254. currentASIODev[2]->callback (index);
  213255. }
  213256. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213257. {
  213258. return asioMessagesCallback (selector, value, 0);
  213259. }
  213260. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213261. {
  213262. return asioMessagesCallback (selector, value, 1);
  213263. }
  213264. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213265. {
  213266. return asioMessagesCallback (selector, value, 2);
  213267. }
  213268. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213269. {
  213270. switch (selector)
  213271. {
  213272. case kAsioSelectorSupported:
  213273. if (value == kAsioResetRequest
  213274. || value == kAsioEngineVersion
  213275. || value == kAsioResyncRequest
  213276. || value == kAsioLatenciesChanged
  213277. || value == kAsioSupportsInputMonitor)
  213278. return 1;
  213279. break;
  213280. case kAsioBufferSizeChange:
  213281. break;
  213282. case kAsioResetRequest:
  213283. if (currentASIODev[deviceIndex] != 0)
  213284. currentASIODev[deviceIndex]->resetRequest();
  213285. return 1;
  213286. case kAsioResyncRequest:
  213287. if (currentASIODev[deviceIndex] != 0)
  213288. currentASIODev[deviceIndex]->resyncRequest();
  213289. return 1;
  213290. case kAsioLatenciesChanged:
  213291. return 1;
  213292. case kAsioEngineVersion:
  213293. return 2;
  213294. case kAsioSupportsTimeInfo:
  213295. case kAsioSupportsTimeCode:
  213296. return 0;
  213297. }
  213298. return 0;
  213299. }
  213300. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213301. {
  213302. }
  213303. static void convertInt16ToFloat (const char* src,
  213304. float* dest,
  213305. const int srcStrideBytes,
  213306. int numSamples,
  213307. const bool littleEndian) throw()
  213308. {
  213309. const double g = 1.0 / 32768.0;
  213310. if (littleEndian)
  213311. {
  213312. while (--numSamples >= 0)
  213313. {
  213314. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213315. src += srcStrideBytes;
  213316. }
  213317. }
  213318. else
  213319. {
  213320. while (--numSamples >= 0)
  213321. {
  213322. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213323. src += srcStrideBytes;
  213324. }
  213325. }
  213326. }
  213327. static void convertFloatToInt16 (const float* src,
  213328. char* dest,
  213329. const int dstStrideBytes,
  213330. int numSamples,
  213331. const bool littleEndian) throw()
  213332. {
  213333. const double maxVal = (double) 0x7fff;
  213334. if (littleEndian)
  213335. {
  213336. while (--numSamples >= 0)
  213337. {
  213338. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213339. dest += dstStrideBytes;
  213340. }
  213341. }
  213342. else
  213343. {
  213344. while (--numSamples >= 0)
  213345. {
  213346. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213347. dest += dstStrideBytes;
  213348. }
  213349. }
  213350. }
  213351. static void convertInt24ToFloat (const char* src,
  213352. float* dest,
  213353. const int srcStrideBytes,
  213354. int numSamples,
  213355. const bool littleEndian) throw()
  213356. {
  213357. const double g = 1.0 / 0x7fffff;
  213358. if (littleEndian)
  213359. {
  213360. while (--numSamples >= 0)
  213361. {
  213362. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213363. src += srcStrideBytes;
  213364. }
  213365. }
  213366. else
  213367. {
  213368. while (--numSamples >= 0)
  213369. {
  213370. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213371. src += srcStrideBytes;
  213372. }
  213373. }
  213374. }
  213375. static void convertFloatToInt24 (const float* src,
  213376. char* dest,
  213377. const int dstStrideBytes,
  213378. int numSamples,
  213379. const bool littleEndian) throw()
  213380. {
  213381. const double maxVal = (double) 0x7fffff;
  213382. if (littleEndian)
  213383. {
  213384. while (--numSamples >= 0)
  213385. {
  213386. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213387. dest += dstStrideBytes;
  213388. }
  213389. }
  213390. else
  213391. {
  213392. while (--numSamples >= 0)
  213393. {
  213394. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213395. dest += dstStrideBytes;
  213396. }
  213397. }
  213398. }
  213399. static void convertInt32ToFloat (const char* src,
  213400. float* dest,
  213401. const int srcStrideBytes,
  213402. int numSamples,
  213403. const bool littleEndian) throw()
  213404. {
  213405. const double g = 1.0 / 0x7fffffff;
  213406. if (littleEndian)
  213407. {
  213408. while (--numSamples >= 0)
  213409. {
  213410. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213411. src += srcStrideBytes;
  213412. }
  213413. }
  213414. else
  213415. {
  213416. while (--numSamples >= 0)
  213417. {
  213418. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213419. src += srcStrideBytes;
  213420. }
  213421. }
  213422. }
  213423. static void convertFloatToInt32 (const float* src,
  213424. char* dest,
  213425. const int dstStrideBytes,
  213426. int numSamples,
  213427. const bool littleEndian) throw()
  213428. {
  213429. const double maxVal = (double) 0x7fffffff;
  213430. if (littleEndian)
  213431. {
  213432. while (--numSamples >= 0)
  213433. {
  213434. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213435. dest += dstStrideBytes;
  213436. }
  213437. }
  213438. else
  213439. {
  213440. while (--numSamples >= 0)
  213441. {
  213442. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213443. dest += dstStrideBytes;
  213444. }
  213445. }
  213446. }
  213447. static void typeToFormatParameters (const long type,
  213448. int& bitDepth,
  213449. int& byteStride,
  213450. bool& formatIsFloat,
  213451. bool& littleEndian) throw()
  213452. {
  213453. bitDepth = 0;
  213454. littleEndian = false;
  213455. formatIsFloat = false;
  213456. switch (type)
  213457. {
  213458. case ASIOSTInt16MSB:
  213459. case ASIOSTInt16LSB:
  213460. case ASIOSTInt32MSB16:
  213461. case ASIOSTInt32LSB16:
  213462. bitDepth = 16; break;
  213463. case ASIOSTFloat32MSB:
  213464. case ASIOSTFloat32LSB:
  213465. formatIsFloat = true;
  213466. bitDepth = 32; break;
  213467. case ASIOSTInt32MSB:
  213468. case ASIOSTInt32LSB:
  213469. bitDepth = 32; break;
  213470. case ASIOSTInt24MSB:
  213471. case ASIOSTInt24LSB:
  213472. case ASIOSTInt32MSB24:
  213473. case ASIOSTInt32LSB24:
  213474. case ASIOSTInt32MSB18:
  213475. case ASIOSTInt32MSB20:
  213476. case ASIOSTInt32LSB18:
  213477. case ASIOSTInt32LSB20:
  213478. bitDepth = 24; break;
  213479. case ASIOSTFloat64MSB:
  213480. case ASIOSTFloat64LSB:
  213481. default:
  213482. bitDepth = 64;
  213483. break;
  213484. }
  213485. switch (type)
  213486. {
  213487. case ASIOSTInt16MSB:
  213488. case ASIOSTInt32MSB16:
  213489. case ASIOSTFloat32MSB:
  213490. case ASIOSTFloat64MSB:
  213491. case ASIOSTInt32MSB:
  213492. case ASIOSTInt32MSB18:
  213493. case ASIOSTInt32MSB20:
  213494. case ASIOSTInt32MSB24:
  213495. case ASIOSTInt24MSB:
  213496. littleEndian = false; break;
  213497. case ASIOSTInt16LSB:
  213498. case ASIOSTInt32LSB16:
  213499. case ASIOSTFloat32LSB:
  213500. case ASIOSTFloat64LSB:
  213501. case ASIOSTInt32LSB:
  213502. case ASIOSTInt32LSB18:
  213503. case ASIOSTInt32LSB20:
  213504. case ASIOSTInt32LSB24:
  213505. case ASIOSTInt24LSB:
  213506. littleEndian = true; break;
  213507. default:
  213508. break;
  213509. }
  213510. switch (type)
  213511. {
  213512. case ASIOSTInt16LSB:
  213513. case ASIOSTInt16MSB:
  213514. byteStride = 2; break;
  213515. case ASIOSTInt24LSB:
  213516. case ASIOSTInt24MSB:
  213517. byteStride = 3; break;
  213518. case ASIOSTInt32MSB16:
  213519. case ASIOSTInt32LSB16:
  213520. case ASIOSTInt32MSB:
  213521. case ASIOSTInt32MSB18:
  213522. case ASIOSTInt32MSB20:
  213523. case ASIOSTInt32MSB24:
  213524. case ASIOSTInt32LSB:
  213525. case ASIOSTInt32LSB18:
  213526. case ASIOSTInt32LSB20:
  213527. case ASIOSTInt32LSB24:
  213528. case ASIOSTFloat32LSB:
  213529. case ASIOSTFloat32MSB:
  213530. byteStride = 4; break;
  213531. case ASIOSTFloat64MSB:
  213532. case ASIOSTFloat64LSB:
  213533. byteStride = 8; break;
  213534. default:
  213535. break;
  213536. }
  213537. }
  213538. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213539. };
  213540. class ASIOAudioIODeviceType : public AudioIODeviceType
  213541. {
  213542. public:
  213543. ASIOAudioIODeviceType()
  213544. : AudioIODeviceType ("ASIO"),
  213545. hasScanned (false)
  213546. {
  213547. CoInitialize (0);
  213548. }
  213549. ~ASIOAudioIODeviceType()
  213550. {
  213551. }
  213552. void scanForDevices()
  213553. {
  213554. hasScanned = true;
  213555. deviceNames.clear();
  213556. classIds.clear();
  213557. HKEY hk = 0;
  213558. int index = 0;
  213559. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213560. {
  213561. for (;;)
  213562. {
  213563. char name [256];
  213564. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213565. {
  213566. addDriverInfo (name, hk);
  213567. }
  213568. else
  213569. {
  213570. break;
  213571. }
  213572. }
  213573. RegCloseKey (hk);
  213574. }
  213575. }
  213576. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213577. {
  213578. jassert (hasScanned); // need to call scanForDevices() before doing this
  213579. return deviceNames;
  213580. }
  213581. int getDefaultDeviceIndex (bool) const
  213582. {
  213583. jassert (hasScanned); // need to call scanForDevices() before doing this
  213584. for (int i = deviceNames.size(); --i >= 0;)
  213585. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213586. return i; // asio4all is a safe choice for a default..
  213587. #if JUCE_DEBUG
  213588. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213589. return 1; // (the digi m-box driver crashes the app when you run
  213590. // it in the debugger, which can be a bit annoying)
  213591. #endif
  213592. return 0;
  213593. }
  213594. static int findFreeSlot()
  213595. {
  213596. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213597. if (currentASIODev[i] == 0)
  213598. return i;
  213599. jassertfalse; // unfortunately you can only have a finite number
  213600. // of ASIO devices open at the same time..
  213601. return -1;
  213602. }
  213603. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213604. {
  213605. jassert (hasScanned); // need to call scanForDevices() before doing this
  213606. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213607. }
  213608. bool hasSeparateInputsAndOutputs() const { return false; }
  213609. AudioIODevice* createDevice (const String& outputDeviceName,
  213610. const String& inputDeviceName)
  213611. {
  213612. // ASIO can't open two different devices for input and output - they must be the same one.
  213613. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213614. jassert (hasScanned); // need to call scanForDevices() before doing this
  213615. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213616. : inputDeviceName);
  213617. if (index >= 0)
  213618. {
  213619. const int freeSlot = findFreeSlot();
  213620. if (freeSlot >= 0)
  213621. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213622. }
  213623. return 0;
  213624. }
  213625. private:
  213626. StringArray deviceNames;
  213627. OwnedArray <CLSID> classIds;
  213628. bool hasScanned;
  213629. static bool checkClassIsOk (const String& classId)
  213630. {
  213631. HKEY hk = 0;
  213632. bool ok = false;
  213633. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213634. {
  213635. int index = 0;
  213636. for (;;)
  213637. {
  213638. WCHAR buf [512];
  213639. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213640. {
  213641. if (classId.equalsIgnoreCase (buf))
  213642. {
  213643. HKEY subKey, pathKey;
  213644. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213645. {
  213646. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213647. {
  213648. WCHAR pathName [1024];
  213649. DWORD dtype = REG_SZ;
  213650. DWORD dsize = sizeof (pathName);
  213651. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213652. ok = File (pathName).exists();
  213653. RegCloseKey (pathKey);
  213654. }
  213655. RegCloseKey (subKey);
  213656. }
  213657. break;
  213658. }
  213659. }
  213660. else
  213661. {
  213662. break;
  213663. }
  213664. }
  213665. RegCloseKey (hk);
  213666. }
  213667. return ok;
  213668. }
  213669. void addDriverInfo (const String& keyName, HKEY hk)
  213670. {
  213671. HKEY subKey;
  213672. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213673. {
  213674. WCHAR buf [256];
  213675. zerostruct (buf);
  213676. DWORD dtype = REG_SZ;
  213677. DWORD dsize = sizeof (buf);
  213678. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213679. {
  213680. if (dsize > 0 && checkClassIsOk (buf))
  213681. {
  213682. CLSID classId;
  213683. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213684. {
  213685. dtype = REG_SZ;
  213686. dsize = sizeof (buf);
  213687. String deviceName;
  213688. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213689. deviceName = buf;
  213690. else
  213691. deviceName = keyName;
  213692. log ("found " + deviceName);
  213693. deviceNames.add (deviceName);
  213694. classIds.add (new CLSID (classId));
  213695. }
  213696. }
  213697. RegCloseKey (subKey);
  213698. }
  213699. }
  213700. }
  213701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213702. };
  213703. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213704. {
  213705. return new ASIOAudioIODeviceType();
  213706. }
  213707. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213708. void* guid,
  213709. const String& optionalDllForDirectLoading)
  213710. {
  213711. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213712. if (freeSlot < 0)
  213713. return 0;
  213714. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213715. }
  213716. #undef logError
  213717. #undef log
  213718. #endif
  213719. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213720. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213721. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213722. // compiled on its own).
  213723. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213724. END_JUCE_NAMESPACE
  213725. extern "C"
  213726. {
  213727. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213728. typedef struct typeDSBUFFERDESC
  213729. {
  213730. DWORD dwSize;
  213731. DWORD dwFlags;
  213732. DWORD dwBufferBytes;
  213733. DWORD dwReserved;
  213734. LPWAVEFORMATEX lpwfxFormat;
  213735. GUID guid3DAlgorithm;
  213736. } DSBUFFERDESC;
  213737. struct IDirectSoundBuffer;
  213738. #undef INTERFACE
  213739. #define INTERFACE IDirectSound
  213740. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213741. {
  213742. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213743. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213744. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213745. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213746. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213747. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213748. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213749. STDMETHOD(Compact) (THIS) PURE;
  213750. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213751. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213752. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213753. };
  213754. #undef INTERFACE
  213755. #define INTERFACE IDirectSoundBuffer
  213756. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213757. {
  213758. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213759. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213760. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213761. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213762. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213763. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213764. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213765. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213766. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213767. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213768. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213769. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213770. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213771. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213772. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213773. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213774. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213775. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213776. STDMETHOD(Stop) (THIS) PURE;
  213777. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213778. STDMETHOD(Restore) (THIS) PURE;
  213779. };
  213780. typedef struct typeDSCBUFFERDESC
  213781. {
  213782. DWORD dwSize;
  213783. DWORD dwFlags;
  213784. DWORD dwBufferBytes;
  213785. DWORD dwReserved;
  213786. LPWAVEFORMATEX lpwfxFormat;
  213787. } DSCBUFFERDESC;
  213788. struct IDirectSoundCaptureBuffer;
  213789. #undef INTERFACE
  213790. #define INTERFACE IDirectSoundCapture
  213791. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213792. {
  213793. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213794. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213795. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213796. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213797. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213798. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213799. };
  213800. #undef INTERFACE
  213801. #define INTERFACE IDirectSoundCaptureBuffer
  213802. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213803. {
  213804. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213805. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213806. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213807. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213808. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213809. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213810. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213811. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213812. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213813. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213814. STDMETHOD(Stop) (THIS) PURE;
  213815. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213816. };
  213817. };
  213818. BEGIN_JUCE_NAMESPACE
  213819. namespace
  213820. {
  213821. const String getDSErrorMessage (HRESULT hr)
  213822. {
  213823. const char* result = 0;
  213824. switch (hr)
  213825. {
  213826. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213827. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213828. case E_INVALIDARG: result = "Invalid parameter"; break;
  213829. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213830. case E_FAIL: result = "Generic error"; break;
  213831. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213832. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213833. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213834. case E_NOTIMPL: result = "Unsupported function"; break;
  213835. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213836. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213837. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213838. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213839. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213840. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213841. case E_NOINTERFACE: result = "No interface"; break;
  213842. case S_OK: result = "No error"; break;
  213843. default: return "Unknown error: " + String ((int) hr);
  213844. }
  213845. return result;
  213846. }
  213847. #define DS_DEBUGGING 1
  213848. #ifdef DS_DEBUGGING
  213849. #define CATCH JUCE_CATCH_EXCEPTION
  213850. #undef log
  213851. #define log(a) Logger::writeToLog(a);
  213852. #undef logError
  213853. #define logError(a) logDSError(a, __LINE__);
  213854. static void logDSError (HRESULT hr, int lineNum)
  213855. {
  213856. if (hr != S_OK)
  213857. {
  213858. String error ("DS error at line ");
  213859. error << lineNum << " - " << getDSErrorMessage (hr);
  213860. log (error);
  213861. }
  213862. }
  213863. #else
  213864. #define CATCH JUCE_CATCH_ALL
  213865. #define log(a)
  213866. #define logError(a)
  213867. #endif
  213868. #define DSOUND_FUNCTION(functionName, params) \
  213869. typedef HRESULT (WINAPI *type##functionName) params; \
  213870. static type##functionName ds##functionName = 0;
  213871. #define DSOUND_FUNCTION_LOAD(functionName) \
  213872. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213873. jassert (ds##functionName != 0);
  213874. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213875. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213876. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213877. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213878. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213879. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213880. void initialiseDSoundFunctions()
  213881. {
  213882. if (dsDirectSoundCreate == 0)
  213883. {
  213884. HMODULE h = LoadLibraryA ("dsound.dll");
  213885. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213886. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213887. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213888. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213889. }
  213890. }
  213891. }
  213892. class DSoundInternalOutChannel
  213893. {
  213894. public:
  213895. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213896. int bufferSize, float* left, float* right)
  213897. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213898. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213899. pDirectSound (0), pOutputBuffer (0)
  213900. {
  213901. }
  213902. ~DSoundInternalOutChannel()
  213903. {
  213904. close();
  213905. }
  213906. void close()
  213907. {
  213908. HRESULT hr;
  213909. if (pOutputBuffer != 0)
  213910. {
  213911. log ("closing dsound out: " + name);
  213912. hr = pOutputBuffer->Stop();
  213913. logError (hr);
  213914. hr = pOutputBuffer->Release();
  213915. pOutputBuffer = 0;
  213916. logError (hr);
  213917. }
  213918. if (pDirectSound != 0)
  213919. {
  213920. hr = pDirectSound->Release();
  213921. pDirectSound = 0;
  213922. logError (hr);
  213923. }
  213924. }
  213925. const String open()
  213926. {
  213927. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213928. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213929. pDirectSound = 0;
  213930. pOutputBuffer = 0;
  213931. writeOffset = 0;
  213932. String error;
  213933. HRESULT hr = E_NOINTERFACE;
  213934. if (dsDirectSoundCreate != 0)
  213935. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213936. if (hr == S_OK)
  213937. {
  213938. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213939. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213940. const int numChannels = 2;
  213941. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213942. logError (hr);
  213943. if (hr == S_OK)
  213944. {
  213945. IDirectSoundBuffer* pPrimaryBuffer;
  213946. DSBUFFERDESC primaryDesc;
  213947. zerostruct (primaryDesc);
  213948. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213949. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213950. primaryDesc.dwBufferBytes = 0;
  213951. primaryDesc.lpwfxFormat = 0;
  213952. log ("opening dsound out step 2");
  213953. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213954. logError (hr);
  213955. if (hr == S_OK)
  213956. {
  213957. WAVEFORMATEX wfFormat;
  213958. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213959. wfFormat.nChannels = (unsigned short) numChannels;
  213960. wfFormat.nSamplesPerSec = sampleRate;
  213961. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213962. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213963. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213964. wfFormat.cbSize = 0;
  213965. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213966. logError (hr);
  213967. if (hr == S_OK)
  213968. {
  213969. DSBUFFERDESC secondaryDesc;
  213970. zerostruct (secondaryDesc);
  213971. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213972. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213973. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213974. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213975. secondaryDesc.lpwfxFormat = &wfFormat;
  213976. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213977. logError (hr);
  213978. if (hr == S_OK)
  213979. {
  213980. log ("opening dsound out step 3");
  213981. DWORD dwDataLen;
  213982. unsigned char* pDSBuffData;
  213983. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213984. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213985. logError (hr);
  213986. if (hr == S_OK)
  213987. {
  213988. zeromem (pDSBuffData, dwDataLen);
  213989. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213990. if (hr == S_OK)
  213991. {
  213992. hr = pOutputBuffer->SetCurrentPosition (0);
  213993. if (hr == S_OK)
  213994. {
  213995. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213996. if (hr == S_OK)
  213997. return String::empty;
  213998. }
  213999. }
  214000. }
  214001. }
  214002. }
  214003. }
  214004. }
  214005. }
  214006. error = getDSErrorMessage (hr);
  214007. close();
  214008. return error;
  214009. }
  214010. void synchronisePosition()
  214011. {
  214012. if (pOutputBuffer != 0)
  214013. {
  214014. DWORD playCursor;
  214015. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214016. }
  214017. }
  214018. bool service()
  214019. {
  214020. if (pOutputBuffer == 0)
  214021. return true;
  214022. DWORD playCursor, writeCursor;
  214023. for (;;)
  214024. {
  214025. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214026. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214027. {
  214028. pOutputBuffer->Restore();
  214029. continue;
  214030. }
  214031. if (hr == S_OK)
  214032. break;
  214033. logError (hr);
  214034. jassertfalse;
  214035. return true;
  214036. }
  214037. int playWriteGap = writeCursor - playCursor;
  214038. if (playWriteGap < 0)
  214039. playWriteGap += totalBytesPerBuffer;
  214040. int bytesEmpty = playCursor - writeOffset;
  214041. if (bytesEmpty < 0)
  214042. bytesEmpty += totalBytesPerBuffer;
  214043. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214044. {
  214045. writeOffset = writeCursor;
  214046. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214047. }
  214048. if (bytesEmpty >= bytesPerBuffer)
  214049. {
  214050. void* lpbuf1 = 0;
  214051. void* lpbuf2 = 0;
  214052. DWORD dwSize1 = 0;
  214053. DWORD dwSize2 = 0;
  214054. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214055. &lpbuf1, &dwSize1,
  214056. &lpbuf2, &dwSize2, 0);
  214057. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214058. {
  214059. pOutputBuffer->Restore();
  214060. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214061. &lpbuf1, &dwSize1,
  214062. &lpbuf2, &dwSize2, 0);
  214063. }
  214064. if (hr == S_OK)
  214065. {
  214066. if (bitDepth == 16)
  214067. {
  214068. int* dest = static_cast<int*> (lpbuf1);
  214069. const float* left = leftBuffer;
  214070. const float* right = rightBuffer;
  214071. int samples1 = dwSize1 >> 2;
  214072. int samples2 = dwSize2 >> 2;
  214073. if (left == 0)
  214074. {
  214075. while (--samples1 >= 0)
  214076. *dest++ = (convertInputValue (*right++) << 16);
  214077. dest = static_cast<int*> (lpbuf2);
  214078. while (--samples2 >= 0)
  214079. *dest++ = (convertInputValue (*right++) << 16);
  214080. }
  214081. else if (right == 0)
  214082. {
  214083. while (--samples1 >= 0)
  214084. *dest++ = (0xffff & convertInputValue (*left++));
  214085. dest = static_cast<int*> (lpbuf2);
  214086. while (--samples2 >= 0)
  214087. *dest++ = (0xffff & convertInputValue (*left++));
  214088. }
  214089. else
  214090. {
  214091. while (--samples1 >= 0)
  214092. {
  214093. const int l = convertInputValue (*left++);
  214094. const int r = convertInputValue (*right++);
  214095. *dest++ = (r << 16) | (0xffff & l);
  214096. }
  214097. dest = static_cast<int*> (lpbuf2);
  214098. while (--samples2 >= 0)
  214099. {
  214100. const int l = convertInputValue (*left++);
  214101. const int r = convertInputValue (*right++);
  214102. *dest++ = (r << 16) | (0xffff & l);
  214103. }
  214104. }
  214105. }
  214106. else
  214107. {
  214108. jassertfalse;
  214109. }
  214110. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214111. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214112. }
  214113. else
  214114. {
  214115. jassertfalse;
  214116. logError (hr);
  214117. }
  214118. bytesEmpty -= bytesPerBuffer;
  214119. return true;
  214120. }
  214121. else
  214122. {
  214123. return false;
  214124. }
  214125. }
  214126. int bitDepth;
  214127. bool doneFlag;
  214128. private:
  214129. String name;
  214130. LPGUID guid;
  214131. int sampleRate, bufferSizeSamples;
  214132. float* leftBuffer;
  214133. float* rightBuffer;
  214134. IDirectSound* pDirectSound;
  214135. IDirectSoundBuffer* pOutputBuffer;
  214136. DWORD writeOffset;
  214137. int totalBytesPerBuffer, bytesPerBuffer;
  214138. unsigned int lastPlayCursor;
  214139. static inline int convertInputValue (const float v) throw()
  214140. {
  214141. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214142. }
  214143. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214144. };
  214145. struct DSoundInternalInChannel
  214146. {
  214147. public:
  214148. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214149. int bufferSize, float* left, float* right)
  214150. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214151. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214152. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214153. {
  214154. }
  214155. ~DSoundInternalInChannel()
  214156. {
  214157. close();
  214158. }
  214159. void close()
  214160. {
  214161. HRESULT hr;
  214162. if (pInputBuffer != 0)
  214163. {
  214164. log ("closing dsound in: " + name);
  214165. hr = pInputBuffer->Stop();
  214166. logError (hr);
  214167. hr = pInputBuffer->Release();
  214168. pInputBuffer = 0;
  214169. logError (hr);
  214170. }
  214171. if (pDirectSoundCapture != 0)
  214172. {
  214173. hr = pDirectSoundCapture->Release();
  214174. pDirectSoundCapture = 0;
  214175. logError (hr);
  214176. }
  214177. if (pDirectSound != 0)
  214178. {
  214179. hr = pDirectSound->Release();
  214180. pDirectSound = 0;
  214181. logError (hr);
  214182. }
  214183. }
  214184. const String open()
  214185. {
  214186. log ("opening dsound in device: " + name
  214187. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214188. pDirectSound = 0;
  214189. pDirectSoundCapture = 0;
  214190. pInputBuffer = 0;
  214191. readOffset = 0;
  214192. totalBytesPerBuffer = 0;
  214193. String error;
  214194. HRESULT hr = E_NOINTERFACE;
  214195. if (dsDirectSoundCaptureCreate != 0)
  214196. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214197. logError (hr);
  214198. if (hr == S_OK)
  214199. {
  214200. const int numChannels = 2;
  214201. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214202. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214203. WAVEFORMATEX wfFormat;
  214204. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214205. wfFormat.nChannels = (unsigned short)numChannels;
  214206. wfFormat.nSamplesPerSec = sampleRate;
  214207. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214208. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214209. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214210. wfFormat.cbSize = 0;
  214211. DSCBUFFERDESC captureDesc;
  214212. zerostruct (captureDesc);
  214213. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214214. captureDesc.dwFlags = 0;
  214215. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214216. captureDesc.lpwfxFormat = &wfFormat;
  214217. log ("opening dsound in step 2");
  214218. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214219. logError (hr);
  214220. if (hr == S_OK)
  214221. {
  214222. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214223. logError (hr);
  214224. if (hr == S_OK)
  214225. return String::empty;
  214226. }
  214227. }
  214228. error = getDSErrorMessage (hr);
  214229. close();
  214230. return error;
  214231. }
  214232. void synchronisePosition()
  214233. {
  214234. if (pInputBuffer != 0)
  214235. {
  214236. DWORD capturePos;
  214237. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214238. }
  214239. }
  214240. bool service()
  214241. {
  214242. if (pInputBuffer == 0)
  214243. return true;
  214244. DWORD capturePos, readPos;
  214245. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214246. logError (hr);
  214247. if (hr != S_OK)
  214248. return true;
  214249. int bytesFilled = readPos - readOffset;
  214250. if (bytesFilled < 0)
  214251. bytesFilled += totalBytesPerBuffer;
  214252. if (bytesFilled >= bytesPerBuffer)
  214253. {
  214254. LPBYTE lpbuf1 = 0;
  214255. LPBYTE lpbuf2 = 0;
  214256. DWORD dwsize1 = 0;
  214257. DWORD dwsize2 = 0;
  214258. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214259. (void**) &lpbuf1, &dwsize1,
  214260. (void**) &lpbuf2, &dwsize2, 0);
  214261. if (hr == S_OK)
  214262. {
  214263. if (bitDepth == 16)
  214264. {
  214265. const float g = 1.0f / 32768.0f;
  214266. float* destL = leftBuffer;
  214267. float* destR = rightBuffer;
  214268. int samples1 = dwsize1 >> 2;
  214269. int samples2 = dwsize2 >> 2;
  214270. const short* src = (const short*)lpbuf1;
  214271. if (destL == 0)
  214272. {
  214273. while (--samples1 >= 0)
  214274. {
  214275. ++src;
  214276. *destR++ = *src++ * g;
  214277. }
  214278. src = (const short*)lpbuf2;
  214279. while (--samples2 >= 0)
  214280. {
  214281. ++src;
  214282. *destR++ = *src++ * g;
  214283. }
  214284. }
  214285. else if (destR == 0)
  214286. {
  214287. while (--samples1 >= 0)
  214288. {
  214289. *destL++ = *src++ * g;
  214290. ++src;
  214291. }
  214292. src = (const short*)lpbuf2;
  214293. while (--samples2 >= 0)
  214294. {
  214295. *destL++ = *src++ * g;
  214296. ++src;
  214297. }
  214298. }
  214299. else
  214300. {
  214301. while (--samples1 >= 0)
  214302. {
  214303. *destL++ = *src++ * g;
  214304. *destR++ = *src++ * g;
  214305. }
  214306. src = (const short*)lpbuf2;
  214307. while (--samples2 >= 0)
  214308. {
  214309. *destL++ = *src++ * g;
  214310. *destR++ = *src++ * g;
  214311. }
  214312. }
  214313. }
  214314. else
  214315. {
  214316. jassertfalse;
  214317. }
  214318. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214319. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214320. }
  214321. else
  214322. {
  214323. logError (hr);
  214324. jassertfalse;
  214325. }
  214326. bytesFilled -= bytesPerBuffer;
  214327. return true;
  214328. }
  214329. else
  214330. {
  214331. return false;
  214332. }
  214333. }
  214334. unsigned int readOffset;
  214335. int bytesPerBuffer, totalBytesPerBuffer;
  214336. int bitDepth;
  214337. bool doneFlag;
  214338. private:
  214339. String name;
  214340. LPGUID guid;
  214341. int sampleRate, bufferSizeSamples;
  214342. float* leftBuffer;
  214343. float* rightBuffer;
  214344. IDirectSound* pDirectSound;
  214345. IDirectSoundCapture* pDirectSoundCapture;
  214346. IDirectSoundCaptureBuffer* pInputBuffer;
  214347. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214348. };
  214349. class DSoundAudioIODevice : public AudioIODevice,
  214350. public Thread
  214351. {
  214352. public:
  214353. DSoundAudioIODevice (const String& deviceName,
  214354. const int outputDeviceIndex_,
  214355. const int inputDeviceIndex_)
  214356. : AudioIODevice (deviceName, "DirectSound"),
  214357. Thread ("Juce DSound"),
  214358. isOpen_ (false),
  214359. isStarted (false),
  214360. outputDeviceIndex (outputDeviceIndex_),
  214361. inputDeviceIndex (inputDeviceIndex_),
  214362. totalSamplesOut (0),
  214363. sampleRate (0.0),
  214364. inputBuffers (1, 1),
  214365. outputBuffers (1, 1),
  214366. callback (0),
  214367. bufferSizeSamples (0)
  214368. {
  214369. if (outputDeviceIndex_ >= 0)
  214370. {
  214371. outChannels.add (TRANS("Left"));
  214372. outChannels.add (TRANS("Right"));
  214373. }
  214374. if (inputDeviceIndex_ >= 0)
  214375. {
  214376. inChannels.add (TRANS("Left"));
  214377. inChannels.add (TRANS("Right"));
  214378. }
  214379. }
  214380. ~DSoundAudioIODevice()
  214381. {
  214382. close();
  214383. }
  214384. const String open (const BigInteger& inputChannels,
  214385. const BigInteger& outputChannels,
  214386. double sampleRate, int bufferSizeSamples)
  214387. {
  214388. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214389. isOpen_ = lastError.isEmpty();
  214390. return lastError;
  214391. }
  214392. void close()
  214393. {
  214394. stop();
  214395. if (isOpen_)
  214396. {
  214397. closeDevice();
  214398. isOpen_ = false;
  214399. }
  214400. }
  214401. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214402. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214403. double getCurrentSampleRate() { return sampleRate; }
  214404. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214405. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214406. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214407. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214408. const StringArray getOutputChannelNames() { return outChannels; }
  214409. const StringArray getInputChannelNames() { return inChannels; }
  214410. int getNumSampleRates() { return 4; }
  214411. int getDefaultBufferSize() { return 2560; }
  214412. int getNumBufferSizesAvailable() { return 50; }
  214413. double getSampleRate (int index)
  214414. {
  214415. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214416. return samps [jlimit (0, 3, index)];
  214417. }
  214418. int getBufferSizeSamples (int index)
  214419. {
  214420. int n = 64;
  214421. for (int i = 0; i < index; ++i)
  214422. n += (n < 512) ? 32
  214423. : ((n < 1024) ? 64
  214424. : ((n < 2048) ? 128 : 256));
  214425. return n;
  214426. }
  214427. int getCurrentBitDepth()
  214428. {
  214429. int i, bits = 256;
  214430. for (i = inChans.size(); --i >= 0;)
  214431. bits = jmin (bits, inChans[i]->bitDepth);
  214432. for (i = outChans.size(); --i >= 0;)
  214433. bits = jmin (bits, outChans[i]->bitDepth);
  214434. if (bits > 32)
  214435. bits = 16;
  214436. return bits;
  214437. }
  214438. void start (AudioIODeviceCallback* call)
  214439. {
  214440. if (isOpen_ && call != 0 && ! isStarted)
  214441. {
  214442. if (! isThreadRunning())
  214443. {
  214444. // something gone wrong and the thread's stopped..
  214445. isOpen_ = false;
  214446. return;
  214447. }
  214448. call->audioDeviceAboutToStart (this);
  214449. const ScopedLock sl (startStopLock);
  214450. callback = call;
  214451. isStarted = true;
  214452. }
  214453. }
  214454. void stop()
  214455. {
  214456. if (isStarted)
  214457. {
  214458. AudioIODeviceCallback* const callbackLocal = callback;
  214459. {
  214460. const ScopedLock sl (startStopLock);
  214461. isStarted = false;
  214462. }
  214463. if (callbackLocal != 0)
  214464. callbackLocal->audioDeviceStopped();
  214465. }
  214466. }
  214467. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214468. const String getLastError() { return lastError; }
  214469. StringArray inChannels, outChannels;
  214470. int outputDeviceIndex, inputDeviceIndex;
  214471. private:
  214472. bool isOpen_;
  214473. bool isStarted;
  214474. String lastError;
  214475. OwnedArray <DSoundInternalInChannel> inChans;
  214476. OwnedArray <DSoundInternalOutChannel> outChans;
  214477. WaitableEvent startEvent;
  214478. int bufferSizeSamples;
  214479. int volatile totalSamplesOut;
  214480. int64 volatile lastBlockTime;
  214481. double sampleRate;
  214482. BigInteger enabledInputs, enabledOutputs;
  214483. AudioSampleBuffer inputBuffers, outputBuffers;
  214484. AudioIODeviceCallback* callback;
  214485. CriticalSection startStopLock;
  214486. const String openDevice (const BigInteger& inputChannels,
  214487. const BigInteger& outputChannels,
  214488. double sampleRate_, int bufferSizeSamples_);
  214489. void closeDevice()
  214490. {
  214491. isStarted = false;
  214492. stopThread (5000);
  214493. inChans.clear();
  214494. outChans.clear();
  214495. inputBuffers.setSize (1, 1);
  214496. outputBuffers.setSize (1, 1);
  214497. }
  214498. void resync()
  214499. {
  214500. if (! threadShouldExit())
  214501. {
  214502. sleep (5);
  214503. int i;
  214504. for (i = 0; i < outChans.size(); ++i)
  214505. outChans.getUnchecked(i)->synchronisePosition();
  214506. for (i = 0; i < inChans.size(); ++i)
  214507. inChans.getUnchecked(i)->synchronisePosition();
  214508. }
  214509. }
  214510. public:
  214511. void run()
  214512. {
  214513. while (! threadShouldExit())
  214514. {
  214515. if (wait (100))
  214516. break;
  214517. }
  214518. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214519. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214520. while (! threadShouldExit())
  214521. {
  214522. int numToDo = 0;
  214523. uint32 startTime = Time::getMillisecondCounter();
  214524. int i;
  214525. for (i = inChans.size(); --i >= 0;)
  214526. {
  214527. inChans.getUnchecked(i)->doneFlag = false;
  214528. ++numToDo;
  214529. }
  214530. for (i = outChans.size(); --i >= 0;)
  214531. {
  214532. outChans.getUnchecked(i)->doneFlag = false;
  214533. ++numToDo;
  214534. }
  214535. if (numToDo > 0)
  214536. {
  214537. const int maxCount = 3;
  214538. int count = maxCount;
  214539. for (;;)
  214540. {
  214541. for (i = inChans.size(); --i >= 0;)
  214542. {
  214543. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214544. if ((! in->doneFlag) && in->service())
  214545. {
  214546. in->doneFlag = true;
  214547. --numToDo;
  214548. }
  214549. }
  214550. for (i = outChans.size(); --i >= 0;)
  214551. {
  214552. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214553. if ((! out->doneFlag) && out->service())
  214554. {
  214555. out->doneFlag = true;
  214556. --numToDo;
  214557. }
  214558. }
  214559. if (numToDo <= 0)
  214560. break;
  214561. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214562. {
  214563. resync();
  214564. break;
  214565. }
  214566. if (--count <= 0)
  214567. {
  214568. Sleep (1);
  214569. count = maxCount;
  214570. }
  214571. if (threadShouldExit())
  214572. return;
  214573. }
  214574. }
  214575. else
  214576. {
  214577. sleep (1);
  214578. }
  214579. const ScopedLock sl (startStopLock);
  214580. if (isStarted)
  214581. {
  214582. JUCE_TRY
  214583. {
  214584. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214585. inputBuffers.getNumChannels(),
  214586. outputBuffers.getArrayOfChannels(),
  214587. outputBuffers.getNumChannels(),
  214588. bufferSizeSamples);
  214589. }
  214590. JUCE_CATCH_EXCEPTION
  214591. totalSamplesOut += bufferSizeSamples;
  214592. }
  214593. else
  214594. {
  214595. outputBuffers.clear();
  214596. totalSamplesOut = 0;
  214597. sleep (1);
  214598. }
  214599. }
  214600. }
  214601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214602. };
  214603. class DSoundAudioIODeviceType : public AudioIODeviceType
  214604. {
  214605. public:
  214606. DSoundAudioIODeviceType()
  214607. : AudioIODeviceType ("DirectSound"),
  214608. hasScanned (false)
  214609. {
  214610. initialiseDSoundFunctions();
  214611. }
  214612. void scanForDevices()
  214613. {
  214614. hasScanned = true;
  214615. outputDeviceNames.clear();
  214616. outputGuids.clear();
  214617. inputDeviceNames.clear();
  214618. inputGuids.clear();
  214619. if (dsDirectSoundEnumerateW != 0)
  214620. {
  214621. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214622. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214623. }
  214624. }
  214625. const StringArray getDeviceNames (bool wantInputNames) const
  214626. {
  214627. jassert (hasScanned); // need to call scanForDevices() before doing this
  214628. return wantInputNames ? inputDeviceNames
  214629. : outputDeviceNames;
  214630. }
  214631. int getDefaultDeviceIndex (bool /*forInput*/) const
  214632. {
  214633. jassert (hasScanned); // need to call scanForDevices() before doing this
  214634. return 0;
  214635. }
  214636. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214637. {
  214638. jassert (hasScanned); // need to call scanForDevices() before doing this
  214639. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214640. if (d == 0)
  214641. return -1;
  214642. return asInput ? d->inputDeviceIndex
  214643. : d->outputDeviceIndex;
  214644. }
  214645. bool hasSeparateInputsAndOutputs() const { return true; }
  214646. AudioIODevice* createDevice (const String& outputDeviceName,
  214647. const String& inputDeviceName)
  214648. {
  214649. jassert (hasScanned); // need to call scanForDevices() before doing this
  214650. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214651. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214652. if (outputIndex >= 0 || inputIndex >= 0)
  214653. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214654. : inputDeviceName,
  214655. outputIndex, inputIndex);
  214656. return 0;
  214657. }
  214658. StringArray outputDeviceNames, inputDeviceNames;
  214659. OwnedArray <GUID> outputGuids, inputGuids;
  214660. private:
  214661. bool hasScanned;
  214662. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214663. {
  214664. desc = desc.trim();
  214665. if (desc.isNotEmpty())
  214666. {
  214667. const String origDesc (desc);
  214668. int n = 2;
  214669. while (outputDeviceNames.contains (desc))
  214670. desc = origDesc + " (" + String (n++) + ")";
  214671. outputDeviceNames.add (desc);
  214672. if (lpGUID != 0)
  214673. outputGuids.add (new GUID (*lpGUID));
  214674. else
  214675. outputGuids.add (0);
  214676. }
  214677. return TRUE;
  214678. }
  214679. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214680. {
  214681. return ((DSoundAudioIODeviceType*) object)
  214682. ->outputEnumProc (lpGUID, String (description));
  214683. }
  214684. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214685. {
  214686. return ((DSoundAudioIODeviceType*) object)
  214687. ->outputEnumProc (lpGUID, String (description));
  214688. }
  214689. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214690. {
  214691. desc = desc.trim();
  214692. if (desc.isNotEmpty())
  214693. {
  214694. const String origDesc (desc);
  214695. int n = 2;
  214696. while (inputDeviceNames.contains (desc))
  214697. desc = origDesc + " (" + String (n++) + ")";
  214698. inputDeviceNames.add (desc);
  214699. if (lpGUID != 0)
  214700. inputGuids.add (new GUID (*lpGUID));
  214701. else
  214702. inputGuids.add (0);
  214703. }
  214704. return TRUE;
  214705. }
  214706. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214707. {
  214708. return ((DSoundAudioIODeviceType*) object)
  214709. ->inputEnumProc (lpGUID, String (description));
  214710. }
  214711. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214712. {
  214713. return ((DSoundAudioIODeviceType*) object)
  214714. ->inputEnumProc (lpGUID, String (description));
  214715. }
  214716. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214717. };
  214718. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214719. const BigInteger& outputChannels,
  214720. double sampleRate_, int bufferSizeSamples_)
  214721. {
  214722. closeDevice();
  214723. totalSamplesOut = 0;
  214724. sampleRate = sampleRate_;
  214725. if (bufferSizeSamples_ <= 0)
  214726. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214727. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214728. DSoundAudioIODeviceType dlh;
  214729. dlh.scanForDevices();
  214730. enabledInputs = inputChannels;
  214731. enabledInputs.setRange (inChannels.size(),
  214732. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214733. false);
  214734. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214735. inputBuffers.clear();
  214736. int i, numIns = 0;
  214737. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214738. {
  214739. float* left = 0;
  214740. if (enabledInputs[i])
  214741. left = inputBuffers.getSampleData (numIns++);
  214742. float* right = 0;
  214743. if (enabledInputs[i + 1])
  214744. right = inputBuffers.getSampleData (numIns++);
  214745. if (left != 0 || right != 0)
  214746. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214747. dlh.inputGuids [inputDeviceIndex],
  214748. (int) sampleRate, bufferSizeSamples,
  214749. left, right));
  214750. }
  214751. enabledOutputs = outputChannels;
  214752. enabledOutputs.setRange (outChannels.size(),
  214753. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214754. false);
  214755. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214756. outputBuffers.clear();
  214757. int numOuts = 0;
  214758. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214759. {
  214760. float* left = 0;
  214761. if (enabledOutputs[i])
  214762. left = outputBuffers.getSampleData (numOuts++);
  214763. float* right = 0;
  214764. if (enabledOutputs[i + 1])
  214765. right = outputBuffers.getSampleData (numOuts++);
  214766. if (left != 0 || right != 0)
  214767. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214768. dlh.outputGuids [outputDeviceIndex],
  214769. (int) sampleRate, bufferSizeSamples,
  214770. left, right));
  214771. }
  214772. String error;
  214773. // boost our priority while opening the devices to try to get better sync between them
  214774. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214775. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214776. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214777. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214778. for (i = 0; i < outChans.size(); ++i)
  214779. {
  214780. error = outChans[i]->open();
  214781. if (error.isNotEmpty())
  214782. {
  214783. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214784. break;
  214785. }
  214786. }
  214787. if (error.isEmpty())
  214788. {
  214789. for (i = 0; i < inChans.size(); ++i)
  214790. {
  214791. error = inChans[i]->open();
  214792. if (error.isNotEmpty())
  214793. {
  214794. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214795. break;
  214796. }
  214797. }
  214798. }
  214799. if (error.isEmpty())
  214800. {
  214801. totalSamplesOut = 0;
  214802. for (i = 0; i < outChans.size(); ++i)
  214803. outChans.getUnchecked(i)->synchronisePosition();
  214804. for (i = 0; i < inChans.size(); ++i)
  214805. inChans.getUnchecked(i)->synchronisePosition();
  214806. startThread (9);
  214807. sleep (10);
  214808. notify();
  214809. }
  214810. else
  214811. {
  214812. log (error);
  214813. }
  214814. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214815. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214816. return error;
  214817. }
  214818. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214819. {
  214820. return new DSoundAudioIODeviceType();
  214821. }
  214822. #undef log
  214823. #endif
  214824. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214825. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214826. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214827. // compiled on its own).
  214828. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214829. #ifndef WASAPI_ENABLE_LOGGING
  214830. #define WASAPI_ENABLE_LOGGING 0
  214831. #endif
  214832. namespace WasapiClasses
  214833. {
  214834. void logFailure (HRESULT hr)
  214835. {
  214836. (void) hr;
  214837. #if WASAPI_ENABLE_LOGGING
  214838. if (FAILED (hr))
  214839. {
  214840. String e;
  214841. e << Time::getCurrentTime().toString (true, true, true, true)
  214842. << " -- WASAPI error: ";
  214843. switch (hr)
  214844. {
  214845. case E_POINTER: e << "E_POINTER"; break;
  214846. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214847. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214848. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214849. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214850. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214851. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214852. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214853. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214854. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214855. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214856. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214857. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214858. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214859. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214860. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214861. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214862. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214863. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214864. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214865. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214866. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214867. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214868. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214869. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214870. default: e << String::toHexString ((int) hr); break;
  214871. }
  214872. DBG (e);
  214873. jassertfalse;
  214874. }
  214875. #endif
  214876. }
  214877. #undef check
  214878. bool check (HRESULT hr)
  214879. {
  214880. logFailure (hr);
  214881. return SUCCEEDED (hr);
  214882. }
  214883. const String getDeviceID (IMMDevice* const device)
  214884. {
  214885. String s;
  214886. WCHAR* deviceId = 0;
  214887. if (check (device->GetId (&deviceId)))
  214888. {
  214889. s = String (deviceId);
  214890. CoTaskMemFree (deviceId);
  214891. }
  214892. return s;
  214893. }
  214894. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214895. {
  214896. EDataFlow flow = eRender;
  214897. ComSmartPtr <IMMEndpoint> endPoint;
  214898. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214899. (void) check (endPoint->GetDataFlow (&flow));
  214900. return flow;
  214901. }
  214902. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214903. {
  214904. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214905. }
  214906. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214907. {
  214908. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214909. : sizeof (WAVEFORMATEX));
  214910. }
  214911. class WASAPIDeviceBase
  214912. {
  214913. public:
  214914. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214915. : device (device_),
  214916. sampleRate (0),
  214917. numChannels (0),
  214918. actualNumChannels (0),
  214919. defaultSampleRate (0),
  214920. minBufferSize (0),
  214921. defaultBufferSize (0),
  214922. latencySamples (0),
  214923. useExclusiveMode (useExclusiveMode_)
  214924. {
  214925. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214926. ComSmartPtr <IAudioClient> tempClient (createClient());
  214927. if (tempClient == 0)
  214928. return;
  214929. REFERENCE_TIME defaultPeriod, minPeriod;
  214930. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214931. return;
  214932. WAVEFORMATEX* mixFormat = 0;
  214933. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214934. return;
  214935. WAVEFORMATEXTENSIBLE format;
  214936. copyWavFormat (format, mixFormat);
  214937. CoTaskMemFree (mixFormat);
  214938. actualNumChannels = numChannels = format.Format.nChannels;
  214939. defaultSampleRate = format.Format.nSamplesPerSec;
  214940. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214941. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214942. rates.addUsingDefaultSort (defaultSampleRate);
  214943. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214944. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214945. {
  214946. if (ratesToTest[i] == defaultSampleRate)
  214947. continue;
  214948. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214949. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214950. (WAVEFORMATEX*) &format, 0)))
  214951. if (! rates.contains (ratesToTest[i]))
  214952. rates.addUsingDefaultSort (ratesToTest[i]);
  214953. }
  214954. }
  214955. ~WASAPIDeviceBase()
  214956. {
  214957. device = 0;
  214958. CloseHandle (clientEvent);
  214959. }
  214960. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214961. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214962. {
  214963. sampleRate = newSampleRate;
  214964. channels = newChannels;
  214965. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214966. numChannels = channels.getHighestBit() + 1;
  214967. if (numChannels == 0)
  214968. return true;
  214969. client = createClient();
  214970. if (client != 0
  214971. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214972. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214973. {
  214974. channelMaps.clear();
  214975. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214976. if (channels[i])
  214977. channelMaps.add (i);
  214978. REFERENCE_TIME latency;
  214979. if (check (client->GetStreamLatency (&latency)))
  214980. latencySamples = refTimeToSamples (latency, sampleRate);
  214981. (void) check (client->GetBufferSize (&actualBufferSize));
  214982. return check (client->SetEventHandle (clientEvent));
  214983. }
  214984. return false;
  214985. }
  214986. void closeClient()
  214987. {
  214988. if (client != 0)
  214989. client->Stop();
  214990. client = 0;
  214991. ResetEvent (clientEvent);
  214992. }
  214993. ComSmartPtr <IMMDevice> device;
  214994. ComSmartPtr <IAudioClient> client;
  214995. double sampleRate, defaultSampleRate;
  214996. int numChannels, actualNumChannels;
  214997. int minBufferSize, defaultBufferSize, latencySamples;
  214998. const bool useExclusiveMode;
  214999. Array <double> rates;
  215000. HANDLE clientEvent;
  215001. BigInteger channels;
  215002. Array <int> channelMaps;
  215003. UINT32 actualBufferSize;
  215004. int bytesPerSample;
  215005. virtual void updateFormat (bool isFloat) = 0;
  215006. private:
  215007. const ComSmartPtr <IAudioClient> createClient()
  215008. {
  215009. ComSmartPtr <IAudioClient> client;
  215010. if (device != 0)
  215011. {
  215012. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215013. logFailure (hr);
  215014. }
  215015. return client;
  215016. }
  215017. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215018. {
  215019. WAVEFORMATEXTENSIBLE format;
  215020. zerostruct (format);
  215021. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215022. {
  215023. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215024. }
  215025. else
  215026. {
  215027. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215028. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215029. }
  215030. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215031. format.Format.nChannels = (WORD) numChannels;
  215032. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215033. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215034. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215035. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215036. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215037. switch (numChannels)
  215038. {
  215039. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215040. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215041. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215042. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215043. 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;
  215044. default: break;
  215045. }
  215046. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215047. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215048. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215049. logFailure (hr);
  215050. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215051. {
  215052. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215053. hr = S_OK;
  215054. }
  215055. CoTaskMemFree (nearestFormat);
  215056. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215057. if (useExclusiveMode)
  215058. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215059. GUID session;
  215060. if (hr == S_OK
  215061. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215062. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215063. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215064. {
  215065. actualNumChannels = format.Format.nChannels;
  215066. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215067. bytesPerSample = format.Format.wBitsPerSample / 8;
  215068. updateFormat (isFloat);
  215069. return true;
  215070. }
  215071. return false;
  215072. }
  215073. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215074. };
  215075. class WASAPIInputDevice : public WASAPIDeviceBase
  215076. {
  215077. public:
  215078. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215079. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215080. reservoir (1, 1)
  215081. {
  215082. }
  215083. ~WASAPIInputDevice()
  215084. {
  215085. close();
  215086. }
  215087. bool open (const double newSampleRate, const BigInteger& newChannels)
  215088. {
  215089. reservoirSize = 0;
  215090. reservoirCapacity = 16384;
  215091. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215092. return openClient (newSampleRate, newChannels)
  215093. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215094. (void**) captureClient.resetAndGetPointerAddress())));
  215095. }
  215096. void close()
  215097. {
  215098. closeClient();
  215099. captureClient = 0;
  215100. reservoir.setSize (0);
  215101. }
  215102. template <class SourceType>
  215103. void updateFormatWithType (SourceType*)
  215104. {
  215105. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215106. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215107. }
  215108. void updateFormat (bool isFloat)
  215109. {
  215110. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215111. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215112. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215113. else updateFormatWithType ((AudioData::Int16*) 0);
  215114. }
  215115. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215116. {
  215117. if (numChannels <= 0)
  215118. return;
  215119. int offset = 0;
  215120. while (bufferSize > 0)
  215121. {
  215122. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215123. {
  215124. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215125. for (int i = 0; i < numDestBuffers; ++i)
  215126. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215127. bufferSize -= samplesToDo;
  215128. offset += samplesToDo;
  215129. reservoirSize = 0;
  215130. }
  215131. else
  215132. {
  215133. UINT32 packetLength = 0;
  215134. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215135. break;
  215136. if (packetLength == 0)
  215137. {
  215138. if (thread.threadShouldExit()
  215139. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215140. break;
  215141. continue;
  215142. }
  215143. uint8* inputData;
  215144. UINT32 numSamplesAvailable;
  215145. DWORD flags;
  215146. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215147. {
  215148. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215149. for (int i = 0; i < numDestBuffers; ++i)
  215150. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215151. bufferSize -= samplesToDo;
  215152. offset += samplesToDo;
  215153. if (samplesToDo < (int) numSamplesAvailable)
  215154. {
  215155. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215156. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215157. bytesPerSample * actualNumChannels * reservoirSize);
  215158. }
  215159. captureClient->ReleaseBuffer (numSamplesAvailable);
  215160. }
  215161. }
  215162. }
  215163. }
  215164. ComSmartPtr <IAudioCaptureClient> captureClient;
  215165. MemoryBlock reservoir;
  215166. int reservoirSize, reservoirCapacity;
  215167. ScopedPointer <AudioData::Converter> converter;
  215168. private:
  215169. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215170. };
  215171. class WASAPIOutputDevice : public WASAPIDeviceBase
  215172. {
  215173. public:
  215174. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215175. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215176. {
  215177. }
  215178. ~WASAPIOutputDevice()
  215179. {
  215180. close();
  215181. }
  215182. bool open (const double newSampleRate, const BigInteger& newChannels)
  215183. {
  215184. return openClient (newSampleRate, newChannels)
  215185. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215186. }
  215187. void close()
  215188. {
  215189. closeClient();
  215190. renderClient = 0;
  215191. }
  215192. template <class DestType>
  215193. void updateFormatWithType (DestType*)
  215194. {
  215195. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215196. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215197. }
  215198. void updateFormat (bool isFloat)
  215199. {
  215200. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215201. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215202. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215203. else updateFormatWithType ((AudioData::Int16*) 0);
  215204. }
  215205. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215206. {
  215207. if (numChannels <= 0)
  215208. return;
  215209. int offset = 0;
  215210. while (bufferSize > 0)
  215211. {
  215212. UINT32 padding = 0;
  215213. if (! check (client->GetCurrentPadding (&padding)))
  215214. return;
  215215. int samplesToDo = useExclusiveMode ? bufferSize
  215216. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215217. if (samplesToDo <= 0)
  215218. {
  215219. if (thread.threadShouldExit()
  215220. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215221. break;
  215222. continue;
  215223. }
  215224. uint8* outputData = 0;
  215225. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215226. {
  215227. for (int i = 0; i < numSrcBuffers; ++i)
  215228. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215229. renderClient->ReleaseBuffer (samplesToDo, 0);
  215230. offset += samplesToDo;
  215231. bufferSize -= samplesToDo;
  215232. }
  215233. }
  215234. }
  215235. ComSmartPtr <IAudioRenderClient> renderClient;
  215236. ScopedPointer <AudioData::Converter> converter;
  215237. private:
  215238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215239. };
  215240. class WASAPIAudioIODevice : public AudioIODevice,
  215241. public Thread
  215242. {
  215243. public:
  215244. WASAPIAudioIODevice (const String& deviceName,
  215245. const String& outputDeviceId_,
  215246. const String& inputDeviceId_,
  215247. const bool useExclusiveMode_)
  215248. : AudioIODevice (deviceName, "Windows Audio"),
  215249. Thread ("Juce WASAPI"),
  215250. isOpen_ (false),
  215251. isStarted (false),
  215252. outputDeviceId (outputDeviceId_),
  215253. inputDeviceId (inputDeviceId_),
  215254. useExclusiveMode (useExclusiveMode_),
  215255. currentBufferSizeSamples (0),
  215256. currentSampleRate (0),
  215257. callback (0)
  215258. {
  215259. }
  215260. ~WASAPIAudioIODevice()
  215261. {
  215262. close();
  215263. }
  215264. bool initialise()
  215265. {
  215266. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215267. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215268. latencyIn = latencyOut = 0;
  215269. Array <double> ratesIn, ratesOut;
  215270. if (createDevices())
  215271. {
  215272. jassert (inputDevice != 0 || outputDevice != 0);
  215273. if (inputDevice != 0 && outputDevice != 0)
  215274. {
  215275. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215276. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215277. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215278. sampleRates = inputDevice->rates;
  215279. sampleRates.removeValuesNotIn (outputDevice->rates);
  215280. }
  215281. else
  215282. {
  215283. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215284. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215285. defaultSampleRate = d->defaultSampleRate;
  215286. minBufferSize = d->minBufferSize;
  215287. defaultBufferSize = d->defaultBufferSize;
  215288. sampleRates = d->rates;
  215289. }
  215290. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215291. if (minBufferSize != defaultBufferSize)
  215292. bufferSizes.addUsingDefaultSort (minBufferSize);
  215293. int n = 64;
  215294. for (int i = 0; i < 40; ++i)
  215295. {
  215296. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215297. bufferSizes.addUsingDefaultSort (n);
  215298. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215299. }
  215300. return true;
  215301. }
  215302. return false;
  215303. }
  215304. const StringArray getOutputChannelNames()
  215305. {
  215306. StringArray outChannels;
  215307. if (outputDevice != 0)
  215308. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215309. outChannels.add ("Output channel " + String (i));
  215310. return outChannels;
  215311. }
  215312. const StringArray getInputChannelNames()
  215313. {
  215314. StringArray inChannels;
  215315. if (inputDevice != 0)
  215316. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215317. inChannels.add ("Input channel " + String (i));
  215318. return inChannels;
  215319. }
  215320. int getNumSampleRates() { return sampleRates.size(); }
  215321. double getSampleRate (int index) { return sampleRates [index]; }
  215322. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215323. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215324. int getDefaultBufferSize() { return defaultBufferSize; }
  215325. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215326. double getCurrentSampleRate() { return currentSampleRate; }
  215327. int getCurrentBitDepth() { return 32; }
  215328. int getOutputLatencyInSamples() { return latencyOut; }
  215329. int getInputLatencyInSamples() { return latencyIn; }
  215330. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215331. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215332. const String getLastError() { return lastError; }
  215333. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215334. double sampleRate, int bufferSizeSamples)
  215335. {
  215336. close();
  215337. lastError = String::empty;
  215338. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215339. {
  215340. lastError = "The input and output devices don't share a common sample rate!";
  215341. return lastError;
  215342. }
  215343. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215344. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215345. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215346. {
  215347. lastError = "Couldn't open the input device!";
  215348. return lastError;
  215349. }
  215350. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215351. {
  215352. close();
  215353. lastError = "Couldn't open the output device!";
  215354. return lastError;
  215355. }
  215356. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215357. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215358. startThread (8);
  215359. Thread::sleep (5);
  215360. if (inputDevice != 0 && inputDevice->client != 0)
  215361. {
  215362. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215363. HRESULT hr = inputDevice->client->Start();
  215364. logFailure (hr); //xxx handle this
  215365. }
  215366. if (outputDevice != 0 && outputDevice->client != 0)
  215367. {
  215368. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215369. HRESULT hr = outputDevice->client->Start();
  215370. logFailure (hr); //xxx handle this
  215371. }
  215372. isOpen_ = true;
  215373. return lastError;
  215374. }
  215375. void close()
  215376. {
  215377. stop();
  215378. signalThreadShouldExit();
  215379. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215380. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215381. stopThread (5000);
  215382. if (inputDevice != 0) inputDevice->close();
  215383. if (outputDevice != 0) outputDevice->close();
  215384. isOpen_ = false;
  215385. }
  215386. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215387. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215388. void start (AudioIODeviceCallback* call)
  215389. {
  215390. if (isOpen_ && call != 0 && ! isStarted)
  215391. {
  215392. if (! isThreadRunning())
  215393. {
  215394. // something's gone wrong and the thread's stopped..
  215395. isOpen_ = false;
  215396. return;
  215397. }
  215398. call->audioDeviceAboutToStart (this);
  215399. const ScopedLock sl (startStopLock);
  215400. callback = call;
  215401. isStarted = true;
  215402. }
  215403. }
  215404. void stop()
  215405. {
  215406. if (isStarted)
  215407. {
  215408. AudioIODeviceCallback* const callbackLocal = callback;
  215409. {
  215410. const ScopedLock sl (startStopLock);
  215411. isStarted = false;
  215412. }
  215413. if (callbackLocal != 0)
  215414. callbackLocal->audioDeviceStopped();
  215415. }
  215416. }
  215417. void setMMThreadPriority()
  215418. {
  215419. DynamicLibraryLoader dll ("avrt.dll");
  215420. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215421. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215422. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215423. {
  215424. DWORD dummy = 0;
  215425. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215426. if (h != 0)
  215427. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215428. }
  215429. }
  215430. void run()
  215431. {
  215432. setMMThreadPriority();
  215433. const int bufferSize = currentBufferSizeSamples;
  215434. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215435. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215436. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215437. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215438. float** const inputBuffers = ins.getArrayOfChannels();
  215439. float** const outputBuffers = outs.getArrayOfChannels();
  215440. ins.clear();
  215441. while (! threadShouldExit())
  215442. {
  215443. if (inputDevice != 0)
  215444. {
  215445. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215446. if (threadShouldExit())
  215447. break;
  215448. }
  215449. JUCE_TRY
  215450. {
  215451. const ScopedLock sl (startStopLock);
  215452. if (isStarted)
  215453. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215454. outputBuffers, numOutputBuffers, bufferSize);
  215455. else
  215456. outs.clear();
  215457. }
  215458. JUCE_CATCH_EXCEPTION
  215459. if (outputDevice != 0)
  215460. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215461. }
  215462. }
  215463. String outputDeviceId, inputDeviceId;
  215464. String lastError;
  215465. private:
  215466. // Device stats...
  215467. ScopedPointer<WASAPIInputDevice> inputDevice;
  215468. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215469. const bool useExclusiveMode;
  215470. double defaultSampleRate;
  215471. int minBufferSize, defaultBufferSize;
  215472. int latencyIn, latencyOut;
  215473. Array <double> sampleRates;
  215474. Array <int> bufferSizes;
  215475. // Active state...
  215476. bool isOpen_, isStarted;
  215477. int currentBufferSizeSamples;
  215478. double currentSampleRate;
  215479. AudioIODeviceCallback* callback;
  215480. CriticalSection startStopLock;
  215481. bool createDevices()
  215482. {
  215483. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215484. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215485. return false;
  215486. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215487. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215488. return false;
  215489. UINT32 numDevices = 0;
  215490. if (! check (deviceCollection->GetCount (&numDevices)))
  215491. return false;
  215492. for (UINT32 i = 0; i < numDevices; ++i)
  215493. {
  215494. ComSmartPtr <IMMDevice> device;
  215495. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215496. continue;
  215497. const String deviceId (getDeviceID (device));
  215498. if (deviceId.isEmpty())
  215499. continue;
  215500. const EDataFlow flow = getDataFlow (device);
  215501. if (deviceId == inputDeviceId && flow == eCapture)
  215502. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215503. else if (deviceId == outputDeviceId && flow == eRender)
  215504. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215505. }
  215506. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215507. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215508. }
  215509. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215510. };
  215511. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215512. {
  215513. public:
  215514. WASAPIAudioIODeviceType()
  215515. : AudioIODeviceType ("Windows Audio"),
  215516. hasScanned (false)
  215517. {
  215518. }
  215519. ~WASAPIAudioIODeviceType()
  215520. {
  215521. }
  215522. void scanForDevices()
  215523. {
  215524. hasScanned = true;
  215525. outputDeviceNames.clear();
  215526. inputDeviceNames.clear();
  215527. outputDeviceIds.clear();
  215528. inputDeviceIds.clear();
  215529. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215530. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215531. return;
  215532. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215533. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215534. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215535. UINT32 numDevices = 0;
  215536. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215537. && check (deviceCollection->GetCount (&numDevices))))
  215538. return;
  215539. for (UINT32 i = 0; i < numDevices; ++i)
  215540. {
  215541. ComSmartPtr <IMMDevice> device;
  215542. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215543. continue;
  215544. const String deviceId (getDeviceID (device));
  215545. DWORD state = 0;
  215546. if (! check (device->GetState (&state)))
  215547. continue;
  215548. if (state != DEVICE_STATE_ACTIVE)
  215549. continue;
  215550. String name;
  215551. {
  215552. ComSmartPtr <IPropertyStore> properties;
  215553. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215554. continue;
  215555. PROPVARIANT value;
  215556. PropVariantInit (&value);
  215557. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215558. name = value.pwszVal;
  215559. PropVariantClear (&value);
  215560. }
  215561. const EDataFlow flow = getDataFlow (device);
  215562. if (flow == eRender)
  215563. {
  215564. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215565. outputDeviceIds.insert (index, deviceId);
  215566. outputDeviceNames.insert (index, name);
  215567. }
  215568. else if (flow == eCapture)
  215569. {
  215570. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215571. inputDeviceIds.insert (index, deviceId);
  215572. inputDeviceNames.insert (index, name);
  215573. }
  215574. }
  215575. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215576. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215577. }
  215578. const StringArray getDeviceNames (bool wantInputNames) const
  215579. {
  215580. jassert (hasScanned); // need to call scanForDevices() before doing this
  215581. return wantInputNames ? inputDeviceNames
  215582. : outputDeviceNames;
  215583. }
  215584. int getDefaultDeviceIndex (bool /*forInput*/) const
  215585. {
  215586. jassert (hasScanned); // need to call scanForDevices() before doing this
  215587. return 0;
  215588. }
  215589. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215590. {
  215591. jassert (hasScanned); // need to call scanForDevices() before doing this
  215592. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215593. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215594. : outputDeviceIds.indexOf (d->outputDeviceId));
  215595. }
  215596. bool hasSeparateInputsAndOutputs() const { return true; }
  215597. AudioIODevice* createDevice (const String& outputDeviceName,
  215598. const String& inputDeviceName)
  215599. {
  215600. jassert (hasScanned); // need to call scanForDevices() before doing this
  215601. const bool useExclusiveMode = false;
  215602. ScopedPointer<WASAPIAudioIODevice> device;
  215603. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215604. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215605. if (outputIndex >= 0 || inputIndex >= 0)
  215606. {
  215607. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215608. : inputDeviceName,
  215609. outputDeviceIds [outputIndex],
  215610. inputDeviceIds [inputIndex],
  215611. useExclusiveMode);
  215612. if (! device->initialise())
  215613. device = 0;
  215614. }
  215615. return device.release();
  215616. }
  215617. StringArray outputDeviceNames, outputDeviceIds;
  215618. StringArray inputDeviceNames, inputDeviceIds;
  215619. private:
  215620. bool hasScanned;
  215621. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215622. {
  215623. String s;
  215624. IMMDevice* dev = 0;
  215625. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215626. eMultimedia, &dev)))
  215627. {
  215628. WCHAR* deviceId = 0;
  215629. if (check (dev->GetId (&deviceId)))
  215630. {
  215631. s = String (deviceId);
  215632. CoTaskMemFree (deviceId);
  215633. }
  215634. dev->Release();
  215635. }
  215636. return s;
  215637. }
  215638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215639. };
  215640. }
  215641. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215642. {
  215643. return new WasapiClasses::WASAPIAudioIODeviceType();
  215644. }
  215645. #endif
  215646. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215647. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215648. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215649. // compiled on its own).
  215650. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215651. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215652. {
  215653. public:
  215654. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215655. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215656. const ComSmartPtr <IBaseFilter>& filter_,
  215657. int minWidth, int minHeight,
  215658. int maxWidth, int maxHeight)
  215659. : owner (owner_),
  215660. captureGraphBuilder (captureGraphBuilder_),
  215661. filter (filter_),
  215662. ok (false),
  215663. imageNeedsFlipping (false),
  215664. width (0),
  215665. height (0),
  215666. activeUsers (0),
  215667. recordNextFrameTime (false),
  215668. previewMaxFPS (60)
  215669. {
  215670. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215671. if (FAILED (hr))
  215672. return;
  215673. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215674. if (FAILED (hr))
  215675. return;
  215676. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215677. if (FAILED (hr))
  215678. return;
  215679. {
  215680. ComSmartPtr <IAMStreamConfig> streamConfig;
  215681. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215682. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215683. if (streamConfig != 0)
  215684. {
  215685. getVideoSizes (streamConfig);
  215686. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215687. return;
  215688. }
  215689. }
  215690. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215691. if (FAILED (hr))
  215692. return;
  215693. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215694. if (FAILED (hr))
  215695. return;
  215696. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215697. if (FAILED (hr))
  215698. return;
  215699. if (! connectFilters (filter, smartTee))
  215700. return;
  215701. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215702. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215703. if (FAILED (hr))
  215704. return;
  215705. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215706. if (FAILED (hr))
  215707. return;
  215708. AM_MEDIA_TYPE mt;
  215709. zerostruct (mt);
  215710. mt.majortype = MEDIATYPE_Video;
  215711. mt.subtype = MEDIASUBTYPE_RGB24;
  215712. mt.formattype = FORMAT_VideoInfo;
  215713. sampleGrabber->SetMediaType (&mt);
  215714. callback = new GrabberCallback (*this);
  215715. hr = sampleGrabber->SetCallback (callback, 1);
  215716. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215717. if (FAILED (hr))
  215718. return;
  215719. ComSmartPtr <IPin> grabberInputPin;
  215720. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215721. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215722. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215723. return;
  215724. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215725. if (FAILED (hr))
  215726. return;
  215727. zerostruct (mt);
  215728. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215729. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215730. width = pVih->bmiHeader.biWidth;
  215731. height = pVih->bmiHeader.biHeight;
  215732. ComSmartPtr <IBaseFilter> nullFilter;
  215733. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215734. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215735. if (connectFilters (sampleGrabberBase, nullFilter)
  215736. && addGraphToRot())
  215737. {
  215738. activeImage = Image (Image::RGB, width, height, true);
  215739. loadingImage = Image (Image::RGB, width, height, true);
  215740. ok = true;
  215741. }
  215742. }
  215743. ~DShowCameraDeviceInteral()
  215744. {
  215745. if (mediaControl != 0)
  215746. mediaControl->Stop();
  215747. removeGraphFromRot();
  215748. for (int i = viewerComps.size(); --i >= 0;)
  215749. viewerComps.getUnchecked(i)->ownerDeleted();
  215750. callback = 0;
  215751. graphBuilder = 0;
  215752. sampleGrabber = 0;
  215753. mediaControl = 0;
  215754. filter = 0;
  215755. captureGraphBuilder = 0;
  215756. smartTee = 0;
  215757. smartTeePreviewOutputPin = 0;
  215758. smartTeeCaptureOutputPin = 0;
  215759. asfWriter = 0;
  215760. }
  215761. void addUser()
  215762. {
  215763. if (ok && activeUsers++ == 0)
  215764. mediaControl->Run();
  215765. }
  215766. void removeUser()
  215767. {
  215768. if (ok && --activeUsers == 0)
  215769. mediaControl->Stop();
  215770. }
  215771. int getPreviewMaxFPS() const
  215772. {
  215773. return previewMaxFPS;
  215774. }
  215775. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215776. {
  215777. if (recordNextFrameTime)
  215778. {
  215779. const double defaultCameraLatency = 0.1;
  215780. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215781. recordNextFrameTime = false;
  215782. ComSmartPtr <IPin> pin;
  215783. if (getPin (filter, PINDIR_OUTPUT, pin))
  215784. {
  215785. ComSmartPtr <IAMPushSource> pushSource;
  215786. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215787. if (pushSource != 0)
  215788. {
  215789. REFERENCE_TIME latency = 0;
  215790. hr = pushSource->GetLatency (&latency);
  215791. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215792. }
  215793. }
  215794. }
  215795. {
  215796. const int lineStride = width * 3;
  215797. const ScopedLock sl (imageSwapLock);
  215798. {
  215799. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215800. for (int i = 0; i < height; ++i)
  215801. memcpy (destData.getLinePointer ((height - 1) - i),
  215802. buffer + lineStride * i,
  215803. lineStride);
  215804. }
  215805. imageNeedsFlipping = true;
  215806. }
  215807. if (listeners.size() > 0)
  215808. callListeners (loadingImage);
  215809. sendChangeMessage();
  215810. }
  215811. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215812. {
  215813. if (imageNeedsFlipping)
  215814. {
  215815. const ScopedLock sl (imageSwapLock);
  215816. swapVariables (loadingImage, activeImage);
  215817. imageNeedsFlipping = false;
  215818. }
  215819. RectanglePlacement rp (RectanglePlacement::centred);
  215820. double dx = 0, dy = 0, dw = width, dh = height;
  215821. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215822. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215823. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215824. {
  215825. Graphics::ScopedSaveState ss (g);
  215826. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215827. g.fillAll (Colours::black);
  215828. }
  215829. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215830. }
  215831. bool createFileCaptureFilter (const File& file, int quality)
  215832. {
  215833. removeFileCaptureFilter();
  215834. file.deleteFile();
  215835. mediaControl->Stop();
  215836. firstRecordedTime = Time();
  215837. recordNextFrameTime = true;
  215838. previewMaxFPS = 60;
  215839. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215840. if (SUCCEEDED (hr))
  215841. {
  215842. ComSmartPtr <IFileSinkFilter> fileSink;
  215843. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215844. if (SUCCEEDED (hr))
  215845. {
  215846. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215847. if (SUCCEEDED (hr))
  215848. {
  215849. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215850. if (SUCCEEDED (hr))
  215851. {
  215852. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215853. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215854. asfConfig->SetIndexMode (true);
  215855. ComSmartPtr <IWMProfileManager> profileManager;
  215856. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215857. // This gibberish is the DirectShow profile for a video-only wmv file.
  215858. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215859. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215860. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215861. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215862. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215863. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215864. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215865. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215866. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215867. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215868. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215869. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215870. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215871. "</videoinfoheader>"
  215872. "</wmmediatype>"
  215873. "</streamconfig>"
  215874. "</profile>");
  215875. const int fps[] = { 10, 15, 30 };
  215876. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215877. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215878. maxFramesPerSecond = (quality >> 24) & 0xff;
  215879. prof = prof.replace ("$WIDTH", String (width))
  215880. .replace ("$HEIGHT", String (height))
  215881. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215882. ComSmartPtr <IWMProfile> currentProfile;
  215883. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  215884. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215885. if (SUCCEEDED (hr))
  215886. {
  215887. ComSmartPtr <IPin> asfWriterInputPin;
  215888. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215889. {
  215890. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215891. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215892. && SUCCEEDED (mediaControl->Run()))
  215893. {
  215894. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215895. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215896. previewMaxFPS = (quality >> 16) & 0xff;
  215897. return true;
  215898. }
  215899. }
  215900. }
  215901. }
  215902. }
  215903. }
  215904. }
  215905. removeFileCaptureFilter();
  215906. if (ok && activeUsers > 0)
  215907. mediaControl->Run();
  215908. return false;
  215909. }
  215910. void removeFileCaptureFilter()
  215911. {
  215912. mediaControl->Stop();
  215913. if (asfWriter != 0)
  215914. {
  215915. graphBuilder->RemoveFilter (asfWriter);
  215916. asfWriter = 0;
  215917. }
  215918. if (ok && activeUsers > 0)
  215919. mediaControl->Run();
  215920. previewMaxFPS = 60;
  215921. }
  215922. void addListener (CameraDevice::Listener* listenerToAdd)
  215923. {
  215924. const ScopedLock sl (listenerLock);
  215925. if (listeners.size() == 0)
  215926. addUser();
  215927. listeners.addIfNotAlreadyThere (listenerToAdd);
  215928. }
  215929. void removeListener (CameraDevice::Listener* listenerToRemove)
  215930. {
  215931. const ScopedLock sl (listenerLock);
  215932. listeners.removeValue (listenerToRemove);
  215933. if (listeners.size() == 0)
  215934. removeUser();
  215935. }
  215936. void callListeners (const Image& image)
  215937. {
  215938. const ScopedLock sl (listenerLock);
  215939. for (int i = listeners.size(); --i >= 0;)
  215940. {
  215941. CameraDevice::Listener* const l = listeners[i];
  215942. if (l != 0)
  215943. l->imageReceived (image);
  215944. }
  215945. }
  215946. class DShowCaptureViewerComp : public Component,
  215947. public ChangeListener
  215948. {
  215949. public:
  215950. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215951. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215952. {
  215953. setOpaque (true);
  215954. owner->addChangeListener (this);
  215955. owner->addUser();
  215956. owner->viewerComps.add (this);
  215957. setSize (owner->width, owner->height);
  215958. }
  215959. ~DShowCaptureViewerComp()
  215960. {
  215961. if (owner != 0)
  215962. {
  215963. owner->viewerComps.removeValue (this);
  215964. owner->removeUser();
  215965. owner->removeChangeListener (this);
  215966. }
  215967. }
  215968. void ownerDeleted()
  215969. {
  215970. owner = 0;
  215971. }
  215972. void paint (Graphics& g)
  215973. {
  215974. g.setColour (Colours::black);
  215975. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215976. if (owner != 0)
  215977. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215978. else
  215979. g.fillAll (Colours::black);
  215980. }
  215981. void changeListenerCallback (ChangeBroadcaster*)
  215982. {
  215983. const int64 now = Time::currentTimeMillis();
  215984. if (now >= lastRepaintTime + (1000 / maxFPS))
  215985. {
  215986. lastRepaintTime = now;
  215987. repaint();
  215988. if (owner != 0)
  215989. maxFPS = owner->getPreviewMaxFPS();
  215990. }
  215991. }
  215992. private:
  215993. DShowCameraDeviceInteral* owner;
  215994. int maxFPS;
  215995. int64 lastRepaintTime;
  215996. };
  215997. bool ok;
  215998. int width, height;
  215999. Time firstRecordedTime;
  216000. Array <DShowCaptureViewerComp*> viewerComps;
  216001. private:
  216002. CameraDevice* const owner;
  216003. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216004. ComSmartPtr <IBaseFilter> filter;
  216005. ComSmartPtr <IBaseFilter> smartTee;
  216006. ComSmartPtr <IGraphBuilder> graphBuilder;
  216007. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216008. ComSmartPtr <IMediaControl> mediaControl;
  216009. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216010. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216011. ComSmartPtr <IBaseFilter> asfWriter;
  216012. int activeUsers;
  216013. Array <int> widths, heights;
  216014. DWORD graphRegistrationID;
  216015. CriticalSection imageSwapLock;
  216016. bool imageNeedsFlipping;
  216017. Image loadingImage;
  216018. Image activeImage;
  216019. bool recordNextFrameTime;
  216020. int previewMaxFPS;
  216021. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216022. {
  216023. widths.clear();
  216024. heights.clear();
  216025. int count = 0, size = 0;
  216026. streamConfig->GetNumberOfCapabilities (&count, &size);
  216027. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216028. {
  216029. for (int i = 0; i < count; ++i)
  216030. {
  216031. VIDEO_STREAM_CONFIG_CAPS scc;
  216032. AM_MEDIA_TYPE* config;
  216033. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216034. if (SUCCEEDED (hr))
  216035. {
  216036. const int w = scc.InputSize.cx;
  216037. const int h = scc.InputSize.cy;
  216038. bool duplicate = false;
  216039. for (int j = widths.size(); --j >= 0;)
  216040. {
  216041. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216042. {
  216043. duplicate = true;
  216044. break;
  216045. }
  216046. }
  216047. if (! duplicate)
  216048. {
  216049. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216050. widths.add (w);
  216051. heights.add (h);
  216052. }
  216053. deleteMediaType (config);
  216054. }
  216055. }
  216056. }
  216057. }
  216058. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216059. const int minWidth, const int minHeight,
  216060. const int maxWidth, const int maxHeight)
  216061. {
  216062. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216063. streamConfig->GetNumberOfCapabilities (&count, &size);
  216064. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216065. {
  216066. AM_MEDIA_TYPE* config;
  216067. VIDEO_STREAM_CONFIG_CAPS scc;
  216068. for (int i = 0; i < count; ++i)
  216069. {
  216070. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216071. if (SUCCEEDED (hr))
  216072. {
  216073. if (scc.InputSize.cx >= minWidth
  216074. && scc.InputSize.cy >= minHeight
  216075. && scc.InputSize.cx <= maxWidth
  216076. && scc.InputSize.cy <= maxHeight)
  216077. {
  216078. int area = scc.InputSize.cx * scc.InputSize.cy;
  216079. if (area > bestArea)
  216080. {
  216081. bestIndex = i;
  216082. bestArea = area;
  216083. }
  216084. }
  216085. deleteMediaType (config);
  216086. }
  216087. }
  216088. if (bestIndex >= 0)
  216089. {
  216090. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216091. hr = streamConfig->SetFormat (config);
  216092. deleteMediaType (config);
  216093. return SUCCEEDED (hr);
  216094. }
  216095. }
  216096. return false;
  216097. }
  216098. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216099. {
  216100. ComSmartPtr <IEnumPins> enumerator;
  216101. ComSmartPtr <IPin> pin;
  216102. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216103. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216104. {
  216105. PIN_DIRECTION dir;
  216106. pin->QueryDirection (&dir);
  216107. if (wantedDirection == dir)
  216108. {
  216109. PIN_INFO info;
  216110. zerostruct (info);
  216111. pin->QueryPinInfo (&info);
  216112. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216113. {
  216114. result = pin;
  216115. return true;
  216116. }
  216117. }
  216118. }
  216119. return false;
  216120. }
  216121. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216122. {
  216123. ComSmartPtr <IPin> in, out;
  216124. return getPin (first, PINDIR_OUTPUT, out)
  216125. && getPin (second, PINDIR_INPUT, in)
  216126. && SUCCEEDED (graphBuilder->Connect (out, in));
  216127. }
  216128. bool addGraphToRot()
  216129. {
  216130. ComSmartPtr <IRunningObjectTable> rot;
  216131. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216132. return false;
  216133. ComSmartPtr <IMoniker> moniker;
  216134. WCHAR buffer[128];
  216135. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216136. if (FAILED (hr))
  216137. return false;
  216138. graphRegistrationID = 0;
  216139. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216140. }
  216141. void removeGraphFromRot()
  216142. {
  216143. ComSmartPtr <IRunningObjectTable> rot;
  216144. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216145. rot->Revoke (graphRegistrationID);
  216146. }
  216147. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216148. {
  216149. if (pmt->cbFormat != 0)
  216150. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216151. if (pmt->pUnk != 0)
  216152. pmt->pUnk->Release();
  216153. CoTaskMemFree (pmt);
  216154. }
  216155. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216156. {
  216157. public:
  216158. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216159. : owner (owner_)
  216160. {
  216161. }
  216162. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216163. {
  216164. return E_FAIL;
  216165. }
  216166. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216167. {
  216168. owner.handleFrame (time, buffer, bufferSize);
  216169. return S_OK;
  216170. }
  216171. private:
  216172. DShowCameraDeviceInteral& owner;
  216173. GrabberCallback (const GrabberCallback&);
  216174. GrabberCallback& operator= (const GrabberCallback&);
  216175. };
  216176. ComSmartPtr <GrabberCallback> callback;
  216177. Array <CameraDevice::Listener*> listeners;
  216178. CriticalSection listenerLock;
  216179. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216180. };
  216181. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216182. : name (name_)
  216183. {
  216184. isRecording = false;
  216185. }
  216186. CameraDevice::~CameraDevice()
  216187. {
  216188. stopRecording();
  216189. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216190. internal = 0;
  216191. }
  216192. Component* CameraDevice::createViewerComponent()
  216193. {
  216194. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216195. }
  216196. const String CameraDevice::getFileExtension()
  216197. {
  216198. return ".wmv";
  216199. }
  216200. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216201. {
  216202. stopRecording();
  216203. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216204. d->addUser();
  216205. isRecording = d->createFileCaptureFilter (file, quality);
  216206. }
  216207. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216208. {
  216209. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216210. return d->firstRecordedTime;
  216211. }
  216212. void CameraDevice::stopRecording()
  216213. {
  216214. if (isRecording)
  216215. {
  216216. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216217. d->removeFileCaptureFilter();
  216218. d->removeUser();
  216219. isRecording = false;
  216220. }
  216221. }
  216222. void CameraDevice::addListener (Listener* listenerToAdd)
  216223. {
  216224. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216225. if (listenerToAdd != 0)
  216226. d->addListener (listenerToAdd);
  216227. }
  216228. void CameraDevice::removeListener (Listener* listenerToRemove)
  216229. {
  216230. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216231. if (listenerToRemove != 0)
  216232. d->removeListener (listenerToRemove);
  216233. }
  216234. namespace
  216235. {
  216236. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216237. const int deviceIndexToOpen,
  216238. String& name)
  216239. {
  216240. int index = 0;
  216241. ComSmartPtr <IBaseFilter> result;
  216242. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216243. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216244. if (SUCCEEDED (hr))
  216245. {
  216246. ComSmartPtr <IEnumMoniker> enumerator;
  216247. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216248. if (SUCCEEDED (hr) && enumerator != 0)
  216249. {
  216250. ComSmartPtr <IMoniker> moniker;
  216251. ULONG fetched;
  216252. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216253. {
  216254. ComSmartPtr <IBaseFilter> captureFilter;
  216255. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216256. if (SUCCEEDED (hr))
  216257. {
  216258. ComSmartPtr <IPropertyBag> propertyBag;
  216259. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216260. if (SUCCEEDED (hr))
  216261. {
  216262. VARIANT var;
  216263. var.vt = VT_BSTR;
  216264. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216265. propertyBag = 0;
  216266. if (SUCCEEDED (hr))
  216267. {
  216268. if (names != 0)
  216269. names->add (var.bstrVal);
  216270. if (index == deviceIndexToOpen)
  216271. {
  216272. name = var.bstrVal;
  216273. result = captureFilter;
  216274. break;
  216275. }
  216276. ++index;
  216277. }
  216278. }
  216279. }
  216280. }
  216281. }
  216282. }
  216283. return result;
  216284. }
  216285. }
  216286. const StringArray CameraDevice::getAvailableDevices()
  216287. {
  216288. StringArray devs;
  216289. String dummy;
  216290. enumerateCameras (&devs, -1, dummy);
  216291. return devs;
  216292. }
  216293. CameraDevice* CameraDevice::openDevice (int index,
  216294. int minWidth, int minHeight,
  216295. int maxWidth, int maxHeight)
  216296. {
  216297. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216298. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216299. if (SUCCEEDED (hr))
  216300. {
  216301. String name;
  216302. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216303. if (filter != 0)
  216304. {
  216305. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216306. DShowCameraDeviceInteral* const intern
  216307. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216308. minWidth, minHeight, maxWidth, maxHeight);
  216309. cam->internal = intern;
  216310. if (intern->ok)
  216311. return cam.release();
  216312. }
  216313. }
  216314. return 0;
  216315. }
  216316. #endif
  216317. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216318. #endif
  216319. // Auto-link the other win32 libs that are needed by library calls..
  216320. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216321. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216322. // Auto-links to various win32 libs that are needed by library calls..
  216323. #pragma comment(lib, "kernel32.lib")
  216324. #pragma comment(lib, "user32.lib")
  216325. #pragma comment(lib, "shell32.lib")
  216326. #pragma comment(lib, "gdi32.lib")
  216327. #pragma comment(lib, "vfw32.lib")
  216328. #pragma comment(lib, "comdlg32.lib")
  216329. #pragma comment(lib, "winmm.lib")
  216330. #pragma comment(lib, "wininet.lib")
  216331. #pragma comment(lib, "ole32.lib")
  216332. #pragma comment(lib, "oleaut32.lib")
  216333. #pragma comment(lib, "advapi32.lib")
  216334. #pragma comment(lib, "ws2_32.lib")
  216335. #pragma comment(lib, "version.lib")
  216336. #ifdef _NATIVE_WCHAR_T_DEFINED
  216337. #ifdef _DEBUG
  216338. #pragma comment(lib, "comsuppwd.lib")
  216339. #else
  216340. #pragma comment(lib, "comsuppw.lib")
  216341. #endif
  216342. #else
  216343. #ifdef _DEBUG
  216344. #pragma comment(lib, "comsuppd.lib")
  216345. #else
  216346. #pragma comment(lib, "comsupp.lib")
  216347. #endif
  216348. #endif
  216349. #if JUCE_OPENGL
  216350. #pragma comment(lib, "OpenGL32.Lib")
  216351. #pragma comment(lib, "GlU32.Lib")
  216352. #endif
  216353. #if JUCE_QUICKTIME
  216354. #pragma comment (lib, "QTMLClient.lib")
  216355. #endif
  216356. #if JUCE_USE_CAMERA
  216357. #pragma comment (lib, "Strmiids.lib")
  216358. #pragma comment (lib, "wmvcore.lib")
  216359. #endif
  216360. #if JUCE_DIRECT2D
  216361. #pragma comment (lib, "Dwrite.lib")
  216362. #pragma comment (lib, "D2d1.lib")
  216363. #endif
  216364. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216365. #endif
  216366. END_JUCE_NAMESPACE
  216367. #endif
  216368. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216369. #endif
  216370. #if JUCE_LINUX
  216371. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216372. /*
  216373. This file wraps together all the mac-specific code, so that
  216374. we can include all the native headers just once, and compile all our
  216375. platform-specific stuff in one big lump, keeping it out of the way of
  216376. the rest of the codebase.
  216377. */
  216378. #if JUCE_LINUX
  216379. #undef JUCE_BUILD_NATIVE
  216380. #define JUCE_BUILD_NATIVE 1
  216381. BEGIN_JUCE_NAMESPACE
  216382. #define JUCE_INCLUDED_FILE 1
  216383. // Now include the actual code files..
  216384. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216385. /*
  216386. This file contains posix routines that are common to both the Linux and Mac builds.
  216387. It gets included directly in the cpp files for these platforms.
  216388. */
  216389. CriticalSection::CriticalSection() throw()
  216390. {
  216391. pthread_mutexattr_t atts;
  216392. pthread_mutexattr_init (&atts);
  216393. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216394. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216395. pthread_mutex_init (&internal, &atts);
  216396. }
  216397. CriticalSection::~CriticalSection() throw()
  216398. {
  216399. pthread_mutex_destroy (&internal);
  216400. }
  216401. void CriticalSection::enter() const throw()
  216402. {
  216403. pthread_mutex_lock (&internal);
  216404. }
  216405. bool CriticalSection::tryEnter() const throw()
  216406. {
  216407. return pthread_mutex_trylock (&internal) == 0;
  216408. }
  216409. void CriticalSection::exit() const throw()
  216410. {
  216411. pthread_mutex_unlock (&internal);
  216412. }
  216413. class WaitableEventImpl
  216414. {
  216415. public:
  216416. WaitableEventImpl (const bool manualReset_)
  216417. : triggered (false),
  216418. manualReset (manualReset_)
  216419. {
  216420. pthread_cond_init (&condition, 0);
  216421. pthread_mutexattr_t atts;
  216422. pthread_mutexattr_init (&atts);
  216423. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216424. pthread_mutex_init (&mutex, &atts);
  216425. }
  216426. ~WaitableEventImpl()
  216427. {
  216428. pthread_cond_destroy (&condition);
  216429. pthread_mutex_destroy (&mutex);
  216430. }
  216431. bool wait (const int timeOutMillisecs) throw()
  216432. {
  216433. pthread_mutex_lock (&mutex);
  216434. if (! triggered)
  216435. {
  216436. if (timeOutMillisecs < 0)
  216437. {
  216438. do
  216439. {
  216440. pthread_cond_wait (&condition, &mutex);
  216441. }
  216442. while (! triggered);
  216443. }
  216444. else
  216445. {
  216446. struct timeval now;
  216447. gettimeofday (&now, 0);
  216448. struct timespec time;
  216449. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216450. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216451. if (time.tv_nsec >= 1000000000)
  216452. {
  216453. time.tv_nsec -= 1000000000;
  216454. time.tv_sec++;
  216455. }
  216456. do
  216457. {
  216458. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216459. {
  216460. pthread_mutex_unlock (&mutex);
  216461. return false;
  216462. }
  216463. }
  216464. while (! triggered);
  216465. }
  216466. }
  216467. if (! manualReset)
  216468. triggered = false;
  216469. pthread_mutex_unlock (&mutex);
  216470. return true;
  216471. }
  216472. void signal() throw()
  216473. {
  216474. pthread_mutex_lock (&mutex);
  216475. triggered = true;
  216476. pthread_cond_broadcast (&condition);
  216477. pthread_mutex_unlock (&mutex);
  216478. }
  216479. void reset() throw()
  216480. {
  216481. pthread_mutex_lock (&mutex);
  216482. triggered = false;
  216483. pthread_mutex_unlock (&mutex);
  216484. }
  216485. private:
  216486. pthread_cond_t condition;
  216487. pthread_mutex_t mutex;
  216488. bool triggered;
  216489. const bool manualReset;
  216490. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216491. };
  216492. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216493. : internal (new WaitableEventImpl (manualReset))
  216494. {
  216495. }
  216496. WaitableEvent::~WaitableEvent() throw()
  216497. {
  216498. delete static_cast <WaitableEventImpl*> (internal);
  216499. }
  216500. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216501. {
  216502. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216503. }
  216504. void WaitableEvent::signal() const throw()
  216505. {
  216506. static_cast <WaitableEventImpl*> (internal)->signal();
  216507. }
  216508. void WaitableEvent::reset() const throw()
  216509. {
  216510. static_cast <WaitableEventImpl*> (internal)->reset();
  216511. }
  216512. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216513. {
  216514. struct timespec time;
  216515. time.tv_sec = millisecs / 1000;
  216516. time.tv_nsec = (millisecs % 1000) * 1000000;
  216517. nanosleep (&time, 0);
  216518. }
  216519. const juce_wchar File::separator = '/';
  216520. const String File::separatorString ("/");
  216521. const File File::getCurrentWorkingDirectory()
  216522. {
  216523. HeapBlock<char> heapBuffer;
  216524. char localBuffer [1024];
  216525. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216526. int bufferSize = 4096;
  216527. while (cwd == 0 && errno == ERANGE)
  216528. {
  216529. heapBuffer.malloc (bufferSize);
  216530. cwd = getcwd (heapBuffer, bufferSize - 1);
  216531. bufferSize += 1024;
  216532. }
  216533. return File (String::fromUTF8 (cwd));
  216534. }
  216535. bool File::setAsCurrentWorkingDirectory() const
  216536. {
  216537. return chdir (getFullPathName().toUTF8()) == 0;
  216538. }
  216539. namespace
  216540. {
  216541. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216542. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216543. #else
  216544. typedef struct stat juce_statStruct;
  216545. #endif
  216546. bool juce_stat (const String& fileName, juce_statStruct& info)
  216547. {
  216548. return fileName.isNotEmpty()
  216549. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216550. && (stat64 (fileName.toUTF8(), &info) == 0);
  216551. #else
  216552. && (stat (fileName.toUTF8(), &info) == 0);
  216553. #endif
  216554. }
  216555. // if this file doesn't exist, find a parent of it that does..
  216556. bool juce_doStatFS (File f, struct statfs& result)
  216557. {
  216558. for (int i = 5; --i >= 0;)
  216559. {
  216560. if (f.exists())
  216561. break;
  216562. f = f.getParentDirectory();
  216563. }
  216564. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216565. }
  216566. }
  216567. bool File::isDirectory() const
  216568. {
  216569. juce_statStruct info;
  216570. return fullPath.isEmpty()
  216571. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216572. }
  216573. bool File::exists() const
  216574. {
  216575. juce_statStruct info;
  216576. return fullPath.isNotEmpty()
  216577. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216578. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216579. #else
  216580. && (lstat (fullPath.toUTF8(), &info) == 0);
  216581. #endif
  216582. }
  216583. bool File::existsAsFile() const
  216584. {
  216585. return exists() && ! isDirectory();
  216586. }
  216587. int64 File::getSize() const
  216588. {
  216589. juce_statStruct info;
  216590. return juce_stat (fullPath, info) ? info.st_size : 0;
  216591. }
  216592. bool File::hasWriteAccess() const
  216593. {
  216594. if (exists())
  216595. return access (fullPath.toUTF8(), W_OK) == 0;
  216596. if ((! isDirectory()) && fullPath.containsChar (separator))
  216597. return getParentDirectory().hasWriteAccess();
  216598. return false;
  216599. }
  216600. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216601. {
  216602. juce_statStruct info;
  216603. if (! juce_stat (fullPath, info))
  216604. return false;
  216605. info.st_mode &= 0777; // Just permissions
  216606. if (shouldBeReadOnly)
  216607. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216608. else
  216609. // Give everybody write permission?
  216610. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216611. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216612. }
  216613. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216614. {
  216615. modificationTime = 0;
  216616. accessTime = 0;
  216617. creationTime = 0;
  216618. juce_statStruct info;
  216619. if (juce_stat (fullPath, info))
  216620. {
  216621. modificationTime = (int64) info.st_mtime * 1000;
  216622. accessTime = (int64) info.st_atime * 1000;
  216623. creationTime = (int64) info.st_ctime * 1000;
  216624. }
  216625. }
  216626. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216627. {
  216628. struct utimbuf times;
  216629. times.actime = (time_t) (accessTime / 1000);
  216630. times.modtime = (time_t) (modificationTime / 1000);
  216631. return utime (fullPath.toUTF8(), &times) == 0;
  216632. }
  216633. bool File::deleteFile() const
  216634. {
  216635. if (! exists())
  216636. return true;
  216637. else if (isDirectory())
  216638. return rmdir (fullPath.toUTF8()) == 0;
  216639. else
  216640. return remove (fullPath.toUTF8()) == 0;
  216641. }
  216642. bool File::moveInternal (const File& dest) const
  216643. {
  216644. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216645. return true;
  216646. if (hasWriteAccess() && copyInternal (dest))
  216647. {
  216648. if (deleteFile())
  216649. return true;
  216650. dest.deleteFile();
  216651. }
  216652. return false;
  216653. }
  216654. void File::createDirectoryInternal (const String& fileName) const
  216655. {
  216656. mkdir (fileName.toUTF8(), 0777);
  216657. }
  216658. int64 juce_fileSetPosition (void* handle, int64 pos)
  216659. {
  216660. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216661. return pos;
  216662. return -1;
  216663. }
  216664. void FileInputStream::openHandle()
  216665. {
  216666. totalSize = file.getSize();
  216667. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216668. if (f != -1)
  216669. fileHandle = (void*) f;
  216670. }
  216671. void FileInputStream::closeHandle()
  216672. {
  216673. if (fileHandle != 0)
  216674. {
  216675. close ((int) (pointer_sized_int) fileHandle);
  216676. fileHandle = 0;
  216677. }
  216678. }
  216679. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216680. {
  216681. if (fileHandle != 0)
  216682. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216683. return 0;
  216684. }
  216685. void FileOutputStream::openHandle()
  216686. {
  216687. if (file.exists())
  216688. {
  216689. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216690. if (f != -1)
  216691. {
  216692. currentPosition = lseek (f, 0, SEEK_END);
  216693. if (currentPosition >= 0)
  216694. fileHandle = (void*) f;
  216695. else
  216696. close (f);
  216697. }
  216698. }
  216699. else
  216700. {
  216701. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216702. if (f != -1)
  216703. fileHandle = (void*) f;
  216704. }
  216705. }
  216706. void FileOutputStream::closeHandle()
  216707. {
  216708. if (fileHandle != 0)
  216709. {
  216710. close ((int) (pointer_sized_int) fileHandle);
  216711. fileHandle = 0;
  216712. }
  216713. }
  216714. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216715. {
  216716. if (fileHandle != 0)
  216717. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216718. return 0;
  216719. }
  216720. void FileOutputStream::flushInternal()
  216721. {
  216722. if (fileHandle != 0)
  216723. fsync ((int) (pointer_sized_int) fileHandle);
  216724. }
  216725. const File juce_getExecutableFile()
  216726. {
  216727. Dl_info exeInfo;
  216728. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216729. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216730. }
  216731. int64 File::getBytesFreeOnVolume() const
  216732. {
  216733. struct statfs buf;
  216734. if (juce_doStatFS (*this, buf))
  216735. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216736. return 0;
  216737. }
  216738. int64 File::getVolumeTotalSize() const
  216739. {
  216740. struct statfs buf;
  216741. if (juce_doStatFS (*this, buf))
  216742. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216743. return 0;
  216744. }
  216745. const String File::getVolumeLabel() const
  216746. {
  216747. #if JUCE_MAC
  216748. struct VolAttrBuf
  216749. {
  216750. u_int32_t length;
  216751. attrreference_t mountPointRef;
  216752. char mountPointSpace [MAXPATHLEN];
  216753. } attrBuf;
  216754. struct attrlist attrList;
  216755. zerostruct (attrList);
  216756. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216757. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216758. File f (*this);
  216759. for (;;)
  216760. {
  216761. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216762. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216763. (int) attrBuf.mountPointRef.attr_length);
  216764. const File parent (f.getParentDirectory());
  216765. if (f == parent)
  216766. break;
  216767. f = parent;
  216768. }
  216769. #endif
  216770. return String::empty;
  216771. }
  216772. int File::getVolumeSerialNumber() const
  216773. {
  216774. return 0; // xxx
  216775. }
  216776. void juce_runSystemCommand (const String& command)
  216777. {
  216778. int result = system (command.toUTF8());
  216779. (void) result;
  216780. }
  216781. const String juce_getOutputFromCommand (const String& command)
  216782. {
  216783. // slight bodge here, as we just pipe the output into a temp file and read it...
  216784. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216785. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216786. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216787. String result (tempFile.loadFileAsString());
  216788. tempFile.deleteFile();
  216789. return result;
  216790. }
  216791. class InterProcessLock::Pimpl
  216792. {
  216793. public:
  216794. Pimpl (const String& name, const int timeOutMillisecs)
  216795. : handle (0), refCount (1)
  216796. {
  216797. #if JUCE_MAC
  216798. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216799. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216800. #else
  216801. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216802. #endif
  216803. temp.create();
  216804. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216805. if (handle != 0)
  216806. {
  216807. struct flock fl;
  216808. zerostruct (fl);
  216809. fl.l_whence = SEEK_SET;
  216810. fl.l_type = F_WRLCK;
  216811. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216812. for (;;)
  216813. {
  216814. const int result = fcntl (handle, F_SETLK, &fl);
  216815. if (result >= 0)
  216816. return;
  216817. if (errno != EINTR)
  216818. {
  216819. if (timeOutMillisecs == 0
  216820. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216821. break;
  216822. Thread::sleep (10);
  216823. }
  216824. }
  216825. }
  216826. closeFile();
  216827. }
  216828. ~Pimpl()
  216829. {
  216830. closeFile();
  216831. }
  216832. void closeFile()
  216833. {
  216834. if (handle != 0)
  216835. {
  216836. struct flock fl;
  216837. zerostruct (fl);
  216838. fl.l_whence = SEEK_SET;
  216839. fl.l_type = F_UNLCK;
  216840. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216841. {}
  216842. close (handle);
  216843. handle = 0;
  216844. }
  216845. }
  216846. int handle, refCount;
  216847. };
  216848. InterProcessLock::InterProcessLock (const String& name_)
  216849. : name (name_)
  216850. {
  216851. }
  216852. InterProcessLock::~InterProcessLock()
  216853. {
  216854. }
  216855. bool InterProcessLock::enter (const int timeOutMillisecs)
  216856. {
  216857. const ScopedLock sl (lock);
  216858. if (pimpl == 0)
  216859. {
  216860. pimpl = new Pimpl (name, timeOutMillisecs);
  216861. if (pimpl->handle == 0)
  216862. pimpl = 0;
  216863. }
  216864. else
  216865. {
  216866. pimpl->refCount++;
  216867. }
  216868. return pimpl != 0;
  216869. }
  216870. void InterProcessLock::exit()
  216871. {
  216872. const ScopedLock sl (lock);
  216873. // Trying to release the lock too many times!
  216874. jassert (pimpl != 0);
  216875. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216876. pimpl = 0;
  216877. }
  216878. void JUCE_API juce_threadEntryPoint (void*);
  216879. void* threadEntryProc (void* userData)
  216880. {
  216881. JUCE_AUTORELEASEPOOL
  216882. juce_threadEntryPoint (userData);
  216883. return 0;
  216884. }
  216885. void Thread::launchThread()
  216886. {
  216887. threadHandle_ = 0;
  216888. pthread_t handle = 0;
  216889. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216890. {
  216891. pthread_detach (handle);
  216892. threadHandle_ = (void*) handle;
  216893. threadId_ = (ThreadID) threadHandle_;
  216894. }
  216895. }
  216896. void Thread::closeThreadHandle()
  216897. {
  216898. threadId_ = 0;
  216899. threadHandle_ = 0;
  216900. }
  216901. void Thread::killThread()
  216902. {
  216903. if (threadHandle_ != 0)
  216904. pthread_cancel ((pthread_t) threadHandle_);
  216905. }
  216906. void Thread::setCurrentThreadName (const String& /*name*/)
  216907. {
  216908. }
  216909. bool Thread::setThreadPriority (void* handle, int priority)
  216910. {
  216911. struct sched_param param;
  216912. int policy;
  216913. priority = jlimit (0, 10, priority);
  216914. if (handle == 0)
  216915. handle = (void*) pthread_self();
  216916. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216917. return false;
  216918. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216919. const int minPriority = sched_get_priority_min (policy);
  216920. const int maxPriority = sched_get_priority_max (policy);
  216921. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216922. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216923. }
  216924. Thread::ThreadID Thread::getCurrentThreadId()
  216925. {
  216926. return (ThreadID) pthread_self();
  216927. }
  216928. void Thread::yield()
  216929. {
  216930. sched_yield();
  216931. }
  216932. /* Remove this macro if you're having problems compiling the cpu affinity
  216933. calls (the API for these has changed about quite a bit in various Linux
  216934. versions, and a lot of distros seem to ship with obsolete versions)
  216935. */
  216936. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216937. #define SUPPORT_AFFINITIES 1
  216938. #endif
  216939. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216940. {
  216941. #if SUPPORT_AFFINITIES
  216942. cpu_set_t affinity;
  216943. CPU_ZERO (&affinity);
  216944. for (int i = 0; i < 32; ++i)
  216945. if ((affinityMask & (1 << i)) != 0)
  216946. CPU_SET (i, &affinity);
  216947. /*
  216948. N.B. If this line causes a compile error, then you've probably not got the latest
  216949. version of glibc installed.
  216950. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216951. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216952. */
  216953. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216954. sched_yield();
  216955. #else
  216956. /* affinities aren't supported because either the appropriate header files weren't found,
  216957. or the SUPPORT_AFFINITIES macro was turned off
  216958. */
  216959. jassertfalse;
  216960. #endif
  216961. }
  216962. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216963. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216964. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216965. // compiled on its own).
  216966. #if JUCE_INCLUDED_FILE
  216967. enum
  216968. {
  216969. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216970. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216971. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216972. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216973. };
  216974. bool File::copyInternal (const File& dest) const
  216975. {
  216976. FileInputStream in (*this);
  216977. if (dest.deleteFile())
  216978. {
  216979. {
  216980. FileOutputStream out (dest);
  216981. if (out.failedToOpen())
  216982. return false;
  216983. if (out.writeFromInputStream (in, -1) == getSize())
  216984. return true;
  216985. }
  216986. dest.deleteFile();
  216987. }
  216988. return false;
  216989. }
  216990. void File::findFileSystemRoots (Array<File>& destArray)
  216991. {
  216992. destArray.add (File ("/"));
  216993. }
  216994. bool File::isOnCDRomDrive() const
  216995. {
  216996. struct statfs buf;
  216997. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216998. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216999. }
  217000. bool File::isOnHardDisk() const
  217001. {
  217002. struct statfs buf;
  217003. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217004. {
  217005. switch (buf.f_type)
  217006. {
  217007. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217008. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217009. case U_NFS_SUPER_MAGIC: // Network NFS
  217010. case U_SMB_SUPER_MAGIC: // Network Samba
  217011. return false;
  217012. default:
  217013. // Assume anything else is a hard-disk (but note it could
  217014. // be a RAM disk. There isn't a good way of determining
  217015. // this for sure)
  217016. return true;
  217017. }
  217018. }
  217019. // Assume so if this fails for some reason
  217020. return true;
  217021. }
  217022. bool File::isOnRemovableDrive() const
  217023. {
  217024. jassertfalse; // xxx not implemented for linux!
  217025. return false;
  217026. }
  217027. bool File::isHidden() const
  217028. {
  217029. return getFileName().startsWithChar ('.');
  217030. }
  217031. namespace
  217032. {
  217033. const File juce_readlink (const String& file, const File& defaultFile)
  217034. {
  217035. const int size = 8192;
  217036. HeapBlock<char> buffer;
  217037. buffer.malloc (size + 4);
  217038. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217039. if (numBytes > 0 && numBytes <= size)
  217040. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217041. return defaultFile;
  217042. }
  217043. }
  217044. const File File::getLinkedTarget() const
  217045. {
  217046. return juce_readlink (getFullPathName().toUTF8(), *this);
  217047. }
  217048. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217049. const File File::getSpecialLocation (const SpecialLocationType type)
  217050. {
  217051. switch (type)
  217052. {
  217053. case userHomeDirectory:
  217054. {
  217055. const char* homeDir = getenv ("HOME");
  217056. if (homeDir == 0)
  217057. {
  217058. struct passwd* const pw = getpwuid (getuid());
  217059. if (pw != 0)
  217060. homeDir = pw->pw_dir;
  217061. }
  217062. return File (String::fromUTF8 (homeDir));
  217063. }
  217064. case userDocumentsDirectory:
  217065. case userMusicDirectory:
  217066. case userMoviesDirectory:
  217067. case userApplicationDataDirectory:
  217068. return File ("~");
  217069. case userDesktopDirectory:
  217070. return File ("~/Desktop");
  217071. case commonApplicationDataDirectory:
  217072. return File ("/var");
  217073. case globalApplicationsDirectory:
  217074. return File ("/usr");
  217075. case tempDirectory:
  217076. {
  217077. File tmp ("/var/tmp");
  217078. if (! tmp.isDirectory())
  217079. {
  217080. tmp = "/tmp";
  217081. if (! tmp.isDirectory())
  217082. tmp = File::getCurrentWorkingDirectory();
  217083. }
  217084. return tmp;
  217085. }
  217086. case invokedExecutableFile:
  217087. if (juce_Argv0 != 0)
  217088. return File (String::fromUTF8 (juce_Argv0));
  217089. // deliberate fall-through...
  217090. case currentExecutableFile:
  217091. case currentApplicationFile:
  217092. return juce_getExecutableFile();
  217093. case hostApplicationPath:
  217094. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217095. default:
  217096. jassertfalse; // unknown type?
  217097. break;
  217098. }
  217099. return File::nonexistent;
  217100. }
  217101. const String File::getVersion() const
  217102. {
  217103. return String::empty; // xxx not yet implemented
  217104. }
  217105. bool File::moveToTrash() const
  217106. {
  217107. if (! exists())
  217108. return true;
  217109. File trashCan ("~/.Trash");
  217110. if (! trashCan.isDirectory())
  217111. trashCan = "~/.local/share/Trash/files";
  217112. if (! trashCan.isDirectory())
  217113. return false;
  217114. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217115. getFileExtension()));
  217116. }
  217117. class DirectoryIterator::NativeIterator::Pimpl
  217118. {
  217119. public:
  217120. Pimpl (const File& directory, const String& wildCard_)
  217121. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217122. wildCard (wildCard_),
  217123. dir (opendir (directory.getFullPathName().toUTF8()))
  217124. {
  217125. if (wildCard == "*.*")
  217126. wildCard = "*";
  217127. wildcardUTF8 = wildCard.toUTF8();
  217128. }
  217129. ~Pimpl()
  217130. {
  217131. if (dir != 0)
  217132. closedir (dir);
  217133. }
  217134. bool next (String& filenameFound,
  217135. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217136. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217137. {
  217138. if (dir == 0)
  217139. return false;
  217140. for (;;)
  217141. {
  217142. struct dirent* const de = readdir (dir);
  217143. if (de == 0)
  217144. return false;
  217145. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217146. {
  217147. filenameFound = String::fromUTF8 (de->d_name);
  217148. const String path (parentDir + filenameFound);
  217149. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217150. {
  217151. struct stat info;
  217152. const bool statOk = juce_stat (path, info);
  217153. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217154. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217155. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217156. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217157. }
  217158. if (isHidden != 0)
  217159. *isHidden = filenameFound.startsWithChar ('.');
  217160. if (isReadOnly != 0)
  217161. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217162. return true;
  217163. }
  217164. }
  217165. }
  217166. private:
  217167. String parentDir, wildCard;
  217168. const char* wildcardUTF8;
  217169. DIR* dir;
  217170. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217171. };
  217172. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217173. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217174. {
  217175. }
  217176. DirectoryIterator::NativeIterator::~NativeIterator()
  217177. {
  217178. }
  217179. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217180. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217181. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217182. {
  217183. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217184. }
  217185. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217186. {
  217187. String cmdString (fileName.replace (" ", "\\ ",false));
  217188. cmdString << " " << parameters;
  217189. if (URL::isProbablyAWebsiteURL (fileName)
  217190. || cmdString.startsWithIgnoreCase ("file:")
  217191. || URL::isProbablyAnEmailAddress (fileName))
  217192. {
  217193. // create a command that tries to launch a bunch of likely browsers
  217194. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217195. StringArray cmdLines;
  217196. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217197. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217198. cmdString = cmdLines.joinIntoString (" || ");
  217199. }
  217200. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217201. const int cpid = fork();
  217202. if (cpid == 0)
  217203. {
  217204. setsid();
  217205. // Child process
  217206. execve (argv[0], (char**) argv, environ);
  217207. exit (0);
  217208. }
  217209. return cpid >= 0;
  217210. }
  217211. void File::revealToUser() const
  217212. {
  217213. if (isDirectory())
  217214. startAsProcess();
  217215. else if (getParentDirectory().exists())
  217216. getParentDirectory().startAsProcess();
  217217. }
  217218. #endif
  217219. /*** End of inlined file: juce_linux_Files.cpp ***/
  217220. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217221. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217222. // compiled on its own).
  217223. #if JUCE_INCLUDED_FILE
  217224. struct NamedPipeInternal
  217225. {
  217226. String pipeInName, pipeOutName;
  217227. int pipeIn, pipeOut;
  217228. bool volatile createdPipe, blocked, stopReadOperation;
  217229. static void signalHandler (int) {}
  217230. };
  217231. void NamedPipe::cancelPendingReads()
  217232. {
  217233. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217234. {
  217235. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217236. intern->stopReadOperation = true;
  217237. char buffer [1] = { 0 };
  217238. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217239. (void) bytesWritten;
  217240. int timeout = 2000;
  217241. while (intern->blocked && --timeout >= 0)
  217242. Thread::sleep (2);
  217243. intern->stopReadOperation = false;
  217244. }
  217245. }
  217246. void NamedPipe::close()
  217247. {
  217248. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217249. if (intern != 0)
  217250. {
  217251. internal = 0;
  217252. if (intern->pipeIn != -1)
  217253. ::close (intern->pipeIn);
  217254. if (intern->pipeOut != -1)
  217255. ::close (intern->pipeOut);
  217256. if (intern->createdPipe)
  217257. {
  217258. unlink (intern->pipeInName.toUTF8());
  217259. unlink (intern->pipeOutName.toUTF8());
  217260. }
  217261. delete intern;
  217262. }
  217263. }
  217264. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217265. {
  217266. close();
  217267. NamedPipeInternal* const intern = new NamedPipeInternal();
  217268. internal = intern;
  217269. intern->createdPipe = createPipe;
  217270. intern->blocked = false;
  217271. intern->stopReadOperation = false;
  217272. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217273. siginterrupt (SIGPIPE, 1);
  217274. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217275. intern->pipeInName = pipePath + "_in";
  217276. intern->pipeOutName = pipePath + "_out";
  217277. intern->pipeIn = -1;
  217278. intern->pipeOut = -1;
  217279. if (createPipe)
  217280. {
  217281. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217282. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217283. {
  217284. delete intern;
  217285. internal = 0;
  217286. return false;
  217287. }
  217288. }
  217289. return true;
  217290. }
  217291. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217292. {
  217293. int bytesRead = -1;
  217294. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217295. if (intern != 0)
  217296. {
  217297. intern->blocked = true;
  217298. if (intern->pipeIn == -1)
  217299. {
  217300. if (intern->createdPipe)
  217301. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217302. else
  217303. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217304. if (intern->pipeIn == -1)
  217305. {
  217306. intern->blocked = false;
  217307. return -1;
  217308. }
  217309. }
  217310. bytesRead = 0;
  217311. char* p = static_cast<char*> (destBuffer);
  217312. while (bytesRead < maxBytesToRead)
  217313. {
  217314. const int bytesThisTime = maxBytesToRead - bytesRead;
  217315. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217316. if (numRead <= 0 || intern->stopReadOperation)
  217317. {
  217318. bytesRead = -1;
  217319. break;
  217320. }
  217321. bytesRead += numRead;
  217322. p += bytesRead;
  217323. }
  217324. intern->blocked = false;
  217325. }
  217326. return bytesRead;
  217327. }
  217328. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217329. {
  217330. int bytesWritten = -1;
  217331. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217332. if (intern != 0)
  217333. {
  217334. if (intern->pipeOut == -1)
  217335. {
  217336. if (intern->createdPipe)
  217337. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217338. else
  217339. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217340. if (intern->pipeOut == -1)
  217341. {
  217342. return -1;
  217343. }
  217344. }
  217345. const char* p = static_cast<const char*> (sourceBuffer);
  217346. bytesWritten = 0;
  217347. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217348. while (bytesWritten < numBytesToWrite
  217349. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217350. {
  217351. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217352. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217353. if (numWritten <= 0)
  217354. {
  217355. bytesWritten = -1;
  217356. break;
  217357. }
  217358. bytesWritten += numWritten;
  217359. p += bytesWritten;
  217360. }
  217361. }
  217362. return bytesWritten;
  217363. }
  217364. #endif
  217365. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217366. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217367. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217368. // compiled on its own).
  217369. #if JUCE_INCLUDED_FILE
  217370. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217371. {
  217372. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217373. if (s != -1)
  217374. {
  217375. char buf [1024];
  217376. struct ifconf ifc;
  217377. ifc.ifc_len = sizeof (buf);
  217378. ifc.ifc_buf = buf;
  217379. ioctl (s, SIOCGIFCONF, &ifc);
  217380. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217381. {
  217382. struct ifreq ifr;
  217383. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217384. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217385. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217386. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217387. {
  217388. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217389. }
  217390. }
  217391. close (s);
  217392. }
  217393. }
  217394. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217395. const String& emailSubject,
  217396. const String& bodyText,
  217397. const StringArray& filesToAttach)
  217398. {
  217399. jassertfalse; // xxx todo
  217400. return false;
  217401. }
  217402. class WebInputStream : public InputStream
  217403. {
  217404. public:
  217405. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217406. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217407. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217408. : socketHandle (-1), levelsOfRedirection (0),
  217409. address (address_), headers (headers_), postData (postData_), position (0),
  217410. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217411. {
  217412. createConnection (progressCallback, progressCallbackContext);
  217413. if (responseHeaders != 0 && ! isError())
  217414. {
  217415. for (int i = 0; i < headerLines.size(); ++i)
  217416. {
  217417. const String& headersEntry = headerLines[i];
  217418. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217419. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217420. const String previousValue ((*responseHeaders) [key]);
  217421. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217422. }
  217423. }
  217424. }
  217425. ~WebInputStream()
  217426. {
  217427. closeSocket();
  217428. }
  217429. bool isError() const { return socketHandle < 0; }
  217430. bool isExhausted() { return finished; }
  217431. int64 getPosition() { return position; }
  217432. int64 getTotalLength()
  217433. {
  217434. jassertfalse; //xxx to do
  217435. return -1;
  217436. }
  217437. int read (void* buffer, int bytesToRead)
  217438. {
  217439. if (finished || isError())
  217440. return 0;
  217441. fd_set readbits;
  217442. FD_ZERO (&readbits);
  217443. FD_SET (socketHandle, &readbits);
  217444. struct timeval tv;
  217445. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217446. tv.tv_usec = 0;
  217447. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217448. return 0; // (timeout)
  217449. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217450. if (bytesRead == 0)
  217451. finished = true;
  217452. position += bytesRead;
  217453. return bytesRead;
  217454. }
  217455. bool setPosition (int64 wantedPos)
  217456. {
  217457. if (isError())
  217458. return false;
  217459. if (wantedPos != position)
  217460. {
  217461. finished = false;
  217462. if (wantedPos < position)
  217463. {
  217464. closeSocket();
  217465. position = 0;
  217466. createConnection (0, 0);
  217467. }
  217468. skipNextBytes (wantedPos - position);
  217469. }
  217470. return true;
  217471. }
  217472. private:
  217473. int socketHandle, levelsOfRedirection;
  217474. StringArray headerLines;
  217475. String address, headers;
  217476. MemoryBlock postData;
  217477. int64 position;
  217478. bool finished;
  217479. const bool isPost;
  217480. const int timeOutMs;
  217481. void closeSocket()
  217482. {
  217483. if (socketHandle >= 0)
  217484. close (socketHandle);
  217485. socketHandle = -1;
  217486. levelsOfRedirection = 0;
  217487. }
  217488. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217489. {
  217490. closeSocket();
  217491. uint32 timeOutTime = Time::getMillisecondCounter();
  217492. if (timeOutMs == 0)
  217493. timeOutTime += 60000;
  217494. else if (timeOutMs < 0)
  217495. timeOutTime = 0xffffffff;
  217496. else
  217497. timeOutTime += timeOutMs;
  217498. String hostName, hostPath;
  217499. int hostPort;
  217500. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217501. return;
  217502. const struct hostent* host = 0;
  217503. int port = 0;
  217504. String proxyName, proxyPath;
  217505. int proxyPort = 0;
  217506. String proxyURL (getenv ("http_proxy"));
  217507. if (proxyURL.startsWithIgnoreCase ("http://"))
  217508. {
  217509. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217510. return;
  217511. host = gethostbyname (proxyName.toUTF8());
  217512. port = proxyPort;
  217513. }
  217514. else
  217515. {
  217516. host = gethostbyname (hostName.toUTF8());
  217517. port = hostPort;
  217518. }
  217519. if (host == 0)
  217520. return;
  217521. {
  217522. struct sockaddr_in socketAddress;
  217523. zerostruct (socketAddress);
  217524. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217525. socketAddress.sin_family = host->h_addrtype;
  217526. socketAddress.sin_port = htons (port);
  217527. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217528. if (socketHandle == -1)
  217529. return;
  217530. int receiveBufferSize = 16384;
  217531. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217532. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217533. #if JUCE_MAC
  217534. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217535. #endif
  217536. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217537. {
  217538. closeSocket();
  217539. return;
  217540. }
  217541. }
  217542. {
  217543. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217544. hostPath, address, headers, postData, isPost));
  217545. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217546. {
  217547. closeSocket();
  217548. return;
  217549. }
  217550. }
  217551. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217552. if (responseHeader.isNotEmpty())
  217553. {
  217554. headerLines.clear();
  217555. headerLines.addLines (responseHeader);
  217556. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217557. .substring (0, 3).getIntValue();
  217558. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217559. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217560. String location (findHeaderItem (headerLines, "Location:"));
  217561. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217562. {
  217563. if (! location.startsWithIgnoreCase ("http://"))
  217564. location = "http://" + location;
  217565. if (++levelsOfRedirection <= 3)
  217566. {
  217567. address = location;
  217568. createConnection (progressCallback, progressCallbackContext);
  217569. return;
  217570. }
  217571. }
  217572. else
  217573. {
  217574. levelsOfRedirection = 0;
  217575. return;
  217576. }
  217577. }
  217578. closeSocket();
  217579. }
  217580. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217581. {
  217582. int bytesRead = 0, numConsecutiveLFs = 0;
  217583. MemoryBlock buffer (1024, true);
  217584. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217585. && Time::getMillisecondCounter() <= timeOutTime)
  217586. {
  217587. fd_set readbits;
  217588. FD_ZERO (&readbits);
  217589. FD_SET (socketHandle, &readbits);
  217590. struct timeval tv;
  217591. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217592. tv.tv_usec = 0;
  217593. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217594. return String::empty; // (timeout)
  217595. buffer.ensureSize (bytesRead + 8, true);
  217596. char* const dest = (char*) buffer.getData() + bytesRead;
  217597. if (recv (socketHandle, dest, 1, 0) == -1)
  217598. return String::empty;
  217599. const char lastByte = *dest;
  217600. ++bytesRead;
  217601. if (lastByte == '\n')
  217602. ++numConsecutiveLFs;
  217603. else if (lastByte != '\r')
  217604. numConsecutiveLFs = 0;
  217605. }
  217606. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217607. if (header.startsWithIgnoreCase ("HTTP/"))
  217608. return header.trimEnd();
  217609. return String::empty;
  217610. }
  217611. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217612. const String& proxyName, const int proxyPort,
  217613. const String& hostPath, const String& originalURL,
  217614. const String& headers, const MemoryBlock& postData,
  217615. const bool isPost)
  217616. {
  217617. String header (isPost ? "POST " : "GET ");
  217618. if (proxyName.isEmpty())
  217619. {
  217620. header << hostPath << " HTTP/1.0\r\nHost: "
  217621. << hostName << ':' << hostPort;
  217622. }
  217623. else
  217624. {
  217625. header << originalURL << " HTTP/1.0\r\nHost: "
  217626. << proxyName << ':' << proxyPort;
  217627. }
  217628. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217629. << "\r\nConnection: Close\r\nContent-Length: "
  217630. << postData.getSize() << "\r\n"
  217631. << headers << "\r\n";
  217632. MemoryBlock mb;
  217633. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217634. mb.append (postData.getData(), postData.getSize());
  217635. return mb;
  217636. }
  217637. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217638. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217639. {
  217640. size_t totalHeaderSent = 0;
  217641. while (totalHeaderSent < requestHeader.getSize())
  217642. {
  217643. if (Time::getMillisecondCounter() > timeOutTime)
  217644. return false;
  217645. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217646. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217647. return false;
  217648. totalHeaderSent += numToSend;
  217649. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217650. return false;
  217651. }
  217652. return true;
  217653. }
  217654. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217655. {
  217656. if (! url.startsWithIgnoreCase ("http://"))
  217657. return false;
  217658. const int nextSlash = url.indexOfChar (7, '/');
  217659. int nextColon = url.indexOfChar (7, ':');
  217660. if (nextColon > nextSlash && nextSlash > 0)
  217661. nextColon = -1;
  217662. if (nextColon >= 0)
  217663. {
  217664. host = url.substring (7, nextColon);
  217665. if (nextSlash >= 0)
  217666. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217667. else
  217668. port = url.substring (nextColon + 1).getIntValue();
  217669. }
  217670. else
  217671. {
  217672. port = 80;
  217673. if (nextSlash >= 0)
  217674. host = url.substring (7, nextSlash);
  217675. else
  217676. host = url.substring (7);
  217677. }
  217678. if (nextSlash >= 0)
  217679. path = url.substring (nextSlash);
  217680. else
  217681. path = "/";
  217682. return true;
  217683. }
  217684. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217685. {
  217686. for (int i = 0; i < lines.size(); ++i)
  217687. if (lines[i].startsWithIgnoreCase (itemName))
  217688. return lines[i].substring (itemName.length()).trim();
  217689. return String::empty;
  217690. }
  217691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217692. };
  217693. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217694. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217695. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217696. {
  217697. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217698. progressCallback, progressCallbackContext,
  217699. headers, timeOutMs, responseHeaders));
  217700. return wi->isError() ? 0 : wi.release();
  217701. }
  217702. #endif
  217703. /*** End of inlined file: juce_linux_Network.cpp ***/
  217704. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217705. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217706. // compiled on its own).
  217707. #if JUCE_INCLUDED_FILE
  217708. void Logger::outputDebugString (const String& text)
  217709. {
  217710. std::cerr << text << std::endl;
  217711. }
  217712. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217713. {
  217714. return Linux;
  217715. }
  217716. const String SystemStats::getOperatingSystemName()
  217717. {
  217718. return "Linux";
  217719. }
  217720. bool SystemStats::isOperatingSystem64Bit()
  217721. {
  217722. #if JUCE_64BIT
  217723. return true;
  217724. #else
  217725. //xxx not sure how to find this out?..
  217726. return false;
  217727. #endif
  217728. }
  217729. namespace LinuxStatsHelpers
  217730. {
  217731. const String getCpuInfo (const char* const key)
  217732. {
  217733. StringArray lines;
  217734. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217735. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217736. if (lines[i].startsWithIgnoreCase (key))
  217737. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217738. return String::empty;
  217739. }
  217740. }
  217741. const String SystemStats::getCpuVendor()
  217742. {
  217743. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217744. }
  217745. int SystemStats::getCpuSpeedInMegaherz()
  217746. {
  217747. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217748. }
  217749. int SystemStats::getMemorySizeInMegabytes()
  217750. {
  217751. struct sysinfo sysi;
  217752. if (sysinfo (&sysi) == 0)
  217753. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217754. return 0;
  217755. }
  217756. int SystemStats::getPageSize()
  217757. {
  217758. return sysconf (_SC_PAGESIZE);
  217759. }
  217760. const String SystemStats::getLogonName()
  217761. {
  217762. const char* user = getenv ("USER");
  217763. if (user == 0)
  217764. {
  217765. struct passwd* const pw = getpwuid (getuid());
  217766. if (pw != 0)
  217767. user = pw->pw_name;
  217768. }
  217769. return String::fromUTF8 (user);
  217770. }
  217771. const String SystemStats::getFullUserName()
  217772. {
  217773. return getLogonName();
  217774. }
  217775. void SystemStats::initialiseStats()
  217776. {
  217777. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217778. cpuFlags.hasMMX = flags.contains ("mmx");
  217779. cpuFlags.hasSSE = flags.contains ("sse");
  217780. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217781. cpuFlags.has3DNow = flags.contains ("3dnow");
  217782. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217783. }
  217784. void PlatformUtilities::fpuReset()
  217785. {
  217786. }
  217787. uint32 juce_millisecondsSinceStartup() throw()
  217788. {
  217789. timespec t;
  217790. clock_gettime (CLOCK_MONOTONIC, &t);
  217791. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217792. }
  217793. int64 Time::getHighResolutionTicks() throw()
  217794. {
  217795. timespec t;
  217796. clock_gettime (CLOCK_MONOTONIC, &t);
  217797. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217798. }
  217799. int64 Time::getHighResolutionTicksPerSecond() throw()
  217800. {
  217801. return 1000000; // (microseconds)
  217802. }
  217803. double Time::getMillisecondCounterHiRes() throw()
  217804. {
  217805. return getHighResolutionTicks() * 0.001;
  217806. }
  217807. bool Time::setSystemTimeToThisTime() const
  217808. {
  217809. timeval t;
  217810. t.tv_sec = millisSinceEpoch / 1000;
  217811. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217812. return settimeofday (&t, 0) == 0;
  217813. }
  217814. #endif
  217815. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217816. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217817. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217818. // compiled on its own).
  217819. #if JUCE_INCLUDED_FILE
  217820. /*
  217821. Note that a lot of methods that you'd expect to find in this file actually
  217822. live in juce_posix_SharedCode.h!
  217823. */
  217824. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217825. void Process::setPriority (ProcessPriority prior)
  217826. {
  217827. struct sched_param param;
  217828. int policy, maxp, minp;
  217829. const int p = (int) prior;
  217830. if (p <= 1)
  217831. policy = SCHED_OTHER;
  217832. else
  217833. policy = SCHED_RR;
  217834. minp = sched_get_priority_min (policy);
  217835. maxp = sched_get_priority_max (policy);
  217836. if (p < 2)
  217837. param.sched_priority = 0;
  217838. else if (p == 2 )
  217839. // Set to middle of lower realtime priority range
  217840. param.sched_priority = minp + (maxp - minp) / 4;
  217841. else
  217842. // Set to middle of higher realtime priority range
  217843. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217844. pthread_setschedparam (pthread_self(), policy, &param);
  217845. }
  217846. void Process::terminate()
  217847. {
  217848. exit (0);
  217849. }
  217850. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217851. {
  217852. static char testResult = 0;
  217853. if (testResult == 0)
  217854. {
  217855. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217856. if (testResult >= 0)
  217857. {
  217858. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217859. testResult = 1;
  217860. }
  217861. }
  217862. return testResult < 0;
  217863. }
  217864. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217865. {
  217866. return juce_isRunningUnderDebugger();
  217867. }
  217868. void Process::raisePrivilege()
  217869. {
  217870. // If running suid root, change effective user
  217871. // to root
  217872. if (geteuid() != 0 && getuid() == 0)
  217873. {
  217874. setreuid (geteuid(), getuid());
  217875. setregid (getegid(), getgid());
  217876. }
  217877. }
  217878. void Process::lowerPrivilege()
  217879. {
  217880. // If runing suid root, change effective user
  217881. // back to real user
  217882. if (geteuid() == 0 && getuid() != 0)
  217883. {
  217884. setreuid (geteuid(), getuid());
  217885. setregid (getegid(), getgid());
  217886. }
  217887. }
  217888. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217889. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217890. {
  217891. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217892. }
  217893. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217894. {
  217895. dlclose(handle);
  217896. }
  217897. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217898. {
  217899. return dlsym (libraryHandle, procedureName.toCString());
  217900. }
  217901. #endif
  217902. #endif
  217903. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217904. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217905. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217906. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217907. // compiled on its own).
  217908. #if JUCE_INCLUDED_FILE
  217909. extern Display* display;
  217910. extern Window juce_messageWindowHandle;
  217911. namespace ClipboardHelpers
  217912. {
  217913. static String localClipboardContent;
  217914. static Atom atom_UTF8_STRING;
  217915. static Atom atom_CLIPBOARD;
  217916. static Atom atom_TARGETS;
  217917. static void initSelectionAtoms()
  217918. {
  217919. static bool isInitialised = false;
  217920. if (! isInitialised)
  217921. {
  217922. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217923. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217924. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217925. }
  217926. }
  217927. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217928. // works only for strings shorter than 1000000 bytes
  217929. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217930. {
  217931. String returnData;
  217932. char* clipData;
  217933. Atom actualType;
  217934. int actualFormat;
  217935. unsigned long numItems, bytesLeft;
  217936. if (XGetWindowProperty (display, window, prop,
  217937. 0L /* offset */, 1000000 /* length (max) */, False,
  217938. AnyPropertyType /* format */,
  217939. &actualType, &actualFormat, &numItems, &bytesLeft,
  217940. (unsigned char**) &clipData) == Success)
  217941. {
  217942. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217943. returnData = String::fromUTF8 (clipData, numItems);
  217944. else if (actualType == XA_STRING && actualFormat == 8)
  217945. returnData = String (clipData, numItems);
  217946. if (clipData != 0)
  217947. XFree (clipData);
  217948. jassert (bytesLeft == 0 || numItems == 1000000);
  217949. }
  217950. XDeleteProperty (display, window, prop);
  217951. return returnData;
  217952. }
  217953. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217954. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217955. {
  217956. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217957. // The selection owner will be asked to set the JUCE_SEL property on the
  217958. // juce_messageWindowHandle with the selection content
  217959. XConvertSelection (display, selection, requestedFormat, property_name,
  217960. juce_messageWindowHandle, CurrentTime);
  217961. int count = 50; // will wait at most for 200 ms
  217962. while (--count >= 0)
  217963. {
  217964. XEvent event;
  217965. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217966. {
  217967. if (event.xselection.property == property_name)
  217968. {
  217969. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217970. selectionContent = readWindowProperty (event.xselection.requestor,
  217971. event.xselection.property,
  217972. requestedFormat);
  217973. return true;
  217974. }
  217975. else
  217976. {
  217977. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217978. }
  217979. }
  217980. // not very elegant.. we could do a select() or something like that...
  217981. // however clipboard content requesting is inherently slow on x11, it
  217982. // often takes 50ms or more so...
  217983. Thread::sleep (4);
  217984. }
  217985. return false;
  217986. }
  217987. }
  217988. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217989. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217990. {
  217991. ClipboardHelpers::initSelectionAtoms();
  217992. // the selection content is sent to the target window as a window property
  217993. XSelectionEvent reply;
  217994. reply.type = SelectionNotify;
  217995. reply.display = evt.display;
  217996. reply.requestor = evt.requestor;
  217997. reply.selection = evt.selection;
  217998. reply.target = evt.target;
  217999. reply.property = None; // == "fail"
  218000. reply.time = evt.time;
  218001. HeapBlock <char> data;
  218002. int propertyFormat = 0, numDataItems = 0;
  218003. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218004. {
  218005. if (evt.target == XA_STRING)
  218006. {
  218007. // format data according to system locale
  218008. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218009. data.calloc (numDataItems + 1);
  218010. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218011. propertyFormat = 8; // bits/item
  218012. }
  218013. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218014. {
  218015. // translate to utf8
  218016. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218017. data.calloc (numDataItems + 1);
  218018. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218019. propertyFormat = 8; // bits/item
  218020. }
  218021. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218022. {
  218023. // another application wants to know what we are able to send
  218024. numDataItems = 2;
  218025. propertyFormat = 32; // atoms are 32-bit
  218026. data.calloc (numDataItems * 4);
  218027. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218028. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218029. atoms[1] = XA_STRING;
  218030. }
  218031. }
  218032. else
  218033. {
  218034. DBG ("requested unsupported clipboard");
  218035. }
  218036. if (data != 0)
  218037. {
  218038. const int maxReasonableSelectionSize = 1000000;
  218039. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218040. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218041. {
  218042. XChangeProperty (evt.display, evt.requestor,
  218043. evt.property, evt.target,
  218044. propertyFormat /* 8 or 32 */, PropModeReplace,
  218045. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218046. reply.property = evt.property; // " == success"
  218047. }
  218048. }
  218049. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218050. }
  218051. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218052. {
  218053. ClipboardHelpers::initSelectionAtoms();
  218054. ClipboardHelpers::localClipboardContent = clipText;
  218055. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218056. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218057. }
  218058. const String SystemClipboard::getTextFromClipboard()
  218059. {
  218060. ClipboardHelpers::initSelectionAtoms();
  218061. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218062. level" clipboard that is supposed to be filled by ctrl-C
  218063. etc). When a clipboard manager is running, the content of this
  218064. selection is preserved even when the original selection owner
  218065. exits.
  218066. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218067. filled by good old x11 apps such as xterm)
  218068. */
  218069. String content;
  218070. Atom selection = XA_PRIMARY;
  218071. Window selectionOwner = None;
  218072. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218073. {
  218074. selection = ClipboardHelpers::atom_CLIPBOARD;
  218075. selectionOwner = XGetSelectionOwner (display, selection);
  218076. }
  218077. if (selectionOwner != None)
  218078. {
  218079. if (selectionOwner == juce_messageWindowHandle)
  218080. {
  218081. content = ClipboardHelpers::localClipboardContent;
  218082. }
  218083. else
  218084. {
  218085. // first try: we want an utf8 string
  218086. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218087. if (! ok)
  218088. {
  218089. // second chance, ask for a good old locale-dependent string ..
  218090. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218091. }
  218092. }
  218093. }
  218094. return content;
  218095. }
  218096. #endif
  218097. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218098. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218099. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218100. // compiled on its own).
  218101. #if JUCE_INCLUDED_FILE
  218102. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218103. #define JUCE_DEBUG_XERRORS 1
  218104. #endif
  218105. Display* display = 0;
  218106. Window juce_messageWindowHandle = None;
  218107. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218108. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218109. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218110. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218111. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218112. class InternalMessageQueue
  218113. {
  218114. public:
  218115. InternalMessageQueue()
  218116. : bytesInSocket (0),
  218117. totalEventCount (0)
  218118. {
  218119. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218120. (void) ret; jassert (ret == 0);
  218121. //setNonBlocking (fd[0]);
  218122. //setNonBlocking (fd[1]);
  218123. }
  218124. ~InternalMessageQueue()
  218125. {
  218126. close (fd[0]);
  218127. close (fd[1]);
  218128. clearSingletonInstance();
  218129. }
  218130. void postMessage (Message* msg)
  218131. {
  218132. const int maxBytesInSocketQueue = 128;
  218133. ScopedLock sl (lock);
  218134. queue.add (msg);
  218135. if (bytesInSocket < maxBytesInSocketQueue)
  218136. {
  218137. ++bytesInSocket;
  218138. ScopedUnlock ul (lock);
  218139. const unsigned char x = 0xff;
  218140. size_t bytesWritten = write (fd[0], &x, 1);
  218141. (void) bytesWritten;
  218142. }
  218143. }
  218144. bool isEmpty() const
  218145. {
  218146. ScopedLock sl (lock);
  218147. return queue.size() == 0;
  218148. }
  218149. bool dispatchNextEvent()
  218150. {
  218151. // This alternates between giving priority to XEvents or internal messages,
  218152. // to keep everything running smoothly..
  218153. if ((++totalEventCount & 1) != 0)
  218154. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218155. else
  218156. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218157. }
  218158. // Wait for an event (either XEvent, or an internal Message)
  218159. bool sleepUntilEvent (const int timeoutMs)
  218160. {
  218161. if (! isEmpty())
  218162. return true;
  218163. if (display != 0)
  218164. {
  218165. ScopedXLock xlock;
  218166. if (XPending (display))
  218167. return true;
  218168. }
  218169. struct timeval tv;
  218170. tv.tv_sec = 0;
  218171. tv.tv_usec = timeoutMs * 1000;
  218172. int fd0 = getWaitHandle();
  218173. int fdmax = fd0;
  218174. fd_set readset;
  218175. FD_ZERO (&readset);
  218176. FD_SET (fd0, &readset);
  218177. if (display != 0)
  218178. {
  218179. ScopedXLock xlock;
  218180. int fd1 = XConnectionNumber (display);
  218181. FD_SET (fd1, &readset);
  218182. fdmax = jmax (fd0, fd1);
  218183. }
  218184. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218185. return (ret > 0); // ret <= 0 if error or timeout
  218186. }
  218187. struct MessageThreadFuncCall
  218188. {
  218189. enum { uniqueID = 0x73774623 };
  218190. MessageCallbackFunction* func;
  218191. void* parameter;
  218192. void* result;
  218193. CriticalSection lock;
  218194. WaitableEvent event;
  218195. };
  218196. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218197. private:
  218198. CriticalSection lock;
  218199. OwnedArray <Message> queue;
  218200. int fd[2];
  218201. int bytesInSocket;
  218202. int totalEventCount;
  218203. int getWaitHandle() const throw() { return fd[1]; }
  218204. static bool setNonBlocking (int handle)
  218205. {
  218206. int socketFlags = fcntl (handle, F_GETFL, 0);
  218207. if (socketFlags == -1)
  218208. return false;
  218209. socketFlags |= O_NONBLOCK;
  218210. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218211. }
  218212. static bool dispatchNextXEvent()
  218213. {
  218214. if (display == 0)
  218215. return false;
  218216. XEvent evt;
  218217. {
  218218. ScopedXLock xlock;
  218219. if (! XPending (display))
  218220. return false;
  218221. XNextEvent (display, &evt);
  218222. }
  218223. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218224. juce_handleSelectionRequest (evt.xselectionrequest);
  218225. else if (evt.xany.window != juce_messageWindowHandle)
  218226. juce_windowMessageReceive (&evt);
  218227. return true;
  218228. }
  218229. Message* popNextMessage()
  218230. {
  218231. ScopedLock sl (lock);
  218232. if (bytesInSocket > 0)
  218233. {
  218234. --bytesInSocket;
  218235. ScopedUnlock ul (lock);
  218236. unsigned char x;
  218237. size_t numBytes = read (fd[1], &x, 1);
  218238. (void) numBytes;
  218239. }
  218240. return queue.removeAndReturn (0);
  218241. }
  218242. bool dispatchNextInternalMessage()
  218243. {
  218244. ScopedPointer <Message> msg (popNextMessage());
  218245. if (msg == 0)
  218246. return false;
  218247. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218248. {
  218249. // Handle callback message
  218250. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218251. call->result = (*(call->func)) (call->parameter);
  218252. call->event.signal();
  218253. }
  218254. else
  218255. {
  218256. // Handle "normal" messages
  218257. MessageManager::getInstance()->deliverMessage (msg.release());
  218258. }
  218259. return true;
  218260. }
  218261. };
  218262. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218263. namespace LinuxErrorHandling
  218264. {
  218265. static bool errorOccurred = false;
  218266. static bool keyboardBreakOccurred = false;
  218267. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218268. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218269. // Usually happens when client-server connection is broken
  218270. static int ioErrorHandler (Display* display)
  218271. {
  218272. DBG ("ERROR: connection to X server broken.. terminating.");
  218273. if (JUCEApplication::isStandaloneApp())
  218274. MessageManager::getInstance()->stopDispatchLoop();
  218275. errorOccurred = true;
  218276. return 0;
  218277. }
  218278. // A protocol error has occurred
  218279. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218280. {
  218281. #if JUCE_DEBUG_XERRORS
  218282. char errorStr[64] = { 0 };
  218283. char requestStr[64] = { 0 };
  218284. XGetErrorText (display, event->error_code, errorStr, 64);
  218285. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218286. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218287. #endif
  218288. return 0;
  218289. }
  218290. static void installXErrorHandlers()
  218291. {
  218292. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218293. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218294. }
  218295. static void removeXErrorHandlers()
  218296. {
  218297. if (JUCEApplication::isStandaloneApp())
  218298. {
  218299. XSetIOErrorHandler (oldIOErrorHandler);
  218300. oldIOErrorHandler = 0;
  218301. XSetErrorHandler (oldErrorHandler);
  218302. oldErrorHandler = 0;
  218303. }
  218304. }
  218305. static void keyboardBreakSignalHandler (int sig)
  218306. {
  218307. if (sig == SIGINT)
  218308. keyboardBreakOccurred = true;
  218309. }
  218310. static void installKeyboardBreakHandler()
  218311. {
  218312. struct sigaction saction;
  218313. sigset_t maskSet;
  218314. sigemptyset (&maskSet);
  218315. saction.sa_handler = keyboardBreakSignalHandler;
  218316. saction.sa_mask = maskSet;
  218317. saction.sa_flags = 0;
  218318. sigaction (SIGINT, &saction, 0);
  218319. }
  218320. }
  218321. void MessageManager::doPlatformSpecificInitialisation()
  218322. {
  218323. if (JUCEApplication::isStandaloneApp())
  218324. {
  218325. // Initialise xlib for multiple thread support
  218326. static bool initThreadCalled = false;
  218327. if (! initThreadCalled)
  218328. {
  218329. if (! XInitThreads())
  218330. {
  218331. // This is fatal! Print error and closedown
  218332. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218333. Process::terminate();
  218334. return;
  218335. }
  218336. initThreadCalled = true;
  218337. }
  218338. LinuxErrorHandling::installXErrorHandlers();
  218339. LinuxErrorHandling::installKeyboardBreakHandler();
  218340. }
  218341. // Create the internal message queue
  218342. InternalMessageQueue::getInstance();
  218343. // Try to connect to a display
  218344. String displayName (getenv ("DISPLAY"));
  218345. if (displayName.isEmpty())
  218346. displayName = ":0.0";
  218347. display = XOpenDisplay (displayName.toCString());
  218348. if (display != 0) // This is not fatal! we can run headless.
  218349. {
  218350. // Create a context to store user data associated with Windows we create in WindowDriver
  218351. windowHandleXContext = XUniqueContext();
  218352. // We're only interested in client messages for this window, which are always sent
  218353. XSetWindowAttributes swa;
  218354. swa.event_mask = NoEventMask;
  218355. // Create our message window (this will never be mapped)
  218356. const int screen = DefaultScreen (display);
  218357. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218358. 0, 0, 1, 1, 0, 0, InputOnly,
  218359. DefaultVisual (display, screen),
  218360. CWEventMask, &swa);
  218361. }
  218362. }
  218363. void MessageManager::doPlatformSpecificShutdown()
  218364. {
  218365. InternalMessageQueue::deleteInstance();
  218366. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218367. {
  218368. XDestroyWindow (display, juce_messageWindowHandle);
  218369. XCloseDisplay (display);
  218370. juce_messageWindowHandle = 0;
  218371. display = 0;
  218372. LinuxErrorHandling::removeXErrorHandlers();
  218373. }
  218374. }
  218375. bool juce_postMessageToSystemQueue (Message* message)
  218376. {
  218377. if (LinuxErrorHandling::errorOccurred)
  218378. return false;
  218379. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218380. return true;
  218381. }
  218382. void MessageManager::broadcastMessage (const String& value)
  218383. {
  218384. /* TODO */
  218385. }
  218386. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218387. {
  218388. if (LinuxErrorHandling::errorOccurred)
  218389. return 0;
  218390. if (isThisTheMessageThread())
  218391. return func (parameter);
  218392. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218393. messageCallContext.func = func;
  218394. messageCallContext.parameter = parameter;
  218395. InternalMessageQueue::getInstanceWithoutCreating()
  218396. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  218397. 0, 0, &messageCallContext));
  218398. // Wait for it to complete before continuing
  218399. messageCallContext.event.wait();
  218400. return messageCallContext.result;
  218401. }
  218402. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218403. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218404. {
  218405. while (! LinuxErrorHandling::errorOccurred)
  218406. {
  218407. if (LinuxErrorHandling::keyboardBreakOccurred)
  218408. {
  218409. LinuxErrorHandling::errorOccurred = true;
  218410. if (JUCEApplication::isStandaloneApp())
  218411. Process::terminate();
  218412. break;
  218413. }
  218414. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218415. return true;
  218416. if (returnIfNoPendingMessages)
  218417. break;
  218418. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218419. }
  218420. return false;
  218421. }
  218422. #endif
  218423. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218424. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218425. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218426. // compiled on its own).
  218427. #if JUCE_INCLUDED_FILE
  218428. class FreeTypeFontFace
  218429. {
  218430. public:
  218431. enum FontStyle
  218432. {
  218433. Plain = 0,
  218434. Bold = 1,
  218435. Italic = 2
  218436. };
  218437. FreeTypeFontFace (const String& familyName)
  218438. : hasSerif (false),
  218439. monospaced (false)
  218440. {
  218441. family = familyName;
  218442. }
  218443. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218444. {
  218445. if (names [(int) style].fileName.isEmpty())
  218446. {
  218447. names [(int) style].fileName = name;
  218448. names [(int) style].faceIndex = faceIndex;
  218449. }
  218450. }
  218451. const String& getFamilyName() const throw() { return family; }
  218452. const String& getFileName (const int style, int& faceIndex) const throw()
  218453. {
  218454. faceIndex = names[style].faceIndex;
  218455. return names[style].fileName;
  218456. }
  218457. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218458. bool getMonospaced() const throw() { return monospaced; }
  218459. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218460. bool getSerif() const throw() { return hasSerif; }
  218461. private:
  218462. String family;
  218463. struct FontNameIndex
  218464. {
  218465. String fileName;
  218466. int faceIndex;
  218467. };
  218468. FontNameIndex names[4];
  218469. bool hasSerif, monospaced;
  218470. };
  218471. class FreeTypeInterface : public DeletedAtShutdown
  218472. {
  218473. public:
  218474. FreeTypeInterface()
  218475. : ftLib (0),
  218476. lastFace (0),
  218477. lastBold (false),
  218478. lastItalic (false)
  218479. {
  218480. if (FT_Init_FreeType (&ftLib) != 0)
  218481. {
  218482. ftLib = 0;
  218483. DBG ("Failed to initialize FreeType");
  218484. }
  218485. StringArray fontDirs;
  218486. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218487. fontDirs.removeEmptyStrings (true);
  218488. if (fontDirs.size() == 0)
  218489. {
  218490. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218491. if (fontsInfo != 0)
  218492. {
  218493. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218494. {
  218495. fontDirs.add (e->getAllSubText().trim());
  218496. }
  218497. }
  218498. }
  218499. if (fontDirs.size() == 0)
  218500. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218501. for (int i = 0; i < fontDirs.size(); ++i)
  218502. enumerateFaces (fontDirs[i]);
  218503. }
  218504. ~FreeTypeInterface()
  218505. {
  218506. if (lastFace != 0)
  218507. FT_Done_Face (lastFace);
  218508. if (ftLib != 0)
  218509. FT_Done_FreeType (ftLib);
  218510. clearSingletonInstance();
  218511. }
  218512. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218513. {
  218514. for (int i = 0; i < faces.size(); i++)
  218515. if (faces[i]->getFamilyName() == familyName)
  218516. return faces[i];
  218517. if (! create)
  218518. return 0;
  218519. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218520. faces.add (newFace);
  218521. return newFace;
  218522. }
  218523. // Enumerate all font faces available in a given directory
  218524. void enumerateFaces (const String& path)
  218525. {
  218526. File dirPath (path);
  218527. if (path.isEmpty() || ! dirPath.isDirectory())
  218528. return;
  218529. DirectoryIterator di (dirPath, true);
  218530. while (di.next())
  218531. {
  218532. File possible (di.getFile());
  218533. if (possible.hasFileExtension ("ttf")
  218534. || possible.hasFileExtension ("pfb")
  218535. || possible.hasFileExtension ("pcf"))
  218536. {
  218537. FT_Face face;
  218538. int faceIndex = 0;
  218539. int numFaces = 0;
  218540. do
  218541. {
  218542. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218543. faceIndex, &face) == 0)
  218544. {
  218545. if (faceIndex == 0)
  218546. numFaces = face->num_faces;
  218547. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218548. {
  218549. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218550. int style = (int) FreeTypeFontFace::Plain;
  218551. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218552. style |= (int) FreeTypeFontFace::Bold;
  218553. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218554. style |= (int) FreeTypeFontFace::Italic;
  218555. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218556. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218557. // Surely there must be a better way to do this?
  218558. const String name (face->family_name);
  218559. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218560. || name.containsIgnoreCase ("Verdana")
  218561. || name.containsIgnoreCase ("Arial")));
  218562. }
  218563. FT_Done_Face (face);
  218564. }
  218565. ++faceIndex;
  218566. }
  218567. while (faceIndex < numFaces);
  218568. }
  218569. }
  218570. }
  218571. // Create a FreeType face object for a given font
  218572. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218573. {
  218574. FT_Face face = 0;
  218575. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218576. {
  218577. face = lastFace;
  218578. }
  218579. else
  218580. {
  218581. if (lastFace != 0)
  218582. {
  218583. FT_Done_Face (lastFace);
  218584. lastFace = 0;
  218585. }
  218586. lastFontName = fontName;
  218587. lastBold = bold;
  218588. lastItalic = italic;
  218589. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218590. if (ftFace != 0)
  218591. {
  218592. int style = (int) FreeTypeFontFace::Plain;
  218593. if (bold)
  218594. style |= (int) FreeTypeFontFace::Bold;
  218595. if (italic)
  218596. style |= (int) FreeTypeFontFace::Italic;
  218597. int faceIndex;
  218598. String fileName (ftFace->getFileName (style, faceIndex));
  218599. if (fileName.isEmpty())
  218600. {
  218601. style ^= (int) FreeTypeFontFace::Bold;
  218602. fileName = ftFace->getFileName (style, faceIndex);
  218603. if (fileName.isEmpty())
  218604. {
  218605. style ^= (int) FreeTypeFontFace::Bold;
  218606. style ^= (int) FreeTypeFontFace::Italic;
  218607. fileName = ftFace->getFileName (style, faceIndex);
  218608. if (! fileName.length())
  218609. {
  218610. style ^= (int) FreeTypeFontFace::Bold;
  218611. fileName = ftFace->getFileName (style, faceIndex);
  218612. }
  218613. }
  218614. }
  218615. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218616. {
  218617. face = lastFace;
  218618. // If there isn't a unicode charmap then select the first one.
  218619. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218620. FT_Set_Charmap (face, face->charmaps[0]);
  218621. }
  218622. }
  218623. }
  218624. return face;
  218625. }
  218626. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218627. {
  218628. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218629. const float height = (float) (face->ascender - face->descender);
  218630. const float scaleX = 1.0f / height;
  218631. const float scaleY = -1.0f / height;
  218632. Path destShape;
  218633. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218634. || face->glyph->format != ft_glyph_format_outline)
  218635. {
  218636. return false;
  218637. }
  218638. const FT_Outline* const outline = &face->glyph->outline;
  218639. const short* const contours = outline->contours;
  218640. const char* const tags = outline->tags;
  218641. FT_Vector* const points = outline->points;
  218642. for (int c = 0; c < outline->n_contours; c++)
  218643. {
  218644. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218645. const int endPoint = contours[c];
  218646. for (int p = startPoint; p <= endPoint; p++)
  218647. {
  218648. const float x = scaleX * points[p].x;
  218649. const float y = scaleY * points[p].y;
  218650. if (p == startPoint)
  218651. {
  218652. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218653. {
  218654. float x2 = scaleX * points [endPoint].x;
  218655. float y2 = scaleY * points [endPoint].y;
  218656. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218657. {
  218658. x2 = (x + x2) * 0.5f;
  218659. y2 = (y + y2) * 0.5f;
  218660. }
  218661. destShape.startNewSubPath (x2, y2);
  218662. }
  218663. else
  218664. {
  218665. destShape.startNewSubPath (x, y);
  218666. }
  218667. }
  218668. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218669. {
  218670. if (p != startPoint)
  218671. destShape.lineTo (x, y);
  218672. }
  218673. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218674. {
  218675. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218676. float x2 = scaleX * points [nextIndex].x;
  218677. float y2 = scaleY * points [nextIndex].y;
  218678. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218679. {
  218680. x2 = (x + x2) * 0.5f;
  218681. y2 = (y + y2) * 0.5f;
  218682. }
  218683. else
  218684. {
  218685. ++p;
  218686. }
  218687. destShape.quadraticTo (x, y, x2, y2);
  218688. }
  218689. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218690. {
  218691. if (p >= endPoint)
  218692. return false;
  218693. const int next1 = p + 1;
  218694. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218695. const float x2 = scaleX * points [next1].x;
  218696. const float y2 = scaleY * points [next1].y;
  218697. const float x3 = scaleX * points [next2].x;
  218698. const float y3 = scaleY * points [next2].y;
  218699. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218700. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218701. return false;
  218702. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218703. p += 2;
  218704. }
  218705. }
  218706. destShape.closeSubPath();
  218707. }
  218708. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218709. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218710. addKerning (face, dest, character, glyphIndex);
  218711. return true;
  218712. }
  218713. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218714. {
  218715. const float height = (float) (face->ascender - face->descender);
  218716. uint32 rightGlyphIndex;
  218717. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218718. while (rightGlyphIndex != 0)
  218719. {
  218720. FT_Vector kerning;
  218721. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218722. {
  218723. if (kerning.x != 0)
  218724. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218725. }
  218726. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218727. }
  218728. }
  218729. // Add a glyph to a font
  218730. bool addGlyphToFont (const uint32 character, const String& fontName,
  218731. bool bold, bool italic, CustomTypeface& dest)
  218732. {
  218733. FT_Face face = createFT_Face (fontName, bold, italic);
  218734. return face != 0 && addGlyph (face, dest, character);
  218735. }
  218736. void getFamilyNames (StringArray& familyNames) const
  218737. {
  218738. for (int i = 0; i < faces.size(); i++)
  218739. familyNames.add (faces[i]->getFamilyName());
  218740. }
  218741. void getMonospacedNames (StringArray& monoSpaced) const
  218742. {
  218743. for (int i = 0; i < faces.size(); i++)
  218744. if (faces[i]->getMonospaced())
  218745. monoSpaced.add (faces[i]->getFamilyName());
  218746. }
  218747. void getSerifNames (StringArray& serif) const
  218748. {
  218749. for (int i = 0; i < faces.size(); i++)
  218750. if (faces[i]->getSerif())
  218751. serif.add (faces[i]->getFamilyName());
  218752. }
  218753. void getSansSerifNames (StringArray& sansSerif) const
  218754. {
  218755. for (int i = 0; i < faces.size(); i++)
  218756. if (! faces[i]->getSerif())
  218757. sansSerif.add (faces[i]->getFamilyName());
  218758. }
  218759. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218760. private:
  218761. FT_Library ftLib;
  218762. FT_Face lastFace;
  218763. String lastFontName;
  218764. bool lastBold, lastItalic;
  218765. OwnedArray<FreeTypeFontFace> faces;
  218766. };
  218767. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218768. class FreetypeTypeface : public CustomTypeface
  218769. {
  218770. public:
  218771. FreetypeTypeface (const Font& font)
  218772. {
  218773. FT_Face face = FreeTypeInterface::getInstance()
  218774. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218775. if (face == 0)
  218776. {
  218777. #if JUCE_DEBUG
  218778. String msg ("Failed to create typeface: ");
  218779. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218780. DBG (msg);
  218781. #endif
  218782. }
  218783. else
  218784. {
  218785. setCharacteristics (font.getTypefaceName(),
  218786. face->ascender / (float) (face->ascender - face->descender),
  218787. font.isBold(), font.isItalic(),
  218788. L' ');
  218789. }
  218790. }
  218791. bool loadGlyphIfPossible (juce_wchar character)
  218792. {
  218793. return FreeTypeInterface::getInstance()
  218794. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218795. }
  218796. };
  218797. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218798. {
  218799. return new FreetypeTypeface (font);
  218800. }
  218801. const StringArray Font::findAllTypefaceNames()
  218802. {
  218803. StringArray s;
  218804. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218805. s.sort (true);
  218806. return s;
  218807. }
  218808. namespace
  218809. {
  218810. const String pickBestFont (const StringArray& names,
  218811. const char* const choicesString)
  218812. {
  218813. StringArray choices;
  218814. choices.addTokens (String (choicesString), ",", String::empty);
  218815. choices.trim();
  218816. choices.removeEmptyStrings();
  218817. int i, j;
  218818. for (j = 0; j < choices.size(); ++j)
  218819. if (names.contains (choices[j], true))
  218820. return choices[j];
  218821. for (j = 0; j < choices.size(); ++j)
  218822. for (i = 0; i < names.size(); i++)
  218823. if (names[i].startsWithIgnoreCase (choices[j]))
  218824. return names[i];
  218825. for (j = 0; j < choices.size(); ++j)
  218826. for (i = 0; i < names.size(); i++)
  218827. if (names[i].containsIgnoreCase (choices[j]))
  218828. return names[i];
  218829. return names[0];
  218830. }
  218831. const String linux_getDefaultSansSerifFontName()
  218832. {
  218833. StringArray allFonts;
  218834. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218835. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218836. }
  218837. const String linux_getDefaultSerifFontName()
  218838. {
  218839. StringArray allFonts;
  218840. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218841. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218842. }
  218843. const String linux_getDefaultMonospacedFontName()
  218844. {
  218845. StringArray allFonts;
  218846. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218847. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218848. }
  218849. }
  218850. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218851. {
  218852. defaultSans = linux_getDefaultSansSerifFontName();
  218853. defaultSerif = linux_getDefaultSerifFontName();
  218854. defaultFixed = linux_getDefaultMonospacedFontName();
  218855. }
  218856. #endif
  218857. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218858. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218859. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218860. // compiled on its own).
  218861. #if JUCE_INCLUDED_FILE
  218862. // These are defined in juce_linux_Messaging.cpp
  218863. extern Display* display;
  218864. extern XContext windowHandleXContext;
  218865. namespace Atoms
  218866. {
  218867. enum ProtocolItems
  218868. {
  218869. TAKE_FOCUS = 0,
  218870. DELETE_WINDOW = 1,
  218871. PING = 2
  218872. };
  218873. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218874. ActiveWin, Pid, WindowType, WindowState,
  218875. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218876. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218877. XdndActionDescription, XdndActionCopy,
  218878. allowedActions[5],
  218879. allowedMimeTypes[2];
  218880. const unsigned long DndVersion = 3;
  218881. static void initialiseAtoms()
  218882. {
  218883. static bool atomsInitialised = false;
  218884. if (! atomsInitialised)
  218885. {
  218886. atomsInitialised = true;
  218887. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218888. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218889. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218890. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218891. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218892. State = XInternAtom (display, "WM_STATE", True);
  218893. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218894. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218895. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218896. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218897. XdndAware = XInternAtom (display, "XdndAware", False);
  218898. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218899. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218900. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218901. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218902. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218903. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218904. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218905. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218906. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218907. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218908. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218909. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218910. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218911. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218912. allowedActions[1] = XdndActionCopy;
  218913. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218914. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218915. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218916. }
  218917. }
  218918. }
  218919. namespace Keys
  218920. {
  218921. enum MouseButtons
  218922. {
  218923. NoButton = 0,
  218924. LeftButton = 1,
  218925. MiddleButton = 2,
  218926. RightButton = 3,
  218927. WheelUp = 4,
  218928. WheelDown = 5
  218929. };
  218930. static int AltMask = 0;
  218931. static int NumLockMask = 0;
  218932. static bool numLock = false;
  218933. static bool capsLock = false;
  218934. static char keyStates [32];
  218935. static const int extendedKeyModifier = 0x10000000;
  218936. }
  218937. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218938. {
  218939. int keysym;
  218940. if (keyCode & Keys::extendedKeyModifier)
  218941. {
  218942. keysym = 0xff00 | (keyCode & 0xff);
  218943. }
  218944. else
  218945. {
  218946. keysym = keyCode;
  218947. if (keysym == (XK_Tab & 0xff)
  218948. || keysym == (XK_Return & 0xff)
  218949. || keysym == (XK_Escape & 0xff)
  218950. || keysym == (XK_BackSpace & 0xff))
  218951. {
  218952. keysym |= 0xff00;
  218953. }
  218954. }
  218955. ScopedXLock xlock;
  218956. const int keycode = XKeysymToKeycode (display, keysym);
  218957. const int keybyte = keycode >> 3;
  218958. const int keybit = (1 << (keycode & 7));
  218959. return (Keys::keyStates [keybyte] & keybit) != 0;
  218960. }
  218961. #if JUCE_USE_XSHM
  218962. namespace XSHMHelpers
  218963. {
  218964. static int trappedErrorCode = 0;
  218965. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218966. {
  218967. trappedErrorCode = err->error_code;
  218968. return 0;
  218969. }
  218970. static bool isShmAvailable() throw()
  218971. {
  218972. static bool isChecked = false;
  218973. static bool isAvailable = false;
  218974. if (! isChecked)
  218975. {
  218976. isChecked = true;
  218977. int major, minor;
  218978. Bool pixmaps;
  218979. ScopedXLock xlock;
  218980. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218981. {
  218982. trappedErrorCode = 0;
  218983. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218984. XShmSegmentInfo segmentInfo;
  218985. zerostruct (segmentInfo);
  218986. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218987. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218988. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218989. xImage->bytes_per_line * xImage->height,
  218990. IPC_CREAT | 0777)) >= 0)
  218991. {
  218992. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218993. if (segmentInfo.shmaddr != (void*) -1)
  218994. {
  218995. segmentInfo.readOnly = False;
  218996. xImage->data = segmentInfo.shmaddr;
  218997. XSync (display, False);
  218998. if (XShmAttach (display, &segmentInfo) != 0)
  218999. {
  219000. XSync (display, False);
  219001. XShmDetach (display, &segmentInfo);
  219002. isAvailable = true;
  219003. }
  219004. }
  219005. XFlush (display);
  219006. XDestroyImage (xImage);
  219007. shmdt (segmentInfo.shmaddr);
  219008. }
  219009. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219010. XSetErrorHandler (oldHandler);
  219011. if (trappedErrorCode != 0)
  219012. isAvailable = false;
  219013. }
  219014. }
  219015. return isAvailable;
  219016. }
  219017. }
  219018. #endif
  219019. #if JUCE_USE_XRENDER
  219020. namespace XRender
  219021. {
  219022. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219023. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219024. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219025. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219026. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219027. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219028. static tXRenderFindFormat xRenderFindFormat = 0;
  219029. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219030. static bool isAvailable()
  219031. {
  219032. static bool hasLoaded = false;
  219033. if (! hasLoaded)
  219034. {
  219035. ScopedXLock xlock;
  219036. hasLoaded = true;
  219037. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219038. if (h != 0)
  219039. {
  219040. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219041. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219042. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219043. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219044. }
  219045. if (xRenderQueryVersion != 0
  219046. && xRenderFindStandardFormat != 0
  219047. && xRenderFindFormat != 0
  219048. && xRenderFindVisualFormat != 0)
  219049. {
  219050. int major, minor;
  219051. if (xRenderQueryVersion (display, &major, &minor))
  219052. return true;
  219053. }
  219054. xRenderQueryVersion = 0;
  219055. }
  219056. return xRenderQueryVersion != 0;
  219057. }
  219058. static XRenderPictFormat* findPictureFormat()
  219059. {
  219060. ScopedXLock xlock;
  219061. XRenderPictFormat* pictFormat = 0;
  219062. if (isAvailable())
  219063. {
  219064. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219065. if (pictFormat == 0)
  219066. {
  219067. XRenderPictFormat desiredFormat;
  219068. desiredFormat.type = PictTypeDirect;
  219069. desiredFormat.depth = 32;
  219070. desiredFormat.direct.alphaMask = 0xff;
  219071. desiredFormat.direct.redMask = 0xff;
  219072. desiredFormat.direct.greenMask = 0xff;
  219073. desiredFormat.direct.blueMask = 0xff;
  219074. desiredFormat.direct.alpha = 24;
  219075. desiredFormat.direct.red = 16;
  219076. desiredFormat.direct.green = 8;
  219077. desiredFormat.direct.blue = 0;
  219078. pictFormat = xRenderFindFormat (display,
  219079. PictFormatType | PictFormatDepth
  219080. | PictFormatRedMask | PictFormatRed
  219081. | PictFormatGreenMask | PictFormatGreen
  219082. | PictFormatBlueMask | PictFormatBlue
  219083. | PictFormatAlphaMask | PictFormatAlpha,
  219084. &desiredFormat,
  219085. 0);
  219086. }
  219087. }
  219088. return pictFormat;
  219089. }
  219090. }
  219091. #endif
  219092. namespace Visuals
  219093. {
  219094. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219095. {
  219096. ScopedXLock xlock;
  219097. Visual* visual = 0;
  219098. int numVisuals = 0;
  219099. long desiredMask = VisualNoMask;
  219100. XVisualInfo desiredVisual;
  219101. desiredVisual.screen = DefaultScreen (display);
  219102. desiredVisual.depth = desiredDepth;
  219103. desiredMask = VisualScreenMask | VisualDepthMask;
  219104. if (desiredDepth == 32)
  219105. {
  219106. desiredVisual.c_class = TrueColor;
  219107. desiredVisual.red_mask = 0x00FF0000;
  219108. desiredVisual.green_mask = 0x0000FF00;
  219109. desiredVisual.blue_mask = 0x000000FF;
  219110. desiredVisual.bits_per_rgb = 8;
  219111. desiredMask |= VisualClassMask;
  219112. desiredMask |= VisualRedMaskMask;
  219113. desiredMask |= VisualGreenMaskMask;
  219114. desiredMask |= VisualBlueMaskMask;
  219115. desiredMask |= VisualBitsPerRGBMask;
  219116. }
  219117. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219118. desiredMask,
  219119. &desiredVisual,
  219120. &numVisuals);
  219121. if (xvinfos != 0)
  219122. {
  219123. for (int i = 0; i < numVisuals; i++)
  219124. {
  219125. if (xvinfos[i].depth == desiredDepth)
  219126. {
  219127. visual = xvinfos[i].visual;
  219128. break;
  219129. }
  219130. }
  219131. XFree (xvinfos);
  219132. }
  219133. return visual;
  219134. }
  219135. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219136. {
  219137. Visual* visual = 0;
  219138. if (desiredDepth == 32)
  219139. {
  219140. #if JUCE_USE_XSHM
  219141. if (XSHMHelpers::isShmAvailable())
  219142. {
  219143. #if JUCE_USE_XRENDER
  219144. if (XRender::isAvailable())
  219145. {
  219146. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219147. if (pictFormat != 0)
  219148. {
  219149. int numVisuals = 0;
  219150. XVisualInfo desiredVisual;
  219151. desiredVisual.screen = DefaultScreen (display);
  219152. desiredVisual.depth = 32;
  219153. desiredVisual.bits_per_rgb = 8;
  219154. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219155. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219156. &desiredVisual, &numVisuals);
  219157. if (xvinfos != 0)
  219158. {
  219159. for (int i = 0; i < numVisuals; ++i)
  219160. {
  219161. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219162. if (pictVisualFormat != 0
  219163. && pictVisualFormat->type == PictTypeDirect
  219164. && pictVisualFormat->direct.alphaMask)
  219165. {
  219166. visual = xvinfos[i].visual;
  219167. matchedDepth = 32;
  219168. break;
  219169. }
  219170. }
  219171. XFree (xvinfos);
  219172. }
  219173. }
  219174. }
  219175. #endif
  219176. if (visual == 0)
  219177. {
  219178. visual = findVisualWithDepth (32);
  219179. if (visual != 0)
  219180. matchedDepth = 32;
  219181. }
  219182. }
  219183. #endif
  219184. }
  219185. if (visual == 0 && desiredDepth >= 24)
  219186. {
  219187. visual = findVisualWithDepth (24);
  219188. if (visual != 0)
  219189. matchedDepth = 24;
  219190. }
  219191. if (visual == 0 && desiredDepth >= 16)
  219192. {
  219193. visual = findVisualWithDepth (16);
  219194. if (visual != 0)
  219195. matchedDepth = 16;
  219196. }
  219197. return visual;
  219198. }
  219199. }
  219200. class XBitmapImage : public Image::SharedImage
  219201. {
  219202. public:
  219203. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219204. const bool clearImage, const int imageDepth_, Visual* visual)
  219205. : Image::SharedImage (format_, w, h),
  219206. imageDepth (imageDepth_),
  219207. gc (None)
  219208. {
  219209. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219210. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219211. lineStride = ((w * pixelStride + 3) & ~3);
  219212. ScopedXLock xlock;
  219213. #if JUCE_USE_XSHM
  219214. usingXShm = false;
  219215. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219216. {
  219217. zerostruct (segmentInfo);
  219218. segmentInfo.shmid = -1;
  219219. segmentInfo.shmaddr = (char *) -1;
  219220. segmentInfo.readOnly = False;
  219221. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219222. if (xImage != 0)
  219223. {
  219224. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219225. xImage->bytes_per_line * xImage->height,
  219226. IPC_CREAT | 0777)) >= 0)
  219227. {
  219228. if (segmentInfo.shmid != -1)
  219229. {
  219230. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219231. if (segmentInfo.shmaddr != (void*) -1)
  219232. {
  219233. segmentInfo.readOnly = False;
  219234. xImage->data = segmentInfo.shmaddr;
  219235. imageData = (uint8*) segmentInfo.shmaddr;
  219236. if (XShmAttach (display, &segmentInfo) != 0)
  219237. usingXShm = true;
  219238. else
  219239. jassertfalse;
  219240. }
  219241. else
  219242. {
  219243. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219244. }
  219245. }
  219246. }
  219247. }
  219248. }
  219249. if (! usingXShm)
  219250. #endif
  219251. {
  219252. imageDataAllocated.malloc (lineStride * h);
  219253. imageData = imageDataAllocated;
  219254. if (format_ == Image::ARGB && clearImage)
  219255. zeromem (imageData, h * lineStride);
  219256. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219257. xImage->width = w;
  219258. xImage->height = h;
  219259. xImage->xoffset = 0;
  219260. xImage->format = ZPixmap;
  219261. xImage->data = (char*) imageData;
  219262. xImage->byte_order = ImageByteOrder (display);
  219263. xImage->bitmap_unit = BitmapUnit (display);
  219264. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219265. xImage->bitmap_pad = 32;
  219266. xImage->depth = pixelStride * 8;
  219267. xImage->bytes_per_line = lineStride;
  219268. xImage->bits_per_pixel = pixelStride * 8;
  219269. xImage->red_mask = 0x00FF0000;
  219270. xImage->green_mask = 0x0000FF00;
  219271. xImage->blue_mask = 0x000000FF;
  219272. if (imageDepth == 16)
  219273. {
  219274. const int pixelStride = 2;
  219275. const int lineStride = ((w * pixelStride + 3) & ~3);
  219276. imageData16Bit.malloc (lineStride * h);
  219277. xImage->data = imageData16Bit;
  219278. xImage->bitmap_pad = 16;
  219279. xImage->depth = pixelStride * 8;
  219280. xImage->bytes_per_line = lineStride;
  219281. xImage->bits_per_pixel = pixelStride * 8;
  219282. xImage->red_mask = visual->red_mask;
  219283. xImage->green_mask = visual->green_mask;
  219284. xImage->blue_mask = visual->blue_mask;
  219285. }
  219286. if (! XInitImage (xImage))
  219287. jassertfalse;
  219288. }
  219289. }
  219290. ~XBitmapImage()
  219291. {
  219292. ScopedXLock xlock;
  219293. if (gc != None)
  219294. XFreeGC (display, gc);
  219295. #if JUCE_USE_XSHM
  219296. if (usingXShm)
  219297. {
  219298. XShmDetach (display, &segmentInfo);
  219299. XFlush (display);
  219300. XDestroyImage (xImage);
  219301. shmdt (segmentInfo.shmaddr);
  219302. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219303. }
  219304. else
  219305. #endif
  219306. {
  219307. xImage->data = 0;
  219308. XDestroyImage (xImage);
  219309. }
  219310. }
  219311. Image::ImageType getType() const { return Image::NativeImage; }
  219312. LowLevelGraphicsContext* createLowLevelContext()
  219313. {
  219314. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219315. }
  219316. SharedImage* clone()
  219317. {
  219318. jassertfalse;
  219319. return 0;
  219320. }
  219321. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219322. {
  219323. ScopedXLock xlock;
  219324. if (gc == None)
  219325. {
  219326. XGCValues gcvalues;
  219327. gcvalues.foreground = None;
  219328. gcvalues.background = None;
  219329. gcvalues.function = GXcopy;
  219330. gcvalues.plane_mask = AllPlanes;
  219331. gcvalues.clip_mask = None;
  219332. gcvalues.graphics_exposures = False;
  219333. gc = XCreateGC (display, window,
  219334. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219335. &gcvalues);
  219336. }
  219337. if (imageDepth == 16)
  219338. {
  219339. const uint32 rMask = xImage->red_mask;
  219340. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219341. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219342. const uint32 gMask = xImage->green_mask;
  219343. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219344. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219345. const uint32 bMask = xImage->blue_mask;
  219346. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219347. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219348. const Image::BitmapData srcData (Image (this), false);
  219349. for (int y = sy; y < sy + dh; ++y)
  219350. {
  219351. const uint8* p = srcData.getPixelPointer (sx, y);
  219352. for (int x = sx; x < sx + dw; ++x)
  219353. {
  219354. const PixelRGB* const pixel = (const PixelRGB*) p;
  219355. p += srcData.pixelStride;
  219356. XPutPixel (xImage, x, y,
  219357. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219358. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219359. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219360. }
  219361. }
  219362. }
  219363. // blit results to screen.
  219364. #if JUCE_USE_XSHM
  219365. if (usingXShm)
  219366. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219367. else
  219368. #endif
  219369. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219370. }
  219371. private:
  219372. XImage* xImage;
  219373. const int imageDepth;
  219374. HeapBlock <uint8> imageDataAllocated;
  219375. HeapBlock <char> imageData16Bit;
  219376. GC gc;
  219377. #if JUCE_USE_XSHM
  219378. XShmSegmentInfo segmentInfo;
  219379. bool usingXShm;
  219380. #endif
  219381. static int getShiftNeeded (const uint32 mask) throw()
  219382. {
  219383. for (int i = 32; --i >= 0;)
  219384. if (((mask >> i) & 1) != 0)
  219385. return i - 7;
  219386. jassertfalse;
  219387. return 0;
  219388. }
  219389. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219390. };
  219391. namespace PixmapHelpers
  219392. {
  219393. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219394. {
  219395. ScopedXLock xlock;
  219396. const int width = image.getWidth();
  219397. const int height = image.getHeight();
  219398. HeapBlock <uint32> colour (width * height);
  219399. int index = 0;
  219400. for (int y = 0; y < height; ++y)
  219401. for (int x = 0; x < width; ++x)
  219402. colour[index++] = image.getPixelAt (x, y).getARGB();
  219403. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219404. 0, reinterpret_cast<char*> (colour.getData()),
  219405. width, height, 32, 0);
  219406. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219407. width, height, 24);
  219408. GC gc = XCreateGC (display, pixmap, 0, 0);
  219409. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219410. XFreeGC (display, gc);
  219411. return pixmap;
  219412. }
  219413. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219414. {
  219415. ScopedXLock xlock;
  219416. const int width = image.getWidth();
  219417. const int height = image.getHeight();
  219418. const int stride = (width + 7) >> 3;
  219419. HeapBlock <char> mask;
  219420. mask.calloc (stride * height);
  219421. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219422. for (int y = 0; y < height; ++y)
  219423. {
  219424. for (int x = 0; x < width; ++x)
  219425. {
  219426. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219427. const int offset = y * stride + (x >> 3);
  219428. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219429. mask[offset] |= bit;
  219430. }
  219431. }
  219432. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219433. mask.getData(), width, height, 1, 0, 1);
  219434. }
  219435. }
  219436. class LinuxComponentPeer : public ComponentPeer
  219437. {
  219438. public:
  219439. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219440. : ComponentPeer (component, windowStyleFlags),
  219441. windowH (0),
  219442. parentWindow (0),
  219443. wx (0),
  219444. wy (0),
  219445. ww (0),
  219446. wh (0),
  219447. fullScreen (false),
  219448. mapped (false),
  219449. visual (0),
  219450. depth (0)
  219451. {
  219452. // it's dangerous to create a window on a thread other than the message thread..
  219453. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219454. repainter = new LinuxRepaintManager (this);
  219455. createWindow();
  219456. setTitle (component->getName());
  219457. }
  219458. ~LinuxComponentPeer()
  219459. {
  219460. // it's dangerous to delete a window on a thread other than the message thread..
  219461. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219462. deleteIconPixmaps();
  219463. destroyWindow();
  219464. windowH = 0;
  219465. }
  219466. void* getNativeHandle() const
  219467. {
  219468. return (void*) windowH;
  219469. }
  219470. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219471. {
  219472. XPointer peer = 0;
  219473. ScopedXLock xlock;
  219474. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219475. {
  219476. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219477. peer = 0;
  219478. }
  219479. return (LinuxComponentPeer*) peer;
  219480. }
  219481. void setVisible (bool shouldBeVisible)
  219482. {
  219483. ScopedXLock xlock;
  219484. if (shouldBeVisible)
  219485. XMapWindow (display, windowH);
  219486. else
  219487. XUnmapWindow (display, windowH);
  219488. }
  219489. void setTitle (const String& title)
  219490. {
  219491. XTextProperty nameProperty;
  219492. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219493. ScopedXLock xlock;
  219494. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219495. {
  219496. XSetWMName (display, windowH, &nameProperty);
  219497. XSetWMIconName (display, windowH, &nameProperty);
  219498. XFree (nameProperty.value);
  219499. }
  219500. }
  219501. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219502. {
  219503. fullScreen = isNowFullScreen;
  219504. if (windowH != 0)
  219505. {
  219506. Component::SafePointer<Component> deletionChecker (component);
  219507. wx = x;
  219508. wy = y;
  219509. ww = jmax (1, w);
  219510. wh = jmax (1, h);
  219511. ScopedXLock xlock;
  219512. // Make sure the Window manager does what we want
  219513. XSizeHints* hints = XAllocSizeHints();
  219514. hints->flags = USSize | USPosition;
  219515. hints->width = ww;
  219516. hints->height = wh;
  219517. hints->x = wx;
  219518. hints->y = wy;
  219519. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219520. {
  219521. hints->min_width = hints->max_width = hints->width;
  219522. hints->min_height = hints->max_height = hints->height;
  219523. hints->flags |= PMinSize | PMaxSize;
  219524. }
  219525. XSetWMNormalHints (display, windowH, hints);
  219526. XFree (hints);
  219527. XMoveResizeWindow (display, windowH,
  219528. wx - windowBorder.getLeft(),
  219529. wy - windowBorder.getTop(), ww, wh);
  219530. if (deletionChecker != 0)
  219531. {
  219532. updateBorderSize();
  219533. handleMovedOrResized();
  219534. }
  219535. }
  219536. }
  219537. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219538. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219539. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219540. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219541. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219542. {
  219543. return relativePosition + getScreenPosition();
  219544. }
  219545. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219546. {
  219547. return screenPosition - getScreenPosition();
  219548. }
  219549. void setAlpha (float newAlpha)
  219550. {
  219551. //xxx todo!
  219552. }
  219553. void setMinimised (bool shouldBeMinimised)
  219554. {
  219555. if (shouldBeMinimised)
  219556. {
  219557. Window root = RootWindow (display, DefaultScreen (display));
  219558. XClientMessageEvent clientMsg;
  219559. clientMsg.display = display;
  219560. clientMsg.window = windowH;
  219561. clientMsg.type = ClientMessage;
  219562. clientMsg.format = 32;
  219563. clientMsg.message_type = Atoms::ChangeState;
  219564. clientMsg.data.l[0] = IconicState;
  219565. ScopedXLock xlock;
  219566. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219567. }
  219568. else
  219569. {
  219570. setVisible (true);
  219571. }
  219572. }
  219573. bool isMinimised() const
  219574. {
  219575. bool minimised = false;
  219576. unsigned char* stateProp;
  219577. unsigned long nitems, bytesLeft;
  219578. Atom actualType;
  219579. int actualFormat;
  219580. ScopedXLock xlock;
  219581. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219582. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219583. &stateProp) == Success
  219584. && actualType == Atoms::State
  219585. && actualFormat == 32
  219586. && nitems > 0)
  219587. {
  219588. if (((unsigned long*) stateProp)[0] == IconicState)
  219589. minimised = true;
  219590. XFree (stateProp);
  219591. }
  219592. return minimised;
  219593. }
  219594. void setFullScreen (const bool shouldBeFullScreen)
  219595. {
  219596. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219597. setMinimised (false);
  219598. if (fullScreen != shouldBeFullScreen)
  219599. {
  219600. if (shouldBeFullScreen)
  219601. r = Desktop::getInstance().getMainMonitorArea();
  219602. if (! r.isEmpty())
  219603. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219604. getComponent()->repaint();
  219605. }
  219606. }
  219607. bool isFullScreen() const
  219608. {
  219609. return fullScreen;
  219610. }
  219611. bool isChildWindowOf (Window possibleParent) const
  219612. {
  219613. Window* windowList = 0;
  219614. uint32 windowListSize = 0;
  219615. Window parent, root;
  219616. ScopedXLock xlock;
  219617. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219618. {
  219619. if (windowList != 0)
  219620. XFree (windowList);
  219621. return parent == possibleParent;
  219622. }
  219623. return false;
  219624. }
  219625. bool isFrontWindow() const
  219626. {
  219627. Window* windowList = 0;
  219628. uint32 windowListSize = 0;
  219629. bool result = false;
  219630. ScopedXLock xlock;
  219631. Window parent, root = RootWindow (display, DefaultScreen (display));
  219632. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219633. {
  219634. for (int i = windowListSize; --i >= 0;)
  219635. {
  219636. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219637. if (peer != 0)
  219638. {
  219639. result = (peer == this);
  219640. break;
  219641. }
  219642. }
  219643. }
  219644. if (windowList != 0)
  219645. XFree (windowList);
  219646. return result;
  219647. }
  219648. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219649. {
  219650. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219651. return false;
  219652. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219653. {
  219654. Component* const c = Desktop::getInstance().getComponent (i);
  219655. if (c == getComponent())
  219656. break;
  219657. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219658. return false;
  219659. }
  219660. if (trueIfInAChildWindow)
  219661. return true;
  219662. ::Window root, child;
  219663. unsigned int bw, depth;
  219664. int wx, wy, w, h;
  219665. ScopedXLock xlock;
  219666. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219667. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219668. &bw, &depth))
  219669. {
  219670. return false;
  219671. }
  219672. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219673. return false;
  219674. return child == None;
  219675. }
  219676. const BorderSize getFrameSize() const
  219677. {
  219678. return BorderSize();
  219679. }
  219680. bool setAlwaysOnTop (bool alwaysOnTop)
  219681. {
  219682. return false;
  219683. }
  219684. void toFront (bool makeActive)
  219685. {
  219686. if (makeActive)
  219687. {
  219688. setVisible (true);
  219689. grabFocus();
  219690. }
  219691. XEvent ev;
  219692. ev.xclient.type = ClientMessage;
  219693. ev.xclient.serial = 0;
  219694. ev.xclient.send_event = True;
  219695. ev.xclient.message_type = Atoms::ActiveWin;
  219696. ev.xclient.window = windowH;
  219697. ev.xclient.format = 32;
  219698. ev.xclient.data.l[0] = 2;
  219699. ev.xclient.data.l[1] = CurrentTime;
  219700. ev.xclient.data.l[2] = 0;
  219701. ev.xclient.data.l[3] = 0;
  219702. ev.xclient.data.l[4] = 0;
  219703. {
  219704. ScopedXLock xlock;
  219705. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219706. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219707. XWindowAttributes attr;
  219708. XGetWindowAttributes (display, windowH, &attr);
  219709. if (component->isAlwaysOnTop())
  219710. XRaiseWindow (display, windowH);
  219711. XSync (display, False);
  219712. }
  219713. handleBroughtToFront();
  219714. }
  219715. void toBehind (ComponentPeer* other)
  219716. {
  219717. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219718. jassert (otherPeer != 0); // wrong type of window?
  219719. if (otherPeer != 0)
  219720. {
  219721. setMinimised (false);
  219722. Window newStack[] = { otherPeer->windowH, windowH };
  219723. ScopedXLock xlock;
  219724. XRestackWindows (display, newStack, 2);
  219725. }
  219726. }
  219727. bool isFocused() const
  219728. {
  219729. int revert = 0;
  219730. Window focusedWindow = 0;
  219731. ScopedXLock xlock;
  219732. XGetInputFocus (display, &focusedWindow, &revert);
  219733. return focusedWindow == windowH;
  219734. }
  219735. void grabFocus()
  219736. {
  219737. XWindowAttributes atts;
  219738. ScopedXLock xlock;
  219739. if (windowH != 0
  219740. && XGetWindowAttributes (display, windowH, &atts)
  219741. && atts.map_state == IsViewable
  219742. && ! isFocused())
  219743. {
  219744. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219745. isActiveApplication = true;
  219746. }
  219747. }
  219748. void textInputRequired (const Point<int>&)
  219749. {
  219750. }
  219751. void repaint (const Rectangle<int>& area)
  219752. {
  219753. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219754. }
  219755. void performAnyPendingRepaintsNow()
  219756. {
  219757. repainter->performAnyPendingRepaintsNow();
  219758. }
  219759. void setIcon (const Image& newIcon)
  219760. {
  219761. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219762. HeapBlock <unsigned long> data (dataSize);
  219763. int index = 0;
  219764. data[index++] = newIcon.getWidth();
  219765. data[index++] = newIcon.getHeight();
  219766. for (int y = 0; y < newIcon.getHeight(); ++y)
  219767. for (int x = 0; x < newIcon.getWidth(); ++x)
  219768. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219769. ScopedXLock xlock;
  219770. XChangeProperty (display, windowH,
  219771. XInternAtom (display, "_NET_WM_ICON", False),
  219772. XA_CARDINAL, 32, PropModeReplace,
  219773. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219774. deleteIconPixmaps();
  219775. XWMHints* wmHints = XGetWMHints (display, windowH);
  219776. if (wmHints == 0)
  219777. wmHints = XAllocWMHints();
  219778. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219779. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219780. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219781. XSetWMHints (display, windowH, wmHints);
  219782. XFree (wmHints);
  219783. XSync (display, False);
  219784. }
  219785. void deleteIconPixmaps()
  219786. {
  219787. ScopedXLock xlock;
  219788. XWMHints* wmHints = XGetWMHints (display, windowH);
  219789. if (wmHints != 0)
  219790. {
  219791. if ((wmHints->flags & IconPixmapHint) != 0)
  219792. {
  219793. wmHints->flags &= ~IconPixmapHint;
  219794. XFreePixmap (display, wmHints->icon_pixmap);
  219795. }
  219796. if ((wmHints->flags & IconMaskHint) != 0)
  219797. {
  219798. wmHints->flags &= ~IconMaskHint;
  219799. XFreePixmap (display, wmHints->icon_mask);
  219800. }
  219801. XSetWMHints (display, windowH, wmHints);
  219802. XFree (wmHints);
  219803. }
  219804. }
  219805. void handleWindowMessage (XEvent* event)
  219806. {
  219807. switch (event->xany.type)
  219808. {
  219809. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219810. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219811. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219812. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219813. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219814. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219815. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219816. case FocusIn: handleFocusInEvent(); break;
  219817. case FocusOut: handleFocusOutEvent(); break;
  219818. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219819. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219820. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219821. case SelectionNotify: handleDragAndDropSelection (event); break;
  219822. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219823. case ReparentNotify: handleReparentNotifyEvent(); break;
  219824. case GravityNotify: handleGravityNotify(); break;
  219825. case CirculateNotify:
  219826. case CreateNotify:
  219827. case DestroyNotify:
  219828. // Think we can ignore these
  219829. break;
  219830. case MapNotify:
  219831. mapped = true;
  219832. handleBroughtToFront();
  219833. break;
  219834. case UnmapNotify:
  219835. mapped = false;
  219836. break;
  219837. case SelectionClear:
  219838. case SelectionRequest:
  219839. break;
  219840. default:
  219841. #if JUCE_USE_XSHM
  219842. {
  219843. ScopedXLock xlock;
  219844. if (event->xany.type == XShmGetEventBase (display))
  219845. repainter->notifyPaintCompleted();
  219846. }
  219847. #endif
  219848. break;
  219849. }
  219850. }
  219851. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219852. {
  219853. char utf8 [64] = { 0 };
  219854. juce_wchar unicodeChar = 0;
  219855. int keyCode = 0;
  219856. bool keyDownChange = false;
  219857. KeySym sym;
  219858. {
  219859. ScopedXLock xlock;
  219860. updateKeyStates (keyEvent->keycode, true);
  219861. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219862. ::setlocale (LC_ALL, "");
  219863. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219864. ::setlocale (LC_ALL, oldLocale);
  219865. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219866. keyCode = (int) unicodeChar;
  219867. if (keyCode < 0x20)
  219868. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219869. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219870. }
  219871. const ModifierKeys oldMods (currentModifiers);
  219872. bool keyPressed = false;
  219873. if ((sym & 0xff00) == 0xff00)
  219874. {
  219875. switch (sym) // Translate keypad
  219876. {
  219877. case XK_KP_Divide: keyCode = XK_slash; break;
  219878. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219879. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219880. case XK_KP_Add: keyCode = XK_plus; break;
  219881. case XK_KP_Enter: keyCode = XK_Return; break;
  219882. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219883. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219884. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219885. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219886. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219887. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219888. case XK_KP_5: keyCode = XK_5; break;
  219889. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219890. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219891. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219892. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219893. default: break;
  219894. }
  219895. switch (sym)
  219896. {
  219897. case XK_Left:
  219898. case XK_Right:
  219899. case XK_Up:
  219900. case XK_Down:
  219901. case XK_Page_Up:
  219902. case XK_Page_Down:
  219903. case XK_End:
  219904. case XK_Home:
  219905. case XK_Delete:
  219906. case XK_Insert:
  219907. keyPressed = true;
  219908. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219909. break;
  219910. case XK_Tab:
  219911. case XK_Return:
  219912. case XK_Escape:
  219913. case XK_BackSpace:
  219914. keyPressed = true;
  219915. keyCode &= 0xff;
  219916. break;
  219917. default:
  219918. if (sym >= XK_F1 && sym <= XK_F16)
  219919. {
  219920. keyPressed = true;
  219921. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219922. }
  219923. break;
  219924. }
  219925. }
  219926. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219927. keyPressed = true;
  219928. if (oldMods != currentModifiers)
  219929. handleModifierKeysChange();
  219930. if (keyDownChange)
  219931. handleKeyUpOrDown (true);
  219932. if (keyPressed)
  219933. handleKeyPress (keyCode, unicodeChar);
  219934. }
  219935. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219936. {
  219937. updateKeyStates (keyEvent->keycode, false);
  219938. KeySym sym;
  219939. {
  219940. ScopedXLock xlock;
  219941. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219942. }
  219943. const ModifierKeys oldMods (currentModifiers);
  219944. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219945. if (oldMods != currentModifiers)
  219946. handleModifierKeysChange();
  219947. if (keyDownChange)
  219948. handleKeyUpOrDown (false);
  219949. }
  219950. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219951. {
  219952. updateKeyModifiers (buttonPressEvent->state);
  219953. bool buttonMsg = false;
  219954. const int map = pointerMap [buttonPressEvent->button - Button1];
  219955. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219956. {
  219957. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219958. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219959. }
  219960. if (map == Keys::LeftButton)
  219961. {
  219962. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219963. buttonMsg = true;
  219964. }
  219965. else if (map == Keys::RightButton)
  219966. {
  219967. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219968. buttonMsg = true;
  219969. }
  219970. else if (map == Keys::MiddleButton)
  219971. {
  219972. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219973. buttonMsg = true;
  219974. }
  219975. if (buttonMsg)
  219976. {
  219977. toFront (true);
  219978. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219979. getEventTime (buttonPressEvent->time));
  219980. }
  219981. clearLastMousePos();
  219982. }
  219983. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219984. {
  219985. updateKeyModifiers (buttonRelEvent->state);
  219986. const int map = pointerMap [buttonRelEvent->button - Button1];
  219987. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219988. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219989. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219990. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219991. getEventTime (buttonRelEvent->time));
  219992. clearLastMousePos();
  219993. }
  219994. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219995. {
  219996. updateKeyModifiers (movedEvent->state);
  219997. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219998. if (lastMousePos != mousePos)
  219999. {
  220000. lastMousePos = mousePos;
  220001. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220002. {
  220003. Window wRoot = 0, wParent = 0;
  220004. {
  220005. ScopedXLock xlock;
  220006. unsigned int numChildren;
  220007. Window* wChild = 0;
  220008. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220009. }
  220010. if (wParent != 0
  220011. && wParent != windowH
  220012. && wParent != wRoot)
  220013. {
  220014. parentWindow = wParent;
  220015. updateBounds();
  220016. }
  220017. else
  220018. {
  220019. parentWindow = 0;
  220020. }
  220021. }
  220022. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220023. }
  220024. }
  220025. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  220026. {
  220027. clearLastMousePos();
  220028. if (! currentModifiers.isAnyMouseButtonDown())
  220029. {
  220030. updateKeyModifiers (enterEvent->state);
  220031. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220032. }
  220033. }
  220034. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  220035. {
  220036. // Suppress the normal leave if we've got a pointer grab, or if
  220037. // it's a bogus one caused by clicking a mouse button when running
  220038. // in a Window manager
  220039. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220040. || leaveEvent->mode == NotifyUngrab)
  220041. {
  220042. updateKeyModifiers (leaveEvent->state);
  220043. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220044. }
  220045. }
  220046. void handleFocusInEvent()
  220047. {
  220048. isActiveApplication = true;
  220049. if (isFocused())
  220050. handleFocusGain();
  220051. }
  220052. void handleFocusOutEvent()
  220053. {
  220054. isActiveApplication = false;
  220055. if (! isFocused())
  220056. handleFocusLoss();
  220057. }
  220058. void handleExposeEvent (XExposeEvent* exposeEvent)
  220059. {
  220060. // Batch together all pending expose events
  220061. XEvent nextEvent;
  220062. ScopedXLock xlock;
  220063. if (exposeEvent->window != windowH)
  220064. {
  220065. Window child;
  220066. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220067. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220068. &child);
  220069. }
  220070. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220071. exposeEvent->width, exposeEvent->height));
  220072. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220073. {
  220074. XPeekEvent (display, (XEvent*) &nextEvent);
  220075. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220076. break;
  220077. XNextEvent (display, (XEvent*) &nextEvent);
  220078. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220079. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220080. nextExposeEvent->width, nextExposeEvent->height));
  220081. }
  220082. }
  220083. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220084. {
  220085. updateBounds();
  220086. updateBorderSize();
  220087. handleMovedOrResized();
  220088. // if the native title bar is dragged, need to tell any active menus, etc.
  220089. if ((styleFlags & windowHasTitleBar) != 0
  220090. && component->isCurrentlyBlockedByAnotherModalComponent())
  220091. {
  220092. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220093. if (currentModalComp != 0)
  220094. currentModalComp->inputAttemptWhenModal();
  220095. }
  220096. if (confEvent->window == windowH
  220097. && confEvent->above != 0
  220098. && isFrontWindow())
  220099. {
  220100. handleBroughtToFront();
  220101. }
  220102. }
  220103. void handleReparentNotifyEvent()
  220104. {
  220105. parentWindow = 0;
  220106. Window wRoot = 0;
  220107. Window* wChild = 0;
  220108. unsigned int numChildren;
  220109. {
  220110. ScopedXLock xlock;
  220111. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220112. }
  220113. if (parentWindow == windowH || parentWindow == wRoot)
  220114. parentWindow = 0;
  220115. handleGravityNotify();
  220116. }
  220117. void handleGravityNotify()
  220118. {
  220119. updateBounds();
  220120. updateBorderSize();
  220121. handleMovedOrResized();
  220122. }
  220123. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220124. {
  220125. if (mappingEvent->request != MappingPointer)
  220126. {
  220127. // Deal with modifier/keyboard mapping
  220128. ScopedXLock xlock;
  220129. XRefreshKeyboardMapping (mappingEvent);
  220130. updateModifierMappings();
  220131. }
  220132. }
  220133. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220134. {
  220135. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220136. {
  220137. const Atom atom = (Atom) clientMsg->data.l[0];
  220138. if (atom == Atoms::ProtocolList [Atoms::PING])
  220139. {
  220140. Window root = RootWindow (display, DefaultScreen (display));
  220141. clientMsg->window = root;
  220142. XSendEvent (display, root, False, NoEventMask, event);
  220143. XFlush (display);
  220144. }
  220145. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220146. {
  220147. XWindowAttributes atts;
  220148. ScopedXLock xlock;
  220149. if (clientMsg->window != 0
  220150. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220151. {
  220152. if (atts.map_state == IsViewable)
  220153. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220154. }
  220155. }
  220156. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220157. {
  220158. handleUserClosingWindow();
  220159. }
  220160. }
  220161. else if (clientMsg->message_type == Atoms::XdndEnter)
  220162. {
  220163. handleDragAndDropEnter (clientMsg);
  220164. }
  220165. else if (clientMsg->message_type == Atoms::XdndLeave)
  220166. {
  220167. resetDragAndDrop();
  220168. }
  220169. else if (clientMsg->message_type == Atoms::XdndPosition)
  220170. {
  220171. handleDragAndDropPosition (clientMsg);
  220172. }
  220173. else if (clientMsg->message_type == Atoms::XdndDrop)
  220174. {
  220175. handleDragAndDropDrop (clientMsg);
  220176. }
  220177. else if (clientMsg->message_type == Atoms::XdndStatus)
  220178. {
  220179. handleDragAndDropStatus (clientMsg);
  220180. }
  220181. else if (clientMsg->message_type == Atoms::XdndFinished)
  220182. {
  220183. resetDragAndDrop();
  220184. }
  220185. }
  220186. void showMouseCursor (Cursor cursor) throw()
  220187. {
  220188. ScopedXLock xlock;
  220189. XDefineCursor (display, windowH, cursor);
  220190. }
  220191. void setTaskBarIcon (const Image& image)
  220192. {
  220193. ScopedXLock xlock;
  220194. taskbarImage = image;
  220195. Screen* const screen = XDefaultScreenOfDisplay (display);
  220196. const int screenNumber = XScreenNumberOfScreen (screen);
  220197. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220198. screenAtom << screenNumber;
  220199. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220200. XGrabServer (display);
  220201. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220202. if (managerWin != None)
  220203. XSelectInput (display, managerWin, StructureNotifyMask);
  220204. XUngrabServer (display);
  220205. XFlush (display);
  220206. if (managerWin != None)
  220207. {
  220208. XEvent ev;
  220209. zerostruct (ev);
  220210. ev.xclient.type = ClientMessage;
  220211. ev.xclient.window = managerWin;
  220212. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220213. ev.xclient.format = 32;
  220214. ev.xclient.data.l[0] = CurrentTime;
  220215. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220216. ev.xclient.data.l[2] = windowH;
  220217. ev.xclient.data.l[3] = 0;
  220218. ev.xclient.data.l[4] = 0;
  220219. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220220. XSync (display, False);
  220221. }
  220222. // For older KDE's ...
  220223. long atomData = 1;
  220224. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220225. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220226. // For more recent KDE's...
  220227. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220228. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220229. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220230. XSizeHints* hints = XAllocSizeHints();
  220231. hints->flags = PMinSize;
  220232. hints->min_width = 22;
  220233. hints->min_height = 22;
  220234. XSetWMNormalHints (display, windowH, hints);
  220235. XFree (hints);
  220236. }
  220237. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220238. bool dontRepaint;
  220239. static ModifierKeys currentModifiers;
  220240. static bool isActiveApplication;
  220241. private:
  220242. class LinuxRepaintManager : public Timer
  220243. {
  220244. public:
  220245. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220246. : peer (peer_),
  220247. lastTimeImageUsed (0)
  220248. {
  220249. #if JUCE_USE_XSHM
  220250. shmCompletedDrawing = true;
  220251. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220252. if (useARGBImagesForRendering)
  220253. {
  220254. ScopedXLock xlock;
  220255. XShmSegmentInfo segmentinfo;
  220256. XImage* const testImage
  220257. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220258. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220259. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220260. XDestroyImage (testImage);
  220261. }
  220262. #endif
  220263. }
  220264. void timerCallback()
  220265. {
  220266. #if JUCE_USE_XSHM
  220267. if (! shmCompletedDrawing)
  220268. return;
  220269. #endif
  220270. if (! regionsNeedingRepaint.isEmpty())
  220271. {
  220272. stopTimer();
  220273. performAnyPendingRepaintsNow();
  220274. }
  220275. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220276. {
  220277. stopTimer();
  220278. image = Image::null;
  220279. }
  220280. }
  220281. void repaint (const Rectangle<int>& area)
  220282. {
  220283. if (! isTimerRunning())
  220284. startTimer (repaintTimerPeriod);
  220285. regionsNeedingRepaint.add (area);
  220286. }
  220287. void performAnyPendingRepaintsNow()
  220288. {
  220289. #if JUCE_USE_XSHM
  220290. if (! shmCompletedDrawing)
  220291. {
  220292. startTimer (repaintTimerPeriod);
  220293. return;
  220294. }
  220295. #endif
  220296. peer->clearMaskedRegion();
  220297. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220298. regionsNeedingRepaint.clear();
  220299. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220300. if (! totalArea.isEmpty())
  220301. {
  220302. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220303. || image.getHeight() < totalArea.getHeight())
  220304. {
  220305. #if JUCE_USE_XSHM
  220306. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220307. : Image::RGB,
  220308. #else
  220309. image = Image (new XBitmapImage (Image::RGB,
  220310. #endif
  220311. (totalArea.getWidth() + 31) & ~31,
  220312. (totalArea.getHeight() + 31) & ~31,
  220313. false, peer->depth, peer->visual));
  220314. }
  220315. startTimer (repaintTimerPeriod);
  220316. RectangleList adjustedList (originalRepaintRegion);
  220317. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220318. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220319. if (peer->depth == 32)
  220320. {
  220321. RectangleList::Iterator i (originalRepaintRegion);
  220322. while (i.next())
  220323. image.clear (*i.getRectangle() - totalArea.getPosition());
  220324. }
  220325. peer->handlePaint (context);
  220326. if (! peer->maskedRegion.isEmpty())
  220327. originalRepaintRegion.subtract (peer->maskedRegion);
  220328. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220329. {
  220330. #if JUCE_USE_XSHM
  220331. shmCompletedDrawing = false;
  220332. #endif
  220333. const Rectangle<int>& r = *i.getRectangle();
  220334. static_cast<XBitmapImage*> (image.getSharedImage())
  220335. ->blitToWindow (peer->windowH,
  220336. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220337. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220338. }
  220339. }
  220340. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220341. startTimer (repaintTimerPeriod);
  220342. }
  220343. #if JUCE_USE_XSHM
  220344. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220345. #endif
  220346. private:
  220347. enum { repaintTimerPeriod = 1000 / 100 };
  220348. LinuxComponentPeer* const peer;
  220349. Image image;
  220350. uint32 lastTimeImageUsed;
  220351. RectangleList regionsNeedingRepaint;
  220352. #if JUCE_USE_XSHM
  220353. bool useARGBImagesForRendering, shmCompletedDrawing;
  220354. #endif
  220355. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220356. };
  220357. ScopedPointer <LinuxRepaintManager> repainter;
  220358. friend class LinuxRepaintManager;
  220359. Window windowH, parentWindow;
  220360. int wx, wy, ww, wh;
  220361. Image taskbarImage;
  220362. bool fullScreen, mapped;
  220363. Visual* visual;
  220364. int depth;
  220365. BorderSize windowBorder;
  220366. struct MotifWmHints
  220367. {
  220368. unsigned long flags;
  220369. unsigned long functions;
  220370. unsigned long decorations;
  220371. long input_mode;
  220372. unsigned long status;
  220373. };
  220374. static void updateKeyStates (const int keycode, const bool press) throw()
  220375. {
  220376. const int keybyte = keycode >> 3;
  220377. const int keybit = (1 << (keycode & 7));
  220378. if (press)
  220379. Keys::keyStates [keybyte] |= keybit;
  220380. else
  220381. Keys::keyStates [keybyte] &= ~keybit;
  220382. }
  220383. static void updateKeyModifiers (const int status) throw()
  220384. {
  220385. int keyMods = 0;
  220386. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220387. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220388. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220389. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220390. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220391. Keys::capsLock = ((status & LockMask) != 0);
  220392. }
  220393. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220394. {
  220395. int modifier = 0;
  220396. bool isModifier = true;
  220397. switch (sym)
  220398. {
  220399. case XK_Shift_L:
  220400. case XK_Shift_R:
  220401. modifier = ModifierKeys::shiftModifier;
  220402. break;
  220403. case XK_Control_L:
  220404. case XK_Control_R:
  220405. modifier = ModifierKeys::ctrlModifier;
  220406. break;
  220407. case XK_Alt_L:
  220408. case XK_Alt_R:
  220409. modifier = ModifierKeys::altModifier;
  220410. break;
  220411. case XK_Num_Lock:
  220412. if (press)
  220413. Keys::numLock = ! Keys::numLock;
  220414. break;
  220415. case XK_Caps_Lock:
  220416. if (press)
  220417. Keys::capsLock = ! Keys::capsLock;
  220418. break;
  220419. case XK_Scroll_Lock:
  220420. break;
  220421. default:
  220422. isModifier = false;
  220423. break;
  220424. }
  220425. if (modifier != 0)
  220426. {
  220427. if (press)
  220428. currentModifiers = currentModifiers.withFlags (modifier);
  220429. else
  220430. currentModifiers = currentModifiers.withoutFlags (modifier);
  220431. }
  220432. return isModifier;
  220433. }
  220434. // Alt and Num lock are not defined by standard X
  220435. // modifier constants: check what they're mapped to
  220436. static void updateModifierMappings() throw()
  220437. {
  220438. ScopedXLock xlock;
  220439. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220440. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220441. Keys::AltMask = 0;
  220442. Keys::NumLockMask = 0;
  220443. XModifierKeymap* mapping = XGetModifierMapping (display);
  220444. if (mapping)
  220445. {
  220446. for (int i = 0; i < 8; i++)
  220447. {
  220448. if (mapping->modifiermap [i << 1] == altLeftCode)
  220449. Keys::AltMask = 1 << i;
  220450. else if (mapping->modifiermap [i << 1] == numLockCode)
  220451. Keys::NumLockMask = 1 << i;
  220452. }
  220453. XFreeModifiermap (mapping);
  220454. }
  220455. }
  220456. void removeWindowDecorations (Window wndH)
  220457. {
  220458. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220459. if (hints != None)
  220460. {
  220461. MotifWmHints motifHints;
  220462. zerostruct (motifHints);
  220463. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220464. motifHints.decorations = 0;
  220465. ScopedXLock xlock;
  220466. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220467. (unsigned char*) &motifHints, 4);
  220468. }
  220469. hints = XInternAtom (display, "_WIN_HINTS", True);
  220470. if (hints != None)
  220471. {
  220472. long gnomeHints = 0;
  220473. ScopedXLock xlock;
  220474. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220475. (unsigned char*) &gnomeHints, 1);
  220476. }
  220477. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220478. if (hints != None)
  220479. {
  220480. long kwmHints = 2; /*KDE_tinyDecoration*/
  220481. ScopedXLock xlock;
  220482. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220483. (unsigned char*) &kwmHints, 1);
  220484. }
  220485. }
  220486. void addWindowButtons (Window wndH)
  220487. {
  220488. ScopedXLock xlock;
  220489. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220490. if (hints != None)
  220491. {
  220492. MotifWmHints motifHints;
  220493. zerostruct (motifHints);
  220494. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220495. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220496. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220497. if ((styleFlags & windowHasCloseButton) != 0)
  220498. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220499. if ((styleFlags & windowHasMinimiseButton) != 0)
  220500. {
  220501. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220502. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220503. }
  220504. if ((styleFlags & windowHasMaximiseButton) != 0)
  220505. {
  220506. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220507. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220508. }
  220509. if ((styleFlags & windowIsResizable) != 0)
  220510. {
  220511. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220512. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220513. }
  220514. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220515. }
  220516. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220517. if (hints != None)
  220518. {
  220519. int netHints [6];
  220520. int num = 0;
  220521. if ((styleFlags & windowIsResizable) != 0)
  220522. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220523. if ((styleFlags & windowHasMaximiseButton) != 0)
  220524. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220525. if ((styleFlags & windowHasMinimiseButton) != 0)
  220526. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220527. if ((styleFlags & windowHasCloseButton) != 0)
  220528. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220529. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220530. }
  220531. }
  220532. void setWindowType()
  220533. {
  220534. int netHints [2];
  220535. int numHints = 0;
  220536. if ((styleFlags & windowIsTemporary) != 0
  220537. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220538. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220539. else
  220540. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220541. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220542. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220543. (unsigned char*) &netHints, numHints);
  220544. numHints = 0;
  220545. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220546. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220547. if (component->isAlwaysOnTop())
  220548. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220549. if (numHints > 0)
  220550. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220551. (unsigned char*) &netHints, numHints);
  220552. }
  220553. void createWindow()
  220554. {
  220555. ScopedXLock xlock;
  220556. Atoms::initialiseAtoms();
  220557. resetDragAndDrop();
  220558. // Get defaults for various properties
  220559. const int screen = DefaultScreen (display);
  220560. Window root = RootWindow (display, screen);
  220561. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220562. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220563. if (visual == 0)
  220564. {
  220565. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220566. Process::terminate();
  220567. }
  220568. // Create and install a colormap suitable fr our visual
  220569. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220570. XInstallColormap (display, colormap);
  220571. // Set up the window attributes
  220572. XSetWindowAttributes swa;
  220573. swa.border_pixel = 0;
  220574. swa.background_pixmap = None;
  220575. swa.colormap = colormap;
  220576. swa.event_mask = getAllEventsMask();
  220577. windowH = XCreateWindow (display, root,
  220578. 0, 0, 1, 1,
  220579. 0, depth, InputOutput, visual,
  220580. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220581. &swa);
  220582. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220583. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220584. GrabModeAsync, GrabModeAsync, None, None);
  220585. // Set the window context to identify the window handle object
  220586. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220587. {
  220588. // Failed
  220589. jassertfalse;
  220590. Logger::outputDebugString ("Failed to create context information for window.\n");
  220591. XDestroyWindow (display, windowH);
  220592. windowH = 0;
  220593. return;
  220594. }
  220595. // Set window manager hints
  220596. XWMHints* wmHints = XAllocWMHints();
  220597. wmHints->flags = InputHint | StateHint;
  220598. wmHints->input = True; // Locally active input model
  220599. wmHints->initial_state = NormalState;
  220600. XSetWMHints (display, windowH, wmHints);
  220601. XFree (wmHints);
  220602. // Set the window type
  220603. setWindowType();
  220604. // Define decoration
  220605. if ((styleFlags & windowHasTitleBar) == 0)
  220606. removeWindowDecorations (windowH);
  220607. else
  220608. addWindowButtons (windowH);
  220609. setTitle (getComponent()->getName());
  220610. // Associate the PID, allowing to be shut down when something goes wrong
  220611. unsigned long pid = getpid();
  220612. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220613. (unsigned char*) &pid, 1);
  220614. // Set window manager protocols
  220615. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220616. (unsigned char*) Atoms::ProtocolList, 2);
  220617. // Set drag and drop flags
  220618. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220619. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220620. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220621. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220622. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220623. (const unsigned char*) "", 0);
  220624. unsigned long dndVersion = Atoms::DndVersion;
  220625. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220626. (const unsigned char*) &dndVersion, 1);
  220627. // Initialise the pointer and keyboard mapping
  220628. // This is not the same as the logical pointer mapping the X server uses:
  220629. // we don't mess with this.
  220630. static bool mappingInitialised = false;
  220631. if (! mappingInitialised)
  220632. {
  220633. mappingInitialised = true;
  220634. const int numButtons = XGetPointerMapping (display, 0, 0);
  220635. if (numButtons == 2)
  220636. {
  220637. pointerMap[0] = Keys::LeftButton;
  220638. pointerMap[1] = Keys::RightButton;
  220639. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220640. }
  220641. else if (numButtons >= 3)
  220642. {
  220643. pointerMap[0] = Keys::LeftButton;
  220644. pointerMap[1] = Keys::MiddleButton;
  220645. pointerMap[2] = Keys::RightButton;
  220646. if (numButtons >= 5)
  220647. {
  220648. pointerMap[3] = Keys::WheelUp;
  220649. pointerMap[4] = Keys::WheelDown;
  220650. }
  220651. }
  220652. updateModifierMappings();
  220653. }
  220654. }
  220655. void destroyWindow()
  220656. {
  220657. ScopedXLock xlock;
  220658. XPointer handlePointer;
  220659. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220660. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220661. XDestroyWindow (display, windowH);
  220662. // Wait for it to complete and then remove any events for this
  220663. // window from the event queue.
  220664. XSync (display, false);
  220665. XEvent event;
  220666. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220667. {}
  220668. }
  220669. static int getAllEventsMask() throw()
  220670. {
  220671. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220672. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220673. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220674. }
  220675. static int64 getEventTime (::Time t)
  220676. {
  220677. static int64 eventTimeOffset = 0x12345678;
  220678. const int64 thisMessageTime = t;
  220679. if (eventTimeOffset == 0x12345678)
  220680. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220681. return eventTimeOffset + thisMessageTime;
  220682. }
  220683. void updateBorderSize()
  220684. {
  220685. if ((styleFlags & windowHasTitleBar) == 0)
  220686. {
  220687. windowBorder = BorderSize (0);
  220688. }
  220689. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220690. {
  220691. ScopedXLock xlock;
  220692. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220693. if (hints != None)
  220694. {
  220695. unsigned char* data = 0;
  220696. unsigned long nitems, bytesLeft;
  220697. Atom actualType;
  220698. int actualFormat;
  220699. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220700. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220701. &data) == Success)
  220702. {
  220703. const unsigned long* const sizes = (const unsigned long*) data;
  220704. if (actualFormat == 32)
  220705. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220706. (int) sizes[3], (int) sizes[1]);
  220707. XFree (data);
  220708. }
  220709. }
  220710. }
  220711. }
  220712. void updateBounds()
  220713. {
  220714. jassert (windowH != 0);
  220715. if (windowH != 0)
  220716. {
  220717. Window root, child;
  220718. unsigned int bw, depth;
  220719. ScopedXLock xlock;
  220720. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220721. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220722. &bw, &depth))
  220723. {
  220724. wx = wy = ww = wh = 0;
  220725. }
  220726. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220727. {
  220728. wx = wy = 0;
  220729. }
  220730. }
  220731. }
  220732. void resetDragAndDrop()
  220733. {
  220734. dragAndDropFiles.clear();
  220735. lastDropPos = Point<int> (-1, -1);
  220736. dragAndDropCurrentMimeType = 0;
  220737. dragAndDropSourceWindow = 0;
  220738. srcMimeTypeAtomList.clear();
  220739. }
  220740. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220741. {
  220742. msg.type = ClientMessage;
  220743. msg.display = display;
  220744. msg.window = dragAndDropSourceWindow;
  220745. msg.format = 32;
  220746. msg.data.l[0] = windowH;
  220747. ScopedXLock xlock;
  220748. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220749. }
  220750. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220751. {
  220752. XClientMessageEvent msg;
  220753. zerostruct (msg);
  220754. msg.message_type = Atoms::XdndStatus;
  220755. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220756. msg.data.l[4] = dropAction;
  220757. sendDragAndDropMessage (msg);
  220758. }
  220759. void sendDragAndDropLeave()
  220760. {
  220761. XClientMessageEvent msg;
  220762. zerostruct (msg);
  220763. msg.message_type = Atoms::XdndLeave;
  220764. sendDragAndDropMessage (msg);
  220765. }
  220766. void sendDragAndDropFinish()
  220767. {
  220768. XClientMessageEvent msg;
  220769. zerostruct (msg);
  220770. msg.message_type = Atoms::XdndFinished;
  220771. sendDragAndDropMessage (msg);
  220772. }
  220773. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220774. {
  220775. if ((clientMsg->data.l[1] & 1) == 0)
  220776. {
  220777. sendDragAndDropLeave();
  220778. if (dragAndDropFiles.size() > 0)
  220779. handleFileDragExit (dragAndDropFiles);
  220780. dragAndDropFiles.clear();
  220781. }
  220782. }
  220783. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220784. {
  220785. if (dragAndDropSourceWindow == 0)
  220786. return;
  220787. dragAndDropSourceWindow = clientMsg->data.l[0];
  220788. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220789. (int) clientMsg->data.l[2] & 0xffff);
  220790. dropPos -= getScreenPosition();
  220791. if (lastDropPos != dropPos)
  220792. {
  220793. lastDropPos = dropPos;
  220794. dragAndDropTimestamp = clientMsg->data.l[3];
  220795. Atom targetAction = Atoms::XdndActionCopy;
  220796. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220797. {
  220798. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220799. {
  220800. targetAction = Atoms::allowedActions[i];
  220801. break;
  220802. }
  220803. }
  220804. sendDragAndDropStatus (true, targetAction);
  220805. if (dragAndDropFiles.size() == 0)
  220806. updateDraggedFileList (clientMsg);
  220807. if (dragAndDropFiles.size() > 0)
  220808. handleFileDragMove (dragAndDropFiles, dropPos);
  220809. }
  220810. }
  220811. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220812. {
  220813. if (dragAndDropFiles.size() == 0)
  220814. updateDraggedFileList (clientMsg);
  220815. const StringArray files (dragAndDropFiles);
  220816. const Point<int> lastPos (lastDropPos);
  220817. sendDragAndDropFinish();
  220818. resetDragAndDrop();
  220819. if (files.size() > 0)
  220820. handleFileDragDrop (files, lastPos);
  220821. }
  220822. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220823. {
  220824. dragAndDropFiles.clear();
  220825. srcMimeTypeAtomList.clear();
  220826. dragAndDropCurrentMimeType = 0;
  220827. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220828. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220829. {
  220830. dragAndDropSourceWindow = 0;
  220831. return;
  220832. }
  220833. dragAndDropSourceWindow = clientMsg->data.l[0];
  220834. if ((clientMsg->data.l[1] & 1) != 0)
  220835. {
  220836. Atom actual;
  220837. int format;
  220838. unsigned long count = 0, remaining = 0;
  220839. unsigned char* data = 0;
  220840. ScopedXLock xlock;
  220841. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220842. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220843. &count, &remaining, &data);
  220844. if (data != 0)
  220845. {
  220846. if (actual == XA_ATOM && format == 32 && count != 0)
  220847. {
  220848. const unsigned long* const types = (const unsigned long*) data;
  220849. for (unsigned int i = 0; i < count; ++i)
  220850. if (types[i] != None)
  220851. srcMimeTypeAtomList.add (types[i]);
  220852. }
  220853. XFree (data);
  220854. }
  220855. }
  220856. if (srcMimeTypeAtomList.size() == 0)
  220857. {
  220858. for (int i = 2; i < 5; ++i)
  220859. if (clientMsg->data.l[i] != None)
  220860. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220861. if (srcMimeTypeAtomList.size() == 0)
  220862. {
  220863. dragAndDropSourceWindow = 0;
  220864. return;
  220865. }
  220866. }
  220867. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220868. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220869. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220870. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220871. handleDragAndDropPosition (clientMsg);
  220872. }
  220873. void handleDragAndDropSelection (const XEvent* const evt)
  220874. {
  220875. dragAndDropFiles.clear();
  220876. if (evt->xselection.property != 0)
  220877. {
  220878. StringArray lines;
  220879. {
  220880. MemoryBlock dropData;
  220881. for (;;)
  220882. {
  220883. Atom actual;
  220884. uint8* data = 0;
  220885. unsigned long count = 0, remaining = 0;
  220886. int format = 0;
  220887. ScopedXLock xlock;
  220888. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220889. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220890. &format, &count, &remaining, &data) == Success)
  220891. {
  220892. dropData.append (data, count * format / 8);
  220893. XFree (data);
  220894. if (remaining == 0)
  220895. break;
  220896. }
  220897. else
  220898. {
  220899. XFree (data);
  220900. break;
  220901. }
  220902. }
  220903. lines.addLines (dropData.toString());
  220904. }
  220905. for (int i = 0; i < lines.size(); ++i)
  220906. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220907. dragAndDropFiles.trim();
  220908. dragAndDropFiles.removeEmptyStrings();
  220909. }
  220910. }
  220911. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220912. {
  220913. dragAndDropFiles.clear();
  220914. if (dragAndDropSourceWindow != None
  220915. && dragAndDropCurrentMimeType != 0)
  220916. {
  220917. dragAndDropTimestamp = clientMsg->data.l[2];
  220918. ScopedXLock xlock;
  220919. XConvertSelection (display,
  220920. Atoms::XdndSelection,
  220921. dragAndDropCurrentMimeType,
  220922. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220923. windowH,
  220924. dragAndDropTimestamp);
  220925. }
  220926. }
  220927. StringArray dragAndDropFiles;
  220928. int dragAndDropTimestamp;
  220929. Point<int> lastDropPos;
  220930. Atom dragAndDropCurrentMimeType;
  220931. Window dragAndDropSourceWindow;
  220932. Array <Atom> srcMimeTypeAtomList;
  220933. static int pointerMap[5];
  220934. static Point<int> lastMousePos;
  220935. static void clearLastMousePos() throw()
  220936. {
  220937. lastMousePos = Point<int> (0x100000, 0x100000);
  220938. }
  220939. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220940. };
  220941. ModifierKeys LinuxComponentPeer::currentModifiers;
  220942. bool LinuxComponentPeer::isActiveApplication = false;
  220943. int LinuxComponentPeer::pointerMap[5];
  220944. Point<int> LinuxComponentPeer::lastMousePos;
  220945. bool Process::isForegroundProcess()
  220946. {
  220947. return LinuxComponentPeer::isActiveApplication;
  220948. }
  220949. void ModifierKeys::updateCurrentModifiers() throw()
  220950. {
  220951. currentModifiers = LinuxComponentPeer::currentModifiers;
  220952. }
  220953. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220954. {
  220955. Window root, child;
  220956. int x, y, winx, winy;
  220957. unsigned int mask;
  220958. int mouseMods = 0;
  220959. ScopedXLock xlock;
  220960. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220961. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220962. {
  220963. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220964. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220965. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220966. }
  220967. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220968. return LinuxComponentPeer::currentModifiers;
  220969. }
  220970. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220971. {
  220972. if (enableOrDisable)
  220973. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220974. }
  220975. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220976. {
  220977. return new LinuxComponentPeer (this, styleFlags);
  220978. }
  220979. // (this callback is hooked up in the messaging code)
  220980. void juce_windowMessageReceive (XEvent* event)
  220981. {
  220982. if (event->xany.window != None)
  220983. {
  220984. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220985. if (ComponentPeer::isValidPeer (peer))
  220986. peer->handleWindowMessage (event);
  220987. }
  220988. else
  220989. {
  220990. switch (event->xany.type)
  220991. {
  220992. case KeymapNotify:
  220993. {
  220994. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220995. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220996. break;
  220997. }
  220998. default:
  220999. break;
  221000. }
  221001. }
  221002. }
  221003. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221004. {
  221005. if (display == 0)
  221006. return;
  221007. #if JUCE_USE_XINERAMA
  221008. int major_opcode, first_event, first_error;
  221009. ScopedXLock xlock;
  221010. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221011. {
  221012. typedef Bool (*tXineramaIsActive) (Display*);
  221013. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221014. static tXineramaIsActive xXineramaIsActive = 0;
  221015. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221016. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221017. {
  221018. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221019. if (h == 0)
  221020. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221021. if (h != 0)
  221022. {
  221023. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221024. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221025. }
  221026. }
  221027. if (xXineramaIsActive != 0
  221028. && xXineramaQueryScreens != 0
  221029. && xXineramaIsActive (display))
  221030. {
  221031. int numMonitors = 0;
  221032. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221033. if (screens != 0)
  221034. {
  221035. for (int i = numMonitors; --i >= 0;)
  221036. {
  221037. int index = screens[i].screen_number;
  221038. if (index >= 0)
  221039. {
  221040. while (monitorCoords.size() < index)
  221041. monitorCoords.add (Rectangle<int>());
  221042. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221043. screens[i].y_org,
  221044. screens[i].width,
  221045. screens[i].height));
  221046. }
  221047. }
  221048. XFree (screens);
  221049. }
  221050. }
  221051. }
  221052. if (monitorCoords.size() == 0)
  221053. #endif
  221054. {
  221055. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221056. if (hints != None)
  221057. {
  221058. const int numMonitors = ScreenCount (display);
  221059. for (int i = 0; i < numMonitors; ++i)
  221060. {
  221061. Window root = RootWindow (display, i);
  221062. unsigned long nitems, bytesLeft;
  221063. Atom actualType;
  221064. int actualFormat;
  221065. unsigned char* data = 0;
  221066. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221067. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221068. &data) == Success)
  221069. {
  221070. const long* const position = (const long*) data;
  221071. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221072. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221073. position[2], position[3]));
  221074. XFree (data);
  221075. }
  221076. }
  221077. }
  221078. if (monitorCoords.size() == 0)
  221079. {
  221080. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221081. DisplayHeight (display, DefaultScreen (display))));
  221082. }
  221083. }
  221084. }
  221085. void Desktop::createMouseInputSources()
  221086. {
  221087. mouseSources.add (new MouseInputSource (0, true));
  221088. }
  221089. bool Desktop::canUseSemiTransparentWindows() throw()
  221090. {
  221091. int matchedDepth = 0;
  221092. const int desiredDepth = 32;
  221093. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221094. && (matchedDepth == desiredDepth);
  221095. }
  221096. const Point<int> MouseInputSource::getCurrentMousePosition()
  221097. {
  221098. Window root, child;
  221099. int x, y, winx, winy;
  221100. unsigned int mask;
  221101. ScopedXLock xlock;
  221102. if (XQueryPointer (display,
  221103. RootWindow (display, DefaultScreen (display)),
  221104. &root, &child,
  221105. &x, &y, &winx, &winy, &mask) == False)
  221106. {
  221107. // Pointer not on the default screen
  221108. x = y = -1;
  221109. }
  221110. return Point<int> (x, y);
  221111. }
  221112. void Desktop::setMousePosition (const Point<int>& newPosition)
  221113. {
  221114. ScopedXLock xlock;
  221115. Window root = RootWindow (display, DefaultScreen (display));
  221116. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221117. }
  221118. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221119. {
  221120. return upright;
  221121. }
  221122. static bool screenSaverAllowed = true;
  221123. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221124. {
  221125. if (screenSaverAllowed != isEnabled)
  221126. {
  221127. screenSaverAllowed = isEnabled;
  221128. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221129. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221130. if (xScreenSaverSuspend == 0)
  221131. {
  221132. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221133. if (h != 0)
  221134. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221135. }
  221136. ScopedXLock xlock;
  221137. if (xScreenSaverSuspend != 0)
  221138. xScreenSaverSuspend (display, ! isEnabled);
  221139. }
  221140. }
  221141. bool Desktop::isScreenSaverEnabled()
  221142. {
  221143. return screenSaverAllowed;
  221144. }
  221145. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221146. {
  221147. ScopedXLock xlock;
  221148. const unsigned int imageW = image.getWidth();
  221149. const unsigned int imageH = image.getHeight();
  221150. #if JUCE_USE_XCURSOR
  221151. {
  221152. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221153. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221154. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221155. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221156. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221157. static tXcursorImageCreate xXcursorImageCreate = 0;
  221158. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221159. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221160. static bool hasBeenLoaded = false;
  221161. if (! hasBeenLoaded)
  221162. {
  221163. hasBeenLoaded = true;
  221164. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221165. if (h != 0)
  221166. {
  221167. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221168. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221169. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221170. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221171. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221172. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221173. || ! xXcursorSupportsARGB (display))
  221174. xXcursorSupportsARGB = 0;
  221175. }
  221176. }
  221177. if (xXcursorSupportsARGB != 0)
  221178. {
  221179. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221180. if (xcImage != 0)
  221181. {
  221182. xcImage->xhot = hotspotX;
  221183. xcImage->yhot = hotspotY;
  221184. XcursorPixel* dest = xcImage->pixels;
  221185. for (int y = 0; y < (int) imageH; ++y)
  221186. for (int x = 0; x < (int) imageW; ++x)
  221187. *dest++ = image.getPixelAt (x, y).getARGB();
  221188. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221189. xXcursorImageDestroy (xcImage);
  221190. if (result != 0)
  221191. return result;
  221192. }
  221193. }
  221194. }
  221195. #endif
  221196. Window root = RootWindow (display, DefaultScreen (display));
  221197. unsigned int cursorW, cursorH;
  221198. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221199. return 0;
  221200. Image im (Image::ARGB, cursorW, cursorH, true);
  221201. {
  221202. Graphics g (im);
  221203. if (imageW > cursorW || imageH > cursorH)
  221204. {
  221205. hotspotX = (hotspotX * cursorW) / imageW;
  221206. hotspotY = (hotspotY * cursorH) / imageH;
  221207. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221208. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221209. false);
  221210. }
  221211. else
  221212. {
  221213. g.drawImageAt (image, 0, 0);
  221214. }
  221215. }
  221216. const int stride = (cursorW + 7) >> 3;
  221217. HeapBlock <char> maskPlane, sourcePlane;
  221218. maskPlane.calloc (stride * cursorH);
  221219. sourcePlane.calloc (stride * cursorH);
  221220. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221221. for (int y = cursorH; --y >= 0;)
  221222. {
  221223. for (int x = cursorW; --x >= 0;)
  221224. {
  221225. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221226. const int offset = y * stride + (x >> 3);
  221227. const Colour c (im.getPixelAt (x, y));
  221228. if (c.getAlpha() >= 128)
  221229. maskPlane[offset] |= mask;
  221230. if (c.getBrightness() >= 0.5f)
  221231. sourcePlane[offset] |= mask;
  221232. }
  221233. }
  221234. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221235. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221236. XColor white, black;
  221237. black.red = black.green = black.blue = 0;
  221238. white.red = white.green = white.blue = 0xffff;
  221239. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221240. XFreePixmap (display, sourcePixmap);
  221241. XFreePixmap (display, maskPixmap);
  221242. return result;
  221243. }
  221244. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221245. {
  221246. ScopedXLock xlock;
  221247. if (cursorHandle != 0)
  221248. XFreeCursor (display, (Cursor) cursorHandle);
  221249. }
  221250. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221251. {
  221252. unsigned int shape;
  221253. switch (type)
  221254. {
  221255. case NormalCursor: return None; // Use parent cursor
  221256. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221257. case WaitCursor: shape = XC_watch; break;
  221258. case IBeamCursor: shape = XC_xterm; break;
  221259. case PointingHandCursor: shape = XC_hand2; break;
  221260. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221261. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221262. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221263. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221264. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221265. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221266. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221267. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221268. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221269. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221270. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221271. case CrosshairCursor: shape = XC_crosshair; break;
  221272. case DraggingHandCursor:
  221273. {
  221274. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221275. 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,
  221276. 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 };
  221277. const int dragHandDataSize = 99;
  221278. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221279. }
  221280. case CopyingCursor:
  221281. {
  221282. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221283. 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,
  221284. 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,
  221285. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221286. const int copyCursorSize = 119;
  221287. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221288. }
  221289. default:
  221290. jassertfalse;
  221291. return None;
  221292. }
  221293. ScopedXLock xlock;
  221294. return (void*) XCreateFontCursor (display, shape);
  221295. }
  221296. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221297. {
  221298. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221299. if (lp != 0)
  221300. lp->showMouseCursor ((Cursor) getHandle());
  221301. }
  221302. void MouseCursor::showInAllWindows() const
  221303. {
  221304. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221305. showInWindow (ComponentPeer::getPeer (i));
  221306. }
  221307. const Image juce_createIconForFile (const File& file)
  221308. {
  221309. return Image::null;
  221310. }
  221311. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221312. {
  221313. return createSoftwareImage (format, width, height, clearImage);
  221314. }
  221315. #if JUCE_OPENGL
  221316. class WindowedGLContext : public OpenGLContext
  221317. {
  221318. public:
  221319. WindowedGLContext (Component* const component,
  221320. const OpenGLPixelFormat& pixelFormat_,
  221321. GLXContext sharedContext)
  221322. : renderContext (0),
  221323. embeddedWindow (0),
  221324. pixelFormat (pixelFormat_),
  221325. swapInterval (0)
  221326. {
  221327. jassert (component != 0);
  221328. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221329. if (peer == 0)
  221330. return;
  221331. ScopedXLock xlock;
  221332. XSync (display, False);
  221333. GLint attribs [64];
  221334. int n = 0;
  221335. attribs[n++] = GLX_RGBA;
  221336. attribs[n++] = GLX_DOUBLEBUFFER;
  221337. attribs[n++] = GLX_RED_SIZE;
  221338. attribs[n++] = pixelFormat.redBits;
  221339. attribs[n++] = GLX_GREEN_SIZE;
  221340. attribs[n++] = pixelFormat.greenBits;
  221341. attribs[n++] = GLX_BLUE_SIZE;
  221342. attribs[n++] = pixelFormat.blueBits;
  221343. attribs[n++] = GLX_ALPHA_SIZE;
  221344. attribs[n++] = pixelFormat.alphaBits;
  221345. attribs[n++] = GLX_DEPTH_SIZE;
  221346. attribs[n++] = pixelFormat.depthBufferBits;
  221347. attribs[n++] = GLX_STENCIL_SIZE;
  221348. attribs[n++] = pixelFormat.stencilBufferBits;
  221349. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221350. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221351. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221352. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221353. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221354. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221355. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221356. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221357. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221358. attribs[n++] = None;
  221359. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221360. if (bestVisual == 0)
  221361. return;
  221362. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221363. Window windowH = (Window) peer->getNativeHandle();
  221364. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221365. XSetWindowAttributes swa;
  221366. swa.colormap = colourMap;
  221367. swa.border_pixel = 0;
  221368. swa.event_mask = ExposureMask | StructureNotifyMask;
  221369. embeddedWindow = XCreateWindow (display, windowH,
  221370. 0, 0, 1, 1, 0,
  221371. bestVisual->depth,
  221372. InputOutput,
  221373. bestVisual->visual,
  221374. CWBorderPixel | CWColormap | CWEventMask,
  221375. &swa);
  221376. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221377. XMapWindow (display, embeddedWindow);
  221378. XFreeColormap (display, colourMap);
  221379. XFree (bestVisual);
  221380. XSync (display, False);
  221381. }
  221382. ~WindowedGLContext()
  221383. {
  221384. ScopedXLock xlock;
  221385. deleteContext();
  221386. XUnmapWindow (display, embeddedWindow);
  221387. XDestroyWindow (display, embeddedWindow);
  221388. }
  221389. void deleteContext()
  221390. {
  221391. makeInactive();
  221392. if (renderContext != 0)
  221393. {
  221394. ScopedXLock xlock;
  221395. glXDestroyContext (display, renderContext);
  221396. renderContext = 0;
  221397. }
  221398. }
  221399. bool makeActive() const throw()
  221400. {
  221401. jassert (renderContext != 0);
  221402. ScopedXLock xlock;
  221403. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221404. && XSync (display, False);
  221405. }
  221406. bool makeInactive() const throw()
  221407. {
  221408. ScopedXLock xlock;
  221409. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221410. }
  221411. bool isActive() const throw()
  221412. {
  221413. ScopedXLock xlock;
  221414. return glXGetCurrentContext() == renderContext;
  221415. }
  221416. const OpenGLPixelFormat getPixelFormat() const
  221417. {
  221418. return pixelFormat;
  221419. }
  221420. void* getRawContext() const throw()
  221421. {
  221422. return renderContext;
  221423. }
  221424. void updateWindowPosition (int x, int y, int w, int h, int)
  221425. {
  221426. ScopedXLock xlock;
  221427. XMoveResizeWindow (display, embeddedWindow,
  221428. x, y, jmax (1, w), jmax (1, h));
  221429. }
  221430. void swapBuffers()
  221431. {
  221432. ScopedXLock xlock;
  221433. glXSwapBuffers (display, embeddedWindow);
  221434. }
  221435. bool setSwapInterval (const int numFramesPerSwap)
  221436. {
  221437. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221438. if (GLXSwapIntervalSGI != 0)
  221439. {
  221440. swapInterval = numFramesPerSwap;
  221441. GLXSwapIntervalSGI (numFramesPerSwap);
  221442. return true;
  221443. }
  221444. return false;
  221445. }
  221446. int getSwapInterval() const
  221447. {
  221448. return swapInterval;
  221449. }
  221450. void repaint()
  221451. {
  221452. }
  221453. GLXContext renderContext;
  221454. private:
  221455. Window embeddedWindow;
  221456. OpenGLPixelFormat pixelFormat;
  221457. int swapInterval;
  221458. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221459. };
  221460. OpenGLContext* OpenGLComponent::createContext()
  221461. {
  221462. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221463. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221464. return (c->renderContext != 0) ? c.release() : 0;
  221465. }
  221466. void juce_glViewport (const int w, const int h)
  221467. {
  221468. glViewport (0, 0, w, h);
  221469. }
  221470. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221471. OwnedArray <OpenGLPixelFormat>& results)
  221472. {
  221473. results.add (new OpenGLPixelFormat()); // xxx
  221474. }
  221475. #endif
  221476. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221477. {
  221478. jassertfalse; // not implemented!
  221479. return false;
  221480. }
  221481. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221482. {
  221483. jassertfalse; // not implemented!
  221484. return false;
  221485. }
  221486. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221487. {
  221488. if (! isOnDesktop ())
  221489. addToDesktop (0);
  221490. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221491. if (wp != 0)
  221492. {
  221493. wp->setTaskBarIcon (newImage);
  221494. setVisible (true);
  221495. toFront (false);
  221496. repaint();
  221497. }
  221498. }
  221499. void SystemTrayIconComponent::paint (Graphics& g)
  221500. {
  221501. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221502. if (wp != 0)
  221503. {
  221504. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221505. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221506. false);
  221507. }
  221508. }
  221509. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221510. {
  221511. // xxx not yet implemented!
  221512. }
  221513. void PlatformUtilities::beep()
  221514. {
  221515. std::cout << "\a" << std::flush;
  221516. }
  221517. bool AlertWindow::showNativeDialogBox (const String& title,
  221518. const String& bodyText,
  221519. bool isOkCancel)
  221520. {
  221521. // use a non-native one for the time being..
  221522. if (isOkCancel)
  221523. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221524. else
  221525. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221526. return true;
  221527. }
  221528. const int KeyPress::spaceKey = XK_space & 0xff;
  221529. const int KeyPress::returnKey = XK_Return & 0xff;
  221530. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221531. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221532. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221533. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221534. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221535. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221536. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221537. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221538. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221539. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221540. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221541. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221542. const int KeyPress::tabKey = XK_Tab & 0xff;
  221543. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221544. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221545. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221546. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221547. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221548. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221549. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221550. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221551. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221552. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221553. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221554. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221555. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221556. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221557. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221558. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221559. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221560. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221561. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221562. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221563. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221564. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221565. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221566. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221567. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221568. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221569. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221570. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221571. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221572. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221573. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221574. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221575. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221576. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221577. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221578. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221579. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221580. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221581. #endif
  221582. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221583. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221584. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221585. // compiled on its own).
  221586. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221587. namespace
  221588. {
  221589. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221590. {
  221591. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221592. snd_pcm_hw_params_t* hwParams;
  221593. snd_pcm_hw_params_alloca (&hwParams);
  221594. for (int i = 0; ratesToTry[i] != 0; ++i)
  221595. {
  221596. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221597. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221598. {
  221599. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221600. }
  221601. }
  221602. }
  221603. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221604. {
  221605. snd_pcm_hw_params_t *params;
  221606. snd_pcm_hw_params_alloca (&params);
  221607. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221608. {
  221609. snd_pcm_hw_params_get_channels_min (params, minChans);
  221610. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221611. }
  221612. }
  221613. void getDeviceProperties (const String& deviceID,
  221614. unsigned int& minChansOut,
  221615. unsigned int& maxChansOut,
  221616. unsigned int& minChansIn,
  221617. unsigned int& maxChansIn,
  221618. Array <int>& rates)
  221619. {
  221620. if (deviceID.isEmpty())
  221621. return;
  221622. snd_ctl_t* handle;
  221623. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221624. {
  221625. snd_pcm_info_t* info;
  221626. snd_pcm_info_alloca (&info);
  221627. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221628. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221629. snd_pcm_info_set_subdevice (info, 0);
  221630. if (snd_ctl_pcm_info (handle, info) >= 0)
  221631. {
  221632. snd_pcm_t* pcmHandle;
  221633. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221634. {
  221635. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221636. getDeviceSampleRates (pcmHandle, rates);
  221637. snd_pcm_close (pcmHandle);
  221638. }
  221639. }
  221640. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221641. if (snd_ctl_pcm_info (handle, info) >= 0)
  221642. {
  221643. snd_pcm_t* pcmHandle;
  221644. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221645. {
  221646. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221647. if (rates.size() == 0)
  221648. getDeviceSampleRates (pcmHandle, rates);
  221649. snd_pcm_close (pcmHandle);
  221650. }
  221651. }
  221652. snd_ctl_close (handle);
  221653. }
  221654. }
  221655. }
  221656. class ALSADevice
  221657. {
  221658. public:
  221659. ALSADevice (const String& deviceID, bool forInput)
  221660. : handle (0),
  221661. bitDepth (16),
  221662. numChannelsRunning (0),
  221663. latency (0),
  221664. isInput (forInput),
  221665. isInterleaved (true)
  221666. {
  221667. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221668. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221669. SND_PCM_ASYNC));
  221670. }
  221671. ~ALSADevice()
  221672. {
  221673. if (handle != 0)
  221674. snd_pcm_close (handle);
  221675. }
  221676. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221677. {
  221678. if (handle == 0)
  221679. return false;
  221680. snd_pcm_hw_params_t* hwParams;
  221681. snd_pcm_hw_params_alloca (&hwParams);
  221682. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221683. return false;
  221684. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221685. isInterleaved = false;
  221686. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221687. isInterleaved = true;
  221688. else
  221689. {
  221690. jassertfalse;
  221691. return false;
  221692. }
  221693. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221694. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221695. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221696. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221697. SND_PCM_FORMAT_S32_BE, 32,
  221698. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221699. SND_PCM_FORMAT_S24_3BE, 24,
  221700. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221701. SND_PCM_FORMAT_S16_BE, 16 };
  221702. bitDepth = 0;
  221703. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221704. {
  221705. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221706. {
  221707. bitDepth = formatsToTry [i + 1] & 255;
  221708. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221709. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221710. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221711. break;
  221712. }
  221713. }
  221714. if (bitDepth == 0)
  221715. {
  221716. error = "device doesn't support a compatible PCM format";
  221717. DBG ("ALSA error: " + error + "\n");
  221718. return false;
  221719. }
  221720. int dir = 0;
  221721. unsigned int periods = 4;
  221722. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221723. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221724. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221725. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221726. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221727. || failed (snd_pcm_hw_params (handle, hwParams)))
  221728. {
  221729. return false;
  221730. }
  221731. snd_pcm_uframes_t frames = 0;
  221732. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221733. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221734. latency = 0;
  221735. else
  221736. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221737. snd_pcm_sw_params_t* swParams;
  221738. snd_pcm_sw_params_alloca (&swParams);
  221739. snd_pcm_uframes_t boundary;
  221740. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221741. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221742. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221743. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221744. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221745. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221746. || failed (snd_pcm_sw_params (handle, swParams)))
  221747. {
  221748. return false;
  221749. }
  221750. #if 0
  221751. // enable this to dump the config of the devices that get opened
  221752. snd_output_t* out;
  221753. snd_output_stdio_attach (&out, stderr, 0);
  221754. snd_pcm_hw_params_dump (hwParams, out);
  221755. snd_pcm_sw_params_dump (swParams, out);
  221756. #endif
  221757. numChannelsRunning = numChannels;
  221758. return true;
  221759. }
  221760. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221761. {
  221762. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221763. float** const data = outputChannelBuffer.getArrayOfChannels();
  221764. snd_pcm_sframes_t numDone = 0;
  221765. if (isInterleaved)
  221766. {
  221767. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221768. for (int i = 0; i < numChannelsRunning; ++i)
  221769. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221770. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221771. }
  221772. else
  221773. {
  221774. for (int i = 0; i < numChannelsRunning; ++i)
  221775. converter->convertSamples (data[i], data[i], numSamples);
  221776. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221777. }
  221778. if (failed (numDone))
  221779. {
  221780. if (numDone == -EPIPE)
  221781. {
  221782. if (failed (snd_pcm_prepare (handle)))
  221783. return false;
  221784. }
  221785. else if (numDone != -ESTRPIPE)
  221786. return false;
  221787. }
  221788. return true;
  221789. }
  221790. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221791. {
  221792. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221793. float** const data = inputChannelBuffer.getArrayOfChannels();
  221794. if (isInterleaved)
  221795. {
  221796. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221797. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221798. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221799. if (failed (num))
  221800. {
  221801. if (num == -EPIPE)
  221802. {
  221803. if (failed (snd_pcm_prepare (handle)))
  221804. return false;
  221805. }
  221806. else if (num != -ESTRPIPE)
  221807. return false;
  221808. }
  221809. for (int i = 0; i < numChannelsRunning; ++i)
  221810. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221811. }
  221812. else
  221813. {
  221814. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221815. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221816. return false;
  221817. for (int i = 0; i < numChannelsRunning; ++i)
  221818. converter->convertSamples (data[i], data[i], numSamples);
  221819. }
  221820. return true;
  221821. }
  221822. snd_pcm_t* handle;
  221823. String error;
  221824. int bitDepth, numChannelsRunning, latency;
  221825. private:
  221826. const bool isInput;
  221827. bool isInterleaved;
  221828. MemoryBlock scratch;
  221829. ScopedPointer<AudioData::Converter> converter;
  221830. template <class SampleType>
  221831. struct ConverterHelper
  221832. {
  221833. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221834. {
  221835. if (forInput)
  221836. {
  221837. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221838. if (isLittleEndian)
  221839. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221840. else
  221841. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221842. }
  221843. else
  221844. {
  221845. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221846. if (isLittleEndian)
  221847. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221848. else
  221849. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221850. }
  221851. }
  221852. };
  221853. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221854. {
  221855. switch (bitDepth)
  221856. {
  221857. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221858. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221859. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221860. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221861. default: jassertfalse; break; // unsupported format!
  221862. }
  221863. return 0;
  221864. }
  221865. bool failed (const int errorNum)
  221866. {
  221867. if (errorNum >= 0)
  221868. return false;
  221869. error = snd_strerror (errorNum);
  221870. DBG ("ALSA error: " + error + "\n");
  221871. return true;
  221872. }
  221873. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221874. };
  221875. class ALSAThread : public Thread
  221876. {
  221877. public:
  221878. ALSAThread (const String& inputId_,
  221879. const String& outputId_)
  221880. : Thread ("Juce ALSA"),
  221881. sampleRate (0),
  221882. bufferSize (0),
  221883. outputLatency (0),
  221884. inputLatency (0),
  221885. callback (0),
  221886. inputId (inputId_),
  221887. outputId (outputId_),
  221888. numCallbacks (0),
  221889. inputChannelBuffer (1, 1),
  221890. outputChannelBuffer (1, 1)
  221891. {
  221892. initialiseRatesAndChannels();
  221893. }
  221894. ~ALSAThread()
  221895. {
  221896. close();
  221897. }
  221898. void open (BigInteger inputChannels,
  221899. BigInteger outputChannels,
  221900. const double sampleRate_,
  221901. const int bufferSize_)
  221902. {
  221903. close();
  221904. error = String::empty;
  221905. sampleRate = sampleRate_;
  221906. bufferSize = bufferSize_;
  221907. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221908. inputChannelBuffer.clear();
  221909. inputChannelDataForCallback.clear();
  221910. currentInputChans.clear();
  221911. if (inputChannels.getHighestBit() >= 0)
  221912. {
  221913. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221914. {
  221915. if (inputChannels[i])
  221916. {
  221917. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221918. currentInputChans.setBit (i);
  221919. }
  221920. }
  221921. }
  221922. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221923. outputChannelBuffer.clear();
  221924. outputChannelDataForCallback.clear();
  221925. currentOutputChans.clear();
  221926. if (outputChannels.getHighestBit() >= 0)
  221927. {
  221928. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221929. {
  221930. if (outputChannels[i])
  221931. {
  221932. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221933. currentOutputChans.setBit (i);
  221934. }
  221935. }
  221936. }
  221937. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221938. {
  221939. outputDevice = new ALSADevice (outputId, false);
  221940. if (outputDevice->error.isNotEmpty())
  221941. {
  221942. error = outputDevice->error;
  221943. outputDevice = 0;
  221944. return;
  221945. }
  221946. currentOutputChans.setRange (0, minChansOut, true);
  221947. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221948. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221949. bufferSize))
  221950. {
  221951. error = outputDevice->error;
  221952. outputDevice = 0;
  221953. return;
  221954. }
  221955. outputLatency = outputDevice->latency;
  221956. }
  221957. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221958. {
  221959. inputDevice = new ALSADevice (inputId, true);
  221960. if (inputDevice->error.isNotEmpty())
  221961. {
  221962. error = inputDevice->error;
  221963. inputDevice = 0;
  221964. return;
  221965. }
  221966. currentInputChans.setRange (0, minChansIn, true);
  221967. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221968. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221969. bufferSize))
  221970. {
  221971. error = inputDevice->error;
  221972. inputDevice = 0;
  221973. return;
  221974. }
  221975. inputLatency = inputDevice->latency;
  221976. }
  221977. if (outputDevice == 0 && inputDevice == 0)
  221978. {
  221979. error = "no channels";
  221980. return;
  221981. }
  221982. if (outputDevice != 0 && inputDevice != 0)
  221983. {
  221984. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221985. }
  221986. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221987. return;
  221988. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221989. return;
  221990. startThread (9);
  221991. int count = 1000;
  221992. while (numCallbacks == 0)
  221993. {
  221994. sleep (5);
  221995. if (--count < 0 || ! isThreadRunning())
  221996. {
  221997. error = "device didn't start";
  221998. break;
  221999. }
  222000. }
  222001. }
  222002. void close()
  222003. {
  222004. stopThread (6000);
  222005. inputDevice = 0;
  222006. outputDevice = 0;
  222007. inputChannelBuffer.setSize (1, 1);
  222008. outputChannelBuffer.setSize (1, 1);
  222009. numCallbacks = 0;
  222010. }
  222011. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222012. {
  222013. const ScopedLock sl (callbackLock);
  222014. callback = newCallback;
  222015. }
  222016. void run()
  222017. {
  222018. while (! threadShouldExit())
  222019. {
  222020. if (inputDevice != 0)
  222021. {
  222022. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222023. {
  222024. DBG ("ALSA: read failure");
  222025. break;
  222026. }
  222027. }
  222028. if (threadShouldExit())
  222029. break;
  222030. {
  222031. const ScopedLock sl (callbackLock);
  222032. ++numCallbacks;
  222033. if (callback != 0)
  222034. {
  222035. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222036. inputChannelDataForCallback.size(),
  222037. outputChannelDataForCallback.getRawDataPointer(),
  222038. outputChannelDataForCallback.size(),
  222039. bufferSize);
  222040. }
  222041. else
  222042. {
  222043. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222044. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222045. }
  222046. }
  222047. if (outputDevice != 0)
  222048. {
  222049. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222050. if (threadShouldExit())
  222051. break;
  222052. failed (snd_pcm_avail_update (outputDevice->handle));
  222053. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222054. {
  222055. DBG ("ALSA: write failure");
  222056. break;
  222057. }
  222058. }
  222059. }
  222060. }
  222061. int getBitDepth() const throw()
  222062. {
  222063. if (outputDevice != 0)
  222064. return outputDevice->bitDepth;
  222065. if (inputDevice != 0)
  222066. return inputDevice->bitDepth;
  222067. return 16;
  222068. }
  222069. String error;
  222070. double sampleRate;
  222071. int bufferSize, outputLatency, inputLatency;
  222072. BigInteger currentInputChans, currentOutputChans;
  222073. Array <int> sampleRates;
  222074. StringArray channelNamesOut, channelNamesIn;
  222075. AudioIODeviceCallback* callback;
  222076. private:
  222077. const String inputId, outputId;
  222078. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222079. int numCallbacks;
  222080. CriticalSection callbackLock;
  222081. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222082. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222083. unsigned int minChansOut, maxChansOut;
  222084. unsigned int minChansIn, maxChansIn;
  222085. bool failed (const int errorNum)
  222086. {
  222087. if (errorNum >= 0)
  222088. return false;
  222089. error = snd_strerror (errorNum);
  222090. DBG ("ALSA error: " + error + "\n");
  222091. return true;
  222092. }
  222093. void initialiseRatesAndChannels()
  222094. {
  222095. sampleRates.clear();
  222096. channelNamesOut.clear();
  222097. channelNamesIn.clear();
  222098. minChansOut = 0;
  222099. maxChansOut = 0;
  222100. minChansIn = 0;
  222101. maxChansIn = 0;
  222102. unsigned int dummy = 0;
  222103. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222104. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222105. unsigned int i;
  222106. for (i = 0; i < maxChansOut; ++i)
  222107. channelNamesOut.add ("channel " + String ((int) i + 1));
  222108. for (i = 0; i < maxChansIn; ++i)
  222109. channelNamesIn.add ("channel " + String ((int) i + 1));
  222110. }
  222111. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222112. };
  222113. class ALSAAudioIODevice : public AudioIODevice
  222114. {
  222115. public:
  222116. ALSAAudioIODevice (const String& deviceName,
  222117. const String& inputId_,
  222118. const String& outputId_)
  222119. : AudioIODevice (deviceName, "ALSA"),
  222120. inputId (inputId_),
  222121. outputId (outputId_),
  222122. isOpen_ (false),
  222123. isStarted (false),
  222124. internal (inputId_, outputId_)
  222125. {
  222126. }
  222127. ~ALSAAudioIODevice()
  222128. {
  222129. }
  222130. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222131. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222132. int getNumSampleRates() { return internal.sampleRates.size(); }
  222133. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222134. int getDefaultBufferSize() { return 512; }
  222135. int getNumBufferSizesAvailable() { return 50; }
  222136. int getBufferSizeSamples (int index)
  222137. {
  222138. int n = 16;
  222139. for (int i = 0; i < index; ++i)
  222140. n += n < 64 ? 16
  222141. : (n < 512 ? 32
  222142. : (n < 1024 ? 64
  222143. : (n < 2048 ? 128 : 256)));
  222144. return n;
  222145. }
  222146. const String open (const BigInteger& inputChannels,
  222147. const BigInteger& outputChannels,
  222148. double sampleRate,
  222149. int bufferSizeSamples)
  222150. {
  222151. close();
  222152. if (bufferSizeSamples <= 0)
  222153. bufferSizeSamples = getDefaultBufferSize();
  222154. if (sampleRate <= 0)
  222155. {
  222156. for (int i = 0; i < getNumSampleRates(); ++i)
  222157. {
  222158. if (getSampleRate (i) >= 44100)
  222159. {
  222160. sampleRate = getSampleRate (i);
  222161. break;
  222162. }
  222163. }
  222164. }
  222165. internal.open (inputChannels, outputChannels,
  222166. sampleRate, bufferSizeSamples);
  222167. isOpen_ = internal.error.isEmpty();
  222168. return internal.error;
  222169. }
  222170. void close()
  222171. {
  222172. stop();
  222173. internal.close();
  222174. isOpen_ = false;
  222175. }
  222176. bool isOpen() { return isOpen_; }
  222177. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222178. const String getLastError() { return internal.error; }
  222179. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222180. double getCurrentSampleRate() { return internal.sampleRate; }
  222181. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222182. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222183. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222184. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222185. int getInputLatencyInSamples() { return internal.inputLatency; }
  222186. void start (AudioIODeviceCallback* callback)
  222187. {
  222188. if (! isOpen_)
  222189. callback = 0;
  222190. if (callback != 0)
  222191. callback->audioDeviceAboutToStart (this);
  222192. internal.setCallback (callback);
  222193. isStarted = (callback != 0);
  222194. }
  222195. void stop()
  222196. {
  222197. AudioIODeviceCallback* const oldCallback = internal.callback;
  222198. start (0);
  222199. if (oldCallback != 0)
  222200. oldCallback->audioDeviceStopped();
  222201. }
  222202. String inputId, outputId;
  222203. private:
  222204. bool isOpen_, isStarted;
  222205. ALSAThread internal;
  222206. };
  222207. class ALSAAudioIODeviceType : public AudioIODeviceType
  222208. {
  222209. public:
  222210. ALSAAudioIODeviceType()
  222211. : AudioIODeviceType ("ALSA"),
  222212. hasScanned (false)
  222213. {
  222214. }
  222215. ~ALSAAudioIODeviceType()
  222216. {
  222217. }
  222218. void scanForDevices()
  222219. {
  222220. if (hasScanned)
  222221. return;
  222222. hasScanned = true;
  222223. inputNames.clear();
  222224. inputIds.clear();
  222225. outputNames.clear();
  222226. outputIds.clear();
  222227. /* void** hints = 0;
  222228. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222229. {
  222230. for (void** hint = hints; *hint != 0; ++hint)
  222231. {
  222232. const String name (getHint (*hint, "NAME"));
  222233. if (name.isNotEmpty())
  222234. {
  222235. const String ioid (getHint (*hint, "IOID"));
  222236. String desc (getHint (*hint, "DESC"));
  222237. if (desc.isEmpty())
  222238. desc = name;
  222239. desc = desc.replaceCharacters ("\n\r", " ");
  222240. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222241. if (ioid.isEmpty() || ioid == "Input")
  222242. {
  222243. inputNames.add (desc);
  222244. inputIds.add (name);
  222245. }
  222246. if (ioid.isEmpty() || ioid == "Output")
  222247. {
  222248. outputNames.add (desc);
  222249. outputIds.add (name);
  222250. }
  222251. }
  222252. }
  222253. snd_device_name_free_hint (hints);
  222254. }
  222255. */
  222256. snd_ctl_t* handle = 0;
  222257. snd_ctl_card_info_t* info = 0;
  222258. snd_ctl_card_info_alloca (&info);
  222259. int cardNum = -1;
  222260. while (outputIds.size() + inputIds.size() <= 32)
  222261. {
  222262. snd_card_next (&cardNum);
  222263. if (cardNum < 0)
  222264. break;
  222265. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222266. {
  222267. if (snd_ctl_card_info (handle, info) >= 0)
  222268. {
  222269. String cardId (snd_ctl_card_info_get_id (info));
  222270. if (cardId.removeCharacters ("0123456789").isEmpty())
  222271. cardId = String (cardNum);
  222272. int device = -1;
  222273. for (;;)
  222274. {
  222275. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222276. break;
  222277. String id, name;
  222278. id << "hw:" << cardId << ',' << device;
  222279. bool isInput, isOutput;
  222280. if (testDevice (id, isInput, isOutput))
  222281. {
  222282. name << snd_ctl_card_info_get_name (info);
  222283. if (name.isEmpty())
  222284. name = id;
  222285. if (isInput)
  222286. {
  222287. inputNames.add (name);
  222288. inputIds.add (id);
  222289. }
  222290. if (isOutput)
  222291. {
  222292. outputNames.add (name);
  222293. outputIds.add (id);
  222294. }
  222295. }
  222296. }
  222297. }
  222298. snd_ctl_close (handle);
  222299. }
  222300. }
  222301. inputNames.appendNumbersToDuplicates (false, true);
  222302. outputNames.appendNumbersToDuplicates (false, true);
  222303. }
  222304. const StringArray getDeviceNames (bool wantInputNames) const
  222305. {
  222306. jassert (hasScanned); // need to call scanForDevices() before doing this
  222307. return wantInputNames ? inputNames : outputNames;
  222308. }
  222309. int getDefaultDeviceIndex (bool forInput) const
  222310. {
  222311. jassert (hasScanned); // need to call scanForDevices() before doing this
  222312. return 0;
  222313. }
  222314. bool hasSeparateInputsAndOutputs() const { return true; }
  222315. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222316. {
  222317. jassert (hasScanned); // need to call scanForDevices() before doing this
  222318. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222319. if (d == 0)
  222320. return -1;
  222321. return asInput ? inputIds.indexOf (d->inputId)
  222322. : outputIds.indexOf (d->outputId);
  222323. }
  222324. AudioIODevice* createDevice (const String& outputDeviceName,
  222325. const String& inputDeviceName)
  222326. {
  222327. jassert (hasScanned); // need to call scanForDevices() before doing this
  222328. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222329. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222330. String deviceName (outputIndex >= 0 ? outputDeviceName
  222331. : inputDeviceName);
  222332. if (inputIndex >= 0 || outputIndex >= 0)
  222333. return new ALSAAudioIODevice (deviceName,
  222334. inputIds [inputIndex],
  222335. outputIds [outputIndex]);
  222336. return 0;
  222337. }
  222338. private:
  222339. StringArray inputNames, outputNames, inputIds, outputIds;
  222340. bool hasScanned;
  222341. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222342. {
  222343. unsigned int minChansOut = 0, maxChansOut = 0;
  222344. unsigned int minChansIn = 0, maxChansIn = 0;
  222345. Array <int> rates;
  222346. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222347. DBG ("ALSA device: " + id
  222348. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222349. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222350. + " rates=" + String (rates.size()));
  222351. isInput = maxChansIn > 0;
  222352. isOutput = maxChansOut > 0;
  222353. return (isInput || isOutput) && rates.size() > 0;
  222354. }
  222355. /*static const String getHint (void* hint, const char* type)
  222356. {
  222357. char* const n = snd_device_name_get_hint (hint, type);
  222358. const String s ((const char*) n);
  222359. free (n);
  222360. return s;
  222361. }*/
  222362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222363. };
  222364. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222365. {
  222366. return new ALSAAudioIODeviceType();
  222367. }
  222368. #endif
  222369. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222370. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222371. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222372. // compiled on its own).
  222373. #ifdef JUCE_INCLUDED_FILE
  222374. #if JUCE_JACK
  222375. static void* juce_libjack_handle = 0;
  222376. void* juce_load_jack_function (const char* const name)
  222377. {
  222378. if (juce_libjack_handle == 0)
  222379. return 0;
  222380. return dlsym (juce_libjack_handle, name);
  222381. }
  222382. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222383. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222384. return_type fn_name argument_types { \
  222385. static fn_name##_ptr_t fn = 0; \
  222386. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222387. if (fn) return (*fn)arguments; \
  222388. else return 0; \
  222389. }
  222390. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222391. typedef void (*fn_name##_ptr_t)argument_types; \
  222392. void fn_name argument_types { \
  222393. static fn_name##_ptr_t fn = 0; \
  222394. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222395. if (fn) (*fn)arguments; \
  222396. }
  222397. 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));
  222398. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222399. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222400. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222401. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222402. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222403. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222404. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222405. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222406. 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));
  222407. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222408. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222409. 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));
  222410. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222411. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222412. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222413. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222414. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222415. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222416. #if JUCE_DEBUG
  222417. #define JACK_LOGGING_ENABLED 1
  222418. #endif
  222419. #if JACK_LOGGING_ENABLED
  222420. namespace
  222421. {
  222422. void jack_Log (const String& s)
  222423. {
  222424. std::cerr << s << std::endl;
  222425. }
  222426. void dumpJackErrorMessage (const jack_status_t status)
  222427. {
  222428. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222429. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222430. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222431. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222432. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222433. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222434. }
  222435. }
  222436. #else
  222437. #define dumpJackErrorMessage(a) {}
  222438. #define jack_Log(...) {}
  222439. #endif
  222440. #ifndef JUCE_JACK_CLIENT_NAME
  222441. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222442. #endif
  222443. class JackAudioIODevice : public AudioIODevice
  222444. {
  222445. public:
  222446. JackAudioIODevice (const String& deviceName,
  222447. const String& inputId_,
  222448. const String& outputId_)
  222449. : AudioIODevice (deviceName, "JACK"),
  222450. inputId (inputId_),
  222451. outputId (outputId_),
  222452. isOpen_ (false),
  222453. callback (0),
  222454. totalNumberOfInputChannels (0),
  222455. totalNumberOfOutputChannels (0)
  222456. {
  222457. jassert (deviceName.isNotEmpty());
  222458. jack_status_t status;
  222459. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222460. if (client == 0)
  222461. {
  222462. dumpJackErrorMessage (status);
  222463. }
  222464. else
  222465. {
  222466. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222467. // open input ports
  222468. const StringArray inputChannels (getInputChannelNames());
  222469. for (int i = 0; i < inputChannels.size(); i++)
  222470. {
  222471. String inputName;
  222472. inputName << "in_" << ++totalNumberOfInputChannels;
  222473. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222474. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222475. }
  222476. // open output ports
  222477. const StringArray outputChannels (getOutputChannelNames());
  222478. for (int i = 0; i < outputChannels.size (); i++)
  222479. {
  222480. String outputName;
  222481. outputName << "out_" << ++totalNumberOfOutputChannels;
  222482. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222483. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222484. }
  222485. inChans.calloc (totalNumberOfInputChannels + 2);
  222486. outChans.calloc (totalNumberOfOutputChannels + 2);
  222487. }
  222488. }
  222489. ~JackAudioIODevice()
  222490. {
  222491. close();
  222492. if (client != 0)
  222493. {
  222494. JUCE_NAMESPACE::jack_client_close (client);
  222495. client = 0;
  222496. }
  222497. }
  222498. const StringArray getChannelNames (bool forInput) const
  222499. {
  222500. StringArray names;
  222501. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222502. forInput ? JackPortIsInput : JackPortIsOutput);
  222503. if (ports != 0)
  222504. {
  222505. int j = 0;
  222506. while (ports[j] != 0)
  222507. {
  222508. const String portName (ports [j++]);
  222509. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222510. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222511. }
  222512. free (ports);
  222513. }
  222514. return names;
  222515. }
  222516. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222517. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222518. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222519. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222520. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222521. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222522. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222523. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222524. double sampleRate, int bufferSizeSamples)
  222525. {
  222526. if (client == 0)
  222527. {
  222528. lastError = "No JACK client running";
  222529. return lastError;
  222530. }
  222531. lastError = String::empty;
  222532. close();
  222533. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222534. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222535. JUCE_NAMESPACE::jack_activate (client);
  222536. isOpen_ = true;
  222537. if (! inputChannels.isZero())
  222538. {
  222539. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222540. if (ports != 0)
  222541. {
  222542. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222543. for (int i = 0; i < numInputChannels; ++i)
  222544. {
  222545. const String portName (ports[i]);
  222546. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222547. {
  222548. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222549. if (error != 0)
  222550. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222551. }
  222552. }
  222553. free (ports);
  222554. }
  222555. }
  222556. if (! outputChannels.isZero())
  222557. {
  222558. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222559. if (ports != 0)
  222560. {
  222561. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222562. for (int i = 0; i < numOutputChannels; ++i)
  222563. {
  222564. const String portName (ports[i]);
  222565. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222566. {
  222567. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222568. if (error != 0)
  222569. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222570. }
  222571. }
  222572. free (ports);
  222573. }
  222574. }
  222575. return lastError;
  222576. }
  222577. void close()
  222578. {
  222579. stop();
  222580. if (client != 0)
  222581. {
  222582. JUCE_NAMESPACE::jack_deactivate (client);
  222583. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222584. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222585. }
  222586. isOpen_ = false;
  222587. }
  222588. void start (AudioIODeviceCallback* newCallback)
  222589. {
  222590. if (isOpen_ && newCallback != callback)
  222591. {
  222592. if (newCallback != 0)
  222593. newCallback->audioDeviceAboutToStart (this);
  222594. AudioIODeviceCallback* const oldCallback = callback;
  222595. {
  222596. const ScopedLock sl (callbackLock);
  222597. callback = newCallback;
  222598. }
  222599. if (oldCallback != 0)
  222600. oldCallback->audioDeviceStopped();
  222601. }
  222602. }
  222603. void stop()
  222604. {
  222605. start (0);
  222606. }
  222607. bool isOpen() { return isOpen_; }
  222608. bool isPlaying() { return callback != 0; }
  222609. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222610. double getCurrentSampleRate() { return getSampleRate (0); }
  222611. int getCurrentBitDepth() { return 32; }
  222612. const String getLastError() { return lastError; }
  222613. const BigInteger getActiveOutputChannels() const
  222614. {
  222615. BigInteger outputBits;
  222616. for (int i = 0; i < outputPorts.size(); i++)
  222617. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222618. outputBits.setBit (i);
  222619. return outputBits;
  222620. }
  222621. const BigInteger getActiveInputChannels() const
  222622. {
  222623. BigInteger inputBits;
  222624. for (int i = 0; i < inputPorts.size(); i++)
  222625. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222626. inputBits.setBit (i);
  222627. return inputBits;
  222628. }
  222629. int getOutputLatencyInSamples()
  222630. {
  222631. int latency = 0;
  222632. for (int i = 0; i < outputPorts.size(); i++)
  222633. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222634. return latency;
  222635. }
  222636. int getInputLatencyInSamples()
  222637. {
  222638. int latency = 0;
  222639. for (int i = 0; i < inputPorts.size(); i++)
  222640. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222641. return latency;
  222642. }
  222643. String inputId, outputId;
  222644. private:
  222645. void process (const int numSamples)
  222646. {
  222647. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222648. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222649. {
  222650. jack_default_audio_sample_t* in
  222651. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222652. if (in != 0)
  222653. inChans [numActiveInChans++] = (float*) in;
  222654. }
  222655. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222656. {
  222657. jack_default_audio_sample_t* out
  222658. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222659. if (out != 0)
  222660. outChans [numActiveOutChans++] = (float*) out;
  222661. }
  222662. const ScopedLock sl (callbackLock);
  222663. if (callback != 0)
  222664. {
  222665. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222666. outChans, numActiveOutChans, numSamples);
  222667. }
  222668. else
  222669. {
  222670. for (i = 0; i < numActiveOutChans; ++i)
  222671. zeromem (outChans[i], sizeof (float) * numSamples);
  222672. }
  222673. }
  222674. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222675. {
  222676. if (callbackArgument != 0)
  222677. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222678. return 0;
  222679. }
  222680. static void threadInitCallback (void* callbackArgument)
  222681. {
  222682. jack_Log ("JackAudioIODevice::initialise");
  222683. }
  222684. static void shutdownCallback (void* callbackArgument)
  222685. {
  222686. jack_Log ("JackAudioIODevice::shutdown");
  222687. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222688. if (device != 0)
  222689. {
  222690. device->client = 0;
  222691. device->close();
  222692. }
  222693. }
  222694. static void errorCallback (const char* msg)
  222695. {
  222696. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222697. }
  222698. bool isOpen_;
  222699. jack_client_t* client;
  222700. String lastError;
  222701. AudioIODeviceCallback* callback;
  222702. CriticalSection callbackLock;
  222703. HeapBlock <float*> inChans, outChans;
  222704. int totalNumberOfInputChannels;
  222705. int totalNumberOfOutputChannels;
  222706. Array<void*> inputPorts, outputPorts;
  222707. };
  222708. class JackAudioIODeviceType : public AudioIODeviceType
  222709. {
  222710. public:
  222711. JackAudioIODeviceType()
  222712. : AudioIODeviceType ("JACK"),
  222713. hasScanned (false)
  222714. {
  222715. }
  222716. ~JackAudioIODeviceType()
  222717. {
  222718. }
  222719. void scanForDevices()
  222720. {
  222721. hasScanned = true;
  222722. inputNames.clear();
  222723. inputIds.clear();
  222724. outputNames.clear();
  222725. outputIds.clear();
  222726. if (juce_libjack_handle == 0)
  222727. {
  222728. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222729. if (juce_libjack_handle == 0)
  222730. return;
  222731. }
  222732. // open a dummy client
  222733. jack_status_t status;
  222734. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222735. if (client == 0)
  222736. {
  222737. dumpJackErrorMessage (status);
  222738. }
  222739. else
  222740. {
  222741. // scan for output devices
  222742. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222743. if (ports != 0)
  222744. {
  222745. int j = 0;
  222746. while (ports[j] != 0)
  222747. {
  222748. String clientName (ports[j]);
  222749. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222750. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222751. && ! inputNames.contains (clientName))
  222752. {
  222753. inputNames.add (clientName);
  222754. inputIds.add (ports [j]);
  222755. }
  222756. ++j;
  222757. }
  222758. free (ports);
  222759. }
  222760. // scan for input devices
  222761. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222762. if (ports != 0)
  222763. {
  222764. int j = 0;
  222765. while (ports[j] != 0)
  222766. {
  222767. String clientName (ports[j]);
  222768. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222769. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222770. && ! outputNames.contains (clientName))
  222771. {
  222772. outputNames.add (clientName);
  222773. outputIds.add (ports [j]);
  222774. }
  222775. ++j;
  222776. }
  222777. free (ports);
  222778. }
  222779. JUCE_NAMESPACE::jack_client_close (client);
  222780. }
  222781. }
  222782. const StringArray getDeviceNames (bool wantInputNames) const
  222783. {
  222784. jassert (hasScanned); // need to call scanForDevices() before doing this
  222785. return wantInputNames ? inputNames : outputNames;
  222786. }
  222787. int getDefaultDeviceIndex (bool forInput) const
  222788. {
  222789. jassert (hasScanned); // need to call scanForDevices() before doing this
  222790. return 0;
  222791. }
  222792. bool hasSeparateInputsAndOutputs() const { return true; }
  222793. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222794. {
  222795. jassert (hasScanned); // need to call scanForDevices() before doing this
  222796. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222797. if (d == 0)
  222798. return -1;
  222799. return asInput ? inputIds.indexOf (d->inputId)
  222800. : outputIds.indexOf (d->outputId);
  222801. }
  222802. AudioIODevice* createDevice (const String& outputDeviceName,
  222803. const String& inputDeviceName)
  222804. {
  222805. jassert (hasScanned); // need to call scanForDevices() before doing this
  222806. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222807. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222808. if (inputIndex >= 0 || outputIndex >= 0)
  222809. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222810. : inputDeviceName,
  222811. inputIds [inputIndex],
  222812. outputIds [outputIndex]);
  222813. return 0;
  222814. }
  222815. private:
  222816. StringArray inputNames, outputNames, inputIds, outputIds;
  222817. bool hasScanned;
  222818. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222819. };
  222820. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222821. {
  222822. return new JackAudioIODeviceType();
  222823. }
  222824. #else // if JACK is turned off..
  222825. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222826. #endif
  222827. #endif
  222828. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222829. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222830. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222831. // compiled on its own).
  222832. #if JUCE_INCLUDED_FILE
  222833. #if JUCE_ALSA
  222834. namespace
  222835. {
  222836. snd_seq_t* iterateMidiDevices (const bool forInput,
  222837. StringArray& deviceNamesFound,
  222838. const int deviceIndexToOpen)
  222839. {
  222840. snd_seq_t* returnedHandle = 0;
  222841. snd_seq_t* seqHandle;
  222842. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222843. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222844. {
  222845. snd_seq_system_info_t* systemInfo;
  222846. snd_seq_client_info_t* clientInfo;
  222847. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222848. {
  222849. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222850. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222851. {
  222852. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222853. while (--numClients >= 0 && returnedHandle == 0)
  222854. {
  222855. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222856. {
  222857. snd_seq_port_info_t* portInfo;
  222858. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222859. {
  222860. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222861. const int client = snd_seq_client_info_get_client (clientInfo);
  222862. snd_seq_port_info_set_client (portInfo, client);
  222863. snd_seq_port_info_set_port (portInfo, -1);
  222864. while (--numPorts >= 0)
  222865. {
  222866. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222867. && (snd_seq_port_info_get_capability (portInfo)
  222868. & (forInput ? SND_SEQ_PORT_CAP_READ
  222869. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222870. {
  222871. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222872. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222873. {
  222874. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222875. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222876. if (sourcePort != -1)
  222877. {
  222878. snd_seq_set_client_name (seqHandle,
  222879. forInput ? "Juce Midi Input"
  222880. : "Juce Midi Output");
  222881. const int portId
  222882. = snd_seq_create_simple_port (seqHandle,
  222883. forInput ? "Juce Midi In Port"
  222884. : "Juce Midi Out Port",
  222885. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222886. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222887. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222888. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222889. returnedHandle = seqHandle;
  222890. }
  222891. }
  222892. }
  222893. }
  222894. snd_seq_port_info_free (portInfo);
  222895. }
  222896. }
  222897. }
  222898. snd_seq_client_info_free (clientInfo);
  222899. }
  222900. snd_seq_system_info_free (systemInfo);
  222901. }
  222902. if (returnedHandle == 0)
  222903. snd_seq_close (seqHandle);
  222904. }
  222905. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222906. return returnedHandle;
  222907. }
  222908. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222909. {
  222910. snd_seq_t* seqHandle = 0;
  222911. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222912. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222913. {
  222914. snd_seq_set_client_name (seqHandle,
  222915. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222916. const int portId
  222917. = snd_seq_create_simple_port (seqHandle,
  222918. forInput ? "in"
  222919. : "out",
  222920. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222921. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222922. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222923. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222924. if (portId < 0)
  222925. {
  222926. snd_seq_close (seqHandle);
  222927. seqHandle = 0;
  222928. }
  222929. }
  222930. return seqHandle;
  222931. }
  222932. }
  222933. class MidiOutputDevice
  222934. {
  222935. public:
  222936. MidiOutputDevice (MidiOutput* const midiOutput_,
  222937. snd_seq_t* const seqHandle_)
  222938. :
  222939. midiOutput (midiOutput_),
  222940. seqHandle (seqHandle_),
  222941. maxEventSize (16 * 1024)
  222942. {
  222943. jassert (seqHandle != 0 && midiOutput != 0);
  222944. snd_midi_event_new (maxEventSize, &midiParser);
  222945. }
  222946. ~MidiOutputDevice()
  222947. {
  222948. snd_midi_event_free (midiParser);
  222949. snd_seq_close (seqHandle);
  222950. }
  222951. void sendMessageNow (const MidiMessage& message)
  222952. {
  222953. if (message.getRawDataSize() > maxEventSize)
  222954. {
  222955. maxEventSize = message.getRawDataSize();
  222956. snd_midi_event_free (midiParser);
  222957. snd_midi_event_new (maxEventSize, &midiParser);
  222958. }
  222959. snd_seq_event_t event;
  222960. snd_seq_ev_clear (&event);
  222961. snd_midi_event_encode (midiParser,
  222962. message.getRawData(),
  222963. message.getRawDataSize(),
  222964. &event);
  222965. snd_midi_event_reset_encode (midiParser);
  222966. snd_seq_ev_set_source (&event, 0);
  222967. snd_seq_ev_set_subs (&event);
  222968. snd_seq_ev_set_direct (&event);
  222969. snd_seq_event_output (seqHandle, &event);
  222970. snd_seq_drain_output (seqHandle);
  222971. }
  222972. private:
  222973. MidiOutput* const midiOutput;
  222974. snd_seq_t* const seqHandle;
  222975. snd_midi_event_t* midiParser;
  222976. int maxEventSize;
  222977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222978. };
  222979. const StringArray MidiOutput::getDevices()
  222980. {
  222981. StringArray devices;
  222982. iterateMidiDevices (false, devices, -1);
  222983. return devices;
  222984. }
  222985. int MidiOutput::getDefaultDeviceIndex()
  222986. {
  222987. return 0;
  222988. }
  222989. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222990. {
  222991. MidiOutput* newDevice = 0;
  222992. StringArray devices;
  222993. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222994. if (handle != 0)
  222995. {
  222996. newDevice = new MidiOutput();
  222997. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222998. }
  222999. return newDevice;
  223000. }
  223001. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223002. {
  223003. MidiOutput* newDevice = 0;
  223004. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223005. if (handle != 0)
  223006. {
  223007. newDevice = new MidiOutput();
  223008. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223009. }
  223010. return newDevice;
  223011. }
  223012. MidiOutput::~MidiOutput()
  223013. {
  223014. delete static_cast <MidiOutputDevice*> (internal);
  223015. }
  223016. void MidiOutput::reset()
  223017. {
  223018. }
  223019. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223020. {
  223021. return false;
  223022. }
  223023. void MidiOutput::setVolume (float leftVol, float rightVol)
  223024. {
  223025. }
  223026. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223027. {
  223028. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223029. }
  223030. class MidiInputThread : public Thread
  223031. {
  223032. public:
  223033. MidiInputThread (MidiInput* const midiInput_,
  223034. snd_seq_t* const seqHandle_,
  223035. MidiInputCallback* const callback_)
  223036. : Thread ("Juce MIDI Input"),
  223037. midiInput (midiInput_),
  223038. seqHandle (seqHandle_),
  223039. callback (callback_)
  223040. {
  223041. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223042. }
  223043. ~MidiInputThread()
  223044. {
  223045. snd_seq_close (seqHandle);
  223046. }
  223047. void run()
  223048. {
  223049. const int maxEventSize = 16 * 1024;
  223050. snd_midi_event_t* midiParser;
  223051. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223052. {
  223053. HeapBlock <uint8> buffer (maxEventSize);
  223054. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223055. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223056. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223057. while (! threadShouldExit())
  223058. {
  223059. if (poll (pfd, numPfds, 500) > 0)
  223060. {
  223061. snd_seq_event_t* inputEvent = 0;
  223062. snd_seq_nonblock (seqHandle, 1);
  223063. do
  223064. {
  223065. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223066. {
  223067. // xxx what about SYSEXes that are too big for the buffer?
  223068. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223069. snd_midi_event_reset_decode (midiParser);
  223070. if (numBytes > 0)
  223071. {
  223072. const MidiMessage message ((const uint8*) buffer,
  223073. numBytes,
  223074. Time::getMillisecondCounter() * 0.001);
  223075. callback->handleIncomingMidiMessage (midiInput, message);
  223076. }
  223077. snd_seq_free_event (inputEvent);
  223078. }
  223079. }
  223080. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223081. snd_seq_free_event (inputEvent);
  223082. }
  223083. }
  223084. snd_midi_event_free (midiParser);
  223085. }
  223086. };
  223087. private:
  223088. MidiInput* const midiInput;
  223089. snd_seq_t* const seqHandle;
  223090. MidiInputCallback* const callback;
  223091. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223092. };
  223093. MidiInput::MidiInput (const String& name_)
  223094. : name (name_),
  223095. internal (0)
  223096. {
  223097. }
  223098. MidiInput::~MidiInput()
  223099. {
  223100. stop();
  223101. delete static_cast <MidiInputThread*> (internal);
  223102. }
  223103. void MidiInput::start()
  223104. {
  223105. static_cast <MidiInputThread*> (internal)->startThread();
  223106. }
  223107. void MidiInput::stop()
  223108. {
  223109. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223110. }
  223111. int MidiInput::getDefaultDeviceIndex()
  223112. {
  223113. return 0;
  223114. }
  223115. const StringArray MidiInput::getDevices()
  223116. {
  223117. StringArray devices;
  223118. iterateMidiDevices (true, devices, -1);
  223119. return devices;
  223120. }
  223121. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223122. {
  223123. MidiInput* newDevice = 0;
  223124. StringArray devices;
  223125. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223126. if (handle != 0)
  223127. {
  223128. newDevice = new MidiInput (devices [deviceIndex]);
  223129. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223130. }
  223131. return newDevice;
  223132. }
  223133. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223134. {
  223135. MidiInput* newDevice = 0;
  223136. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223137. if (handle != 0)
  223138. {
  223139. newDevice = new MidiInput (deviceName);
  223140. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223141. }
  223142. return newDevice;
  223143. }
  223144. #else
  223145. // (These are just stub functions if ALSA is unavailable...)
  223146. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223147. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223148. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223149. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223150. MidiOutput::~MidiOutput() {}
  223151. void MidiOutput::reset() {}
  223152. bool MidiOutput::getVolume (float&, float&) { return false; }
  223153. void MidiOutput::setVolume (float, float) {}
  223154. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223155. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223156. MidiInput::~MidiInput() {}
  223157. void MidiInput::start() {}
  223158. void MidiInput::stop() {}
  223159. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223160. const StringArray MidiInput::getDevices() { return StringArray(); }
  223161. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223162. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223163. #endif
  223164. #endif
  223165. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223166. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223167. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223168. // compiled on its own).
  223169. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223170. AudioCDReader::AudioCDReader()
  223171. : AudioFormatReader (0, "CD Audio")
  223172. {
  223173. }
  223174. const StringArray AudioCDReader::getAvailableCDNames()
  223175. {
  223176. StringArray names;
  223177. return names;
  223178. }
  223179. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223180. {
  223181. return 0;
  223182. }
  223183. AudioCDReader::~AudioCDReader()
  223184. {
  223185. }
  223186. void AudioCDReader::refreshTrackLengths()
  223187. {
  223188. }
  223189. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223190. int64 startSampleInFile, int numSamples)
  223191. {
  223192. return false;
  223193. }
  223194. bool AudioCDReader::isCDStillPresent() const
  223195. {
  223196. return false;
  223197. }
  223198. bool AudioCDReader::isTrackAudio (int trackNum) const
  223199. {
  223200. return false;
  223201. }
  223202. void AudioCDReader::enableIndexScanning (bool b)
  223203. {
  223204. }
  223205. int AudioCDReader::getLastIndex() const
  223206. {
  223207. return 0;
  223208. }
  223209. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223210. {
  223211. return Array<int>();
  223212. }
  223213. #endif
  223214. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223215. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223216. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223217. // compiled on its own).
  223218. #if JUCE_INCLUDED_FILE
  223219. void FileChooser::showPlatformDialog (Array<File>& results,
  223220. const String& title,
  223221. const File& file,
  223222. const String& filters,
  223223. bool isDirectory,
  223224. bool selectsFiles,
  223225. bool isSave,
  223226. bool warnAboutOverwritingExistingFiles,
  223227. bool selectMultipleFiles,
  223228. FilePreviewComponent* previewComponent)
  223229. {
  223230. const String separator (":");
  223231. String command ("zenity --file-selection");
  223232. if (title.isNotEmpty())
  223233. command << " --title=\"" << title << "\"";
  223234. if (file != File::nonexistent)
  223235. command << " --filename=\"" << file.getFullPathName () << "\"";
  223236. if (isDirectory)
  223237. command << " --directory";
  223238. if (isSave)
  223239. command << " --save";
  223240. if (selectMultipleFiles)
  223241. command << " --multiple --separator=\"" << separator << "\"";
  223242. command << " 2>&1";
  223243. MemoryOutputStream result;
  223244. int status = -1;
  223245. FILE* stream = popen (command.toUTF8(), "r");
  223246. if (stream != 0)
  223247. {
  223248. for (;;)
  223249. {
  223250. char buffer [1024];
  223251. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223252. if (bytesRead <= 0)
  223253. break;
  223254. result.write (buffer, bytesRead);
  223255. }
  223256. status = pclose (stream);
  223257. }
  223258. if (status == 0)
  223259. {
  223260. StringArray tokens;
  223261. if (selectMultipleFiles)
  223262. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223263. else
  223264. tokens.add (result.toUTF8());
  223265. for (int i = 0; i < tokens.size(); i++)
  223266. results.add (File (tokens[i]));
  223267. return;
  223268. }
  223269. //xxx ain't got one!
  223270. jassertfalse;
  223271. }
  223272. #endif
  223273. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223274. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223275. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223276. // compiled on its own).
  223277. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223278. /*
  223279. Sorry.. This class isn't implemented on Linux!
  223280. */
  223281. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223282. : browser (0),
  223283. blankPageShown (false),
  223284. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223285. {
  223286. setOpaque (true);
  223287. }
  223288. WebBrowserComponent::~WebBrowserComponent()
  223289. {
  223290. }
  223291. void WebBrowserComponent::goToURL (const String& url,
  223292. const StringArray* headers,
  223293. const MemoryBlock* postData)
  223294. {
  223295. lastURL = url;
  223296. lastHeaders.clear();
  223297. if (headers != 0)
  223298. lastHeaders = *headers;
  223299. lastPostData.setSize (0);
  223300. if (postData != 0)
  223301. lastPostData = *postData;
  223302. blankPageShown = false;
  223303. }
  223304. void WebBrowserComponent::stop()
  223305. {
  223306. }
  223307. void WebBrowserComponent::goBack()
  223308. {
  223309. lastURL = String::empty;
  223310. blankPageShown = false;
  223311. }
  223312. void WebBrowserComponent::goForward()
  223313. {
  223314. lastURL = String::empty;
  223315. }
  223316. void WebBrowserComponent::refresh()
  223317. {
  223318. }
  223319. void WebBrowserComponent::paint (Graphics& g)
  223320. {
  223321. g.fillAll (Colours::white);
  223322. }
  223323. void WebBrowserComponent::checkWindowAssociation()
  223324. {
  223325. }
  223326. void WebBrowserComponent::reloadLastURL()
  223327. {
  223328. if (lastURL.isNotEmpty())
  223329. {
  223330. goToURL (lastURL, &lastHeaders, &lastPostData);
  223331. lastURL = String::empty;
  223332. }
  223333. }
  223334. void WebBrowserComponent::parentHierarchyChanged()
  223335. {
  223336. checkWindowAssociation();
  223337. }
  223338. void WebBrowserComponent::resized()
  223339. {
  223340. }
  223341. void WebBrowserComponent::visibilityChanged()
  223342. {
  223343. checkWindowAssociation();
  223344. }
  223345. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223346. {
  223347. return true;
  223348. }
  223349. #endif
  223350. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223351. #endif
  223352. END_JUCE_NAMESPACE
  223353. #endif
  223354. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223355. #endif
  223356. #if JUCE_MAC || JUCE_IPHONE
  223357. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223358. /*
  223359. This file wraps together all the mac-specific code, so that
  223360. we can include all the native headers just once, and compile all our
  223361. platform-specific stuff in one big lump, keeping it out of the way of
  223362. the rest of the codebase.
  223363. */
  223364. #if JUCE_MAC || JUCE_IOS
  223365. #undef JUCE_BUILD_NATIVE
  223366. #define JUCE_BUILD_NATIVE 1
  223367. BEGIN_JUCE_NAMESPACE
  223368. #undef Point
  223369. namespace
  223370. {
  223371. template <class RectType>
  223372. const Rectangle<int> convertToRectInt (const RectType& r)
  223373. {
  223374. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223375. }
  223376. template <class RectType>
  223377. const Rectangle<float> convertToRectFloat (const RectType& r)
  223378. {
  223379. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223380. }
  223381. template <class RectType>
  223382. CGRect convertToCGRect (const RectType& r)
  223383. {
  223384. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223385. }
  223386. }
  223387. #define JUCE_INCLUDED_FILE 1
  223388. // Now include the actual code files..
  223389. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223390. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223391. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223392. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223393. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223394. actually calling into a similarly named class in the other module's address space.
  223395. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223396. have unique names, and should avoid this problem.
  223397. If you're using the amalgamated version, you can just set this macro to something unique before
  223398. you include juce_amalgamated.cpp.
  223399. */
  223400. #ifndef JUCE_ObjCExtraSuffix
  223401. #define JUCE_ObjCExtraSuffix 3
  223402. #endif
  223403. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223404. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223405. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223406. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223407. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223408. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223409. // compiled on its own).
  223410. #if JUCE_INCLUDED_FILE
  223411. namespace
  223412. {
  223413. const String nsStringToJuce (NSString* s)
  223414. {
  223415. return String::fromUTF8 ([s UTF8String]);
  223416. }
  223417. NSString* juceStringToNS (const String& s)
  223418. {
  223419. return [NSString stringWithUTF8String: s.toUTF8()];
  223420. }
  223421. const String convertUTF16ToString (const UniChar* utf16)
  223422. {
  223423. String s;
  223424. while (*utf16 != 0)
  223425. s += (juce_wchar) *utf16++;
  223426. return s;
  223427. }
  223428. }
  223429. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223430. {
  223431. String result;
  223432. if (cfString != 0)
  223433. {
  223434. CFRange range = { 0, CFStringGetLength (cfString) };
  223435. HeapBlock <UniChar> u (range.length + 1);
  223436. CFStringGetCharacters (cfString, range, u);
  223437. u[range.length] = 0;
  223438. result = convertUTF16ToString (u);
  223439. }
  223440. return result;
  223441. }
  223442. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223443. {
  223444. const int len = s.length();
  223445. HeapBlock <UniChar> temp (len + 2);
  223446. for (int i = 0; i <= len; ++i)
  223447. temp[i] = s[i];
  223448. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223449. }
  223450. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223451. {
  223452. #if JUCE_IOS
  223453. const ScopedAutoReleasePool pool;
  223454. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223455. #else
  223456. UnicodeMapping map;
  223457. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223458. kUnicodeNoSubset,
  223459. kTextEncodingDefaultFormat);
  223460. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223461. kUnicodeCanonicalCompVariant,
  223462. kTextEncodingDefaultFormat);
  223463. map.mappingVersion = kUnicodeUseLatestMapping;
  223464. UnicodeToTextInfo conversionInfo = 0;
  223465. String result;
  223466. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223467. {
  223468. const int len = s.length();
  223469. HeapBlock <UniChar> tempIn, tempOut;
  223470. tempIn.calloc (len + 2);
  223471. tempOut.calloc (len + 2);
  223472. for (int i = 0; i <= len; ++i)
  223473. tempIn[i] = s[i];
  223474. ByteCount bytesRead = 0;
  223475. ByteCount outputBufferSize = 0;
  223476. if (ConvertFromUnicodeToText (conversionInfo,
  223477. len * sizeof (UniChar), tempIn,
  223478. kUnicodeDefaultDirectionMask,
  223479. 0, 0, 0, 0,
  223480. len * sizeof (UniChar), &bytesRead,
  223481. &outputBufferSize, tempOut) == noErr)
  223482. {
  223483. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223484. juce_wchar* t = result;
  223485. unsigned int i;
  223486. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223487. t[i] = (juce_wchar) tempOut[i];
  223488. t[i] = 0;
  223489. }
  223490. DisposeUnicodeToTextInfo (&conversionInfo);
  223491. }
  223492. return result;
  223493. #endif
  223494. }
  223495. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223496. void SystemClipboard::copyTextToClipboard (const String& text)
  223497. {
  223498. #if JUCE_IOS
  223499. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223500. forPasteboardType: @"public.text"];
  223501. #else
  223502. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223503. owner: nil];
  223504. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223505. forType: NSStringPboardType];
  223506. #endif
  223507. }
  223508. const String SystemClipboard::getTextFromClipboard()
  223509. {
  223510. #if JUCE_IOS
  223511. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223512. #else
  223513. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223514. #endif
  223515. return text == 0 ? String::empty
  223516. : nsStringToJuce (text);
  223517. }
  223518. #endif
  223519. #endif
  223520. /*** End of inlined file: juce_mac_Strings.mm ***/
  223521. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223522. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223523. // compiled on its own).
  223524. #if JUCE_INCLUDED_FILE
  223525. namespace SystemStatsHelpers
  223526. {
  223527. static int64 highResTimerFrequency = 0;
  223528. static double highResTimerToMillisecRatio = 0;
  223529. #if JUCE_INTEL
  223530. static void juce_getCpuVendor (char* const v) throw()
  223531. {
  223532. int vendor[4];
  223533. zerostruct (vendor);
  223534. int dummy = 0;
  223535. asm ("mov %%ebx, %%esi \n\t"
  223536. "cpuid \n\t"
  223537. "xchg %%esi, %%ebx"
  223538. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  223539. memcpy (v, vendor, 16);
  223540. }
  223541. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  223542. {
  223543. unsigned int cpu = 0;
  223544. unsigned int ext = 0;
  223545. unsigned int family = 0;
  223546. unsigned int dummy = 0;
  223547. asm ("mov %%ebx, %%esi \n\t"
  223548. "cpuid \n\t"
  223549. "xchg %%esi, %%ebx"
  223550. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  223551. familyModel = family;
  223552. extFeatures = ext;
  223553. return cpu;
  223554. }
  223555. #endif
  223556. }
  223557. void SystemStats::initialiseStats()
  223558. {
  223559. using namespace SystemStatsHelpers;
  223560. static bool initialised = false;
  223561. if (! initialised)
  223562. {
  223563. initialised = true;
  223564. #if JUCE_MAC
  223565. [NSApplication sharedApplication];
  223566. #endif
  223567. #if JUCE_INTEL
  223568. unsigned int familyModel, extFeatures;
  223569. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  223570. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223571. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223572. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223573. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223574. #else
  223575. cpuFlags.hasMMX = false;
  223576. cpuFlags.hasSSE = false;
  223577. cpuFlags.hasSSE2 = false;
  223578. cpuFlags.has3DNow = false;
  223579. #endif
  223580. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223581. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223582. #else
  223583. cpuFlags.numCpus = (int) MPProcessors();
  223584. #endif
  223585. mach_timebase_info_data_t timebase;
  223586. (void) mach_timebase_info (&timebase);
  223587. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223588. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223589. String s (SystemStats::getJUCEVersion());
  223590. rlimit lim;
  223591. getrlimit (RLIMIT_NOFILE, &lim);
  223592. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223593. setrlimit (RLIMIT_NOFILE, &lim);
  223594. }
  223595. }
  223596. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223597. {
  223598. return MacOSX;
  223599. }
  223600. const String SystemStats::getOperatingSystemName()
  223601. {
  223602. return "Mac OS X";
  223603. }
  223604. #if ! JUCE_IOS
  223605. int PlatformUtilities::getOSXMinorVersionNumber()
  223606. {
  223607. SInt32 versionMinor = 0;
  223608. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223609. (void) err;
  223610. jassert (err == noErr);
  223611. return (int) versionMinor;
  223612. }
  223613. #endif
  223614. bool SystemStats::isOperatingSystem64Bit()
  223615. {
  223616. #if JUCE_IOS
  223617. return false;
  223618. #elif JUCE_64BIT
  223619. return true;
  223620. #else
  223621. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223622. #endif
  223623. }
  223624. int SystemStats::getMemorySizeInMegabytes()
  223625. {
  223626. uint64 mem = 0;
  223627. size_t memSize = sizeof (mem);
  223628. int mib[] = { CTL_HW, HW_MEMSIZE };
  223629. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223630. return (int) (mem / (1024 * 1024));
  223631. }
  223632. const String SystemStats::getCpuVendor()
  223633. {
  223634. #if JUCE_INTEL
  223635. char v [16];
  223636. SystemStatsHelpers::juce_getCpuVendor (v);
  223637. return String (v, 16);
  223638. #else
  223639. return String::empty;
  223640. #endif
  223641. }
  223642. int SystemStats::getCpuSpeedInMegaherz()
  223643. {
  223644. uint64 speedHz = 0;
  223645. size_t speedSize = sizeof (speedHz);
  223646. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223647. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223648. #if JUCE_BIG_ENDIAN
  223649. if (speedSize == 4)
  223650. speedHz >>= 32;
  223651. #endif
  223652. return (int) (speedHz / 1000000);
  223653. }
  223654. const String SystemStats::getLogonName()
  223655. {
  223656. return nsStringToJuce (NSUserName());
  223657. }
  223658. const String SystemStats::getFullUserName()
  223659. {
  223660. return nsStringToJuce (NSFullUserName());
  223661. }
  223662. uint32 juce_millisecondsSinceStartup() throw()
  223663. {
  223664. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223665. }
  223666. double Time::getMillisecondCounterHiRes() throw()
  223667. {
  223668. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223669. }
  223670. int64 Time::getHighResolutionTicks() throw()
  223671. {
  223672. return (int64) mach_absolute_time();
  223673. }
  223674. int64 Time::getHighResolutionTicksPerSecond() throw()
  223675. {
  223676. return SystemStatsHelpers::highResTimerFrequency;
  223677. }
  223678. bool Time::setSystemTimeToThisTime() const
  223679. {
  223680. jassertfalse;
  223681. return false;
  223682. }
  223683. int SystemStats::getPageSize()
  223684. {
  223685. return (int) NSPageSize();
  223686. }
  223687. void PlatformUtilities::fpuReset()
  223688. {
  223689. }
  223690. #endif
  223691. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223692. /*** Start of inlined file: juce_mac_Network.mm ***/
  223693. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223694. // compiled on its own).
  223695. #if JUCE_INCLUDED_FILE
  223696. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223697. {
  223698. ifaddrs* addrs = 0;
  223699. if (getifaddrs (&addrs) == 0)
  223700. {
  223701. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223702. {
  223703. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223704. if (sto->ss_family == AF_LINK)
  223705. {
  223706. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223707. #ifndef IFT_ETHER
  223708. #define IFT_ETHER 6
  223709. #endif
  223710. if (sadd->sdl_type == IFT_ETHER)
  223711. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223712. }
  223713. }
  223714. freeifaddrs (addrs);
  223715. }
  223716. }
  223717. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223718. const String& emailSubject,
  223719. const String& bodyText,
  223720. const StringArray& filesToAttach)
  223721. {
  223722. #if JUCE_IOS
  223723. //xxx probably need to use MFMailComposeViewController
  223724. jassertfalse;
  223725. return false;
  223726. #else
  223727. const ScopedAutoReleasePool pool;
  223728. String script;
  223729. script << "tell application \"Mail\"\r\n"
  223730. "set newMessage to make new outgoing message with properties {subject:\""
  223731. << emailSubject.replace ("\"", "\\\"")
  223732. << "\", content:\""
  223733. << bodyText.replace ("\"", "\\\"")
  223734. << "\" & return & return}\r\n"
  223735. "tell newMessage\r\n"
  223736. "set visible to true\r\n"
  223737. "set sender to \"sdfsdfsdfewf\"\r\n"
  223738. "make new to recipient at end of to recipients with properties {address:\""
  223739. << targetEmailAddress
  223740. << "\"}\r\n";
  223741. for (int i = 0; i < filesToAttach.size(); ++i)
  223742. {
  223743. script << "tell content\r\n"
  223744. "make new attachment with properties {file name:\""
  223745. << filesToAttach[i].replace ("\"", "\\\"")
  223746. << "\"} at after the last paragraph\r\n"
  223747. "end tell\r\n";
  223748. }
  223749. script << "end tell\r\n"
  223750. "end tell\r\n";
  223751. NSAppleScript* s = [[NSAppleScript alloc]
  223752. initWithSource: juceStringToNS (script)];
  223753. NSDictionary* error = 0;
  223754. const bool ok = [s executeAndReturnError: &error] != nil;
  223755. [s release];
  223756. return ok;
  223757. #endif
  223758. }
  223759. END_JUCE_NAMESPACE
  223760. using namespace JUCE_NAMESPACE;
  223761. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223762. @interface JuceURLConnection : NSObject
  223763. {
  223764. @public
  223765. NSURLRequest* request;
  223766. NSURLConnection* connection;
  223767. NSMutableData* data;
  223768. Thread* runLoopThread;
  223769. bool initialised, hasFailed, hasFinished;
  223770. int position;
  223771. int64 contentLength;
  223772. NSDictionary* headers;
  223773. NSLock* dataLock;
  223774. }
  223775. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223776. - (void) dealloc;
  223777. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223778. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223779. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223780. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223781. - (BOOL) isOpen;
  223782. - (int) read: (char*) dest numBytes: (int) num;
  223783. - (int) readPosition;
  223784. - (void) stop;
  223785. - (void) createConnection;
  223786. @end
  223787. class JuceURLConnectionMessageThread : public Thread
  223788. {
  223789. public:
  223790. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223791. : Thread ("http connection"),
  223792. owner (owner_)
  223793. {
  223794. }
  223795. ~JuceURLConnectionMessageThread()
  223796. {
  223797. stopThread (10000);
  223798. }
  223799. void run()
  223800. {
  223801. [owner createConnection];
  223802. while (! threadShouldExit())
  223803. {
  223804. const ScopedAutoReleasePool pool;
  223805. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223806. }
  223807. }
  223808. private:
  223809. JuceURLConnection* owner;
  223810. };
  223811. @implementation JuceURLConnection
  223812. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223813. withCallback: (URL::OpenStreamProgressCallback*) callback
  223814. withContext: (void*) context;
  223815. {
  223816. [super init];
  223817. request = req;
  223818. [request retain];
  223819. data = [[NSMutableData data] retain];
  223820. dataLock = [[NSLock alloc] init];
  223821. connection = 0;
  223822. initialised = false;
  223823. hasFailed = false;
  223824. hasFinished = false;
  223825. contentLength = -1;
  223826. headers = 0;
  223827. runLoopThread = new JuceURLConnectionMessageThread (self);
  223828. runLoopThread->startThread();
  223829. while (runLoopThread->isThreadRunning() && ! initialised)
  223830. {
  223831. if (callback != 0)
  223832. callback (context, -1, (int) [[request HTTPBody] length]);
  223833. Thread::sleep (1);
  223834. }
  223835. return self;
  223836. }
  223837. - (void) dealloc
  223838. {
  223839. [self stop];
  223840. deleteAndZero (runLoopThread);
  223841. [connection release];
  223842. [data release];
  223843. [dataLock release];
  223844. [request release];
  223845. [headers release];
  223846. [super dealloc];
  223847. }
  223848. - (void) createConnection
  223849. {
  223850. NSUInteger oldRetainCount = [self retainCount];
  223851. connection = [[NSURLConnection alloc] initWithRequest: request
  223852. delegate: self];
  223853. if (oldRetainCount == [self retainCount])
  223854. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223855. if (connection == nil)
  223856. runLoopThread->signalThreadShouldExit();
  223857. }
  223858. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223859. {
  223860. (void) conn;
  223861. [dataLock lock];
  223862. [data setLength: 0];
  223863. [dataLock unlock];
  223864. initialised = true;
  223865. contentLength = [response expectedContentLength];
  223866. [headers release];
  223867. headers = 0;
  223868. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223869. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223870. }
  223871. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223872. {
  223873. (void) conn;
  223874. DBG (nsStringToJuce ([error description]));
  223875. hasFailed = true;
  223876. initialised = true;
  223877. if (runLoopThread != 0)
  223878. runLoopThread->signalThreadShouldExit();
  223879. }
  223880. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223881. {
  223882. (void) conn;
  223883. [dataLock lock];
  223884. [data appendData: newData];
  223885. [dataLock unlock];
  223886. initialised = true;
  223887. }
  223888. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223889. {
  223890. (void) conn;
  223891. hasFinished = true;
  223892. initialised = true;
  223893. if (runLoopThread != 0)
  223894. runLoopThread->signalThreadShouldExit();
  223895. }
  223896. - (BOOL) isOpen
  223897. {
  223898. return connection != 0 && ! hasFailed;
  223899. }
  223900. - (int) readPosition
  223901. {
  223902. return position;
  223903. }
  223904. - (int) read: (char*) dest numBytes: (int) numNeeded
  223905. {
  223906. int numDone = 0;
  223907. while (numNeeded > 0)
  223908. {
  223909. int available = jmin (numNeeded, (int) [data length]);
  223910. if (available > 0)
  223911. {
  223912. [dataLock lock];
  223913. [data getBytes: dest length: available];
  223914. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223915. [dataLock unlock];
  223916. numDone += available;
  223917. numNeeded -= available;
  223918. dest += available;
  223919. }
  223920. else
  223921. {
  223922. if (hasFailed || hasFinished)
  223923. break;
  223924. Thread::sleep (1);
  223925. }
  223926. }
  223927. position += numDone;
  223928. return numDone;
  223929. }
  223930. - (void) stop
  223931. {
  223932. [connection cancel];
  223933. if (runLoopThread != 0)
  223934. runLoopThread->stopThread (10000);
  223935. }
  223936. @end
  223937. BEGIN_JUCE_NAMESPACE
  223938. class WebInputStream : public InputStream
  223939. {
  223940. public:
  223941. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223942. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223943. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223944. : connection (nil),
  223945. address (address_), headers (headers_), postData (postData_), position (0),
  223946. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223947. {
  223948. JUCE_AUTORELEASEPOOL
  223949. connection = createConnection (progressCallback, progressCallbackContext);
  223950. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223951. {
  223952. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223953. NSString* key;
  223954. while ((key = [enumerator nextObject]) != nil)
  223955. responseHeaders->set (nsStringToJuce (key),
  223956. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223957. }
  223958. }
  223959. ~WebInputStream()
  223960. {
  223961. close();
  223962. }
  223963. bool isError() const { return connection == nil; }
  223964. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223965. bool isExhausted() { return finished; }
  223966. int64 getPosition() { return position; }
  223967. int read (void* buffer, int bytesToRead)
  223968. {
  223969. if (finished || isError())
  223970. {
  223971. return 0;
  223972. }
  223973. else
  223974. {
  223975. JUCE_AUTORELEASEPOOL
  223976. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223977. position += bytesRead;
  223978. if (bytesRead == 0)
  223979. finished = true;
  223980. return bytesRead;
  223981. }
  223982. }
  223983. bool setPosition (int64 wantedPos)
  223984. {
  223985. if (wantedPos != position)
  223986. {
  223987. finished = false;
  223988. if (wantedPos < position)
  223989. {
  223990. close();
  223991. position = 0;
  223992. connection = createConnection (0, 0);
  223993. }
  223994. skipNextBytes (wantedPos - position);
  223995. }
  223996. return true;
  223997. }
  223998. private:
  223999. JuceURLConnection* connection;
  224000. String address, headers;
  224001. MemoryBlock postData;
  224002. int64 position;
  224003. bool finished;
  224004. const bool isPost;
  224005. const int timeOutMs;
  224006. void close()
  224007. {
  224008. [connection stop];
  224009. [connection release];
  224010. connection = nil;
  224011. }
  224012. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224013. void* progressCallbackContext)
  224014. {
  224015. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224016. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224017. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224018. if (req == nil)
  224019. return 0;
  224020. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224021. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224022. StringArray headerLines;
  224023. headerLines.addLines (headers);
  224024. headerLines.removeEmptyStrings (true);
  224025. for (int i = 0; i < headerLines.size(); ++i)
  224026. {
  224027. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224028. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224029. if (key.isNotEmpty() && value.isNotEmpty())
  224030. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224031. }
  224032. if (isPost && postData.getSize() > 0)
  224033. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224034. length: postData.getSize()]];
  224035. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224036. withCallback: progressCallback
  224037. withContext: progressCallbackContext];
  224038. if ([s isOpen])
  224039. return s;
  224040. [s release];
  224041. return 0;
  224042. }
  224043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224044. };
  224045. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224046. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224047. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224048. {
  224049. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224050. progressCallback, progressCallbackContext,
  224051. headers, timeOutMs, responseHeaders));
  224052. return wi->isError() ? 0 : wi.release();
  224053. }
  224054. #endif
  224055. /*** End of inlined file: juce_mac_Network.mm ***/
  224056. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224057. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224058. // compiled on its own).
  224059. #if JUCE_INCLUDED_FILE
  224060. struct NamedPipeInternal
  224061. {
  224062. String pipeInName, pipeOutName;
  224063. int pipeIn, pipeOut;
  224064. bool volatile createdPipe, blocked, stopReadOperation;
  224065. static void signalHandler (int) {}
  224066. };
  224067. void NamedPipe::cancelPendingReads()
  224068. {
  224069. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224070. {
  224071. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224072. intern->stopReadOperation = true;
  224073. char buffer [1] = { 0 };
  224074. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224075. (void) bytesWritten;
  224076. int timeout = 2000;
  224077. while (intern->blocked && --timeout >= 0)
  224078. Thread::sleep (2);
  224079. intern->stopReadOperation = false;
  224080. }
  224081. }
  224082. void NamedPipe::close()
  224083. {
  224084. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224085. if (intern != 0)
  224086. {
  224087. internal = 0;
  224088. if (intern->pipeIn != -1)
  224089. ::close (intern->pipeIn);
  224090. if (intern->pipeOut != -1)
  224091. ::close (intern->pipeOut);
  224092. if (intern->createdPipe)
  224093. {
  224094. unlink (intern->pipeInName.toUTF8());
  224095. unlink (intern->pipeOutName.toUTF8());
  224096. }
  224097. delete intern;
  224098. }
  224099. }
  224100. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224101. {
  224102. close();
  224103. NamedPipeInternal* const intern = new NamedPipeInternal();
  224104. internal = intern;
  224105. intern->createdPipe = createPipe;
  224106. intern->blocked = false;
  224107. intern->stopReadOperation = false;
  224108. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224109. siginterrupt (SIGPIPE, 1);
  224110. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224111. intern->pipeInName = pipePath + "_in";
  224112. intern->pipeOutName = pipePath + "_out";
  224113. intern->pipeIn = -1;
  224114. intern->pipeOut = -1;
  224115. if (createPipe)
  224116. {
  224117. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224118. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224119. {
  224120. delete intern;
  224121. internal = 0;
  224122. return false;
  224123. }
  224124. }
  224125. return true;
  224126. }
  224127. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224128. {
  224129. int bytesRead = -1;
  224130. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224131. if (intern != 0)
  224132. {
  224133. intern->blocked = true;
  224134. if (intern->pipeIn == -1)
  224135. {
  224136. if (intern->createdPipe)
  224137. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224138. else
  224139. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224140. if (intern->pipeIn == -1)
  224141. {
  224142. intern->blocked = false;
  224143. return -1;
  224144. }
  224145. }
  224146. bytesRead = 0;
  224147. char* p = static_cast<char*> (destBuffer);
  224148. while (bytesRead < maxBytesToRead)
  224149. {
  224150. const int bytesThisTime = maxBytesToRead - bytesRead;
  224151. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224152. if (numRead <= 0 || intern->stopReadOperation)
  224153. {
  224154. bytesRead = -1;
  224155. break;
  224156. }
  224157. bytesRead += numRead;
  224158. p += bytesRead;
  224159. }
  224160. intern->blocked = false;
  224161. }
  224162. return bytesRead;
  224163. }
  224164. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224165. {
  224166. int bytesWritten = -1;
  224167. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224168. if (intern != 0)
  224169. {
  224170. if (intern->pipeOut == -1)
  224171. {
  224172. if (intern->createdPipe)
  224173. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224174. else
  224175. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224176. if (intern->pipeOut == -1)
  224177. {
  224178. return -1;
  224179. }
  224180. }
  224181. const char* p = static_cast<const char*> (sourceBuffer);
  224182. bytesWritten = 0;
  224183. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224184. while (bytesWritten < numBytesToWrite
  224185. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224186. {
  224187. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224188. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224189. if (numWritten <= 0)
  224190. {
  224191. bytesWritten = -1;
  224192. break;
  224193. }
  224194. bytesWritten += numWritten;
  224195. p += bytesWritten;
  224196. }
  224197. }
  224198. return bytesWritten;
  224199. }
  224200. #endif
  224201. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224202. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224203. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224204. // compiled on its own).
  224205. #if JUCE_INCLUDED_FILE
  224206. /*
  224207. Note that a lot of methods that you'd expect to find in this file actually
  224208. live in juce_posix_SharedCode.h!
  224209. */
  224210. bool Process::isForegroundProcess()
  224211. {
  224212. #if JUCE_MAC
  224213. return [NSApp isActive];
  224214. #else
  224215. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224216. #endif
  224217. }
  224218. void Process::raisePrivilege()
  224219. {
  224220. jassertfalse;
  224221. }
  224222. void Process::lowerPrivilege()
  224223. {
  224224. jassertfalse;
  224225. }
  224226. void Process::terminate()
  224227. {
  224228. exit (0);
  224229. }
  224230. void Process::setPriority (ProcessPriority)
  224231. {
  224232. // xxx
  224233. }
  224234. #endif
  224235. /*** End of inlined file: juce_mac_Threads.mm ***/
  224236. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224237. /*
  224238. This file contains posix routines that are common to both the Linux and Mac builds.
  224239. It gets included directly in the cpp files for these platforms.
  224240. */
  224241. CriticalSection::CriticalSection() throw()
  224242. {
  224243. pthread_mutexattr_t atts;
  224244. pthread_mutexattr_init (&atts);
  224245. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224246. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224247. pthread_mutex_init (&internal, &atts);
  224248. }
  224249. CriticalSection::~CriticalSection() throw()
  224250. {
  224251. pthread_mutex_destroy (&internal);
  224252. }
  224253. void CriticalSection::enter() const throw()
  224254. {
  224255. pthread_mutex_lock (&internal);
  224256. }
  224257. bool CriticalSection::tryEnter() const throw()
  224258. {
  224259. return pthread_mutex_trylock (&internal) == 0;
  224260. }
  224261. void CriticalSection::exit() const throw()
  224262. {
  224263. pthread_mutex_unlock (&internal);
  224264. }
  224265. class WaitableEventImpl
  224266. {
  224267. public:
  224268. WaitableEventImpl (const bool manualReset_)
  224269. : triggered (false),
  224270. manualReset (manualReset_)
  224271. {
  224272. pthread_cond_init (&condition, 0);
  224273. pthread_mutexattr_t atts;
  224274. pthread_mutexattr_init (&atts);
  224275. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224276. pthread_mutex_init (&mutex, &atts);
  224277. }
  224278. ~WaitableEventImpl()
  224279. {
  224280. pthread_cond_destroy (&condition);
  224281. pthread_mutex_destroy (&mutex);
  224282. }
  224283. bool wait (const int timeOutMillisecs) throw()
  224284. {
  224285. pthread_mutex_lock (&mutex);
  224286. if (! triggered)
  224287. {
  224288. if (timeOutMillisecs < 0)
  224289. {
  224290. do
  224291. {
  224292. pthread_cond_wait (&condition, &mutex);
  224293. }
  224294. while (! triggered);
  224295. }
  224296. else
  224297. {
  224298. struct timeval now;
  224299. gettimeofday (&now, 0);
  224300. struct timespec time;
  224301. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224302. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224303. if (time.tv_nsec >= 1000000000)
  224304. {
  224305. time.tv_nsec -= 1000000000;
  224306. time.tv_sec++;
  224307. }
  224308. do
  224309. {
  224310. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224311. {
  224312. pthread_mutex_unlock (&mutex);
  224313. return false;
  224314. }
  224315. }
  224316. while (! triggered);
  224317. }
  224318. }
  224319. if (! manualReset)
  224320. triggered = false;
  224321. pthread_mutex_unlock (&mutex);
  224322. return true;
  224323. }
  224324. void signal() throw()
  224325. {
  224326. pthread_mutex_lock (&mutex);
  224327. triggered = true;
  224328. pthread_cond_broadcast (&condition);
  224329. pthread_mutex_unlock (&mutex);
  224330. }
  224331. void reset() throw()
  224332. {
  224333. pthread_mutex_lock (&mutex);
  224334. triggered = false;
  224335. pthread_mutex_unlock (&mutex);
  224336. }
  224337. private:
  224338. pthread_cond_t condition;
  224339. pthread_mutex_t mutex;
  224340. bool triggered;
  224341. const bool manualReset;
  224342. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224343. };
  224344. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224345. : internal (new WaitableEventImpl (manualReset))
  224346. {
  224347. }
  224348. WaitableEvent::~WaitableEvent() throw()
  224349. {
  224350. delete static_cast <WaitableEventImpl*> (internal);
  224351. }
  224352. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224353. {
  224354. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224355. }
  224356. void WaitableEvent::signal() const throw()
  224357. {
  224358. static_cast <WaitableEventImpl*> (internal)->signal();
  224359. }
  224360. void WaitableEvent::reset() const throw()
  224361. {
  224362. static_cast <WaitableEventImpl*> (internal)->reset();
  224363. }
  224364. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224365. {
  224366. struct timespec time;
  224367. time.tv_sec = millisecs / 1000;
  224368. time.tv_nsec = (millisecs % 1000) * 1000000;
  224369. nanosleep (&time, 0);
  224370. }
  224371. const juce_wchar File::separator = '/';
  224372. const String File::separatorString ("/");
  224373. const File File::getCurrentWorkingDirectory()
  224374. {
  224375. HeapBlock<char> heapBuffer;
  224376. char localBuffer [1024];
  224377. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224378. int bufferSize = 4096;
  224379. while (cwd == 0 && errno == ERANGE)
  224380. {
  224381. heapBuffer.malloc (bufferSize);
  224382. cwd = getcwd (heapBuffer, bufferSize - 1);
  224383. bufferSize += 1024;
  224384. }
  224385. return File (String::fromUTF8 (cwd));
  224386. }
  224387. bool File::setAsCurrentWorkingDirectory() const
  224388. {
  224389. return chdir (getFullPathName().toUTF8()) == 0;
  224390. }
  224391. namespace
  224392. {
  224393. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224394. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224395. #else
  224396. typedef struct stat juce_statStruct;
  224397. #endif
  224398. bool juce_stat (const String& fileName, juce_statStruct& info)
  224399. {
  224400. return fileName.isNotEmpty()
  224401. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224402. && (stat64 (fileName.toUTF8(), &info) == 0);
  224403. #else
  224404. && (stat (fileName.toUTF8(), &info) == 0);
  224405. #endif
  224406. }
  224407. // if this file doesn't exist, find a parent of it that does..
  224408. bool juce_doStatFS (File f, struct statfs& result)
  224409. {
  224410. for (int i = 5; --i >= 0;)
  224411. {
  224412. if (f.exists())
  224413. break;
  224414. f = f.getParentDirectory();
  224415. }
  224416. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224417. }
  224418. }
  224419. bool File::isDirectory() const
  224420. {
  224421. juce_statStruct info;
  224422. return fullPath.isEmpty()
  224423. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224424. }
  224425. bool File::exists() const
  224426. {
  224427. juce_statStruct info;
  224428. return fullPath.isNotEmpty()
  224429. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224430. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224431. #else
  224432. && (lstat (fullPath.toUTF8(), &info) == 0);
  224433. #endif
  224434. }
  224435. bool File::existsAsFile() const
  224436. {
  224437. return exists() && ! isDirectory();
  224438. }
  224439. int64 File::getSize() const
  224440. {
  224441. juce_statStruct info;
  224442. return juce_stat (fullPath, info) ? info.st_size : 0;
  224443. }
  224444. bool File::hasWriteAccess() const
  224445. {
  224446. if (exists())
  224447. return access (fullPath.toUTF8(), W_OK) == 0;
  224448. if ((! isDirectory()) && fullPath.containsChar (separator))
  224449. return getParentDirectory().hasWriteAccess();
  224450. return false;
  224451. }
  224452. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224453. {
  224454. juce_statStruct info;
  224455. if (! juce_stat (fullPath, info))
  224456. return false;
  224457. info.st_mode &= 0777; // Just permissions
  224458. if (shouldBeReadOnly)
  224459. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224460. else
  224461. // Give everybody write permission?
  224462. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224463. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224464. }
  224465. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224466. {
  224467. modificationTime = 0;
  224468. accessTime = 0;
  224469. creationTime = 0;
  224470. juce_statStruct info;
  224471. if (juce_stat (fullPath, info))
  224472. {
  224473. modificationTime = (int64) info.st_mtime * 1000;
  224474. accessTime = (int64) info.st_atime * 1000;
  224475. creationTime = (int64) info.st_ctime * 1000;
  224476. }
  224477. }
  224478. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224479. {
  224480. struct utimbuf times;
  224481. times.actime = (time_t) (accessTime / 1000);
  224482. times.modtime = (time_t) (modificationTime / 1000);
  224483. return utime (fullPath.toUTF8(), &times) == 0;
  224484. }
  224485. bool File::deleteFile() const
  224486. {
  224487. if (! exists())
  224488. return true;
  224489. else if (isDirectory())
  224490. return rmdir (fullPath.toUTF8()) == 0;
  224491. else
  224492. return remove (fullPath.toUTF8()) == 0;
  224493. }
  224494. bool File::moveInternal (const File& dest) const
  224495. {
  224496. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224497. return true;
  224498. if (hasWriteAccess() && copyInternal (dest))
  224499. {
  224500. if (deleteFile())
  224501. return true;
  224502. dest.deleteFile();
  224503. }
  224504. return false;
  224505. }
  224506. void File::createDirectoryInternal (const String& fileName) const
  224507. {
  224508. mkdir (fileName.toUTF8(), 0777);
  224509. }
  224510. int64 juce_fileSetPosition (void* handle, int64 pos)
  224511. {
  224512. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224513. return pos;
  224514. return -1;
  224515. }
  224516. void FileInputStream::openHandle()
  224517. {
  224518. totalSize = file.getSize();
  224519. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224520. if (f != -1)
  224521. fileHandle = (void*) f;
  224522. }
  224523. void FileInputStream::closeHandle()
  224524. {
  224525. if (fileHandle != 0)
  224526. {
  224527. close ((int) (pointer_sized_int) fileHandle);
  224528. fileHandle = 0;
  224529. }
  224530. }
  224531. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224532. {
  224533. if (fileHandle != 0)
  224534. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224535. return 0;
  224536. }
  224537. void FileOutputStream::openHandle()
  224538. {
  224539. if (file.exists())
  224540. {
  224541. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224542. if (f != -1)
  224543. {
  224544. currentPosition = lseek (f, 0, SEEK_END);
  224545. if (currentPosition >= 0)
  224546. fileHandle = (void*) f;
  224547. else
  224548. close (f);
  224549. }
  224550. }
  224551. else
  224552. {
  224553. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224554. if (f != -1)
  224555. fileHandle = (void*) f;
  224556. }
  224557. }
  224558. void FileOutputStream::closeHandle()
  224559. {
  224560. if (fileHandle != 0)
  224561. {
  224562. close ((int) (pointer_sized_int) fileHandle);
  224563. fileHandle = 0;
  224564. }
  224565. }
  224566. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224567. {
  224568. if (fileHandle != 0)
  224569. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224570. return 0;
  224571. }
  224572. void FileOutputStream::flushInternal()
  224573. {
  224574. if (fileHandle != 0)
  224575. fsync ((int) (pointer_sized_int) fileHandle);
  224576. }
  224577. const File juce_getExecutableFile()
  224578. {
  224579. Dl_info exeInfo;
  224580. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  224581. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224582. }
  224583. int64 File::getBytesFreeOnVolume() const
  224584. {
  224585. struct statfs buf;
  224586. if (juce_doStatFS (*this, buf))
  224587. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224588. return 0;
  224589. }
  224590. int64 File::getVolumeTotalSize() const
  224591. {
  224592. struct statfs buf;
  224593. if (juce_doStatFS (*this, buf))
  224594. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224595. return 0;
  224596. }
  224597. const String File::getVolumeLabel() const
  224598. {
  224599. #if JUCE_MAC
  224600. struct VolAttrBuf
  224601. {
  224602. u_int32_t length;
  224603. attrreference_t mountPointRef;
  224604. char mountPointSpace [MAXPATHLEN];
  224605. } attrBuf;
  224606. struct attrlist attrList;
  224607. zerostruct (attrList);
  224608. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224609. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224610. File f (*this);
  224611. for (;;)
  224612. {
  224613. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224614. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224615. (int) attrBuf.mountPointRef.attr_length);
  224616. const File parent (f.getParentDirectory());
  224617. if (f == parent)
  224618. break;
  224619. f = parent;
  224620. }
  224621. #endif
  224622. return String::empty;
  224623. }
  224624. int File::getVolumeSerialNumber() const
  224625. {
  224626. return 0; // xxx
  224627. }
  224628. void juce_runSystemCommand (const String& command)
  224629. {
  224630. int result = system (command.toUTF8());
  224631. (void) result;
  224632. }
  224633. const String juce_getOutputFromCommand (const String& command)
  224634. {
  224635. // slight bodge here, as we just pipe the output into a temp file and read it...
  224636. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224637. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224638. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224639. String result (tempFile.loadFileAsString());
  224640. tempFile.deleteFile();
  224641. return result;
  224642. }
  224643. class InterProcessLock::Pimpl
  224644. {
  224645. public:
  224646. Pimpl (const String& name, const int timeOutMillisecs)
  224647. : handle (0), refCount (1)
  224648. {
  224649. #if JUCE_MAC
  224650. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224651. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224652. #else
  224653. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224654. #endif
  224655. temp.create();
  224656. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224657. if (handle != 0)
  224658. {
  224659. struct flock fl;
  224660. zerostruct (fl);
  224661. fl.l_whence = SEEK_SET;
  224662. fl.l_type = F_WRLCK;
  224663. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224664. for (;;)
  224665. {
  224666. const int result = fcntl (handle, F_SETLK, &fl);
  224667. if (result >= 0)
  224668. return;
  224669. if (errno != EINTR)
  224670. {
  224671. if (timeOutMillisecs == 0
  224672. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224673. break;
  224674. Thread::sleep (10);
  224675. }
  224676. }
  224677. }
  224678. closeFile();
  224679. }
  224680. ~Pimpl()
  224681. {
  224682. closeFile();
  224683. }
  224684. void closeFile()
  224685. {
  224686. if (handle != 0)
  224687. {
  224688. struct flock fl;
  224689. zerostruct (fl);
  224690. fl.l_whence = SEEK_SET;
  224691. fl.l_type = F_UNLCK;
  224692. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224693. {}
  224694. close (handle);
  224695. handle = 0;
  224696. }
  224697. }
  224698. int handle, refCount;
  224699. };
  224700. InterProcessLock::InterProcessLock (const String& name_)
  224701. : name (name_)
  224702. {
  224703. }
  224704. InterProcessLock::~InterProcessLock()
  224705. {
  224706. }
  224707. bool InterProcessLock::enter (const int timeOutMillisecs)
  224708. {
  224709. const ScopedLock sl (lock);
  224710. if (pimpl == 0)
  224711. {
  224712. pimpl = new Pimpl (name, timeOutMillisecs);
  224713. if (pimpl->handle == 0)
  224714. pimpl = 0;
  224715. }
  224716. else
  224717. {
  224718. pimpl->refCount++;
  224719. }
  224720. return pimpl != 0;
  224721. }
  224722. void InterProcessLock::exit()
  224723. {
  224724. const ScopedLock sl (lock);
  224725. // Trying to release the lock too many times!
  224726. jassert (pimpl != 0);
  224727. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224728. pimpl = 0;
  224729. }
  224730. void JUCE_API juce_threadEntryPoint (void*);
  224731. void* threadEntryProc (void* userData)
  224732. {
  224733. JUCE_AUTORELEASEPOOL
  224734. juce_threadEntryPoint (userData);
  224735. return 0;
  224736. }
  224737. void Thread::launchThread()
  224738. {
  224739. threadHandle_ = 0;
  224740. pthread_t handle = 0;
  224741. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224742. {
  224743. pthread_detach (handle);
  224744. threadHandle_ = (void*) handle;
  224745. threadId_ = (ThreadID) threadHandle_;
  224746. }
  224747. }
  224748. void Thread::closeThreadHandle()
  224749. {
  224750. threadId_ = 0;
  224751. threadHandle_ = 0;
  224752. }
  224753. void Thread::killThread()
  224754. {
  224755. if (threadHandle_ != 0)
  224756. pthread_cancel ((pthread_t) threadHandle_);
  224757. }
  224758. void Thread::setCurrentThreadName (const String& /*name*/)
  224759. {
  224760. }
  224761. bool Thread::setThreadPriority (void* handle, int priority)
  224762. {
  224763. struct sched_param param;
  224764. int policy;
  224765. priority = jlimit (0, 10, priority);
  224766. if (handle == 0)
  224767. handle = (void*) pthread_self();
  224768. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224769. return false;
  224770. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224771. const int minPriority = sched_get_priority_min (policy);
  224772. const int maxPriority = sched_get_priority_max (policy);
  224773. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224774. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224775. }
  224776. Thread::ThreadID Thread::getCurrentThreadId()
  224777. {
  224778. return (ThreadID) pthread_self();
  224779. }
  224780. void Thread::yield()
  224781. {
  224782. sched_yield();
  224783. }
  224784. /* Remove this macro if you're having problems compiling the cpu affinity
  224785. calls (the API for these has changed about quite a bit in various Linux
  224786. versions, and a lot of distros seem to ship with obsolete versions)
  224787. */
  224788. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224789. #define SUPPORT_AFFINITIES 1
  224790. #endif
  224791. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224792. {
  224793. #if SUPPORT_AFFINITIES
  224794. cpu_set_t affinity;
  224795. CPU_ZERO (&affinity);
  224796. for (int i = 0; i < 32; ++i)
  224797. if ((affinityMask & (1 << i)) != 0)
  224798. CPU_SET (i, &affinity);
  224799. /*
  224800. N.B. If this line causes a compile error, then you've probably not got the latest
  224801. version of glibc installed.
  224802. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224803. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224804. */
  224805. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224806. sched_yield();
  224807. #else
  224808. /* affinities aren't supported because either the appropriate header files weren't found,
  224809. or the SUPPORT_AFFINITIES macro was turned off
  224810. */
  224811. jassertfalse;
  224812. #endif
  224813. }
  224814. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224815. /*** Start of inlined file: juce_mac_Files.mm ***/
  224816. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224817. // compiled on its own).
  224818. #if JUCE_INCLUDED_FILE
  224819. /*
  224820. Note that a lot of methods that you'd expect to find in this file actually
  224821. live in juce_posix_SharedCode.h!
  224822. */
  224823. bool File::copyInternal (const File& dest) const
  224824. {
  224825. const ScopedAutoReleasePool pool;
  224826. NSFileManager* fm = [NSFileManager defaultManager];
  224827. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224828. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224829. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224830. toPath: juceStringToNS (dest.getFullPathName())
  224831. error: nil];
  224832. #else
  224833. && [fm copyPath: juceStringToNS (fullPath)
  224834. toPath: juceStringToNS (dest.getFullPathName())
  224835. handler: nil];
  224836. #endif
  224837. }
  224838. void File::findFileSystemRoots (Array<File>& destArray)
  224839. {
  224840. destArray.add (File ("/"));
  224841. }
  224842. namespace FileHelpers
  224843. {
  224844. bool isFileOnDriveType (const File& f, const char* const* types)
  224845. {
  224846. struct statfs buf;
  224847. if (juce_doStatFS (f, buf))
  224848. {
  224849. const String type (buf.f_fstypename);
  224850. while (*types != 0)
  224851. if (type.equalsIgnoreCase (*types++))
  224852. return true;
  224853. }
  224854. return false;
  224855. }
  224856. bool isHiddenFile (const String& path)
  224857. {
  224858. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224859. const ScopedAutoReleasePool pool;
  224860. NSNumber* hidden = nil;
  224861. NSError* err = nil;
  224862. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224863. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224864. && [hidden boolValue];
  224865. #else
  224866. #if JUCE_IOS
  224867. return File (path).getFileName().startsWithChar ('.');
  224868. #else
  224869. FSRef ref;
  224870. LSItemInfoRecord info;
  224871. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224872. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224873. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224874. #endif
  224875. #endif
  224876. }
  224877. #if JUCE_IOS
  224878. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224879. {
  224880. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224881. objectAtIndex: 0]);
  224882. }
  224883. #endif
  224884. bool launchExecutable (const String& pathAndArguments)
  224885. {
  224886. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224887. const int cpid = fork();
  224888. if (cpid == 0)
  224889. {
  224890. // Child process
  224891. if (execve (argv[0], (char**) argv, 0) < 0)
  224892. exit (0);
  224893. }
  224894. else
  224895. {
  224896. if (cpid < 0)
  224897. return false;
  224898. }
  224899. return true;
  224900. }
  224901. }
  224902. bool File::isOnCDRomDrive() const
  224903. {
  224904. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224905. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224906. }
  224907. bool File::isOnHardDisk() const
  224908. {
  224909. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224910. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224911. }
  224912. bool File::isOnRemovableDrive() const
  224913. {
  224914. #if JUCE_IOS
  224915. return false; // xxx is this possible?
  224916. #else
  224917. const ScopedAutoReleasePool pool;
  224918. BOOL removable = false;
  224919. [[NSWorkspace sharedWorkspace]
  224920. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224921. isRemovable: &removable
  224922. isWritable: nil
  224923. isUnmountable: nil
  224924. description: nil
  224925. type: nil];
  224926. return removable;
  224927. #endif
  224928. }
  224929. bool File::isHidden() const
  224930. {
  224931. return FileHelpers::isHiddenFile (getFullPathName());
  224932. }
  224933. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224934. const File File::getSpecialLocation (const SpecialLocationType type)
  224935. {
  224936. const ScopedAutoReleasePool pool;
  224937. String resultPath;
  224938. switch (type)
  224939. {
  224940. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224941. #if JUCE_IOS
  224942. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  224943. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  224944. case tempDirectory:
  224945. {
  224946. File tmp (getIOSSystemLocation (NSCachesDirectory));
  224947. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224948. tmp.createDirectory();
  224949. return tmp.getFullPathName();
  224950. }
  224951. #else
  224952. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224953. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224954. case tempDirectory:
  224955. {
  224956. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224957. tmp.createDirectory();
  224958. return tmp.getFullPathName();
  224959. }
  224960. #endif
  224961. case userMusicDirectory: resultPath = "~/Music"; break;
  224962. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224963. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224964. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224965. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224966. case invokedExecutableFile:
  224967. if (juce_Argv0 != 0)
  224968. return File (String::fromUTF8 (juce_Argv0));
  224969. // deliberate fall-through...
  224970. case currentExecutableFile:
  224971. return juce_getExecutableFile();
  224972. case currentApplicationFile:
  224973. {
  224974. const File exe (juce_getExecutableFile());
  224975. const File parent (exe.getParentDirectory());
  224976. #if JUCE_IOS
  224977. return parent;
  224978. #else
  224979. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224980. ? parent.getParentDirectory().getParentDirectory()
  224981. : exe;
  224982. #endif
  224983. }
  224984. case hostApplicationPath:
  224985. {
  224986. unsigned int size = 8192;
  224987. HeapBlock<char> buffer;
  224988. buffer.calloc (size + 8);
  224989. _NSGetExecutablePath (buffer.getData(), &size);
  224990. return String::fromUTF8 (buffer, size);
  224991. }
  224992. default:
  224993. jassertfalse; // unknown type?
  224994. break;
  224995. }
  224996. if (resultPath.isNotEmpty())
  224997. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224998. return File::nonexistent;
  224999. }
  225000. const String File::getVersion() const
  225001. {
  225002. const ScopedAutoReleasePool pool;
  225003. String result;
  225004. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225005. if (bundle != 0)
  225006. {
  225007. NSDictionary* info = [bundle infoDictionary];
  225008. if (info != 0)
  225009. {
  225010. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225011. if (name != nil)
  225012. result = nsStringToJuce (name);
  225013. }
  225014. }
  225015. return result;
  225016. }
  225017. const File File::getLinkedTarget() const
  225018. {
  225019. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225020. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225021. #else
  225022. // (the cast here avoids a deprecation warning)
  225023. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225024. #endif
  225025. if (dest != nil)
  225026. return File (nsStringToJuce (dest));
  225027. return *this;
  225028. }
  225029. bool File::moveToTrash() const
  225030. {
  225031. if (! exists())
  225032. return true;
  225033. #if JUCE_IOS
  225034. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225035. #else
  225036. const ScopedAutoReleasePool pool;
  225037. NSString* p = juceStringToNS (getFullPathName());
  225038. return [[NSWorkspace sharedWorkspace]
  225039. performFileOperation: NSWorkspaceRecycleOperation
  225040. source: [p stringByDeletingLastPathComponent]
  225041. destination: @""
  225042. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225043. tag: nil ];
  225044. #endif
  225045. }
  225046. class DirectoryIterator::NativeIterator::Pimpl
  225047. {
  225048. public:
  225049. Pimpl (const File& directory, const String& wildCard_)
  225050. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225051. wildCard (wildCard_),
  225052. enumerator (0)
  225053. {
  225054. const ScopedAutoReleasePool pool;
  225055. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225056. wildcardUTF8 = wildCard.toUTF8();
  225057. }
  225058. ~Pimpl()
  225059. {
  225060. [enumerator release];
  225061. }
  225062. bool next (String& filenameFound,
  225063. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225064. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225065. {
  225066. const ScopedAutoReleasePool pool;
  225067. for (;;)
  225068. {
  225069. NSString* file;
  225070. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225071. return false;
  225072. [enumerator skipDescendents];
  225073. filenameFound = nsStringToJuce (file);
  225074. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225075. continue;
  225076. const String path (parentDir + filenameFound);
  225077. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225078. {
  225079. juce_statStruct info;
  225080. const bool statOk = juce_stat (path, info);
  225081. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225082. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225083. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225084. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225085. }
  225086. if (isHidden != 0)
  225087. *isHidden = FileHelpers::isHiddenFile (path);
  225088. if (isReadOnly != 0)
  225089. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225090. return true;
  225091. }
  225092. }
  225093. private:
  225094. String parentDir, wildCard;
  225095. const char* wildcardUTF8;
  225096. NSDirectoryEnumerator* enumerator;
  225097. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225098. };
  225099. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225100. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225101. {
  225102. }
  225103. DirectoryIterator::NativeIterator::~NativeIterator()
  225104. {
  225105. }
  225106. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225107. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225108. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225109. {
  225110. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225111. }
  225112. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225113. {
  225114. #if JUCE_IOS
  225115. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225116. #else
  225117. const ScopedAutoReleasePool pool;
  225118. if (parameters.isEmpty())
  225119. {
  225120. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225121. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225122. }
  225123. bool ok = false;
  225124. if (PlatformUtilities::isBundle (fileName))
  225125. {
  225126. NSMutableArray* urls = [NSMutableArray array];
  225127. StringArray docs;
  225128. docs.addTokens (parameters, true);
  225129. for (int i = 0; i < docs.size(); ++i)
  225130. [urls addObject: juceStringToNS (docs[i])];
  225131. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225132. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225133. options: 0
  225134. additionalEventParamDescriptor: nil
  225135. launchIdentifiers: nil];
  225136. }
  225137. else if (File (fileName).exists())
  225138. {
  225139. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225140. }
  225141. return ok;
  225142. #endif
  225143. }
  225144. void File::revealToUser() const
  225145. {
  225146. #if ! JUCE_IOS
  225147. if (exists())
  225148. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225149. else if (getParentDirectory().exists())
  225150. getParentDirectory().revealToUser();
  225151. #endif
  225152. }
  225153. #if ! JUCE_IOS
  225154. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225155. {
  225156. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225157. }
  225158. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225159. {
  225160. char path [2048];
  225161. zerostruct (path);
  225162. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225163. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225164. return String::empty;
  225165. }
  225166. #endif
  225167. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225168. {
  225169. const ScopedAutoReleasePool pool;
  225170. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225171. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225172. #else
  225173. // (the cast here avoids a deprecation warning)
  225174. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225175. #endif
  225176. return [fileDict fileHFSTypeCode];
  225177. }
  225178. bool PlatformUtilities::isBundle (const String& filename)
  225179. {
  225180. #if JUCE_IOS
  225181. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225182. #else
  225183. const ScopedAutoReleasePool pool;
  225184. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225185. #endif
  225186. }
  225187. #endif
  225188. /*** End of inlined file: juce_mac_Files.mm ***/
  225189. #if JUCE_IOS
  225190. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225191. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225192. // compiled on its own).
  225193. #if JUCE_INCLUDED_FILE
  225194. END_JUCE_NAMESPACE
  225195. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225196. {
  225197. }
  225198. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225199. - (void) applicationWillTerminate: (UIApplication*) application;
  225200. @end
  225201. @implementation JuceAppStartupDelegate
  225202. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225203. {
  225204. initialiseJuce_GUI();
  225205. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225206. exit (0);
  225207. }
  225208. - (void) applicationWillTerminate: (UIApplication*) application
  225209. {
  225210. JUCEApplication::appWillTerminateByForce();
  225211. }
  225212. @end
  225213. BEGIN_JUCE_NAMESPACE
  225214. int juce_iOSMain (int argc, const char* argv[])
  225215. {
  225216. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225217. }
  225218. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225219. {
  225220. pool = [[NSAutoreleasePool alloc] init];
  225221. }
  225222. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225223. {
  225224. [((NSAutoreleasePool*) pool) release];
  225225. }
  225226. void PlatformUtilities::beep()
  225227. {
  225228. //xxx
  225229. //AudioServicesPlaySystemSound ();
  225230. }
  225231. void PlatformUtilities::addItemToDock (const File& file)
  225232. {
  225233. }
  225234. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225235. END_JUCE_NAMESPACE
  225236. @interface JuceAlertBoxDelegate : NSObject
  225237. {
  225238. @public
  225239. bool clickedOk;
  225240. }
  225241. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225242. @end
  225243. @implementation JuceAlertBoxDelegate
  225244. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225245. {
  225246. clickedOk = (buttonIndex == 0);
  225247. alertView.hidden = true;
  225248. }
  225249. @end
  225250. BEGIN_JUCE_NAMESPACE
  225251. // (This function is used directly by other bits of code)
  225252. bool juce_iPhoneShowModalAlert (const String& title,
  225253. const String& bodyText,
  225254. NSString* okButtonText,
  225255. NSString* cancelButtonText)
  225256. {
  225257. const ScopedAutoReleasePool pool;
  225258. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225259. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225260. message: juceStringToNS (bodyText)
  225261. delegate: callback
  225262. cancelButtonTitle: okButtonText
  225263. otherButtonTitles: cancelButtonText, nil];
  225264. [alert retain];
  225265. [alert show];
  225266. while (! alert.hidden && alert.superview != nil)
  225267. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225268. const bool result = callback->clickedOk;
  225269. [alert release];
  225270. [callback release];
  225271. return result;
  225272. }
  225273. bool AlertWindow::showNativeDialogBox (const String& title,
  225274. const String& bodyText,
  225275. bool isOkCancel)
  225276. {
  225277. return juce_iPhoneShowModalAlert (title, bodyText,
  225278. @"OK",
  225279. isOkCancel ? @"Cancel" : nil);
  225280. }
  225281. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225282. {
  225283. jassertfalse; // no such thing on the iphone!
  225284. return false;
  225285. }
  225286. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225287. {
  225288. jassertfalse; // no such thing on the iphone!
  225289. return false;
  225290. }
  225291. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225292. {
  225293. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225294. }
  225295. bool Desktop::isScreenSaverEnabled()
  225296. {
  225297. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225298. }
  225299. #endif
  225300. #endif
  225301. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225302. #else
  225303. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225304. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225305. // compiled on its own).
  225306. #if JUCE_INCLUDED_FILE
  225307. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225308. {
  225309. pool = [[NSAutoreleasePool alloc] init];
  225310. }
  225311. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225312. {
  225313. [((NSAutoreleasePool*) pool) release];
  225314. }
  225315. void PlatformUtilities::beep()
  225316. {
  225317. NSBeep();
  225318. }
  225319. void PlatformUtilities::addItemToDock (const File& file)
  225320. {
  225321. // check that it's not already there...
  225322. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225323. .containsIgnoreCase (file.getFullPathName()))
  225324. {
  225325. 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>"
  225326. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225327. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225328. }
  225329. }
  225330. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225331. bool AlertWindow::showNativeDialogBox (const String& title,
  225332. const String& bodyText,
  225333. bool isOkCancel)
  225334. {
  225335. const ScopedAutoReleasePool pool;
  225336. return NSRunAlertPanel (juceStringToNS (title),
  225337. juceStringToNS (bodyText),
  225338. @"Ok",
  225339. isOkCancel ? @"Cancel" : nil,
  225340. nil) == NSAlertDefaultReturn;
  225341. }
  225342. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225343. {
  225344. if (files.size() == 0)
  225345. return false;
  225346. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225347. if (draggingSource == 0)
  225348. {
  225349. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225350. return false;
  225351. }
  225352. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225353. if (sourceComp == 0)
  225354. {
  225355. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225356. return false;
  225357. }
  225358. const ScopedAutoReleasePool pool;
  225359. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225360. if (view == 0)
  225361. return false;
  225362. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225363. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225364. owner: nil];
  225365. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225366. for (int i = 0; i < files.size(); ++i)
  225367. [filesArray addObject: juceStringToNS (files[i])];
  225368. [pboard setPropertyList: filesArray
  225369. forType: NSFilenamesPboardType];
  225370. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225371. fromView: nil];
  225372. dragPosition.x -= 16;
  225373. dragPosition.y -= 16;
  225374. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225375. at: dragPosition
  225376. offset: NSMakeSize (0, 0)
  225377. event: [[view window] currentEvent]
  225378. pasteboard: pboard
  225379. source: view
  225380. slideBack: YES];
  225381. return true;
  225382. }
  225383. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225384. {
  225385. jassertfalse; // not implemented!
  225386. return false;
  225387. }
  225388. bool Desktop::canUseSemiTransparentWindows() throw()
  225389. {
  225390. return true;
  225391. }
  225392. const Point<int> MouseInputSource::getCurrentMousePosition()
  225393. {
  225394. const ScopedAutoReleasePool pool;
  225395. const NSPoint p ([NSEvent mouseLocation]);
  225396. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225397. }
  225398. void Desktop::setMousePosition (const Point<int>& newPosition)
  225399. {
  225400. // this rubbish needs to be done around the warp call, to avoid causing a
  225401. // bizarre glitch..
  225402. CGAssociateMouseAndMouseCursorPosition (false);
  225403. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225404. CGAssociateMouseAndMouseCursorPosition (true);
  225405. }
  225406. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225407. {
  225408. return upright;
  225409. }
  225410. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225411. class ScreenSaverDefeater : public Timer,
  225412. public DeletedAtShutdown
  225413. {
  225414. public:
  225415. ScreenSaverDefeater()
  225416. {
  225417. startTimer (10000);
  225418. timerCallback();
  225419. }
  225420. ~ScreenSaverDefeater() {}
  225421. void timerCallback()
  225422. {
  225423. if (Process::isForegroundProcess())
  225424. UpdateSystemActivity (UsrActivity);
  225425. }
  225426. };
  225427. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225428. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225429. {
  225430. if (isEnabled)
  225431. deleteAndZero (screenSaverDefeater);
  225432. else if (screenSaverDefeater == 0)
  225433. screenSaverDefeater = new ScreenSaverDefeater();
  225434. }
  225435. bool Desktop::isScreenSaverEnabled()
  225436. {
  225437. return screenSaverDefeater == 0;
  225438. }
  225439. #else
  225440. static IOPMAssertionID screenSaverDisablerID = 0;
  225441. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225442. {
  225443. if (isEnabled)
  225444. {
  225445. if (screenSaverDisablerID != 0)
  225446. {
  225447. IOPMAssertionRelease (screenSaverDisablerID);
  225448. screenSaverDisablerID = 0;
  225449. }
  225450. }
  225451. else
  225452. {
  225453. if (screenSaverDisablerID == 0)
  225454. {
  225455. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225456. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225457. CFSTR ("Juce"), &screenSaverDisablerID);
  225458. #else
  225459. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225460. &screenSaverDisablerID);
  225461. #endif
  225462. }
  225463. }
  225464. }
  225465. bool Desktop::isScreenSaverEnabled()
  225466. {
  225467. return screenSaverDisablerID == 0;
  225468. }
  225469. #endif
  225470. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225471. {
  225472. const ScopedAutoReleasePool pool;
  225473. monitorCoords.clear();
  225474. NSArray* screens = [NSScreen screens];
  225475. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225476. for (unsigned int i = 0; i < [screens count]; ++i)
  225477. {
  225478. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225479. NSRect r = clipToWorkArea ? [s visibleFrame]
  225480. : [s frame];
  225481. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225482. monitorCoords.add (convertToRectInt (r));
  225483. }
  225484. jassert (monitorCoords.size() > 0);
  225485. }
  225486. #endif
  225487. #endif
  225488. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225489. #endif
  225490. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225491. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225492. // compiled on its own).
  225493. #if JUCE_INCLUDED_FILE
  225494. void Logger::outputDebugString (const String& text)
  225495. {
  225496. std::cerr << text << std::endl;
  225497. }
  225498. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225499. {
  225500. static char testResult = 0;
  225501. if (testResult == 0)
  225502. {
  225503. struct kinfo_proc info;
  225504. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225505. size_t sz = sizeof (info);
  225506. sysctl (m, 4, &info, &sz, 0, 0);
  225507. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225508. }
  225509. return testResult > 0;
  225510. }
  225511. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225512. {
  225513. return juce_isRunningUnderDebugger();
  225514. }
  225515. #endif
  225516. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225517. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225518. #if JUCE_IOS
  225519. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225520. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225521. // compiled on its own).
  225522. #if JUCE_INCLUDED_FILE
  225523. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225524. #define SUPPORT_10_4_FONTS 1
  225525. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225526. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225527. #define SUPPORT_ONLY_10_4_FONTS 1
  225528. #endif
  225529. END_JUCE_NAMESPACE
  225530. @interface NSFont (PrivateHack)
  225531. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225532. @end
  225533. BEGIN_JUCE_NAMESPACE
  225534. #endif
  225535. class MacTypeface : public Typeface
  225536. {
  225537. public:
  225538. MacTypeface (const Font& font)
  225539. : Typeface (font.getTypefaceName())
  225540. {
  225541. const ScopedAutoReleasePool pool;
  225542. renderingTransform = CGAffineTransformIdentity;
  225543. bool needsItalicTransform = false;
  225544. #if JUCE_IOS
  225545. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225546. if (font.isItalic() || font.isBold())
  225547. {
  225548. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225549. for (NSString* i in familyFonts)
  225550. {
  225551. const String fn (nsStringToJuce (i));
  225552. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225553. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225554. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225555. || afterDash.containsIgnoreCase ("italic")
  225556. || fn.endsWithIgnoreCase ("oblique")
  225557. || fn.endsWithIgnoreCase ("italic");
  225558. if (probablyBold == font.isBold()
  225559. && probablyItalic == font.isItalic())
  225560. {
  225561. fontName = i;
  225562. needsItalicTransform = false;
  225563. break;
  225564. }
  225565. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225566. {
  225567. fontName = i;
  225568. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225569. }
  225570. }
  225571. if (needsItalicTransform)
  225572. renderingTransform.c = 0.15f;
  225573. }
  225574. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225575. const int ascender = abs (CGFontGetAscent (fontRef));
  225576. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225577. ascent = ascender / totalHeight;
  225578. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225579. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225580. #else
  225581. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225582. if (font.isItalic())
  225583. {
  225584. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225585. toHaveTrait: NSItalicFontMask];
  225586. if (newFont == nsFont)
  225587. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225588. nsFont = newFont;
  225589. }
  225590. if (font.isBold())
  225591. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225592. [nsFont retain];
  225593. ascent = std::abs ((float) [nsFont ascender]);
  225594. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225595. ascent /= totalSize;
  225596. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225597. if (needsItalicTransform)
  225598. {
  225599. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225600. renderingTransform.c = 0.15f;
  225601. }
  225602. #if SUPPORT_ONLY_10_4_FONTS
  225603. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225604. if (atsFont == 0)
  225605. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225606. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225607. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225608. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225609. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225610. #else
  225611. #if SUPPORT_10_4_FONTS
  225612. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225613. {
  225614. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225615. if (atsFont == 0)
  225616. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225617. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225618. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225619. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225620. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225621. }
  225622. else
  225623. #endif
  225624. {
  225625. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225626. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225627. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225628. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225629. }
  225630. #endif
  225631. #endif
  225632. }
  225633. ~MacTypeface()
  225634. {
  225635. #if ! JUCE_IOS
  225636. [nsFont release];
  225637. #endif
  225638. if (fontRef != 0)
  225639. CGFontRelease (fontRef);
  225640. }
  225641. float getAscent() const
  225642. {
  225643. return ascent;
  225644. }
  225645. float getDescent() const
  225646. {
  225647. return 1.0f - ascent;
  225648. }
  225649. float getStringWidth (const String& text)
  225650. {
  225651. if (fontRef == 0 || text.isEmpty())
  225652. return 0;
  225653. const int length = text.length();
  225654. HeapBlock <CGGlyph> glyphs;
  225655. createGlyphsForString (text, length, glyphs);
  225656. float x = 0;
  225657. #if SUPPORT_ONLY_10_4_FONTS
  225658. HeapBlock <NSSize> advances (length);
  225659. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225660. for (int i = 0; i < length; ++i)
  225661. x += advances[i].width;
  225662. #else
  225663. #if SUPPORT_10_4_FONTS
  225664. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225665. {
  225666. HeapBlock <NSSize> advances (length);
  225667. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225668. for (int i = 0; i < length; ++i)
  225669. x += advances[i].width;
  225670. }
  225671. else
  225672. #endif
  225673. {
  225674. HeapBlock <int> advances (length);
  225675. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225676. for (int i = 0; i < length; ++i)
  225677. x += advances[i];
  225678. }
  225679. #endif
  225680. return x * unitsToHeightScaleFactor;
  225681. }
  225682. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225683. {
  225684. xOffsets.add (0);
  225685. if (fontRef == 0 || text.isEmpty())
  225686. return;
  225687. const int length = text.length();
  225688. HeapBlock <CGGlyph> glyphs;
  225689. createGlyphsForString (text, length, glyphs);
  225690. #if SUPPORT_ONLY_10_4_FONTS
  225691. HeapBlock <NSSize> advances (length);
  225692. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225693. int x = 0;
  225694. for (int i = 0; i < length; ++i)
  225695. {
  225696. x += advances[i].width;
  225697. xOffsets.add (x * unitsToHeightScaleFactor);
  225698. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225699. }
  225700. #else
  225701. #if SUPPORT_10_4_FONTS
  225702. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225703. {
  225704. HeapBlock <NSSize> advances (length);
  225705. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225706. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225707. float x = 0;
  225708. for (int i = 0; i < length; ++i)
  225709. {
  225710. x += advances[i].width;
  225711. xOffsets.add (x * unitsToHeightScaleFactor);
  225712. resultGlyphs.add (nsGlyphs[i]);
  225713. }
  225714. }
  225715. else
  225716. #endif
  225717. {
  225718. HeapBlock <int> advances (length);
  225719. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225720. {
  225721. int x = 0;
  225722. for (int i = 0; i < length; ++i)
  225723. {
  225724. x += advances [i];
  225725. xOffsets.add (x * unitsToHeightScaleFactor);
  225726. resultGlyphs.add (glyphs[i]);
  225727. }
  225728. }
  225729. }
  225730. #endif
  225731. }
  225732. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225733. {
  225734. #if JUCE_IOS
  225735. return false;
  225736. #else
  225737. if (nsFont == 0)
  225738. return false;
  225739. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225740. jassert (path.isEmpty());
  225741. const ScopedAutoReleasePool pool;
  225742. NSBezierPath* bez = [NSBezierPath bezierPath];
  225743. [bez moveToPoint: NSMakePoint (0, 0)];
  225744. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225745. inFont: nsFont];
  225746. for (int i = 0; i < [bez elementCount]; ++i)
  225747. {
  225748. NSPoint p[3];
  225749. switch ([bez elementAtIndex: i associatedPoints: p])
  225750. {
  225751. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225752. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225753. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225754. (float) p[1].x, (float) -p[1].y,
  225755. (float) p[2].x, (float) -p[2].y); break;
  225756. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225757. default: jassertfalse; break;
  225758. }
  225759. }
  225760. path.applyTransform (pathTransform);
  225761. return true;
  225762. #endif
  225763. }
  225764. CGFontRef fontRef;
  225765. float fontHeightToCGSizeFactor;
  225766. CGAffineTransform renderingTransform;
  225767. private:
  225768. float ascent, unitsToHeightScaleFactor;
  225769. #if JUCE_IOS
  225770. #else
  225771. NSFont* nsFont;
  225772. AffineTransform pathTransform;
  225773. #endif
  225774. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225775. {
  225776. #if SUPPORT_10_4_FONTS
  225777. #if ! SUPPORT_ONLY_10_4_FONTS
  225778. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225779. #endif
  225780. {
  225781. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225782. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225783. for (int i = 0; i < length; ++i)
  225784. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225785. return;
  225786. }
  225787. #endif
  225788. #if ! SUPPORT_ONLY_10_4_FONTS
  225789. if (charToGlyphMapper == 0)
  225790. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225791. glyphs.malloc (length);
  225792. for (int i = 0; i < length; ++i)
  225793. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225794. #endif
  225795. }
  225796. #if ! SUPPORT_ONLY_10_4_FONTS
  225797. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225798. class CharToGlyphMapper
  225799. {
  225800. public:
  225801. CharToGlyphMapper (CGFontRef fontRef)
  225802. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225803. idRangeOffset (0), glyphIndexes (0)
  225804. {
  225805. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225806. if (cmapTable != 0)
  225807. {
  225808. const int numSubtables = getValue16 (cmapTable, 2);
  225809. for (int i = 0; i < numSubtables; ++i)
  225810. {
  225811. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225812. {
  225813. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225814. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225815. {
  225816. const int length = getValue16 (cmapTable, offset + 2);
  225817. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225818. segCount = segCountX2 / 2;
  225819. const int endCodeOffset = offset + 14;
  225820. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225821. const int idDeltaOffset = startCodeOffset + segCountX2;
  225822. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225823. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225824. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225825. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225826. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225827. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225828. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225829. }
  225830. break;
  225831. }
  225832. }
  225833. CFRelease (cmapTable);
  225834. }
  225835. }
  225836. ~CharToGlyphMapper()
  225837. {
  225838. if (endCode != 0)
  225839. {
  225840. CFRelease (endCode);
  225841. CFRelease (startCode);
  225842. CFRelease (idDelta);
  225843. CFRelease (idRangeOffset);
  225844. CFRelease (glyphIndexes);
  225845. }
  225846. }
  225847. int getGlyphForCharacter (const juce_wchar c) const
  225848. {
  225849. for (int i = 0; i < segCount; ++i)
  225850. {
  225851. if (getValue16 (endCode, i * 2) >= c)
  225852. {
  225853. const int start = getValue16 (startCode, i * 2);
  225854. if (start > c)
  225855. break;
  225856. const int delta = getValue16 (idDelta, i * 2);
  225857. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225858. if (rangeOffset == 0)
  225859. return delta + c;
  225860. else
  225861. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225862. }
  225863. }
  225864. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225865. return jmax (-1, (int) c - 29);
  225866. }
  225867. private:
  225868. int segCount;
  225869. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225870. static uint16 getValue16 (CFDataRef data, const int index)
  225871. {
  225872. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225873. }
  225874. static uint32 getValue32 (CFDataRef data, const int index)
  225875. {
  225876. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225877. }
  225878. };
  225879. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225880. #endif
  225881. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225882. };
  225883. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225884. {
  225885. return new MacTypeface (font);
  225886. }
  225887. const StringArray Font::findAllTypefaceNames()
  225888. {
  225889. StringArray names;
  225890. const ScopedAutoReleasePool pool;
  225891. #if JUCE_IOS
  225892. NSArray* fonts = [UIFont familyNames];
  225893. #else
  225894. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225895. #endif
  225896. for (unsigned int i = 0; i < [fonts count]; ++i)
  225897. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225898. names.sort (true);
  225899. return names;
  225900. }
  225901. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225902. {
  225903. #if JUCE_IOS
  225904. defaultSans = "Helvetica";
  225905. defaultSerif = "Times New Roman";
  225906. defaultFixed = "Courier New";
  225907. #else
  225908. defaultSans = "Lucida Grande";
  225909. defaultSerif = "Times New Roman";
  225910. defaultFixed = "Monaco";
  225911. #endif
  225912. defaultFallback = "Arial Unicode MS";
  225913. }
  225914. #endif
  225915. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225916. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225917. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225918. // compiled on its own).
  225919. #if JUCE_INCLUDED_FILE
  225920. class CoreGraphicsImage : public Image::SharedImage
  225921. {
  225922. public:
  225923. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225924. : Image::SharedImage (format_, width_, height_)
  225925. {
  225926. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225927. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225928. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225929. imageData = imageDataAllocated;
  225930. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225931. : CGColorSpaceCreateDeviceRGB();
  225932. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225933. colourSpace, getCGImageFlags (format_));
  225934. CGColorSpaceRelease (colourSpace);
  225935. }
  225936. ~CoreGraphicsImage()
  225937. {
  225938. CGContextRelease (context);
  225939. }
  225940. Image::ImageType getType() const { return Image::NativeImage; }
  225941. LowLevelGraphicsContext* createLowLevelContext();
  225942. SharedImage* clone()
  225943. {
  225944. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225945. memcpy (im->imageData, imageData, lineStride * height);
  225946. return im;
  225947. }
  225948. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225949. {
  225950. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225951. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225952. {
  225953. return CGBitmapContextCreateImage (nativeImage->context);
  225954. }
  225955. else
  225956. {
  225957. const Image::BitmapData srcData (juceImage, false);
  225958. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225959. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225960. 8, srcData.pixelStride * 8, srcData.lineStride,
  225961. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225962. 0, true, kCGRenderingIntentDefault);
  225963. CGDataProviderRelease (provider);
  225964. return imageRef;
  225965. }
  225966. }
  225967. #if JUCE_MAC
  225968. static NSImage* createNSImage (const Image& image)
  225969. {
  225970. const ScopedAutoReleasePool pool;
  225971. NSImage* im = [[NSImage alloc] init];
  225972. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225973. [im lockFocus];
  225974. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225975. CGImageRef imageRef = createImage (image, false, colourSpace);
  225976. CGColorSpaceRelease (colourSpace);
  225977. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225978. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225979. CGImageRelease (imageRef);
  225980. [im unlockFocus];
  225981. return im;
  225982. }
  225983. #endif
  225984. CGContextRef context;
  225985. HeapBlock<uint8> imageDataAllocated;
  225986. private:
  225987. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225988. {
  225989. #if JUCE_BIG_ENDIAN
  225990. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225991. #else
  225992. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225993. #endif
  225994. }
  225995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225996. };
  225997. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225998. {
  225999. #if USE_COREGRAPHICS_RENDERING
  226000. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226001. #else
  226002. return createSoftwareImage (format, width, height, clearImage);
  226003. #endif
  226004. }
  226005. class CoreGraphicsContext : public LowLevelGraphicsContext
  226006. {
  226007. public:
  226008. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226009. : context (context_),
  226010. flipHeight (flipHeight_),
  226011. lastClipRectIsValid (false),
  226012. state (new SavedState()),
  226013. numGradientLookupEntries (0)
  226014. {
  226015. CGContextRetain (context);
  226016. CGContextSaveGState(context);
  226017. CGContextSetShouldSmoothFonts (context, true);
  226018. CGContextSetShouldAntialias (context, true);
  226019. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226020. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226021. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226022. gradientCallbacks.version = 0;
  226023. gradientCallbacks.evaluate = gradientCallback;
  226024. gradientCallbacks.releaseInfo = 0;
  226025. setFont (Font());
  226026. }
  226027. ~CoreGraphicsContext()
  226028. {
  226029. CGContextRestoreGState (context);
  226030. CGContextRelease (context);
  226031. CGColorSpaceRelease (rgbColourSpace);
  226032. CGColorSpaceRelease (greyColourSpace);
  226033. }
  226034. bool isVectorDevice() const { return false; }
  226035. void setOrigin (int x, int y)
  226036. {
  226037. CGContextTranslateCTM (context, x, -y);
  226038. if (lastClipRectIsValid)
  226039. lastClipRect.translate (-x, -y);
  226040. }
  226041. void addTransform (const AffineTransform& transform)
  226042. {
  226043. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226044. .translated (0, flipHeight)
  226045. .followedBy (transform)
  226046. .translated (0, -flipHeight)
  226047. .scaled (1.0f, -1.0f));
  226048. lastClipRectIsValid = false;
  226049. }
  226050. float getScaleFactor()
  226051. {
  226052. CGAffineTransform t = CGContextGetCTM (context);
  226053. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226054. }
  226055. bool clipToRectangle (const Rectangle<int>& r)
  226056. {
  226057. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226058. if (lastClipRectIsValid)
  226059. {
  226060. // This is actually incorrect, because the actual clip region may be complex, and
  226061. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226062. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226063. // when calculating the resultant clip bounds, and makes the same mistake!
  226064. lastClipRect = lastClipRect.getIntersection (r);
  226065. return ! lastClipRect.isEmpty();
  226066. }
  226067. return ! isClipEmpty();
  226068. }
  226069. bool clipToRectangleList (const RectangleList& clipRegion)
  226070. {
  226071. if (clipRegion.isEmpty())
  226072. {
  226073. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226074. lastClipRectIsValid = true;
  226075. lastClipRect = Rectangle<int>();
  226076. return false;
  226077. }
  226078. else
  226079. {
  226080. const int numRects = clipRegion.getNumRectangles();
  226081. HeapBlock <CGRect> rects (numRects);
  226082. for (int i = 0; i < numRects; ++i)
  226083. {
  226084. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226085. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226086. }
  226087. CGContextClipToRects (context, rects, numRects);
  226088. lastClipRectIsValid = false;
  226089. return ! isClipEmpty();
  226090. }
  226091. }
  226092. void excludeClipRectangle (const Rectangle<int>& r)
  226093. {
  226094. RectangleList remaining (getClipBounds());
  226095. remaining.subtract (r);
  226096. clipToRectangleList (remaining);
  226097. lastClipRectIsValid = false;
  226098. }
  226099. void clipToPath (const Path& path, const AffineTransform& transform)
  226100. {
  226101. createPath (path, transform);
  226102. CGContextClip (context);
  226103. lastClipRectIsValid = false;
  226104. }
  226105. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226106. {
  226107. if (! transform.isSingularity())
  226108. {
  226109. Image singleChannelImage (sourceImage);
  226110. if (sourceImage.getFormat() != Image::SingleChannel)
  226111. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226112. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226113. flip();
  226114. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226115. applyTransform (t);
  226116. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226117. CGContextClipToMask (context, r, image);
  226118. applyTransform (t.inverted());
  226119. flip();
  226120. CGImageRelease (image);
  226121. lastClipRectIsValid = false;
  226122. }
  226123. }
  226124. bool clipRegionIntersects (const Rectangle<int>& r)
  226125. {
  226126. return getClipBounds().intersects (r);
  226127. }
  226128. const Rectangle<int> getClipBounds() const
  226129. {
  226130. if (! lastClipRectIsValid)
  226131. {
  226132. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226133. lastClipRectIsValid = true;
  226134. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226135. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226136. roundToInt (bounds.size.width),
  226137. roundToInt (bounds.size.height));
  226138. }
  226139. return lastClipRect;
  226140. }
  226141. bool isClipEmpty() const
  226142. {
  226143. return getClipBounds().isEmpty();
  226144. }
  226145. void saveState()
  226146. {
  226147. CGContextSaveGState (context);
  226148. stateStack.add (new SavedState (*state));
  226149. }
  226150. void restoreState()
  226151. {
  226152. CGContextRestoreGState (context);
  226153. SavedState* const top = stateStack.getLast();
  226154. if (top != 0)
  226155. {
  226156. state = top;
  226157. stateStack.removeLast (1, false);
  226158. lastClipRectIsValid = false;
  226159. }
  226160. else
  226161. {
  226162. jassertfalse; // trying to pop with an empty stack!
  226163. }
  226164. }
  226165. void beginTransparencyLayer (float opacity)
  226166. {
  226167. saveState();
  226168. CGContextSetAlpha (context, opacity);
  226169. CGContextBeginTransparencyLayer (context, 0);
  226170. }
  226171. void endTransparencyLayer()
  226172. {
  226173. CGContextEndTransparencyLayer (context);
  226174. restoreState();
  226175. }
  226176. void setFill (const FillType& fillType)
  226177. {
  226178. state->fillType = fillType;
  226179. if (fillType.isColour())
  226180. {
  226181. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226182. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226183. CGContextSetAlpha (context, 1.0f);
  226184. }
  226185. }
  226186. void setOpacity (float newOpacity)
  226187. {
  226188. state->fillType.setOpacity (newOpacity);
  226189. setFill (state->fillType);
  226190. }
  226191. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226192. {
  226193. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226194. ? kCGInterpolationLow
  226195. : kCGInterpolationHigh);
  226196. }
  226197. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226198. {
  226199. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226200. }
  226201. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226202. {
  226203. if (replaceExistingContents)
  226204. {
  226205. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226206. CGContextClearRect (context, cgRect);
  226207. #else
  226208. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226209. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226210. CGContextClearRect (context, cgRect);
  226211. else
  226212. #endif
  226213. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226214. #endif
  226215. fillCGRect (cgRect, false);
  226216. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226217. }
  226218. else
  226219. {
  226220. if (state->fillType.isColour())
  226221. {
  226222. CGContextFillRect (context, cgRect);
  226223. }
  226224. else if (state->fillType.isGradient())
  226225. {
  226226. CGContextSaveGState (context);
  226227. CGContextClipToRect (context, cgRect);
  226228. drawGradient();
  226229. CGContextRestoreGState (context);
  226230. }
  226231. else
  226232. {
  226233. CGContextSaveGState (context);
  226234. CGContextClipToRect (context, cgRect);
  226235. drawImage (state->fillType.image, state->fillType.transform, true);
  226236. CGContextRestoreGState (context);
  226237. }
  226238. }
  226239. }
  226240. void fillPath (const Path& path, const AffineTransform& transform)
  226241. {
  226242. CGContextSaveGState (context);
  226243. if (state->fillType.isColour())
  226244. {
  226245. flip();
  226246. applyTransform (transform);
  226247. createPath (path);
  226248. if (path.isUsingNonZeroWinding())
  226249. CGContextFillPath (context);
  226250. else
  226251. CGContextEOFillPath (context);
  226252. }
  226253. else
  226254. {
  226255. createPath (path, transform);
  226256. if (path.isUsingNonZeroWinding())
  226257. CGContextClip (context);
  226258. else
  226259. CGContextEOClip (context);
  226260. if (state->fillType.isGradient())
  226261. drawGradient();
  226262. else
  226263. drawImage (state->fillType.image, state->fillType.transform, true);
  226264. }
  226265. CGContextRestoreGState (context);
  226266. }
  226267. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226268. {
  226269. const int iw = sourceImage.getWidth();
  226270. const int ih = sourceImage.getHeight();
  226271. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226272. CGContextSaveGState (context);
  226273. CGContextSetAlpha (context, state->fillType.getOpacity());
  226274. flip();
  226275. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226276. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226277. if (fillEntireClipAsTiles)
  226278. {
  226279. #if JUCE_IOS
  226280. CGContextDrawTiledImage (context, imageRect, image);
  226281. #else
  226282. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226283. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226284. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226285. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226286. CGContextDrawTiledImage (context, imageRect, image);
  226287. else
  226288. #endif
  226289. {
  226290. // Fallback to manually doing a tiled fill on 10.4
  226291. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226292. int x = 0, y = 0;
  226293. while (x > clip.origin.x) x -= iw;
  226294. while (y > clip.origin.y) y -= ih;
  226295. const int right = (int) (clip.origin.x + clip.size.width);
  226296. const int bottom = (int) (clip.origin.y + clip.size.height);
  226297. while (y < bottom)
  226298. {
  226299. for (int x2 = x; x2 < right; x2 += iw)
  226300. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226301. y += ih;
  226302. }
  226303. }
  226304. #endif
  226305. }
  226306. else
  226307. {
  226308. CGContextDrawImage (context, imageRect, image);
  226309. }
  226310. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226311. CGContextRestoreGState (context);
  226312. }
  226313. void drawLine (const Line<float>& line)
  226314. {
  226315. if (state->fillType.isColour())
  226316. {
  226317. CGContextSetLineCap (context, kCGLineCapSquare);
  226318. CGContextSetLineWidth (context, 1.0f);
  226319. CGContextSetRGBStrokeColor (context,
  226320. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226321. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226322. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226323. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226324. CGContextStrokeLineSegments (context, cgLine, 1);
  226325. }
  226326. else
  226327. {
  226328. Path p;
  226329. p.addLineSegment (line, 1.0f);
  226330. fillPath (p, AffineTransform::identity);
  226331. }
  226332. }
  226333. void drawVerticalLine (const int x, float top, float bottom)
  226334. {
  226335. if (state->fillType.isColour())
  226336. {
  226337. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226338. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226339. #else
  226340. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226341. // the x co-ord slightly to trick it..
  226342. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226343. #endif
  226344. }
  226345. else
  226346. {
  226347. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226348. }
  226349. }
  226350. void drawHorizontalLine (const int y, float left, float right)
  226351. {
  226352. if (state->fillType.isColour())
  226353. {
  226354. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226355. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226356. #else
  226357. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226358. // the x co-ord slightly to trick it..
  226359. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226360. #endif
  226361. }
  226362. else
  226363. {
  226364. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226365. }
  226366. }
  226367. void setFont (const Font& newFont)
  226368. {
  226369. if (state->font != newFont)
  226370. {
  226371. state->fontRef = 0;
  226372. state->font = newFont;
  226373. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226374. if (mf != 0)
  226375. {
  226376. state->fontRef = mf->fontRef;
  226377. CGContextSetFont (context, state->fontRef);
  226378. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226379. state->fontTransform = mf->renderingTransform;
  226380. state->fontTransform.a *= state->font.getHorizontalScale();
  226381. CGContextSetTextMatrix (context, state->fontTransform);
  226382. }
  226383. }
  226384. }
  226385. const Font getFont()
  226386. {
  226387. return state->font;
  226388. }
  226389. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226390. {
  226391. if (state->fontRef != 0 && state->fillType.isColour())
  226392. {
  226393. if (transform.isOnlyTranslation())
  226394. {
  226395. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226396. CGGlyph g = glyphNumber;
  226397. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226398. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226399. }
  226400. else
  226401. {
  226402. CGContextSaveGState (context);
  226403. flip();
  226404. applyTransform (transform);
  226405. CGAffineTransform t = state->fontTransform;
  226406. t.d = -t.d;
  226407. CGContextSetTextMatrix (context, t);
  226408. CGGlyph g = glyphNumber;
  226409. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226410. CGContextRestoreGState (context);
  226411. }
  226412. }
  226413. else
  226414. {
  226415. Path p;
  226416. Font& f = state->font;
  226417. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226418. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226419. .followedBy (transform));
  226420. }
  226421. }
  226422. private:
  226423. CGContextRef context;
  226424. const CGFloat flipHeight;
  226425. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226426. CGFunctionCallbacks gradientCallbacks;
  226427. mutable Rectangle<int> lastClipRect;
  226428. mutable bool lastClipRectIsValid;
  226429. struct SavedState
  226430. {
  226431. SavedState()
  226432. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226433. {
  226434. }
  226435. SavedState (const SavedState& other)
  226436. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226437. fontTransform (other.fontTransform)
  226438. {
  226439. }
  226440. FillType fillType;
  226441. Font font;
  226442. CGFontRef fontRef;
  226443. CGAffineTransform fontTransform;
  226444. };
  226445. ScopedPointer <SavedState> state;
  226446. OwnedArray <SavedState> stateStack;
  226447. HeapBlock <PixelARGB> gradientLookupTable;
  226448. int numGradientLookupEntries;
  226449. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226450. {
  226451. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226452. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226453. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226454. colour.unpremultiply();
  226455. outData[0] = colour.getRed() / 255.0f;
  226456. outData[1] = colour.getGreen() / 255.0f;
  226457. outData[2] = colour.getBlue() / 255.0f;
  226458. outData[3] = colour.getAlpha() / 255.0f;
  226459. }
  226460. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226461. {
  226462. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  226463. --numGradientLookupEntries;
  226464. CGShadingRef result = 0;
  226465. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226466. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226467. if (gradient.isRadial)
  226468. {
  226469. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226470. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226471. function, true, true);
  226472. }
  226473. else
  226474. {
  226475. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226476. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226477. function, true, true);
  226478. }
  226479. CGFunctionRelease (function);
  226480. return result;
  226481. }
  226482. void drawGradient()
  226483. {
  226484. flip();
  226485. applyTransform (state->fillType.transform);
  226486. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226487. // you draw a gradient with high quality interp enabled).
  226488. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226489. CGContextSetAlpha (context, state->fillType.getOpacity());
  226490. CGContextDrawShading (context, shading);
  226491. CGShadingRelease (shading);
  226492. }
  226493. void createPath (const Path& path) const
  226494. {
  226495. CGContextBeginPath (context);
  226496. Path::Iterator i (path);
  226497. while (i.next())
  226498. {
  226499. switch (i.elementType)
  226500. {
  226501. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226502. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226503. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226504. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226505. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226506. default: jassertfalse; break;
  226507. }
  226508. }
  226509. }
  226510. void createPath (const Path& path, const AffineTransform& transform) const
  226511. {
  226512. CGContextBeginPath (context);
  226513. Path::Iterator i (path);
  226514. while (i.next())
  226515. {
  226516. switch (i.elementType)
  226517. {
  226518. case Path::Iterator::startNewSubPath:
  226519. transform.transformPoint (i.x1, i.y1);
  226520. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226521. break;
  226522. case Path::Iterator::lineTo:
  226523. transform.transformPoint (i.x1, i.y1);
  226524. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226525. break;
  226526. case Path::Iterator::quadraticTo:
  226527. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226528. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226529. break;
  226530. case Path::Iterator::cubicTo:
  226531. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226532. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226533. break;
  226534. case Path::Iterator::closePath:
  226535. CGContextClosePath (context); break;
  226536. default:
  226537. jassertfalse;
  226538. break;
  226539. }
  226540. }
  226541. }
  226542. void flip() const
  226543. {
  226544. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226545. }
  226546. void applyTransform (const AffineTransform& transform) const
  226547. {
  226548. CGAffineTransform t;
  226549. t.a = transform.mat00;
  226550. t.b = transform.mat10;
  226551. t.c = transform.mat01;
  226552. t.d = transform.mat11;
  226553. t.tx = transform.mat02;
  226554. t.ty = transform.mat12;
  226555. CGContextConcatCTM (context, t);
  226556. }
  226557. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226558. };
  226559. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226560. {
  226561. return new CoreGraphicsContext (context, height);
  226562. }
  226563. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226564. const Image juce_loadWithCoreImage (InputStream& input)
  226565. {
  226566. MemoryBlock data;
  226567. input.readIntoMemoryBlock (data, -1);
  226568. #if JUCE_IOS
  226569. JUCE_AUTORELEASEPOOL
  226570. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226571. length: data.getSize()
  226572. freeWhenDone: NO]];
  226573. if (image != nil)
  226574. {
  226575. CGImageRef loadedImage = image.CGImage;
  226576. #else
  226577. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226578. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226579. CGDataProviderRelease (provider);
  226580. if (imageSource != 0)
  226581. {
  226582. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226583. CFRelease (imageSource);
  226584. #endif
  226585. if (loadedImage != 0)
  226586. {
  226587. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226588. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226589. && alphaInfo != kCGImageAlphaNoneSkipLast
  226590. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226591. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226592. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226593. hasAlphaChan, Image::NativeImage);
  226594. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226595. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226596. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226597. CGContextFlush (cgImage->context);
  226598. #if ! JUCE_IOS
  226599. CFRelease (loadedImage);
  226600. #endif
  226601. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226602. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226603. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226604. return image;
  226605. }
  226606. }
  226607. return Image::null;
  226608. }
  226609. #endif
  226610. #endif
  226611. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226612. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226613. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226614. // compiled on its own).
  226615. #if JUCE_INCLUDED_FILE
  226616. class UIViewComponentPeer;
  226617. END_JUCE_NAMESPACE
  226618. #define JuceUIView MakeObjCClassName(JuceUIView)
  226619. @interface JuceUIView : UIView <UITextViewDelegate>
  226620. {
  226621. @public
  226622. UIViewComponentPeer* owner;
  226623. UITextView* hiddenTextView;
  226624. }
  226625. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226626. - (void) dealloc;
  226627. - (void) drawRect: (CGRect) r;
  226628. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226629. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226630. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226631. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226632. - (BOOL) becomeFirstResponder;
  226633. - (BOOL) resignFirstResponder;
  226634. - (BOOL) canBecomeFirstResponder;
  226635. - (void) asyncRepaint: (id) rect;
  226636. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226637. @end
  226638. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226639. @interface JuceUIViewController : UIViewController
  226640. {
  226641. }
  226642. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226643. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226644. @end
  226645. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226646. @interface JuceUIWindow : UIWindow
  226647. {
  226648. @private
  226649. UIViewComponentPeer* owner;
  226650. bool isZooming;
  226651. }
  226652. - (void) setOwner: (UIViewComponentPeer*) owner;
  226653. - (void) becomeKeyWindow;
  226654. @end
  226655. BEGIN_JUCE_NAMESPACE
  226656. class UIViewComponentPeer : public ComponentPeer,
  226657. public FocusChangeListener
  226658. {
  226659. public:
  226660. UIViewComponentPeer (Component* const component,
  226661. const int windowStyleFlags,
  226662. UIView* viewToAttachTo);
  226663. ~UIViewComponentPeer();
  226664. void* getNativeHandle() const;
  226665. void setVisible (bool shouldBeVisible);
  226666. void setTitle (const String& title);
  226667. void setPosition (int x, int y);
  226668. void setSize (int w, int h);
  226669. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226670. const Rectangle<int> getBounds() const;
  226671. const Rectangle<int> getBounds (const bool global) const;
  226672. const Point<int> getScreenPosition() const;
  226673. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226674. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226675. void setAlpha (float newAlpha);
  226676. void setMinimised (bool shouldBeMinimised);
  226677. bool isMinimised() const;
  226678. void setFullScreen (bool shouldBeFullScreen);
  226679. bool isFullScreen() const;
  226680. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226681. const BorderSize getFrameSize() const;
  226682. bool setAlwaysOnTop (bool alwaysOnTop);
  226683. void toFront (bool makeActiveWindow);
  226684. void toBehind (ComponentPeer* other);
  226685. void setIcon (const Image& newIcon);
  226686. virtual void drawRect (CGRect r);
  226687. virtual bool canBecomeKeyWindow();
  226688. virtual bool windowShouldClose();
  226689. virtual void redirectMovedOrResized();
  226690. virtual CGRect constrainRect (CGRect r);
  226691. virtual void viewFocusGain();
  226692. virtual void viewFocusLoss();
  226693. bool isFocused() const;
  226694. void grabFocus();
  226695. void textInputRequired (const Point<int>& position);
  226696. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226697. void updateHiddenTextContent (TextInputTarget* target);
  226698. void globalFocusChanged (Component*);
  226699. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226700. virtual void displayRotated();
  226701. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226702. void repaint (const Rectangle<int>& area);
  226703. void performAnyPendingRepaintsNow();
  226704. UIWindow* window;
  226705. JuceUIView* view;
  226706. JuceUIViewController* controller;
  226707. bool isSharedWindow, fullScreen, insideDrawRect;
  226708. static ModifierKeys currentModifiers;
  226709. static int64 getMouseTime (UIEvent* e)
  226710. {
  226711. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226712. + (int64) ([e timestamp] * 1000.0);
  226713. }
  226714. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226715. {
  226716. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226717. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226718. {
  226719. case UIInterfaceOrientationPortrait:
  226720. return r;
  226721. case UIInterfaceOrientationPortraitUpsideDown:
  226722. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226723. r.getWidth(), r.getHeight());
  226724. case UIInterfaceOrientationLandscapeLeft:
  226725. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226726. r.getHeight(), r.getWidth());
  226727. case UIInterfaceOrientationLandscapeRight:
  226728. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226729. r.getHeight(), r.getWidth());
  226730. default: jassertfalse; // unknown orientation!
  226731. }
  226732. return r;
  226733. }
  226734. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226735. {
  226736. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226737. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226738. {
  226739. case UIInterfaceOrientationPortrait:
  226740. return r;
  226741. case UIInterfaceOrientationPortraitUpsideDown:
  226742. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226743. r.getWidth(), r.getHeight());
  226744. case UIInterfaceOrientationLandscapeLeft:
  226745. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226746. r.getHeight(), r.getWidth());
  226747. case UIInterfaceOrientationLandscapeRight:
  226748. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226749. r.getHeight(), r.getWidth());
  226750. default: jassertfalse; // unknown orientation!
  226751. }
  226752. return r;
  226753. }
  226754. Array <UITouch*> currentTouches;
  226755. private:
  226756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226757. };
  226758. END_JUCE_NAMESPACE
  226759. @implementation JuceUIViewController
  226760. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226761. {
  226762. JuceUIView* juceView = (JuceUIView*) [self view];
  226763. jassert (juceView != 0 && juceView->owner != 0);
  226764. return juceView->owner->shouldRotate (interfaceOrientation);
  226765. }
  226766. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226767. {
  226768. JuceUIView* juceView = (JuceUIView*) [self view];
  226769. jassert (juceView != 0 && juceView->owner != 0);
  226770. juceView->owner->displayRotated();
  226771. }
  226772. @end
  226773. @implementation JuceUIView
  226774. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226775. withFrame: (CGRect) frame
  226776. {
  226777. [super initWithFrame: frame];
  226778. owner = owner_;
  226779. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226780. [self addSubview: hiddenTextView];
  226781. hiddenTextView.delegate = self;
  226782. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226783. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226784. return self;
  226785. }
  226786. - (void) dealloc
  226787. {
  226788. [hiddenTextView removeFromSuperview];
  226789. [hiddenTextView release];
  226790. [super dealloc];
  226791. }
  226792. - (void) drawRect: (CGRect) r
  226793. {
  226794. if (owner != 0)
  226795. owner->drawRect (r);
  226796. }
  226797. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226798. {
  226799. return false;
  226800. }
  226801. ModifierKeys UIViewComponentPeer::currentModifiers;
  226802. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226803. {
  226804. return UIViewComponentPeer::currentModifiers;
  226805. }
  226806. void ModifierKeys::updateCurrentModifiers() throw()
  226807. {
  226808. currentModifiers = UIViewComponentPeer::currentModifiers;
  226809. }
  226810. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226811. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226812. {
  226813. if (owner != 0)
  226814. owner->handleTouches (event, true, false, false);
  226815. }
  226816. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226817. {
  226818. if (owner != 0)
  226819. owner->handleTouches (event, false, false, false);
  226820. }
  226821. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226822. {
  226823. if (owner != 0)
  226824. owner->handleTouches (event, false, true, false);
  226825. }
  226826. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226827. {
  226828. if (owner != 0)
  226829. owner->handleTouches (event, false, true, true);
  226830. [self touchesEnded: touches withEvent: event];
  226831. }
  226832. - (BOOL) becomeFirstResponder
  226833. {
  226834. if (owner != 0)
  226835. owner->viewFocusGain();
  226836. return true;
  226837. }
  226838. - (BOOL) resignFirstResponder
  226839. {
  226840. if (owner != 0)
  226841. owner->viewFocusLoss();
  226842. return true;
  226843. }
  226844. - (BOOL) canBecomeFirstResponder
  226845. {
  226846. return owner != 0 && owner->canBecomeKeyWindow();
  226847. }
  226848. - (void) asyncRepaint: (id) rect
  226849. {
  226850. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226851. [self setNeedsDisplayInRect: *r];
  226852. }
  226853. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226854. {
  226855. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226856. nsStringToJuce (text));
  226857. }
  226858. @end
  226859. @implementation JuceUIWindow
  226860. - (void) setOwner: (UIViewComponentPeer*) owner_
  226861. {
  226862. owner = owner_;
  226863. isZooming = false;
  226864. }
  226865. - (void) becomeKeyWindow
  226866. {
  226867. [super becomeKeyWindow];
  226868. if (owner != 0)
  226869. owner->grabFocus();
  226870. }
  226871. @end
  226872. BEGIN_JUCE_NAMESPACE
  226873. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226874. const int windowStyleFlags,
  226875. UIView* viewToAttachTo)
  226876. : ComponentPeer (component, windowStyleFlags),
  226877. window (0),
  226878. view (0), controller (0),
  226879. isSharedWindow (viewToAttachTo != 0),
  226880. fullScreen (false),
  226881. insideDrawRect (false)
  226882. {
  226883. CGRect r = convertToCGRect (component->getLocalBounds());
  226884. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226885. if (isSharedWindow)
  226886. {
  226887. window = [viewToAttachTo window];
  226888. [viewToAttachTo addSubview: view];
  226889. setVisible (component->isVisible());
  226890. }
  226891. else
  226892. {
  226893. controller = [[JuceUIViewController alloc] init];
  226894. controller.view = view;
  226895. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226896. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226897. window = [[JuceUIWindow alloc] init];
  226898. window.frame = r;
  226899. window.opaque = component->isOpaque();
  226900. view.opaque = component->isOpaque();
  226901. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226902. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226903. [((JuceUIWindow*) window) setOwner: this];
  226904. if (component->isAlwaysOnTop())
  226905. window.windowLevel = UIWindowLevelAlert;
  226906. [window addSubview: view];
  226907. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226908. view.hidden = ! component->isVisible();
  226909. window.hidden = ! component->isVisible();
  226910. view.multipleTouchEnabled = YES;
  226911. }
  226912. setTitle (component->getName());
  226913. Desktop::getInstance().addFocusChangeListener (this);
  226914. }
  226915. UIViewComponentPeer::~UIViewComponentPeer()
  226916. {
  226917. Desktop::getInstance().removeFocusChangeListener (this);
  226918. view->owner = 0;
  226919. [view removeFromSuperview];
  226920. [view release];
  226921. [controller release];
  226922. if (! isSharedWindow)
  226923. {
  226924. [((JuceUIWindow*) window) setOwner: 0];
  226925. [window release];
  226926. }
  226927. }
  226928. void* UIViewComponentPeer::getNativeHandle() const
  226929. {
  226930. return view;
  226931. }
  226932. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226933. {
  226934. view.hidden = ! shouldBeVisible;
  226935. if (! isSharedWindow)
  226936. window.hidden = ! shouldBeVisible;
  226937. }
  226938. void UIViewComponentPeer::setTitle (const String& title)
  226939. {
  226940. // xxx is this possible?
  226941. }
  226942. void UIViewComponentPeer::setPosition (int x, int y)
  226943. {
  226944. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226945. }
  226946. void UIViewComponentPeer::setSize (int w, int h)
  226947. {
  226948. setBounds (component->getX(), component->getY(), w, h, false);
  226949. }
  226950. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226951. {
  226952. fullScreen = isNowFullScreen;
  226953. w = jmax (0, w);
  226954. h = jmax (0, h);
  226955. if (isSharedWindow)
  226956. {
  226957. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226958. if ([view frame].size.width != r.size.width
  226959. || [view frame].size.height != r.size.height)
  226960. [view setNeedsDisplay];
  226961. view.frame = r;
  226962. }
  226963. else
  226964. {
  226965. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226966. window.frame = convertToCGRect (bounds);
  226967. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226968. handleMovedOrResized();
  226969. }
  226970. }
  226971. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226972. {
  226973. CGRect r = [view frame];
  226974. if (global && [view window] != 0)
  226975. {
  226976. r = [view convertRect: r toView: nil];
  226977. CGRect wr = [[view window] frame];
  226978. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226979. r.origin.x = windowBounds.getX();
  226980. r.origin.y = windowBounds.getY();
  226981. }
  226982. return convertToRectInt (r);
  226983. }
  226984. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226985. {
  226986. return getBounds (! isSharedWindow);
  226987. }
  226988. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226989. {
  226990. return getBounds (true).getPosition();
  226991. }
  226992. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226993. {
  226994. return relativePosition + getScreenPosition();
  226995. }
  226996. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226997. {
  226998. return screenPosition - getScreenPosition();
  226999. }
  227000. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227001. {
  227002. if (constrainer != 0)
  227003. {
  227004. CGRect current = [window frame];
  227005. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227006. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227007. Rectangle<int> pos (convertToRectInt (r));
  227008. Rectangle<int> original (convertToRectInt (current));
  227009. constrainer->checkBounds (pos, original,
  227010. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227011. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227012. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227013. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227014. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227015. r.origin.x = pos.getX();
  227016. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227017. r.size.width = pos.getWidth();
  227018. r.size.height = pos.getHeight();
  227019. }
  227020. return r;
  227021. }
  227022. void UIViewComponentPeer::setAlpha (float newAlpha)
  227023. {
  227024. [[view window] setAlpha: (CGFloat) newAlpha];
  227025. }
  227026. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227027. {
  227028. }
  227029. bool UIViewComponentPeer::isMinimised() const
  227030. {
  227031. return false;
  227032. }
  227033. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227034. {
  227035. if (! isSharedWindow)
  227036. {
  227037. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227038. : lastNonFullscreenBounds);
  227039. if ((! shouldBeFullScreen) && r.isEmpty())
  227040. r = getBounds();
  227041. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227042. if (! r.isEmpty())
  227043. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227044. component->repaint();
  227045. }
  227046. }
  227047. bool UIViewComponentPeer::isFullScreen() const
  227048. {
  227049. return fullScreen;
  227050. }
  227051. namespace
  227052. {
  227053. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227054. {
  227055. switch (interfaceOrientation)
  227056. {
  227057. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227058. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227059. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227060. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227061. default: jassertfalse; // unknown orientation!
  227062. }
  227063. return Desktop::upright;
  227064. }
  227065. }
  227066. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227067. {
  227068. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227069. }
  227070. void UIViewComponentPeer::displayRotated()
  227071. {
  227072. const Rectangle<int> oldArea (component->getBounds());
  227073. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227074. Desktop::getInstance().refreshMonitorSizes();
  227075. if (fullScreen)
  227076. {
  227077. fullScreen = false;
  227078. setFullScreen (true);
  227079. }
  227080. else
  227081. {
  227082. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227083. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227084. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227085. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227086. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227087. setBounds ((int) (l * newDesktop.getWidth()),
  227088. (int) (t * newDesktop.getHeight()),
  227089. (int) ((r - l) * newDesktop.getWidth()),
  227090. (int) ((b - t) * newDesktop.getHeight()),
  227091. false);
  227092. }
  227093. }
  227094. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227095. {
  227096. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227097. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227098. return false;
  227099. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227100. withEvent: nil];
  227101. if (trueIfInAChildWindow)
  227102. return v != nil;
  227103. return v == view;
  227104. }
  227105. const BorderSize UIViewComponentPeer::getFrameSize() const
  227106. {
  227107. return BorderSize();
  227108. }
  227109. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227110. {
  227111. if (! isSharedWindow)
  227112. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227113. return true;
  227114. }
  227115. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227116. {
  227117. if (isSharedWindow)
  227118. [[view superview] bringSubviewToFront: view];
  227119. if (window != 0 && component->isVisible())
  227120. [window makeKeyAndVisible];
  227121. }
  227122. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227123. {
  227124. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227125. jassert (otherPeer != 0); // wrong type of window?
  227126. if (otherPeer != 0)
  227127. {
  227128. if (isSharedWindow)
  227129. {
  227130. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227131. }
  227132. else
  227133. {
  227134. jassertfalse; // don't know how to do this
  227135. }
  227136. }
  227137. }
  227138. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227139. {
  227140. // to do..
  227141. }
  227142. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227143. {
  227144. NSArray* touches = [[event touchesForView: view] allObjects];
  227145. for (unsigned int i = 0; i < [touches count]; ++i)
  227146. {
  227147. UITouch* touch = [touches objectAtIndex: i];
  227148. CGPoint p = [touch locationInView: view];
  227149. const Point<int> pos ((int) p.x, (int) p.y);
  227150. juce_lastMousePos = pos + getScreenPosition();
  227151. const int64 time = getMouseTime (event);
  227152. int touchIndex = currentTouches.indexOf (touch);
  227153. if (touchIndex < 0)
  227154. {
  227155. touchIndex = currentTouches.size();
  227156. currentTouches.add (touch);
  227157. }
  227158. if (isDown)
  227159. {
  227160. currentModifiers = currentModifiers.withoutMouseButtons();
  227161. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227162. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227163. }
  227164. else if (isUp)
  227165. {
  227166. currentModifiers = currentModifiers.withoutMouseButtons();
  227167. currentTouches.remove (touchIndex);
  227168. }
  227169. if (isCancel)
  227170. currentTouches.clear();
  227171. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227172. }
  227173. }
  227174. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227175. void UIViewComponentPeer::viewFocusGain()
  227176. {
  227177. if (currentlyFocusedPeer != this)
  227178. {
  227179. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227180. currentlyFocusedPeer->handleFocusLoss();
  227181. currentlyFocusedPeer = this;
  227182. handleFocusGain();
  227183. }
  227184. }
  227185. void UIViewComponentPeer::viewFocusLoss()
  227186. {
  227187. if (currentlyFocusedPeer == this)
  227188. {
  227189. currentlyFocusedPeer = 0;
  227190. handleFocusLoss();
  227191. }
  227192. }
  227193. void juce_HandleProcessFocusChange()
  227194. {
  227195. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227196. {
  227197. if (Process::isForegroundProcess())
  227198. {
  227199. currentlyFocusedPeer->handleFocusGain();
  227200. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227201. }
  227202. else
  227203. {
  227204. currentlyFocusedPeer->handleFocusLoss();
  227205. // turn kiosk mode off if we lose focus..
  227206. Desktop::getInstance().setKioskModeComponent (0);
  227207. }
  227208. }
  227209. }
  227210. bool UIViewComponentPeer::isFocused() const
  227211. {
  227212. return isSharedWindow ? this == currentlyFocusedPeer
  227213. : (window != 0 && [window isKeyWindow]);
  227214. }
  227215. void UIViewComponentPeer::grabFocus()
  227216. {
  227217. if (window != 0)
  227218. {
  227219. [window makeKeyWindow];
  227220. viewFocusGain();
  227221. }
  227222. }
  227223. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227224. {
  227225. }
  227226. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227227. {
  227228. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227229. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227230. }
  227231. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227232. {
  227233. TextInputTarget* const target = findCurrentTextInputTarget();
  227234. if (target != 0)
  227235. {
  227236. const Range<int> currentSelection (target->getHighlightedRegion());
  227237. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227238. if (currentSelection.isEmpty())
  227239. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227240. target->insertTextAtCaret (text);
  227241. updateHiddenTextContent (target);
  227242. }
  227243. return NO;
  227244. }
  227245. void UIViewComponentPeer::globalFocusChanged (Component*)
  227246. {
  227247. TextInputTarget* const target = findCurrentTextInputTarget();
  227248. if (target != 0)
  227249. {
  227250. Component* comp = dynamic_cast<Component*> (target);
  227251. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227252. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227253. updateHiddenTextContent (target);
  227254. [view->hiddenTextView becomeFirstResponder];
  227255. }
  227256. else
  227257. {
  227258. [view->hiddenTextView resignFirstResponder];
  227259. }
  227260. }
  227261. void UIViewComponentPeer::drawRect (CGRect r)
  227262. {
  227263. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227264. return;
  227265. CGContextRef cg = UIGraphicsGetCurrentContext();
  227266. if (! component->isOpaque())
  227267. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227268. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227269. CoreGraphicsContext g (cg, view.bounds.size.height);
  227270. insideDrawRect = true;
  227271. handlePaint (g);
  227272. insideDrawRect = false;
  227273. }
  227274. bool UIViewComponentPeer::canBecomeKeyWindow()
  227275. {
  227276. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227277. }
  227278. bool UIViewComponentPeer::windowShouldClose()
  227279. {
  227280. if (! isValidPeer (this))
  227281. return YES;
  227282. handleUserClosingWindow();
  227283. return NO;
  227284. }
  227285. void UIViewComponentPeer::redirectMovedOrResized()
  227286. {
  227287. handleMovedOrResized();
  227288. }
  227289. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227290. {
  227291. }
  227292. class AsyncRepaintMessage : public CallbackMessage
  227293. {
  227294. public:
  227295. UIViewComponentPeer* const peer;
  227296. const Rectangle<int> rect;
  227297. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227298. : peer (peer_), rect (rect_)
  227299. {
  227300. }
  227301. void messageCallback()
  227302. {
  227303. if (ComponentPeer::isValidPeer (peer))
  227304. peer->repaint (rect);
  227305. }
  227306. };
  227307. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227308. {
  227309. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227310. {
  227311. (new AsyncRepaintMessage (this, area))->post();
  227312. }
  227313. else
  227314. {
  227315. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227316. }
  227317. }
  227318. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227319. {
  227320. }
  227321. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227322. {
  227323. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227324. }
  227325. const Image juce_createIconForFile (const File& file)
  227326. {
  227327. return Image::null;
  227328. }
  227329. void Desktop::createMouseInputSources()
  227330. {
  227331. for (int i = 0; i < 10; ++i)
  227332. mouseSources.add (new MouseInputSource (i, false));
  227333. }
  227334. bool Desktop::canUseSemiTransparentWindows() throw()
  227335. {
  227336. return true;
  227337. }
  227338. const Point<int> MouseInputSource::getCurrentMousePosition()
  227339. {
  227340. return juce_lastMousePos;
  227341. }
  227342. void Desktop::setMousePosition (const Point<int>&)
  227343. {
  227344. }
  227345. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227346. {
  227347. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227348. }
  227349. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227350. {
  227351. const ScopedAutoReleasePool pool;
  227352. monitorCoords.clear();
  227353. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227354. : [[UIScreen mainScreen] bounds];
  227355. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227356. }
  227357. const int KeyPress::spaceKey = ' ';
  227358. const int KeyPress::returnKey = 0x0d;
  227359. const int KeyPress::escapeKey = 0x1b;
  227360. const int KeyPress::backspaceKey = 0x7f;
  227361. const int KeyPress::leftKey = 0x1000;
  227362. const int KeyPress::rightKey = 0x1001;
  227363. const int KeyPress::upKey = 0x1002;
  227364. const int KeyPress::downKey = 0x1003;
  227365. const int KeyPress::pageUpKey = 0x1004;
  227366. const int KeyPress::pageDownKey = 0x1005;
  227367. const int KeyPress::endKey = 0x1006;
  227368. const int KeyPress::homeKey = 0x1007;
  227369. const int KeyPress::deleteKey = 0x1008;
  227370. const int KeyPress::insertKey = -1;
  227371. const int KeyPress::tabKey = 9;
  227372. const int KeyPress::F1Key = 0x2001;
  227373. const int KeyPress::F2Key = 0x2002;
  227374. const int KeyPress::F3Key = 0x2003;
  227375. const int KeyPress::F4Key = 0x2004;
  227376. const int KeyPress::F5Key = 0x2005;
  227377. const int KeyPress::F6Key = 0x2006;
  227378. const int KeyPress::F7Key = 0x2007;
  227379. const int KeyPress::F8Key = 0x2008;
  227380. const int KeyPress::F9Key = 0x2009;
  227381. const int KeyPress::F10Key = 0x200a;
  227382. const int KeyPress::F11Key = 0x200b;
  227383. const int KeyPress::F12Key = 0x200c;
  227384. const int KeyPress::F13Key = 0x200d;
  227385. const int KeyPress::F14Key = 0x200e;
  227386. const int KeyPress::F15Key = 0x200f;
  227387. const int KeyPress::F16Key = 0x2010;
  227388. const int KeyPress::numberPad0 = 0x30020;
  227389. const int KeyPress::numberPad1 = 0x30021;
  227390. const int KeyPress::numberPad2 = 0x30022;
  227391. const int KeyPress::numberPad3 = 0x30023;
  227392. const int KeyPress::numberPad4 = 0x30024;
  227393. const int KeyPress::numberPad5 = 0x30025;
  227394. const int KeyPress::numberPad6 = 0x30026;
  227395. const int KeyPress::numberPad7 = 0x30027;
  227396. const int KeyPress::numberPad8 = 0x30028;
  227397. const int KeyPress::numberPad9 = 0x30029;
  227398. const int KeyPress::numberPadAdd = 0x3002a;
  227399. const int KeyPress::numberPadSubtract = 0x3002b;
  227400. const int KeyPress::numberPadMultiply = 0x3002c;
  227401. const int KeyPress::numberPadDivide = 0x3002d;
  227402. const int KeyPress::numberPadSeparator = 0x3002e;
  227403. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227404. const int KeyPress::numberPadEquals = 0x30030;
  227405. const int KeyPress::numberPadDelete = 0x30031;
  227406. const int KeyPress::playKey = 0x30000;
  227407. const int KeyPress::stopKey = 0x30001;
  227408. const int KeyPress::fastForwardKey = 0x30002;
  227409. const int KeyPress::rewindKey = 0x30003;
  227410. #endif
  227411. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227412. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227413. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227414. // compiled on its own).
  227415. #if JUCE_INCLUDED_FILE
  227416. struct CallbackMessagePayload
  227417. {
  227418. MessageCallbackFunction* function;
  227419. void* parameter;
  227420. void* volatile result;
  227421. bool volatile hasBeenExecuted;
  227422. };
  227423. END_JUCE_NAMESPACE
  227424. @interface JuceCustomMessageHandler : NSObject
  227425. {
  227426. }
  227427. - (void) performCallback: (id) info;
  227428. @end
  227429. @implementation JuceCustomMessageHandler
  227430. - (void) performCallback: (id) info
  227431. {
  227432. if ([info isKindOfClass: [NSData class]])
  227433. {
  227434. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227435. if (pl != 0)
  227436. {
  227437. pl->result = (*pl->function) (pl->parameter);
  227438. pl->hasBeenExecuted = true;
  227439. }
  227440. }
  227441. else
  227442. {
  227443. jassertfalse; // should never get here!
  227444. }
  227445. }
  227446. @end
  227447. BEGIN_JUCE_NAMESPACE
  227448. void MessageManager::runDispatchLoop()
  227449. {
  227450. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227451. runDispatchLoopUntil (-1);
  227452. }
  227453. void MessageManager::stopDispatchLoop()
  227454. {
  227455. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227456. exit (0); // iPhone apps get no mercy..
  227457. }
  227458. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227459. {
  227460. const ScopedAutoReleasePool pool;
  227461. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227462. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227463. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227464. while (! quitMessagePosted)
  227465. {
  227466. const ScopedAutoReleasePool pool;
  227467. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227468. beforeDate: endDate];
  227469. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227470. break;
  227471. }
  227472. return ! quitMessagePosted;
  227473. }
  227474. namespace iOSMessageLoopHelpers
  227475. {
  227476. static CFRunLoopRef runLoop = 0;
  227477. static CFRunLoopSourceRef runLoopSource = 0;
  227478. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  227479. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  227480. void runLoopSourceCallback (void*)
  227481. {
  227482. if (pendingMessages != 0)
  227483. {
  227484. int numDispatched = 0;
  227485. do
  227486. {
  227487. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  227488. if (nextMessage == 0)
  227489. return;
  227490. const ScopedAutoReleasePool pool;
  227491. MessageManager::getInstance()->deliverMessage (nextMessage);
  227492. } while (++numDispatched <= 4);
  227493. CFRunLoopSourceSignal (runLoopSource);
  227494. CFRunLoopWakeUp (runLoop);
  227495. }
  227496. }
  227497. }
  227498. void MessageManager::doPlatformSpecificInitialisation()
  227499. {
  227500. using namespace iOSMessageLoopHelpers;
  227501. pendingMessages = new OwnedArray <Message, CriticalSection>();
  227502. runLoop = CFRunLoopGetCurrent();
  227503. CFRunLoopSourceContext sourceContext;
  227504. zerostruct (sourceContext);
  227505. sourceContext.perform = runLoopSourceCallback;
  227506. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  227507. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  227508. if (juceCustomMessageHandler == 0)
  227509. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227510. }
  227511. void MessageManager::doPlatformSpecificShutdown()
  227512. {
  227513. using namespace iOSMessageLoopHelpers;
  227514. CFRunLoopSourceInvalidate (runLoopSource);
  227515. CFRelease (runLoopSource);
  227516. runLoopSource = 0;
  227517. deleteAndZero (pendingMessages);
  227518. if (juceCustomMessageHandler != 0)
  227519. {
  227520. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227521. [juceCustomMessageHandler release];
  227522. juceCustomMessageHandler = 0;
  227523. }
  227524. }
  227525. bool juce_postMessageToSystemQueue (Message* message)
  227526. {
  227527. using namespace iOSMessageLoopHelpers;
  227528. if (pendingMessages != 0)
  227529. {
  227530. pendingMessages->add (message);
  227531. CFRunLoopSourceSignal (runLoopSource);
  227532. CFRunLoopWakeUp (runLoop);
  227533. }
  227534. return true;
  227535. }
  227536. void MessageManager::broadcastMessage (const String& value)
  227537. {
  227538. }
  227539. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227540. {
  227541. using namespace iOSMessageLoopHelpers;
  227542. if (isThisTheMessageThread())
  227543. {
  227544. return (*callback) (data);
  227545. }
  227546. else
  227547. {
  227548. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227549. // deadlock because the message manager is blocked from running, so can never
  227550. // call your function..
  227551. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227552. const ScopedAutoReleasePool pool;
  227553. CallbackMessagePayload cmp;
  227554. cmp.function = callback;
  227555. cmp.parameter = data;
  227556. cmp.result = 0;
  227557. cmp.hasBeenExecuted = false;
  227558. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227559. withObject: [NSData dataWithBytesNoCopy: &cmp
  227560. length: sizeof (cmp)
  227561. freeWhenDone: NO]
  227562. waitUntilDone: YES];
  227563. return cmp.result;
  227564. }
  227565. }
  227566. #endif
  227567. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227568. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227569. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227570. // compiled on its own).
  227571. #if JUCE_INCLUDED_FILE
  227572. #if JUCE_MAC
  227573. END_JUCE_NAMESPACE
  227574. using namespace JUCE_NAMESPACE;
  227575. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227576. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227577. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227578. #else
  227579. @interface JuceFileChooserDelegate : NSObject
  227580. #endif
  227581. {
  227582. StringArray* filters;
  227583. }
  227584. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227585. - (void) dealloc;
  227586. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227587. @end
  227588. @implementation JuceFileChooserDelegate
  227589. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227590. {
  227591. [super init];
  227592. filters = filters_;
  227593. return self;
  227594. }
  227595. - (void) dealloc
  227596. {
  227597. delete filters;
  227598. [super dealloc];
  227599. }
  227600. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227601. {
  227602. (void) sender;
  227603. const File f (nsStringToJuce (filename));
  227604. for (int i = filters->size(); --i >= 0;)
  227605. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227606. return true;
  227607. return f.isDirectory();
  227608. }
  227609. @end
  227610. BEGIN_JUCE_NAMESPACE
  227611. void FileChooser::showPlatformDialog (Array<File>& results,
  227612. const String& title,
  227613. const File& currentFileOrDirectory,
  227614. const String& filter,
  227615. bool selectsDirectory,
  227616. bool selectsFiles,
  227617. bool isSaveDialogue,
  227618. bool warnAboutOverwritingExistingFiles,
  227619. bool selectMultipleFiles,
  227620. FilePreviewComponent* extraInfoComponent)
  227621. {
  227622. const ScopedAutoReleasePool pool;
  227623. StringArray* filters = new StringArray();
  227624. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227625. filters->trim();
  227626. filters->removeEmptyStrings();
  227627. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227628. [delegate autorelease];
  227629. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227630. : [NSOpenPanel openPanel];
  227631. [panel setTitle: juceStringToNS (title)];
  227632. if (! isSaveDialogue)
  227633. {
  227634. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227635. [openPanel setCanChooseDirectories: selectsDirectory];
  227636. [openPanel setCanChooseFiles: selectsFiles];
  227637. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227638. }
  227639. [panel setDelegate: delegate];
  227640. if (isSaveDialogue || selectsDirectory)
  227641. [panel setCanCreateDirectories: YES];
  227642. String directory, filename;
  227643. if (currentFileOrDirectory.isDirectory())
  227644. {
  227645. directory = currentFileOrDirectory.getFullPathName();
  227646. }
  227647. else
  227648. {
  227649. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227650. filename = currentFileOrDirectory.getFileName();
  227651. }
  227652. if ([panel runModalForDirectory: juceStringToNS (directory)
  227653. file: juceStringToNS (filename)]
  227654. == NSOKButton)
  227655. {
  227656. if (isSaveDialogue)
  227657. {
  227658. results.add (File (nsStringToJuce ([panel filename])));
  227659. }
  227660. else
  227661. {
  227662. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227663. NSArray* urls = [openPanel filenames];
  227664. for (unsigned int i = 0; i < [urls count]; ++i)
  227665. {
  227666. NSString* f = [urls objectAtIndex: i];
  227667. results.add (File (nsStringToJuce (f)));
  227668. }
  227669. }
  227670. }
  227671. [panel setDelegate: nil];
  227672. }
  227673. #else
  227674. void FileChooser::showPlatformDialog (Array<File>& results,
  227675. const String& title,
  227676. const File& currentFileOrDirectory,
  227677. const String& filter,
  227678. bool selectsDirectory,
  227679. bool selectsFiles,
  227680. bool isSaveDialogue,
  227681. bool warnAboutOverwritingExistingFiles,
  227682. bool selectMultipleFiles,
  227683. FilePreviewComponent* extraInfoComponent)
  227684. {
  227685. const ScopedAutoReleasePool pool;
  227686. jassertfalse; //xxx to do
  227687. }
  227688. #endif
  227689. #endif
  227690. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227691. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227692. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227693. // compiled on its own).
  227694. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227695. #if JUCE_MAC
  227696. END_JUCE_NAMESPACE
  227697. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227698. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227699. {
  227700. CriticalSection* contextLock;
  227701. bool needsUpdate;
  227702. }
  227703. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227704. - (bool) makeActive;
  227705. - (void) makeInactive;
  227706. - (void) reshape;
  227707. @end
  227708. @implementation ThreadSafeNSOpenGLView
  227709. - (id) initWithFrame: (NSRect) frameRect
  227710. pixelFormat: (NSOpenGLPixelFormat*) format
  227711. {
  227712. contextLock = new CriticalSection();
  227713. self = [super initWithFrame: frameRect pixelFormat: format];
  227714. if (self != nil)
  227715. [[NSNotificationCenter defaultCenter] addObserver: self
  227716. selector: @selector (_surfaceNeedsUpdate:)
  227717. name: NSViewGlobalFrameDidChangeNotification
  227718. object: self];
  227719. return self;
  227720. }
  227721. - (void) dealloc
  227722. {
  227723. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227724. delete contextLock;
  227725. [super dealloc];
  227726. }
  227727. - (bool) makeActive
  227728. {
  227729. const ScopedLock sl (*contextLock);
  227730. if ([self openGLContext] == 0)
  227731. return false;
  227732. [[self openGLContext] makeCurrentContext];
  227733. if (needsUpdate)
  227734. {
  227735. [super update];
  227736. needsUpdate = false;
  227737. }
  227738. return true;
  227739. }
  227740. - (void) makeInactive
  227741. {
  227742. const ScopedLock sl (*contextLock);
  227743. [NSOpenGLContext clearCurrentContext];
  227744. }
  227745. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227746. {
  227747. const ScopedLock sl (*contextLock);
  227748. needsUpdate = true;
  227749. }
  227750. - (void) update
  227751. {
  227752. const ScopedLock sl (*contextLock);
  227753. needsUpdate = true;
  227754. }
  227755. - (void) reshape
  227756. {
  227757. const ScopedLock sl (*contextLock);
  227758. needsUpdate = true;
  227759. }
  227760. @end
  227761. BEGIN_JUCE_NAMESPACE
  227762. class WindowedGLContext : public OpenGLContext
  227763. {
  227764. public:
  227765. WindowedGLContext (Component* const component,
  227766. const OpenGLPixelFormat& pixelFormat_,
  227767. NSOpenGLContext* sharedContext)
  227768. : renderContext (0),
  227769. pixelFormat (pixelFormat_)
  227770. {
  227771. jassert (component != 0);
  227772. NSOpenGLPixelFormatAttribute attribs [64];
  227773. int n = 0;
  227774. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227775. attribs[n++] = NSOpenGLPFAAccelerated;
  227776. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227777. attribs[n++] = NSOpenGLPFAColorSize;
  227778. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227779. pixelFormat.greenBits,
  227780. pixelFormat.blueBits);
  227781. attribs[n++] = NSOpenGLPFAAlphaSize;
  227782. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227783. attribs[n++] = NSOpenGLPFADepthSize;
  227784. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227785. attribs[n++] = NSOpenGLPFAStencilSize;
  227786. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227787. attribs[n++] = NSOpenGLPFAAccumSize;
  227788. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227789. pixelFormat.accumulationBufferGreenBits,
  227790. pixelFormat.accumulationBufferBlueBits,
  227791. pixelFormat.accumulationBufferAlphaBits);
  227792. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227793. attribs[n++] = NSOpenGLPFASampleBuffers;
  227794. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227795. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227796. attribs[n++] = NSOpenGLPFANoRecovery;
  227797. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227798. NSOpenGLPixelFormat* format
  227799. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227800. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227801. pixelFormat: format];
  227802. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227803. shareContext: sharedContext] autorelease];
  227804. const GLint swapInterval = 1;
  227805. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227806. [view setOpenGLContext: renderContext];
  227807. [format release];
  227808. viewHolder = new NSViewComponentInternal (view, component);
  227809. }
  227810. ~WindowedGLContext()
  227811. {
  227812. deleteContext();
  227813. viewHolder = 0;
  227814. }
  227815. void deleteContext()
  227816. {
  227817. makeInactive();
  227818. [renderContext clearDrawable];
  227819. [renderContext setView: nil];
  227820. [view setOpenGLContext: nil];
  227821. renderContext = nil;
  227822. }
  227823. bool makeActive() const throw()
  227824. {
  227825. jassert (renderContext != 0);
  227826. if ([renderContext view] != view)
  227827. [renderContext setView: view];
  227828. [view makeActive];
  227829. return isActive();
  227830. }
  227831. bool makeInactive() const throw()
  227832. {
  227833. [view makeInactive];
  227834. return true;
  227835. }
  227836. bool isActive() const throw()
  227837. {
  227838. return [NSOpenGLContext currentContext] == renderContext;
  227839. }
  227840. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227841. void* getRawContext() const throw() { return renderContext; }
  227842. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227843. {
  227844. }
  227845. void swapBuffers()
  227846. {
  227847. [renderContext flushBuffer];
  227848. }
  227849. bool setSwapInterval (const int numFramesPerSwap)
  227850. {
  227851. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227852. forParameter: NSOpenGLCPSwapInterval];
  227853. return true;
  227854. }
  227855. int getSwapInterval() const
  227856. {
  227857. GLint numFrames = 0;
  227858. [renderContext getValues: &numFrames
  227859. forParameter: NSOpenGLCPSwapInterval];
  227860. return numFrames;
  227861. }
  227862. void repaint()
  227863. {
  227864. // we need to invalidate the juce view that holds this gl view, to make it
  227865. // cause a repaint callback
  227866. NSView* v = (NSView*) viewHolder->view;
  227867. NSRect r = [v frame];
  227868. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227869. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227870. // repaint message, thus never causing our paint() callback, and never repainting
  227871. // the comp. So invalidating just a little bit around the edge helps..
  227872. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227873. }
  227874. void* getNativeWindowHandle() const { return viewHolder->view; }
  227875. NSOpenGLContext* renderContext;
  227876. ThreadSafeNSOpenGLView* view;
  227877. private:
  227878. OpenGLPixelFormat pixelFormat;
  227879. ScopedPointer <NSViewComponentInternal> viewHolder;
  227880. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227881. };
  227882. OpenGLContext* OpenGLComponent::createContext()
  227883. {
  227884. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  227885. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227886. return (c->renderContext != 0) ? c.release() : 0;
  227887. }
  227888. void* OpenGLComponent::getNativeWindowHandle() const
  227889. {
  227890. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227891. : 0;
  227892. }
  227893. void juce_glViewport (const int w, const int h)
  227894. {
  227895. glViewport (0, 0, w, h);
  227896. }
  227897. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227898. OwnedArray <OpenGLPixelFormat>& results)
  227899. {
  227900. /* GLint attribs [64];
  227901. int n = 0;
  227902. attribs[n++] = AGL_RGBA;
  227903. attribs[n++] = AGL_DOUBLEBUFFER;
  227904. attribs[n++] = AGL_ACCELERATED;
  227905. attribs[n++] = AGL_NO_RECOVERY;
  227906. attribs[n++] = AGL_NONE;
  227907. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227908. while (p != 0)
  227909. {
  227910. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227911. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227912. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227913. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227914. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227915. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227916. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227917. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227918. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227919. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227920. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227921. results.add (pf);
  227922. p = aglNextPixelFormat (p);
  227923. }*/
  227924. //jassertfalse // can't see how you do this in cocoa!
  227925. }
  227926. #else
  227927. END_JUCE_NAMESPACE
  227928. @interface JuceGLView : UIView
  227929. {
  227930. }
  227931. + (Class) layerClass;
  227932. @end
  227933. @implementation JuceGLView
  227934. + (Class) layerClass
  227935. {
  227936. return [CAEAGLLayer class];
  227937. }
  227938. @end
  227939. BEGIN_JUCE_NAMESPACE
  227940. class GLESContext : public OpenGLContext
  227941. {
  227942. public:
  227943. GLESContext (UIViewComponentPeer* peer,
  227944. Component* const component_,
  227945. const OpenGLPixelFormat& pixelFormat_,
  227946. const GLESContext* const sharedContext,
  227947. NSUInteger apiType)
  227948. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227949. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227950. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227951. {
  227952. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227953. view.opaque = YES;
  227954. view.hidden = NO;
  227955. view.backgroundColor = [UIColor blackColor];
  227956. view.userInteractionEnabled = NO;
  227957. glLayer = (CAEAGLLayer*) [view layer];
  227958. [peer->view addSubview: view];
  227959. if (sharedContext != 0)
  227960. context = [[EAGLContext alloc] initWithAPI: apiType
  227961. sharegroup: [sharedContext->context sharegroup]];
  227962. else
  227963. context = [[EAGLContext alloc] initWithAPI: apiType];
  227964. createGLBuffers();
  227965. }
  227966. ~GLESContext()
  227967. {
  227968. deleteContext();
  227969. [view removeFromSuperview];
  227970. [view release];
  227971. freeGLBuffers();
  227972. }
  227973. void deleteContext()
  227974. {
  227975. makeInactive();
  227976. [context release];
  227977. context = nil;
  227978. }
  227979. bool makeActive() const throw()
  227980. {
  227981. jassert (context != 0);
  227982. [EAGLContext setCurrentContext: context];
  227983. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227984. return true;
  227985. }
  227986. void swapBuffers()
  227987. {
  227988. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227989. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227990. }
  227991. bool makeInactive() const throw()
  227992. {
  227993. return [EAGLContext setCurrentContext: nil];
  227994. }
  227995. bool isActive() const throw()
  227996. {
  227997. return [EAGLContext currentContext] == context;
  227998. }
  227999. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228000. void* getRawContext() const throw() { return glLayer; }
  228001. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228002. {
  228003. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228004. if (lastWidth != w || lastHeight != h)
  228005. {
  228006. lastWidth = w;
  228007. lastHeight = h;
  228008. freeGLBuffers();
  228009. createGLBuffers();
  228010. }
  228011. }
  228012. bool setSwapInterval (const int numFramesPerSwap)
  228013. {
  228014. numFrames = numFramesPerSwap;
  228015. return true;
  228016. }
  228017. int getSwapInterval() const
  228018. {
  228019. return numFrames;
  228020. }
  228021. void repaint()
  228022. {
  228023. }
  228024. void createGLBuffers()
  228025. {
  228026. makeActive();
  228027. glGenFramebuffersOES (1, &frameBufferHandle);
  228028. glGenRenderbuffersOES (1, &colorBufferHandle);
  228029. glGenRenderbuffersOES (1, &depthBufferHandle);
  228030. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228031. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228032. GLint width, height;
  228033. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228034. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228035. if (useDepthBuffer)
  228036. {
  228037. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228038. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228039. }
  228040. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228041. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228042. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228043. if (useDepthBuffer)
  228044. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228045. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228046. }
  228047. void freeGLBuffers()
  228048. {
  228049. if (frameBufferHandle != 0)
  228050. {
  228051. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228052. frameBufferHandle = 0;
  228053. }
  228054. if (colorBufferHandle != 0)
  228055. {
  228056. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228057. colorBufferHandle = 0;
  228058. }
  228059. if (depthBufferHandle != 0)
  228060. {
  228061. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228062. depthBufferHandle = 0;
  228063. }
  228064. }
  228065. private:
  228066. Component::SafePointer<Component> component;
  228067. OpenGLPixelFormat pixelFormat;
  228068. JuceGLView* view;
  228069. CAEAGLLayer* glLayer;
  228070. EAGLContext* context;
  228071. bool useDepthBuffer;
  228072. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228073. int numFrames;
  228074. int lastWidth, lastHeight;
  228075. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228076. };
  228077. OpenGLContext* OpenGLComponent::createContext()
  228078. {
  228079. ScopedAutoReleasePool pool;
  228080. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228081. if (peer != 0)
  228082. return new GLESContext (peer, this, preferredPixelFormat,
  228083. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228084. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228085. return 0;
  228086. }
  228087. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228088. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228089. {
  228090. }
  228091. void juce_glViewport (const int w, const int h)
  228092. {
  228093. glViewport (0, 0, w, h);
  228094. }
  228095. #endif
  228096. #endif
  228097. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228098. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228099. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228100. // compiled on its own).
  228101. #if JUCE_INCLUDED_FILE
  228102. #if JUCE_MAC
  228103. namespace MouseCursorHelpers
  228104. {
  228105. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228106. {
  228107. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228108. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228109. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228110. [im release];
  228111. return c;
  228112. }
  228113. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228114. {
  228115. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228116. BufferedInputStream buf (fileStream, 4096);
  228117. PNGImageFormat pngFormat;
  228118. Image im (pngFormat.decodeImage (buf));
  228119. if (im.isValid())
  228120. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228121. jassertfalse;
  228122. return 0;
  228123. }
  228124. }
  228125. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228126. {
  228127. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228128. }
  228129. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228130. {
  228131. const ScopedAutoReleasePool pool;
  228132. NSCursor* c = 0;
  228133. switch (type)
  228134. {
  228135. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228136. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228137. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228138. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228139. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228140. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228141. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228142. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228143. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228144. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228145. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228146. case UpDownResizeCursor:
  228147. case TopEdgeResizeCursor:
  228148. case BottomEdgeResizeCursor:
  228149. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228150. case TopLeftCornerResizeCursor:
  228151. case BottomRightCornerResizeCursor:
  228152. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228153. case TopRightCornerResizeCursor:
  228154. case BottomLeftCornerResizeCursor:
  228155. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228156. case UpDownLeftRightResizeCursor:
  228157. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228158. default:
  228159. jassertfalse;
  228160. break;
  228161. }
  228162. [c retain];
  228163. return c;
  228164. }
  228165. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228166. {
  228167. [((NSCursor*) cursorHandle) release];
  228168. }
  228169. void MouseCursor::showInAllWindows() const
  228170. {
  228171. showInWindow (0);
  228172. }
  228173. void MouseCursor::showInWindow (ComponentPeer*) const
  228174. {
  228175. NSCursor* c = (NSCursor*) getHandle();
  228176. if (c == 0)
  228177. c = [NSCursor arrowCursor];
  228178. [c set];
  228179. }
  228180. #else
  228181. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228182. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228183. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228184. void MouseCursor::showInAllWindows() const {}
  228185. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228186. #endif
  228187. #endif
  228188. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228189. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228190. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228191. // compiled on its own).
  228192. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228193. #if JUCE_MAC
  228194. END_JUCE_NAMESPACE
  228195. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228196. @interface DownloadClickDetector : NSObject
  228197. {
  228198. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228199. }
  228200. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228201. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228202. request: (NSURLRequest*) request
  228203. frame: (WebFrame*) frame
  228204. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228205. @end
  228206. @implementation DownloadClickDetector
  228207. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228208. {
  228209. [super init];
  228210. ownerComponent = ownerComponent_;
  228211. return self;
  228212. }
  228213. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228214. request: (NSURLRequest*) request
  228215. frame: (WebFrame*) frame
  228216. decisionListener: (id <WebPolicyDecisionListener>) listener
  228217. {
  228218. (void) sender;
  228219. (void) request;
  228220. (void) frame;
  228221. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228222. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228223. [listener use];
  228224. else
  228225. [listener ignore];
  228226. }
  228227. @end
  228228. BEGIN_JUCE_NAMESPACE
  228229. class WebBrowserComponentInternal : public NSViewComponent
  228230. {
  228231. public:
  228232. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228233. {
  228234. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228235. frameName: @""
  228236. groupName: @""];
  228237. setView (webView);
  228238. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228239. [webView setPolicyDelegate: clickListener];
  228240. }
  228241. ~WebBrowserComponentInternal()
  228242. {
  228243. [webView setPolicyDelegate: nil];
  228244. [clickListener release];
  228245. setView (0);
  228246. }
  228247. void goToURL (const String& url,
  228248. const StringArray* headers,
  228249. const MemoryBlock* postData)
  228250. {
  228251. NSMutableURLRequest* r
  228252. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228253. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228254. timeoutInterval: 30.0];
  228255. if (postData != 0 && postData->getSize() > 0)
  228256. {
  228257. [r setHTTPMethod: @"POST"];
  228258. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228259. length: postData->getSize()]];
  228260. }
  228261. if (headers != 0)
  228262. {
  228263. for (int i = 0; i < headers->size(); ++i)
  228264. {
  228265. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228266. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228267. [r setValue: juceStringToNS (headerValue)
  228268. forHTTPHeaderField: juceStringToNS (headerName)];
  228269. }
  228270. }
  228271. stop();
  228272. [[webView mainFrame] loadRequest: r];
  228273. }
  228274. void goBack()
  228275. {
  228276. [webView goBack];
  228277. }
  228278. void goForward()
  228279. {
  228280. [webView goForward];
  228281. }
  228282. void stop()
  228283. {
  228284. [webView stopLoading: nil];
  228285. }
  228286. void refresh()
  228287. {
  228288. [webView reload: nil];
  228289. }
  228290. void mouseMove (const MouseEvent&)
  228291. {
  228292. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228293. // them work is to push them via this non-public method..
  228294. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228295. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228296. }
  228297. private:
  228298. WebView* webView;
  228299. DownloadClickDetector* clickListener;
  228300. };
  228301. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228302. : browser (0),
  228303. blankPageShown (false),
  228304. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228305. {
  228306. setOpaque (true);
  228307. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228308. }
  228309. WebBrowserComponent::~WebBrowserComponent()
  228310. {
  228311. deleteAndZero (browser);
  228312. }
  228313. void WebBrowserComponent::goToURL (const String& url,
  228314. const StringArray* headers,
  228315. const MemoryBlock* postData)
  228316. {
  228317. lastURL = url;
  228318. lastHeaders.clear();
  228319. if (headers != 0)
  228320. lastHeaders = *headers;
  228321. lastPostData.setSize (0);
  228322. if (postData != 0)
  228323. lastPostData = *postData;
  228324. blankPageShown = false;
  228325. browser->goToURL (url, headers, postData);
  228326. }
  228327. void WebBrowserComponent::stop()
  228328. {
  228329. browser->stop();
  228330. }
  228331. void WebBrowserComponent::goBack()
  228332. {
  228333. lastURL = String::empty;
  228334. blankPageShown = false;
  228335. browser->goBack();
  228336. }
  228337. void WebBrowserComponent::goForward()
  228338. {
  228339. lastURL = String::empty;
  228340. browser->goForward();
  228341. }
  228342. void WebBrowserComponent::refresh()
  228343. {
  228344. browser->refresh();
  228345. }
  228346. void WebBrowserComponent::paint (Graphics&)
  228347. {
  228348. }
  228349. void WebBrowserComponent::checkWindowAssociation()
  228350. {
  228351. if (isShowing())
  228352. {
  228353. if (blankPageShown)
  228354. goBack();
  228355. }
  228356. else
  228357. {
  228358. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228359. {
  228360. // when the component becomes invisible, some stuff like flash
  228361. // carries on playing audio, so we need to force it onto a blank
  228362. // page to avoid this, (and send it back when it's made visible again).
  228363. blankPageShown = true;
  228364. browser->goToURL ("about:blank", 0, 0);
  228365. }
  228366. }
  228367. }
  228368. void WebBrowserComponent::reloadLastURL()
  228369. {
  228370. if (lastURL.isNotEmpty())
  228371. {
  228372. goToURL (lastURL, &lastHeaders, &lastPostData);
  228373. lastURL = String::empty;
  228374. }
  228375. }
  228376. void WebBrowserComponent::parentHierarchyChanged()
  228377. {
  228378. checkWindowAssociation();
  228379. }
  228380. void WebBrowserComponent::resized()
  228381. {
  228382. browser->setSize (getWidth(), getHeight());
  228383. }
  228384. void WebBrowserComponent::visibilityChanged()
  228385. {
  228386. checkWindowAssociation();
  228387. }
  228388. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228389. {
  228390. return true;
  228391. }
  228392. #else
  228393. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228394. {
  228395. }
  228396. WebBrowserComponent::~WebBrowserComponent()
  228397. {
  228398. }
  228399. void WebBrowserComponent::goToURL (const String& url,
  228400. const StringArray* headers,
  228401. const MemoryBlock* postData)
  228402. {
  228403. }
  228404. void WebBrowserComponent::stop()
  228405. {
  228406. }
  228407. void WebBrowserComponent::goBack()
  228408. {
  228409. }
  228410. void WebBrowserComponent::goForward()
  228411. {
  228412. }
  228413. void WebBrowserComponent::refresh()
  228414. {
  228415. }
  228416. void WebBrowserComponent::paint (Graphics& g)
  228417. {
  228418. }
  228419. void WebBrowserComponent::checkWindowAssociation()
  228420. {
  228421. }
  228422. void WebBrowserComponent::reloadLastURL()
  228423. {
  228424. }
  228425. void WebBrowserComponent::parentHierarchyChanged()
  228426. {
  228427. }
  228428. void WebBrowserComponent::resized()
  228429. {
  228430. }
  228431. void WebBrowserComponent::visibilityChanged()
  228432. {
  228433. }
  228434. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228435. {
  228436. return true;
  228437. }
  228438. #endif
  228439. #endif
  228440. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228441. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228442. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228443. // compiled on its own).
  228444. #if JUCE_INCLUDED_FILE
  228445. class IPhoneAudioIODevice : public AudioIODevice
  228446. {
  228447. public:
  228448. IPhoneAudioIODevice (const String& deviceName)
  228449. : AudioIODevice (deviceName, "Audio"),
  228450. actualBufferSize (0),
  228451. isRunning (false),
  228452. audioUnit (0),
  228453. callback (0),
  228454. floatData (1, 2)
  228455. {
  228456. numInputChannels = 2;
  228457. numOutputChannels = 2;
  228458. preferredBufferSize = 0;
  228459. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228460. updateDeviceInfo();
  228461. }
  228462. ~IPhoneAudioIODevice()
  228463. {
  228464. close();
  228465. }
  228466. const StringArray getOutputChannelNames()
  228467. {
  228468. StringArray s;
  228469. s.add ("Left");
  228470. s.add ("Right");
  228471. return s;
  228472. }
  228473. const StringArray getInputChannelNames()
  228474. {
  228475. StringArray s;
  228476. if (audioInputIsAvailable)
  228477. {
  228478. s.add ("Left");
  228479. s.add ("Right");
  228480. }
  228481. return s;
  228482. }
  228483. int getNumSampleRates()
  228484. {
  228485. return 1;
  228486. }
  228487. double getSampleRate (int index)
  228488. {
  228489. return sampleRate;
  228490. }
  228491. int getNumBufferSizesAvailable()
  228492. {
  228493. return 1;
  228494. }
  228495. int getBufferSizeSamples (int index)
  228496. {
  228497. return getDefaultBufferSize();
  228498. }
  228499. int getDefaultBufferSize()
  228500. {
  228501. return 1024;
  228502. }
  228503. const String open (const BigInteger& inputChannels,
  228504. const BigInteger& outputChannels,
  228505. double sampleRate,
  228506. int bufferSize)
  228507. {
  228508. close();
  228509. lastError = String::empty;
  228510. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228511. // xxx set up channel mapping
  228512. activeOutputChans = outputChannels;
  228513. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228514. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228515. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228516. activeInputChans = inputChannels;
  228517. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228518. numInputChannels = activeInputChans.countNumberOfSetBits();
  228519. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228520. AudioSessionSetActive (true);
  228521. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228522. : kAudioSessionCategory_MediaPlayback;
  228523. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228524. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228525. fixAudioRouteIfSetToReceiver();
  228526. updateDeviceInfo();
  228527. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228528. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228529. actualBufferSize = preferredBufferSize;
  228530. prepareFloatBuffers();
  228531. isRunning = true;
  228532. propertyChanged (0, 0, 0); // creates and starts the AU
  228533. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228534. return lastError;
  228535. }
  228536. void close()
  228537. {
  228538. if (isRunning)
  228539. {
  228540. isRunning = false;
  228541. AudioSessionSetActive (false);
  228542. if (audioUnit != 0)
  228543. {
  228544. AudioComponentInstanceDispose (audioUnit);
  228545. audioUnit = 0;
  228546. }
  228547. }
  228548. }
  228549. bool isOpen()
  228550. {
  228551. return isRunning;
  228552. }
  228553. int getCurrentBufferSizeSamples()
  228554. {
  228555. return actualBufferSize;
  228556. }
  228557. double getCurrentSampleRate()
  228558. {
  228559. return sampleRate;
  228560. }
  228561. int getCurrentBitDepth()
  228562. {
  228563. return 16;
  228564. }
  228565. const BigInteger getActiveOutputChannels() const
  228566. {
  228567. return activeOutputChans;
  228568. }
  228569. const BigInteger getActiveInputChannels() const
  228570. {
  228571. return activeInputChans;
  228572. }
  228573. int getOutputLatencyInSamples()
  228574. {
  228575. return 0; //xxx
  228576. }
  228577. int getInputLatencyInSamples()
  228578. {
  228579. return 0; //xxx
  228580. }
  228581. void start (AudioIODeviceCallback* callback_)
  228582. {
  228583. if (isRunning && callback != callback_)
  228584. {
  228585. if (callback_ != 0)
  228586. callback_->audioDeviceAboutToStart (this);
  228587. const ScopedLock sl (callbackLock);
  228588. callback = callback_;
  228589. }
  228590. }
  228591. void stop()
  228592. {
  228593. if (isRunning)
  228594. {
  228595. AudioIODeviceCallback* lastCallback;
  228596. {
  228597. const ScopedLock sl (callbackLock);
  228598. lastCallback = callback;
  228599. callback = 0;
  228600. }
  228601. if (lastCallback != 0)
  228602. lastCallback->audioDeviceStopped();
  228603. }
  228604. }
  228605. bool isPlaying()
  228606. {
  228607. return isRunning && callback != 0;
  228608. }
  228609. const String getLastError()
  228610. {
  228611. return lastError;
  228612. }
  228613. private:
  228614. CriticalSection callbackLock;
  228615. Float64 sampleRate;
  228616. int numInputChannels, numOutputChannels;
  228617. int preferredBufferSize;
  228618. int actualBufferSize;
  228619. bool isRunning;
  228620. String lastError;
  228621. AudioStreamBasicDescription format;
  228622. AudioUnit audioUnit;
  228623. UInt32 audioInputIsAvailable;
  228624. AudioIODeviceCallback* callback;
  228625. BigInteger activeOutputChans, activeInputChans;
  228626. AudioSampleBuffer floatData;
  228627. float* inputChannels[3];
  228628. float* outputChannels[3];
  228629. bool monoInputChannelNumber, monoOutputChannelNumber;
  228630. void prepareFloatBuffers()
  228631. {
  228632. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228633. zerostruct (inputChannels);
  228634. zerostruct (outputChannels);
  228635. for (int i = 0; i < numInputChannels; ++i)
  228636. inputChannels[i] = floatData.getSampleData (i);
  228637. for (int i = 0; i < numOutputChannels; ++i)
  228638. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228639. }
  228640. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228641. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228642. {
  228643. OSStatus err = noErr;
  228644. if (audioInputIsAvailable)
  228645. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228646. const ScopedLock sl (callbackLock);
  228647. if (callback != 0)
  228648. {
  228649. if (audioInputIsAvailable && numInputChannels > 0)
  228650. {
  228651. short* shortData = (short*) ioData->mBuffers[0].mData;
  228652. if (numInputChannels >= 2)
  228653. {
  228654. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228655. {
  228656. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228657. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228658. }
  228659. }
  228660. else
  228661. {
  228662. if (monoInputChannelNumber > 0)
  228663. ++shortData;
  228664. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228665. {
  228666. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228667. ++shortData;
  228668. }
  228669. }
  228670. }
  228671. else
  228672. {
  228673. for (int i = numInputChannels; --i >= 0;)
  228674. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228675. }
  228676. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228677. outputChannels, numOutputChannels,
  228678. (int) inNumberFrames);
  228679. short* shortData = (short*) ioData->mBuffers[0].mData;
  228680. int n = 0;
  228681. if (numOutputChannels >= 2)
  228682. {
  228683. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228684. {
  228685. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228686. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228687. }
  228688. }
  228689. else if (numOutputChannels == 1)
  228690. {
  228691. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228692. {
  228693. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228694. shortData [n++] = s;
  228695. shortData [n++] = s;
  228696. }
  228697. }
  228698. else
  228699. {
  228700. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228701. }
  228702. }
  228703. else
  228704. {
  228705. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228706. }
  228707. return err;
  228708. }
  228709. void updateDeviceInfo()
  228710. {
  228711. UInt32 size = sizeof (sampleRate);
  228712. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228713. size = sizeof (audioInputIsAvailable);
  228714. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228715. }
  228716. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228717. {
  228718. if (! isRunning)
  228719. return;
  228720. if (inPropertyValue != 0)
  228721. {
  228722. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228723. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228724. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228725. SInt32 routeChangeReason;
  228726. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228727. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228728. fixAudioRouteIfSetToReceiver();
  228729. }
  228730. updateDeviceInfo();
  228731. createAudioUnit();
  228732. AudioSessionSetActive (true);
  228733. if (audioUnit != 0)
  228734. {
  228735. UInt32 formatSize = sizeof (format);
  228736. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228737. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228738. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228739. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228740. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228741. AudioOutputUnitStart (audioUnit);
  228742. }
  228743. }
  228744. void interruptionListener (UInt32 inInterruption)
  228745. {
  228746. /*if (inInterruption == kAudioSessionBeginInterruption)
  228747. {
  228748. isRunning = false;
  228749. AudioOutputUnitStop (audioUnit);
  228750. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228751. "This could have been interrupted by another application or by unplugging a headset",
  228752. @"Resume",
  228753. @"Cancel"))
  228754. {
  228755. isRunning = true;
  228756. propertyChanged (0, 0, 0);
  228757. }
  228758. }*/
  228759. if (inInterruption == kAudioSessionEndInterruption)
  228760. {
  228761. isRunning = true;
  228762. AudioSessionSetActive (true);
  228763. AudioOutputUnitStart (audioUnit);
  228764. }
  228765. }
  228766. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228767. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228768. {
  228769. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228770. }
  228771. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228772. {
  228773. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228774. }
  228775. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228776. {
  228777. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228778. }
  228779. void resetFormat (const int numChannels)
  228780. {
  228781. memset (&format, 0, sizeof (format));
  228782. format.mFormatID = kAudioFormatLinearPCM;
  228783. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228784. format.mBitsPerChannel = 8 * sizeof (short);
  228785. format.mChannelsPerFrame = 2;
  228786. format.mFramesPerPacket = 1;
  228787. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228788. }
  228789. bool createAudioUnit()
  228790. {
  228791. if (audioUnit != 0)
  228792. {
  228793. AudioComponentInstanceDispose (audioUnit);
  228794. audioUnit = 0;
  228795. }
  228796. resetFormat (2);
  228797. AudioComponentDescription desc;
  228798. desc.componentType = kAudioUnitType_Output;
  228799. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228800. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228801. desc.componentFlags = 0;
  228802. desc.componentFlagsMask = 0;
  228803. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228804. AudioComponentInstanceNew (comp, &audioUnit);
  228805. if (audioUnit == 0)
  228806. return false;
  228807. const UInt32 one = 1;
  228808. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228809. AudioChannelLayout layout;
  228810. layout.mChannelBitmap = 0;
  228811. layout.mNumberChannelDescriptions = 0;
  228812. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228813. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228814. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228815. AURenderCallbackStruct inputProc;
  228816. inputProc.inputProc = processStatic;
  228817. inputProc.inputProcRefCon = this;
  228818. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228819. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228820. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228821. AudioUnitInitialize (audioUnit);
  228822. return true;
  228823. }
  228824. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228825. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228826. static void fixAudioRouteIfSetToReceiver()
  228827. {
  228828. CFStringRef audioRoute = 0;
  228829. UInt32 propertySize = sizeof (audioRoute);
  228830. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228831. {
  228832. NSString* route = (NSString*) audioRoute;
  228833. //DBG ("audio route: " + nsStringToJuce (route));
  228834. if ([route hasPrefix: @"Receiver"])
  228835. {
  228836. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228837. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228838. }
  228839. CFRelease (audioRoute);
  228840. }
  228841. }
  228842. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228843. };
  228844. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228845. {
  228846. public:
  228847. IPhoneAudioIODeviceType()
  228848. : AudioIODeviceType ("iPhone Audio")
  228849. {
  228850. }
  228851. void scanForDevices()
  228852. {
  228853. }
  228854. const StringArray getDeviceNames (bool wantInputNames) const
  228855. {
  228856. StringArray s;
  228857. s.add ("iPhone Audio");
  228858. return s;
  228859. }
  228860. int getDefaultDeviceIndex (bool forInput) const
  228861. {
  228862. return 0;
  228863. }
  228864. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228865. {
  228866. return device != 0 ? 0 : -1;
  228867. }
  228868. bool hasSeparateInputsAndOutputs() const { return false; }
  228869. AudioIODevice* createDevice (const String& outputDeviceName,
  228870. const String& inputDeviceName)
  228871. {
  228872. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228873. {
  228874. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228875. : inputDeviceName);
  228876. }
  228877. return 0;
  228878. }
  228879. private:
  228880. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228881. };
  228882. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228883. {
  228884. return new IPhoneAudioIODeviceType();
  228885. }
  228886. #endif
  228887. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228888. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228889. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228890. // compiled on its own).
  228891. #if JUCE_INCLUDED_FILE
  228892. #if JUCE_MAC
  228893. namespace CoreMidiHelpers
  228894. {
  228895. bool logError (const OSStatus err, const int lineNum)
  228896. {
  228897. if (err == noErr)
  228898. return true;
  228899. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228900. jassertfalse;
  228901. return false;
  228902. }
  228903. #undef CHECK_ERROR
  228904. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228905. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228906. {
  228907. String result;
  228908. CFStringRef str = 0;
  228909. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228910. if (str != 0)
  228911. {
  228912. result = PlatformUtilities::cfStringToJuceString (str);
  228913. CFRelease (str);
  228914. str = 0;
  228915. }
  228916. MIDIEntityRef entity = 0;
  228917. MIDIEndpointGetEntity (endpoint, &entity);
  228918. if (entity == 0)
  228919. return result; // probably virtual
  228920. if (result.isEmpty())
  228921. {
  228922. // endpoint name has zero length - try the entity
  228923. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228924. if (str != 0)
  228925. {
  228926. result += PlatformUtilities::cfStringToJuceString (str);
  228927. CFRelease (str);
  228928. str = 0;
  228929. }
  228930. }
  228931. // now consider the device's name
  228932. MIDIDeviceRef device = 0;
  228933. MIDIEntityGetDevice (entity, &device);
  228934. if (device == 0)
  228935. return result;
  228936. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228937. if (str != 0)
  228938. {
  228939. const String s (PlatformUtilities::cfStringToJuceString (str));
  228940. CFRelease (str);
  228941. // if an external device has only one entity, throw away
  228942. // the endpoint name and just use the device name
  228943. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228944. {
  228945. result = s;
  228946. }
  228947. else if (! result.startsWithIgnoreCase (s))
  228948. {
  228949. // prepend the device name to the entity name
  228950. result = (s + " " + result).trimEnd();
  228951. }
  228952. }
  228953. return result;
  228954. }
  228955. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228956. {
  228957. String result;
  228958. // Does the endpoint have connections?
  228959. CFDataRef connections = 0;
  228960. int numConnections = 0;
  228961. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228962. if (connections != 0)
  228963. {
  228964. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228965. if (numConnections > 0)
  228966. {
  228967. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228968. for (int i = 0; i < numConnections; ++i, ++pid)
  228969. {
  228970. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228971. MIDIObjectRef connObject;
  228972. MIDIObjectType connObjectType;
  228973. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228974. if (err == noErr)
  228975. {
  228976. String s;
  228977. if (connObjectType == kMIDIObjectType_ExternalSource
  228978. || connObjectType == kMIDIObjectType_ExternalDestination)
  228979. {
  228980. // Connected to an external device's endpoint (10.3 and later).
  228981. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228982. }
  228983. else
  228984. {
  228985. // Connected to an external device (10.2) (or something else, catch-all)
  228986. CFStringRef str = 0;
  228987. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228988. if (str != 0)
  228989. {
  228990. s = PlatformUtilities::cfStringToJuceString (str);
  228991. CFRelease (str);
  228992. }
  228993. }
  228994. if (s.isNotEmpty())
  228995. {
  228996. if (result.isNotEmpty())
  228997. result += ", ";
  228998. result += s;
  228999. }
  229000. }
  229001. }
  229002. }
  229003. CFRelease (connections);
  229004. }
  229005. if (result.isNotEmpty())
  229006. return result;
  229007. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229008. return getEndpointName (endpoint, false);
  229009. }
  229010. MIDIClientRef getGlobalMidiClient()
  229011. {
  229012. static MIDIClientRef globalMidiClient = 0;
  229013. if (globalMidiClient == 0)
  229014. {
  229015. String name ("JUCE");
  229016. if (JUCEApplication::getInstance() != 0)
  229017. name = JUCEApplication::getInstance()->getApplicationName();
  229018. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229019. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229020. CFRelease (appName);
  229021. }
  229022. return globalMidiClient;
  229023. }
  229024. class MidiPortAndEndpoint
  229025. {
  229026. public:
  229027. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229028. : port (port_), endPoint (endPoint_)
  229029. {
  229030. }
  229031. ~MidiPortAndEndpoint()
  229032. {
  229033. if (port != 0)
  229034. MIDIPortDispose (port);
  229035. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229036. MIDIEndpointDispose (endPoint);
  229037. }
  229038. void send (const MIDIPacketList* const packets)
  229039. {
  229040. if (port != 0)
  229041. MIDISend (port, endPoint, packets);
  229042. else
  229043. MIDIReceived (endPoint, packets);
  229044. }
  229045. MIDIPortRef port;
  229046. MIDIEndpointRef endPoint;
  229047. };
  229048. class MidiPortAndCallback;
  229049. CriticalSection callbackLock;
  229050. Array<MidiPortAndCallback*> activeCallbacks;
  229051. class MidiPortAndCallback
  229052. {
  229053. public:
  229054. MidiPortAndCallback (MidiInputCallback& callback_)
  229055. : input (0), active (false), callback (callback_), concatenator (2048)
  229056. {
  229057. }
  229058. ~MidiPortAndCallback()
  229059. {
  229060. active = false;
  229061. {
  229062. const ScopedLock sl (callbackLock);
  229063. activeCallbacks.removeValue (this);
  229064. }
  229065. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229066. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229067. }
  229068. void handlePackets (const MIDIPacketList* const pktlist)
  229069. {
  229070. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229071. const ScopedLock sl (callbackLock);
  229072. if (activeCallbacks.contains (this) && active)
  229073. {
  229074. const MIDIPacket* packet = &pktlist->packet[0];
  229075. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229076. {
  229077. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229078. input, callback);
  229079. packet = MIDIPacketNext (packet);
  229080. }
  229081. }
  229082. }
  229083. MidiInput* input;
  229084. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229085. volatile bool active;
  229086. private:
  229087. MidiInputCallback& callback;
  229088. MidiDataConcatenator concatenator;
  229089. };
  229090. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229091. {
  229092. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229093. }
  229094. }
  229095. const StringArray MidiOutput::getDevices()
  229096. {
  229097. StringArray s;
  229098. const ItemCount num = MIDIGetNumberOfDestinations();
  229099. for (ItemCount i = 0; i < num; ++i)
  229100. {
  229101. MIDIEndpointRef dest = MIDIGetDestination (i);
  229102. if (dest != 0)
  229103. {
  229104. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229105. if (name.isEmpty())
  229106. name = "<error>";
  229107. s.add (name);
  229108. }
  229109. else
  229110. {
  229111. s.add ("<error>");
  229112. }
  229113. }
  229114. return s;
  229115. }
  229116. int MidiOutput::getDefaultDeviceIndex()
  229117. {
  229118. return 0;
  229119. }
  229120. MidiOutput* MidiOutput::openDevice (int index)
  229121. {
  229122. MidiOutput* mo = 0;
  229123. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229124. {
  229125. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229126. CFStringRef pname;
  229127. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229128. {
  229129. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229130. MIDIPortRef port;
  229131. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229132. {
  229133. mo = new MidiOutput();
  229134. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229135. }
  229136. CFRelease (pname);
  229137. }
  229138. }
  229139. return mo;
  229140. }
  229141. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229142. {
  229143. MidiOutput* mo = 0;
  229144. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229145. MIDIEndpointRef endPoint;
  229146. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229147. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229148. {
  229149. mo = new MidiOutput();
  229150. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229151. }
  229152. CFRelease (name);
  229153. return mo;
  229154. }
  229155. MidiOutput::~MidiOutput()
  229156. {
  229157. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229158. }
  229159. void MidiOutput::reset()
  229160. {
  229161. }
  229162. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229163. {
  229164. return false;
  229165. }
  229166. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229167. {
  229168. }
  229169. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229170. {
  229171. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229172. if (message.isSysEx())
  229173. {
  229174. const int maxPacketSize = 256;
  229175. int pos = 0, bytesLeft = message.getRawDataSize();
  229176. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229177. HeapBlock <MIDIPacketList> packets;
  229178. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229179. packets->numPackets = numPackets;
  229180. MIDIPacket* p = packets->packet;
  229181. for (int i = 0; i < numPackets; ++i)
  229182. {
  229183. p->timeStamp = 0;
  229184. p->length = jmin (maxPacketSize, bytesLeft);
  229185. memcpy (p->data, message.getRawData() + pos, p->length);
  229186. pos += p->length;
  229187. bytesLeft -= p->length;
  229188. p = MIDIPacketNext (p);
  229189. }
  229190. mpe->send (packets);
  229191. }
  229192. else
  229193. {
  229194. MIDIPacketList packets;
  229195. packets.numPackets = 1;
  229196. packets.packet[0].timeStamp = 0;
  229197. packets.packet[0].length = message.getRawDataSize();
  229198. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229199. mpe->send (&packets);
  229200. }
  229201. }
  229202. const StringArray MidiInput::getDevices()
  229203. {
  229204. StringArray s;
  229205. const ItemCount num = MIDIGetNumberOfSources();
  229206. for (ItemCount i = 0; i < num; ++i)
  229207. {
  229208. MIDIEndpointRef source = MIDIGetSource (i);
  229209. if (source != 0)
  229210. {
  229211. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229212. if (name.isEmpty())
  229213. name = "<error>";
  229214. s.add (name);
  229215. }
  229216. else
  229217. {
  229218. s.add ("<error>");
  229219. }
  229220. }
  229221. return s;
  229222. }
  229223. int MidiInput::getDefaultDeviceIndex()
  229224. {
  229225. return 0;
  229226. }
  229227. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229228. {
  229229. jassert (callback != 0);
  229230. using namespace CoreMidiHelpers;
  229231. MidiInput* newInput = 0;
  229232. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229233. {
  229234. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229235. if (endPoint != 0)
  229236. {
  229237. CFStringRef name;
  229238. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229239. {
  229240. MIDIClientRef client = getGlobalMidiClient();
  229241. if (client != 0)
  229242. {
  229243. MIDIPortRef port;
  229244. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229245. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229246. {
  229247. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229248. {
  229249. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229250. newInput = new MidiInput (getDevices() [index]);
  229251. mpc->input = newInput;
  229252. newInput->internal = mpc;
  229253. const ScopedLock sl (callbackLock);
  229254. activeCallbacks.add (mpc.release());
  229255. }
  229256. else
  229257. {
  229258. CHECK_ERROR (MIDIPortDispose (port));
  229259. }
  229260. }
  229261. }
  229262. }
  229263. CFRelease (name);
  229264. }
  229265. }
  229266. return newInput;
  229267. }
  229268. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229269. {
  229270. jassert (callback != 0);
  229271. using namespace CoreMidiHelpers;
  229272. MidiInput* mi = 0;
  229273. MIDIClientRef client = getGlobalMidiClient();
  229274. if (client != 0)
  229275. {
  229276. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229277. mpc->active = false;
  229278. MIDIEndpointRef endPoint;
  229279. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229280. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229281. {
  229282. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229283. mi = new MidiInput (deviceName);
  229284. mpc->input = mi;
  229285. mi->internal = mpc;
  229286. const ScopedLock sl (callbackLock);
  229287. activeCallbacks.add (mpc.release());
  229288. }
  229289. CFRelease (name);
  229290. }
  229291. return mi;
  229292. }
  229293. MidiInput::MidiInput (const String& name_)
  229294. : name (name_)
  229295. {
  229296. }
  229297. MidiInput::~MidiInput()
  229298. {
  229299. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229300. }
  229301. void MidiInput::start()
  229302. {
  229303. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229304. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229305. }
  229306. void MidiInput::stop()
  229307. {
  229308. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229309. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229310. }
  229311. #undef CHECK_ERROR
  229312. #else // Stubs for iOS...
  229313. MidiOutput::~MidiOutput() {}
  229314. void MidiOutput::reset() {}
  229315. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229316. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229317. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229318. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229319. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229320. const StringArray MidiInput::getDevices() { return StringArray(); }
  229321. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229322. #endif
  229323. #endif
  229324. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229325. #else
  229326. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229327. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229328. // compiled on its own).
  229329. #if JUCE_INCLUDED_FILE
  229330. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229331. #define SUPPORT_10_4_FONTS 1
  229332. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229333. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229334. #define SUPPORT_ONLY_10_4_FONTS 1
  229335. #endif
  229336. END_JUCE_NAMESPACE
  229337. @interface NSFont (PrivateHack)
  229338. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229339. @end
  229340. BEGIN_JUCE_NAMESPACE
  229341. #endif
  229342. class MacTypeface : public Typeface
  229343. {
  229344. public:
  229345. MacTypeface (const Font& font)
  229346. : Typeface (font.getTypefaceName())
  229347. {
  229348. const ScopedAutoReleasePool pool;
  229349. renderingTransform = CGAffineTransformIdentity;
  229350. bool needsItalicTransform = false;
  229351. #if JUCE_IOS
  229352. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229353. if (font.isItalic() || font.isBold())
  229354. {
  229355. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229356. for (NSString* i in familyFonts)
  229357. {
  229358. const String fn (nsStringToJuce (i));
  229359. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229360. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229361. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229362. || afterDash.containsIgnoreCase ("italic")
  229363. || fn.endsWithIgnoreCase ("oblique")
  229364. || fn.endsWithIgnoreCase ("italic");
  229365. if (probablyBold == font.isBold()
  229366. && probablyItalic == font.isItalic())
  229367. {
  229368. fontName = i;
  229369. needsItalicTransform = false;
  229370. break;
  229371. }
  229372. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229373. {
  229374. fontName = i;
  229375. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229376. }
  229377. }
  229378. if (needsItalicTransform)
  229379. renderingTransform.c = 0.15f;
  229380. }
  229381. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229382. const int ascender = abs (CGFontGetAscent (fontRef));
  229383. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229384. ascent = ascender / totalHeight;
  229385. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229386. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229387. #else
  229388. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229389. if (font.isItalic())
  229390. {
  229391. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229392. toHaveTrait: NSItalicFontMask];
  229393. if (newFont == nsFont)
  229394. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229395. nsFont = newFont;
  229396. }
  229397. if (font.isBold())
  229398. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229399. [nsFont retain];
  229400. ascent = std::abs ((float) [nsFont ascender]);
  229401. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229402. ascent /= totalSize;
  229403. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229404. if (needsItalicTransform)
  229405. {
  229406. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229407. renderingTransform.c = 0.15f;
  229408. }
  229409. #if SUPPORT_ONLY_10_4_FONTS
  229410. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229411. if (atsFont == 0)
  229412. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229413. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229414. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229415. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229416. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229417. #else
  229418. #if SUPPORT_10_4_FONTS
  229419. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229420. {
  229421. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229422. if (atsFont == 0)
  229423. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229424. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229425. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229426. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229427. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229428. }
  229429. else
  229430. #endif
  229431. {
  229432. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229433. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229434. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229435. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229436. }
  229437. #endif
  229438. #endif
  229439. }
  229440. ~MacTypeface()
  229441. {
  229442. #if ! JUCE_IOS
  229443. [nsFont release];
  229444. #endif
  229445. if (fontRef != 0)
  229446. CGFontRelease (fontRef);
  229447. }
  229448. float getAscent() const
  229449. {
  229450. return ascent;
  229451. }
  229452. float getDescent() const
  229453. {
  229454. return 1.0f - ascent;
  229455. }
  229456. float getStringWidth (const String& text)
  229457. {
  229458. if (fontRef == 0 || text.isEmpty())
  229459. return 0;
  229460. const int length = text.length();
  229461. HeapBlock <CGGlyph> glyphs;
  229462. createGlyphsForString (text, length, glyphs);
  229463. float x = 0;
  229464. #if SUPPORT_ONLY_10_4_FONTS
  229465. HeapBlock <NSSize> advances (length);
  229466. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229467. for (int i = 0; i < length; ++i)
  229468. x += advances[i].width;
  229469. #else
  229470. #if SUPPORT_10_4_FONTS
  229471. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229472. {
  229473. HeapBlock <NSSize> advances (length);
  229474. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229475. for (int i = 0; i < length; ++i)
  229476. x += advances[i].width;
  229477. }
  229478. else
  229479. #endif
  229480. {
  229481. HeapBlock <int> advances (length);
  229482. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229483. for (int i = 0; i < length; ++i)
  229484. x += advances[i];
  229485. }
  229486. #endif
  229487. return x * unitsToHeightScaleFactor;
  229488. }
  229489. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229490. {
  229491. xOffsets.add (0);
  229492. if (fontRef == 0 || text.isEmpty())
  229493. return;
  229494. const int length = text.length();
  229495. HeapBlock <CGGlyph> glyphs;
  229496. createGlyphsForString (text, length, glyphs);
  229497. #if SUPPORT_ONLY_10_4_FONTS
  229498. HeapBlock <NSSize> advances (length);
  229499. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229500. int x = 0;
  229501. for (int i = 0; i < length; ++i)
  229502. {
  229503. x += advances[i].width;
  229504. xOffsets.add (x * unitsToHeightScaleFactor);
  229505. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229506. }
  229507. #else
  229508. #if SUPPORT_10_4_FONTS
  229509. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229510. {
  229511. HeapBlock <NSSize> advances (length);
  229512. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229513. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229514. float x = 0;
  229515. for (int i = 0; i < length; ++i)
  229516. {
  229517. x += advances[i].width;
  229518. xOffsets.add (x * unitsToHeightScaleFactor);
  229519. resultGlyphs.add (nsGlyphs[i]);
  229520. }
  229521. }
  229522. else
  229523. #endif
  229524. {
  229525. HeapBlock <int> advances (length);
  229526. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229527. {
  229528. int x = 0;
  229529. for (int i = 0; i < length; ++i)
  229530. {
  229531. x += advances [i];
  229532. xOffsets.add (x * unitsToHeightScaleFactor);
  229533. resultGlyphs.add (glyphs[i]);
  229534. }
  229535. }
  229536. }
  229537. #endif
  229538. }
  229539. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229540. {
  229541. #if JUCE_IOS
  229542. return false;
  229543. #else
  229544. if (nsFont == 0)
  229545. return false;
  229546. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229547. jassert (path.isEmpty());
  229548. const ScopedAutoReleasePool pool;
  229549. NSBezierPath* bez = [NSBezierPath bezierPath];
  229550. [bez moveToPoint: NSMakePoint (0, 0)];
  229551. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229552. inFont: nsFont];
  229553. for (int i = 0; i < [bez elementCount]; ++i)
  229554. {
  229555. NSPoint p[3];
  229556. switch ([bez elementAtIndex: i associatedPoints: p])
  229557. {
  229558. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229559. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229560. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229561. (float) p[1].x, (float) -p[1].y,
  229562. (float) p[2].x, (float) -p[2].y); break;
  229563. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229564. default: jassertfalse; break;
  229565. }
  229566. }
  229567. path.applyTransform (pathTransform);
  229568. return true;
  229569. #endif
  229570. }
  229571. CGFontRef fontRef;
  229572. float fontHeightToCGSizeFactor;
  229573. CGAffineTransform renderingTransform;
  229574. private:
  229575. float ascent, unitsToHeightScaleFactor;
  229576. #if JUCE_IOS
  229577. #else
  229578. NSFont* nsFont;
  229579. AffineTransform pathTransform;
  229580. #endif
  229581. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229582. {
  229583. #if SUPPORT_10_4_FONTS
  229584. #if ! SUPPORT_ONLY_10_4_FONTS
  229585. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229586. #endif
  229587. {
  229588. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229589. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229590. for (int i = 0; i < length; ++i)
  229591. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229592. return;
  229593. }
  229594. #endif
  229595. #if ! SUPPORT_ONLY_10_4_FONTS
  229596. if (charToGlyphMapper == 0)
  229597. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229598. glyphs.malloc (length);
  229599. for (int i = 0; i < length; ++i)
  229600. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229601. #endif
  229602. }
  229603. #if ! SUPPORT_ONLY_10_4_FONTS
  229604. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229605. class CharToGlyphMapper
  229606. {
  229607. public:
  229608. CharToGlyphMapper (CGFontRef fontRef)
  229609. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229610. idRangeOffset (0), glyphIndexes (0)
  229611. {
  229612. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229613. if (cmapTable != 0)
  229614. {
  229615. const int numSubtables = getValue16 (cmapTable, 2);
  229616. for (int i = 0; i < numSubtables; ++i)
  229617. {
  229618. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229619. {
  229620. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229621. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229622. {
  229623. const int length = getValue16 (cmapTable, offset + 2);
  229624. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229625. segCount = segCountX2 / 2;
  229626. const int endCodeOffset = offset + 14;
  229627. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229628. const int idDeltaOffset = startCodeOffset + segCountX2;
  229629. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229630. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229631. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229632. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229633. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229634. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229635. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229636. }
  229637. break;
  229638. }
  229639. }
  229640. CFRelease (cmapTable);
  229641. }
  229642. }
  229643. ~CharToGlyphMapper()
  229644. {
  229645. if (endCode != 0)
  229646. {
  229647. CFRelease (endCode);
  229648. CFRelease (startCode);
  229649. CFRelease (idDelta);
  229650. CFRelease (idRangeOffset);
  229651. CFRelease (glyphIndexes);
  229652. }
  229653. }
  229654. int getGlyphForCharacter (const juce_wchar c) const
  229655. {
  229656. for (int i = 0; i < segCount; ++i)
  229657. {
  229658. if (getValue16 (endCode, i * 2) >= c)
  229659. {
  229660. const int start = getValue16 (startCode, i * 2);
  229661. if (start > c)
  229662. break;
  229663. const int delta = getValue16 (idDelta, i * 2);
  229664. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229665. if (rangeOffset == 0)
  229666. return delta + c;
  229667. else
  229668. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229669. }
  229670. }
  229671. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229672. return jmax (-1, (int) c - 29);
  229673. }
  229674. private:
  229675. int segCount;
  229676. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229677. static uint16 getValue16 (CFDataRef data, const int index)
  229678. {
  229679. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229680. }
  229681. static uint32 getValue32 (CFDataRef data, const int index)
  229682. {
  229683. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229684. }
  229685. };
  229686. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229687. #endif
  229688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229689. };
  229690. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229691. {
  229692. return new MacTypeface (font);
  229693. }
  229694. const StringArray Font::findAllTypefaceNames()
  229695. {
  229696. StringArray names;
  229697. const ScopedAutoReleasePool pool;
  229698. #if JUCE_IOS
  229699. NSArray* fonts = [UIFont familyNames];
  229700. #else
  229701. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229702. #endif
  229703. for (unsigned int i = 0; i < [fonts count]; ++i)
  229704. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229705. names.sort (true);
  229706. return names;
  229707. }
  229708. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229709. {
  229710. #if JUCE_IOS
  229711. defaultSans = "Helvetica";
  229712. defaultSerif = "Times New Roman";
  229713. defaultFixed = "Courier New";
  229714. #else
  229715. defaultSans = "Lucida Grande";
  229716. defaultSerif = "Times New Roman";
  229717. defaultFixed = "Monaco";
  229718. #endif
  229719. defaultFallback = "Arial Unicode MS";
  229720. }
  229721. #endif
  229722. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229723. // (must go before juce_mac_CoreGraphicsContext.mm)
  229724. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229725. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229726. // compiled on its own).
  229727. #if JUCE_INCLUDED_FILE
  229728. class CoreGraphicsImage : public Image::SharedImage
  229729. {
  229730. public:
  229731. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229732. : Image::SharedImage (format_, width_, height_)
  229733. {
  229734. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229735. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229736. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229737. imageData = imageDataAllocated;
  229738. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229739. : CGColorSpaceCreateDeviceRGB();
  229740. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229741. colourSpace, getCGImageFlags (format_));
  229742. CGColorSpaceRelease (colourSpace);
  229743. }
  229744. ~CoreGraphicsImage()
  229745. {
  229746. CGContextRelease (context);
  229747. }
  229748. Image::ImageType getType() const { return Image::NativeImage; }
  229749. LowLevelGraphicsContext* createLowLevelContext();
  229750. SharedImage* clone()
  229751. {
  229752. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229753. memcpy (im->imageData, imageData, lineStride * height);
  229754. return im;
  229755. }
  229756. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  229757. {
  229758. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229759. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229760. {
  229761. return CGBitmapContextCreateImage (nativeImage->context);
  229762. }
  229763. else
  229764. {
  229765. const Image::BitmapData srcData (juceImage, false);
  229766. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229767. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229768. 8, srcData.pixelStride * 8, srcData.lineStride,
  229769. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229770. 0, true, kCGRenderingIntentDefault);
  229771. CGDataProviderRelease (provider);
  229772. return imageRef;
  229773. }
  229774. }
  229775. #if JUCE_MAC
  229776. static NSImage* createNSImage (const Image& image)
  229777. {
  229778. const ScopedAutoReleasePool pool;
  229779. NSImage* im = [[NSImage alloc] init];
  229780. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229781. [im lockFocus];
  229782. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229783. CGImageRef imageRef = createImage (image, false, colourSpace);
  229784. CGColorSpaceRelease (colourSpace);
  229785. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229786. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229787. CGImageRelease (imageRef);
  229788. [im unlockFocus];
  229789. return im;
  229790. }
  229791. #endif
  229792. CGContextRef context;
  229793. HeapBlock<uint8> imageDataAllocated;
  229794. private:
  229795. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229796. {
  229797. #if JUCE_BIG_ENDIAN
  229798. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229799. #else
  229800. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229801. #endif
  229802. }
  229803. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229804. };
  229805. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229806. {
  229807. #if USE_COREGRAPHICS_RENDERING
  229808. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229809. #else
  229810. return createSoftwareImage (format, width, height, clearImage);
  229811. #endif
  229812. }
  229813. class CoreGraphicsContext : public LowLevelGraphicsContext
  229814. {
  229815. public:
  229816. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229817. : context (context_),
  229818. flipHeight (flipHeight_),
  229819. lastClipRectIsValid (false),
  229820. state (new SavedState()),
  229821. numGradientLookupEntries (0)
  229822. {
  229823. CGContextRetain (context);
  229824. CGContextSaveGState(context);
  229825. CGContextSetShouldSmoothFonts (context, true);
  229826. CGContextSetShouldAntialias (context, true);
  229827. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229828. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229829. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229830. gradientCallbacks.version = 0;
  229831. gradientCallbacks.evaluate = gradientCallback;
  229832. gradientCallbacks.releaseInfo = 0;
  229833. setFont (Font());
  229834. }
  229835. ~CoreGraphicsContext()
  229836. {
  229837. CGContextRestoreGState (context);
  229838. CGContextRelease (context);
  229839. CGColorSpaceRelease (rgbColourSpace);
  229840. CGColorSpaceRelease (greyColourSpace);
  229841. }
  229842. bool isVectorDevice() const { return false; }
  229843. void setOrigin (int x, int y)
  229844. {
  229845. CGContextTranslateCTM (context, x, -y);
  229846. if (lastClipRectIsValid)
  229847. lastClipRect.translate (-x, -y);
  229848. }
  229849. void addTransform (const AffineTransform& transform)
  229850. {
  229851. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229852. .translated (0, flipHeight)
  229853. .followedBy (transform)
  229854. .translated (0, -flipHeight)
  229855. .scaled (1.0f, -1.0f));
  229856. lastClipRectIsValid = false;
  229857. }
  229858. float getScaleFactor()
  229859. {
  229860. CGAffineTransform t = CGContextGetCTM (context);
  229861. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229862. }
  229863. bool clipToRectangle (const Rectangle<int>& r)
  229864. {
  229865. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229866. if (lastClipRectIsValid)
  229867. {
  229868. // This is actually incorrect, because the actual clip region may be complex, and
  229869. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229870. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229871. // when calculating the resultant clip bounds, and makes the same mistake!
  229872. lastClipRect = lastClipRect.getIntersection (r);
  229873. return ! lastClipRect.isEmpty();
  229874. }
  229875. return ! isClipEmpty();
  229876. }
  229877. bool clipToRectangleList (const RectangleList& clipRegion)
  229878. {
  229879. if (clipRegion.isEmpty())
  229880. {
  229881. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229882. lastClipRectIsValid = true;
  229883. lastClipRect = Rectangle<int>();
  229884. return false;
  229885. }
  229886. else
  229887. {
  229888. const int numRects = clipRegion.getNumRectangles();
  229889. HeapBlock <CGRect> rects (numRects);
  229890. for (int i = 0; i < numRects; ++i)
  229891. {
  229892. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229893. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229894. }
  229895. CGContextClipToRects (context, rects, numRects);
  229896. lastClipRectIsValid = false;
  229897. return ! isClipEmpty();
  229898. }
  229899. }
  229900. void excludeClipRectangle (const Rectangle<int>& r)
  229901. {
  229902. RectangleList remaining (getClipBounds());
  229903. remaining.subtract (r);
  229904. clipToRectangleList (remaining);
  229905. lastClipRectIsValid = false;
  229906. }
  229907. void clipToPath (const Path& path, const AffineTransform& transform)
  229908. {
  229909. createPath (path, transform);
  229910. CGContextClip (context);
  229911. lastClipRectIsValid = false;
  229912. }
  229913. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229914. {
  229915. if (! transform.isSingularity())
  229916. {
  229917. Image singleChannelImage (sourceImage);
  229918. if (sourceImage.getFormat() != Image::SingleChannel)
  229919. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229920. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  229921. flip();
  229922. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229923. applyTransform (t);
  229924. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229925. CGContextClipToMask (context, r, image);
  229926. applyTransform (t.inverted());
  229927. flip();
  229928. CGImageRelease (image);
  229929. lastClipRectIsValid = false;
  229930. }
  229931. }
  229932. bool clipRegionIntersects (const Rectangle<int>& r)
  229933. {
  229934. return getClipBounds().intersects (r);
  229935. }
  229936. const Rectangle<int> getClipBounds() const
  229937. {
  229938. if (! lastClipRectIsValid)
  229939. {
  229940. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229941. lastClipRectIsValid = true;
  229942. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229943. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229944. roundToInt (bounds.size.width),
  229945. roundToInt (bounds.size.height));
  229946. }
  229947. return lastClipRect;
  229948. }
  229949. bool isClipEmpty() const
  229950. {
  229951. return getClipBounds().isEmpty();
  229952. }
  229953. void saveState()
  229954. {
  229955. CGContextSaveGState (context);
  229956. stateStack.add (new SavedState (*state));
  229957. }
  229958. void restoreState()
  229959. {
  229960. CGContextRestoreGState (context);
  229961. SavedState* const top = stateStack.getLast();
  229962. if (top != 0)
  229963. {
  229964. state = top;
  229965. stateStack.removeLast (1, false);
  229966. lastClipRectIsValid = false;
  229967. }
  229968. else
  229969. {
  229970. jassertfalse; // trying to pop with an empty stack!
  229971. }
  229972. }
  229973. void beginTransparencyLayer (float opacity)
  229974. {
  229975. saveState();
  229976. CGContextSetAlpha (context, opacity);
  229977. CGContextBeginTransparencyLayer (context, 0);
  229978. }
  229979. void endTransparencyLayer()
  229980. {
  229981. CGContextEndTransparencyLayer (context);
  229982. restoreState();
  229983. }
  229984. void setFill (const FillType& fillType)
  229985. {
  229986. state->fillType = fillType;
  229987. if (fillType.isColour())
  229988. {
  229989. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229990. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229991. CGContextSetAlpha (context, 1.0f);
  229992. }
  229993. }
  229994. void setOpacity (float newOpacity)
  229995. {
  229996. state->fillType.setOpacity (newOpacity);
  229997. setFill (state->fillType);
  229998. }
  229999. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230000. {
  230001. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230002. ? kCGInterpolationLow
  230003. : kCGInterpolationHigh);
  230004. }
  230005. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230006. {
  230007. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230008. }
  230009. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230010. {
  230011. if (replaceExistingContents)
  230012. {
  230013. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230014. CGContextClearRect (context, cgRect);
  230015. #else
  230016. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230017. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230018. CGContextClearRect (context, cgRect);
  230019. else
  230020. #endif
  230021. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230022. #endif
  230023. fillCGRect (cgRect, false);
  230024. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230025. }
  230026. else
  230027. {
  230028. if (state->fillType.isColour())
  230029. {
  230030. CGContextFillRect (context, cgRect);
  230031. }
  230032. else if (state->fillType.isGradient())
  230033. {
  230034. CGContextSaveGState (context);
  230035. CGContextClipToRect (context, cgRect);
  230036. drawGradient();
  230037. CGContextRestoreGState (context);
  230038. }
  230039. else
  230040. {
  230041. CGContextSaveGState (context);
  230042. CGContextClipToRect (context, cgRect);
  230043. drawImage (state->fillType.image, state->fillType.transform, true);
  230044. CGContextRestoreGState (context);
  230045. }
  230046. }
  230047. }
  230048. void fillPath (const Path& path, const AffineTransform& transform)
  230049. {
  230050. CGContextSaveGState (context);
  230051. if (state->fillType.isColour())
  230052. {
  230053. flip();
  230054. applyTransform (transform);
  230055. createPath (path);
  230056. if (path.isUsingNonZeroWinding())
  230057. CGContextFillPath (context);
  230058. else
  230059. CGContextEOFillPath (context);
  230060. }
  230061. else
  230062. {
  230063. createPath (path, transform);
  230064. if (path.isUsingNonZeroWinding())
  230065. CGContextClip (context);
  230066. else
  230067. CGContextEOClip (context);
  230068. if (state->fillType.isGradient())
  230069. drawGradient();
  230070. else
  230071. drawImage (state->fillType.image, state->fillType.transform, true);
  230072. }
  230073. CGContextRestoreGState (context);
  230074. }
  230075. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230076. {
  230077. const int iw = sourceImage.getWidth();
  230078. const int ih = sourceImage.getHeight();
  230079. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230080. CGContextSaveGState (context);
  230081. CGContextSetAlpha (context, state->fillType.getOpacity());
  230082. flip();
  230083. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230084. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230085. if (fillEntireClipAsTiles)
  230086. {
  230087. #if JUCE_IOS
  230088. CGContextDrawTiledImage (context, imageRect, image);
  230089. #else
  230090. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230091. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230092. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230093. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230094. CGContextDrawTiledImage (context, imageRect, image);
  230095. else
  230096. #endif
  230097. {
  230098. // Fallback to manually doing a tiled fill on 10.4
  230099. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230100. int x = 0, y = 0;
  230101. while (x > clip.origin.x) x -= iw;
  230102. while (y > clip.origin.y) y -= ih;
  230103. const int right = (int) (clip.origin.x + clip.size.width);
  230104. const int bottom = (int) (clip.origin.y + clip.size.height);
  230105. while (y < bottom)
  230106. {
  230107. for (int x2 = x; x2 < right; x2 += iw)
  230108. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230109. y += ih;
  230110. }
  230111. }
  230112. #endif
  230113. }
  230114. else
  230115. {
  230116. CGContextDrawImage (context, imageRect, image);
  230117. }
  230118. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230119. CGContextRestoreGState (context);
  230120. }
  230121. void drawLine (const Line<float>& line)
  230122. {
  230123. if (state->fillType.isColour())
  230124. {
  230125. CGContextSetLineCap (context, kCGLineCapSquare);
  230126. CGContextSetLineWidth (context, 1.0f);
  230127. CGContextSetRGBStrokeColor (context,
  230128. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230129. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230130. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230131. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230132. CGContextStrokeLineSegments (context, cgLine, 1);
  230133. }
  230134. else
  230135. {
  230136. Path p;
  230137. p.addLineSegment (line, 1.0f);
  230138. fillPath (p, AffineTransform::identity);
  230139. }
  230140. }
  230141. void drawVerticalLine (const int x, float top, float bottom)
  230142. {
  230143. if (state->fillType.isColour())
  230144. {
  230145. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230146. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230147. #else
  230148. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230149. // the x co-ord slightly to trick it..
  230150. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230151. #endif
  230152. }
  230153. else
  230154. {
  230155. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230156. }
  230157. }
  230158. void drawHorizontalLine (const int y, float left, float right)
  230159. {
  230160. if (state->fillType.isColour())
  230161. {
  230162. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230163. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230164. #else
  230165. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230166. // the x co-ord slightly to trick it..
  230167. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230168. #endif
  230169. }
  230170. else
  230171. {
  230172. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230173. }
  230174. }
  230175. void setFont (const Font& newFont)
  230176. {
  230177. if (state->font != newFont)
  230178. {
  230179. state->fontRef = 0;
  230180. state->font = newFont;
  230181. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230182. if (mf != 0)
  230183. {
  230184. state->fontRef = mf->fontRef;
  230185. CGContextSetFont (context, state->fontRef);
  230186. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230187. state->fontTransform = mf->renderingTransform;
  230188. state->fontTransform.a *= state->font.getHorizontalScale();
  230189. CGContextSetTextMatrix (context, state->fontTransform);
  230190. }
  230191. }
  230192. }
  230193. const Font getFont()
  230194. {
  230195. return state->font;
  230196. }
  230197. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230198. {
  230199. if (state->fontRef != 0 && state->fillType.isColour())
  230200. {
  230201. if (transform.isOnlyTranslation())
  230202. {
  230203. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230204. CGGlyph g = glyphNumber;
  230205. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230206. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230207. }
  230208. else
  230209. {
  230210. CGContextSaveGState (context);
  230211. flip();
  230212. applyTransform (transform);
  230213. CGAffineTransform t = state->fontTransform;
  230214. t.d = -t.d;
  230215. CGContextSetTextMatrix (context, t);
  230216. CGGlyph g = glyphNumber;
  230217. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230218. CGContextRestoreGState (context);
  230219. }
  230220. }
  230221. else
  230222. {
  230223. Path p;
  230224. Font& f = state->font;
  230225. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230226. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230227. .followedBy (transform));
  230228. }
  230229. }
  230230. private:
  230231. CGContextRef context;
  230232. const CGFloat flipHeight;
  230233. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230234. CGFunctionCallbacks gradientCallbacks;
  230235. mutable Rectangle<int> lastClipRect;
  230236. mutable bool lastClipRectIsValid;
  230237. struct SavedState
  230238. {
  230239. SavedState()
  230240. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230241. {
  230242. }
  230243. SavedState (const SavedState& other)
  230244. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230245. fontTransform (other.fontTransform)
  230246. {
  230247. }
  230248. FillType fillType;
  230249. Font font;
  230250. CGFontRef fontRef;
  230251. CGAffineTransform fontTransform;
  230252. };
  230253. ScopedPointer <SavedState> state;
  230254. OwnedArray <SavedState> stateStack;
  230255. HeapBlock <PixelARGB> gradientLookupTable;
  230256. int numGradientLookupEntries;
  230257. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230258. {
  230259. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230260. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230261. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230262. colour.unpremultiply();
  230263. outData[0] = colour.getRed() / 255.0f;
  230264. outData[1] = colour.getGreen() / 255.0f;
  230265. outData[2] = colour.getBlue() / 255.0f;
  230266. outData[3] = colour.getAlpha() / 255.0f;
  230267. }
  230268. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230269. {
  230270. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230271. --numGradientLookupEntries;
  230272. CGShadingRef result = 0;
  230273. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230274. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230275. if (gradient.isRadial)
  230276. {
  230277. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230278. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230279. function, true, true);
  230280. }
  230281. else
  230282. {
  230283. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230284. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230285. function, true, true);
  230286. }
  230287. CGFunctionRelease (function);
  230288. return result;
  230289. }
  230290. void drawGradient()
  230291. {
  230292. flip();
  230293. applyTransform (state->fillType.transform);
  230294. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230295. // you draw a gradient with high quality interp enabled).
  230296. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230297. CGContextSetAlpha (context, state->fillType.getOpacity());
  230298. CGContextDrawShading (context, shading);
  230299. CGShadingRelease (shading);
  230300. }
  230301. void createPath (const Path& path) const
  230302. {
  230303. CGContextBeginPath (context);
  230304. Path::Iterator i (path);
  230305. while (i.next())
  230306. {
  230307. switch (i.elementType)
  230308. {
  230309. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230310. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230311. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230312. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230313. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230314. default: jassertfalse; break;
  230315. }
  230316. }
  230317. }
  230318. void createPath (const Path& path, const AffineTransform& transform) const
  230319. {
  230320. CGContextBeginPath (context);
  230321. Path::Iterator i (path);
  230322. while (i.next())
  230323. {
  230324. switch (i.elementType)
  230325. {
  230326. case Path::Iterator::startNewSubPath:
  230327. transform.transformPoint (i.x1, i.y1);
  230328. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230329. break;
  230330. case Path::Iterator::lineTo:
  230331. transform.transformPoint (i.x1, i.y1);
  230332. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230333. break;
  230334. case Path::Iterator::quadraticTo:
  230335. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230336. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230337. break;
  230338. case Path::Iterator::cubicTo:
  230339. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230340. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230341. break;
  230342. case Path::Iterator::closePath:
  230343. CGContextClosePath (context); break;
  230344. default:
  230345. jassertfalse;
  230346. break;
  230347. }
  230348. }
  230349. }
  230350. void flip() const
  230351. {
  230352. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230353. }
  230354. void applyTransform (const AffineTransform& transform) const
  230355. {
  230356. CGAffineTransform t;
  230357. t.a = transform.mat00;
  230358. t.b = transform.mat10;
  230359. t.c = transform.mat01;
  230360. t.d = transform.mat11;
  230361. t.tx = transform.mat02;
  230362. t.ty = transform.mat12;
  230363. CGContextConcatCTM (context, t);
  230364. }
  230365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230366. };
  230367. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230368. {
  230369. return new CoreGraphicsContext (context, height);
  230370. }
  230371. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230372. const Image juce_loadWithCoreImage (InputStream& input)
  230373. {
  230374. MemoryBlock data;
  230375. input.readIntoMemoryBlock (data, -1);
  230376. #if JUCE_IOS
  230377. JUCE_AUTORELEASEPOOL
  230378. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230379. length: data.getSize()
  230380. freeWhenDone: NO]];
  230381. if (image != nil)
  230382. {
  230383. CGImageRef loadedImage = image.CGImage;
  230384. #else
  230385. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230386. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230387. CGDataProviderRelease (provider);
  230388. if (imageSource != 0)
  230389. {
  230390. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230391. CFRelease (imageSource);
  230392. #endif
  230393. if (loadedImage != 0)
  230394. {
  230395. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230396. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230397. && alphaInfo != kCGImageAlphaNoneSkipLast
  230398. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230399. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230400. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230401. hasAlphaChan, Image::NativeImage);
  230402. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230403. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230404. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230405. CGContextFlush (cgImage->context);
  230406. #if ! JUCE_IOS
  230407. CFRelease (loadedImage);
  230408. #endif
  230409. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230410. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230411. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230412. return image;
  230413. }
  230414. }
  230415. return Image::null;
  230416. }
  230417. #endif
  230418. #endif
  230419. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230420. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230421. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230422. // compiled on its own).
  230423. #if JUCE_INCLUDED_FILE
  230424. class NSViewComponentPeer;
  230425. END_JUCE_NAMESPACE
  230426. @interface NSEvent (JuceDeviceDelta)
  230427. - (float) deviceDeltaX;
  230428. - (float) deviceDeltaY;
  230429. @end
  230430. #define JuceNSView MakeObjCClassName(JuceNSView)
  230431. @interface JuceNSView : NSView<NSTextInput>
  230432. {
  230433. @public
  230434. NSViewComponentPeer* owner;
  230435. NSNotificationCenter* notificationCenter;
  230436. String* stringBeingComposed;
  230437. bool textWasInserted;
  230438. }
  230439. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230440. - (void) dealloc;
  230441. - (BOOL) isOpaque;
  230442. - (void) drawRect: (NSRect) r;
  230443. - (void) mouseDown: (NSEvent*) ev;
  230444. - (void) asyncMouseDown: (NSEvent*) ev;
  230445. - (void) mouseUp: (NSEvent*) ev;
  230446. - (void) asyncMouseUp: (NSEvent*) ev;
  230447. - (void) mouseDragged: (NSEvent*) ev;
  230448. - (void) mouseMoved: (NSEvent*) ev;
  230449. - (void) mouseEntered: (NSEvent*) ev;
  230450. - (void) mouseExited: (NSEvent*) ev;
  230451. - (void) rightMouseDown: (NSEvent*) ev;
  230452. - (void) rightMouseDragged: (NSEvent*) ev;
  230453. - (void) rightMouseUp: (NSEvent*) ev;
  230454. - (void) otherMouseDown: (NSEvent*) ev;
  230455. - (void) otherMouseDragged: (NSEvent*) ev;
  230456. - (void) otherMouseUp: (NSEvent*) ev;
  230457. - (void) scrollWheel: (NSEvent*) ev;
  230458. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230459. - (void) frameChanged: (NSNotification*) n;
  230460. - (void) viewDidMoveToWindow;
  230461. - (void) keyDown: (NSEvent*) ev;
  230462. - (void) keyUp: (NSEvent*) ev;
  230463. // NSTextInput Methods
  230464. - (void) insertText: (id) aString;
  230465. - (void) doCommandBySelector: (SEL) aSelector;
  230466. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230467. - (void) unmarkText;
  230468. - (BOOL) hasMarkedText;
  230469. - (long) conversationIdentifier;
  230470. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230471. - (NSRange) markedRange;
  230472. - (NSRange) selectedRange;
  230473. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230474. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230475. - (NSArray*) validAttributesForMarkedText;
  230476. - (void) flagsChanged: (NSEvent*) ev;
  230477. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230478. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230479. #endif
  230480. - (BOOL) becomeFirstResponder;
  230481. - (BOOL) resignFirstResponder;
  230482. - (BOOL) acceptsFirstResponder;
  230483. - (void) asyncRepaint: (id) rect;
  230484. - (NSArray*) getSupportedDragTypes;
  230485. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230486. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230487. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230488. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230489. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230490. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230491. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230492. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230493. @end
  230494. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230495. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230496. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230497. #else
  230498. @interface JuceNSWindow : NSWindow
  230499. #endif
  230500. {
  230501. @private
  230502. NSViewComponentPeer* owner;
  230503. bool isZooming;
  230504. }
  230505. - (void) setOwner: (NSViewComponentPeer*) owner;
  230506. - (BOOL) canBecomeKeyWindow;
  230507. - (void) becomeKeyWindow;
  230508. - (BOOL) windowShouldClose: (id) window;
  230509. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230510. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230511. - (void) zoom: (id) sender;
  230512. @end
  230513. BEGIN_JUCE_NAMESPACE
  230514. class NSViewComponentPeer : public ComponentPeer
  230515. {
  230516. public:
  230517. NSViewComponentPeer (Component* const component,
  230518. const int windowStyleFlags,
  230519. NSView* viewToAttachTo);
  230520. ~NSViewComponentPeer();
  230521. void* getNativeHandle() const;
  230522. void setVisible (bool shouldBeVisible);
  230523. void setTitle (const String& title);
  230524. void setPosition (int x, int y);
  230525. void setSize (int w, int h);
  230526. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230527. const Rectangle<int> getBounds (const bool global) const;
  230528. const Rectangle<int> getBounds() const;
  230529. const Point<int> getScreenPosition() const;
  230530. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230531. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230532. void setAlpha (float newAlpha);
  230533. void setMinimised (bool shouldBeMinimised);
  230534. bool isMinimised() const;
  230535. void setFullScreen (bool shouldBeFullScreen);
  230536. bool isFullScreen() const;
  230537. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230538. const BorderSize getFrameSize() const;
  230539. bool setAlwaysOnTop (bool alwaysOnTop);
  230540. void toFront (bool makeActiveWindow);
  230541. void toBehind (ComponentPeer* other);
  230542. void setIcon (const Image& newIcon);
  230543. const StringArray getAvailableRenderingEngines();
  230544. int getCurrentRenderingEngine() throw();
  230545. void setCurrentRenderingEngine (int index);
  230546. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230547. for example having more than one juce plugin loaded into a host, then when a
  230548. method is called, the actual code that runs might actually be in a different module
  230549. than the one you expect... So any calls to library functions or statics that are
  230550. made inside obj-c methods will probably end up getting executed in a different DLL's
  230551. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230552. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230553. virtual methods of an object that's known to live inside the right module's space.
  230554. */
  230555. virtual void redirectMouseDown (NSEvent* ev);
  230556. virtual void redirectMouseUp (NSEvent* ev);
  230557. virtual void redirectMouseDrag (NSEvent* ev);
  230558. virtual void redirectMouseMove (NSEvent* ev);
  230559. virtual void redirectMouseEnter (NSEvent* ev);
  230560. virtual void redirectMouseExit (NSEvent* ev);
  230561. virtual void redirectMouseWheel (NSEvent* ev);
  230562. void sendMouseEvent (NSEvent* ev);
  230563. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230564. virtual bool redirectKeyDown (NSEvent* ev);
  230565. virtual bool redirectKeyUp (NSEvent* ev);
  230566. virtual void redirectModKeyChange (NSEvent* ev);
  230567. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230568. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230569. #endif
  230570. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230571. virtual bool isOpaque();
  230572. virtual void drawRect (NSRect r);
  230573. virtual bool canBecomeKeyWindow();
  230574. virtual bool windowShouldClose();
  230575. virtual void redirectMovedOrResized();
  230576. virtual void viewMovedToWindow();
  230577. virtual NSRect constrainRect (NSRect r);
  230578. static void showArrowCursorIfNeeded();
  230579. static void updateModifiers (NSEvent* e);
  230580. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230581. static int getKeyCodeFromEvent (NSEvent* ev)
  230582. {
  230583. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230584. int keyCode = unmodified[0];
  230585. if (keyCode == 0x19) // (backwards-tab)
  230586. keyCode = '\t';
  230587. else if (keyCode == 0x03) // (enter)
  230588. keyCode = '\r';
  230589. else
  230590. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230591. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230592. {
  230593. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230594. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230595. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230596. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230597. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230598. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230599. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230600. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230601. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230602. if (keyCode == numPadConversions [i])
  230603. keyCode = numPadConversions [i + 1];
  230604. }
  230605. return keyCode;
  230606. }
  230607. static int64 getMouseTime (NSEvent* e)
  230608. {
  230609. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230610. + (int64) ([e timestamp] * 1000.0);
  230611. }
  230612. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230613. {
  230614. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230615. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230616. }
  230617. static int getModifierForButtonNumber (const NSInteger num)
  230618. {
  230619. return num == 0 ? ModifierKeys::leftButtonModifier
  230620. : (num == 1 ? ModifierKeys::rightButtonModifier
  230621. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230622. }
  230623. virtual void viewFocusGain();
  230624. virtual void viewFocusLoss();
  230625. bool isFocused() const;
  230626. void grabFocus();
  230627. void textInputRequired (const Point<int>& position);
  230628. void repaint (const Rectangle<int>& area);
  230629. void performAnyPendingRepaintsNow();
  230630. NSWindow* window;
  230631. JuceNSView* view;
  230632. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230633. static ModifierKeys currentModifiers;
  230634. static ComponentPeer* currentlyFocusedPeer;
  230635. static Array<int> keysCurrentlyDown;
  230636. private:
  230637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230638. };
  230639. END_JUCE_NAMESPACE
  230640. @implementation JuceNSView
  230641. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230642. withFrame: (NSRect) frame
  230643. {
  230644. [super initWithFrame: frame];
  230645. owner = owner_;
  230646. stringBeingComposed = 0;
  230647. textWasInserted = false;
  230648. notificationCenter = [NSNotificationCenter defaultCenter];
  230649. [notificationCenter addObserver: self
  230650. selector: @selector (frameChanged:)
  230651. name: NSViewFrameDidChangeNotification
  230652. object: self];
  230653. if (! owner_->isSharedWindow)
  230654. {
  230655. [notificationCenter addObserver: self
  230656. selector: @selector (frameChanged:)
  230657. name: NSWindowDidMoveNotification
  230658. object: owner_->window];
  230659. }
  230660. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230661. return self;
  230662. }
  230663. - (void) dealloc
  230664. {
  230665. [notificationCenter removeObserver: self];
  230666. delete stringBeingComposed;
  230667. [super dealloc];
  230668. }
  230669. - (void) drawRect: (NSRect) r
  230670. {
  230671. if (owner != 0)
  230672. owner->drawRect (r);
  230673. }
  230674. - (BOOL) isOpaque
  230675. {
  230676. return owner == 0 || owner->isOpaque();
  230677. }
  230678. - (void) mouseDown: (NSEvent*) ev
  230679. {
  230680. if (JUCEApplication::isStandaloneApp())
  230681. [self asyncMouseDown: ev];
  230682. else
  230683. // In some host situations, the host will stop modal loops from working
  230684. // correctly if they're called from a mouse event, so we'll trigger
  230685. // the event asynchronously..
  230686. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230687. withObject: ev
  230688. waitUntilDone: NO];
  230689. }
  230690. - (void) asyncMouseDown: (NSEvent*) ev
  230691. {
  230692. if (owner != 0)
  230693. owner->redirectMouseDown (ev);
  230694. }
  230695. - (void) mouseUp: (NSEvent*) ev
  230696. {
  230697. if (! JUCEApplication::isStandaloneApp())
  230698. [self asyncMouseUp: ev];
  230699. else
  230700. // In some host situations, the host will stop modal loops from working
  230701. // correctly if they're called from a mouse event, so we'll trigger
  230702. // the event asynchronously..
  230703. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230704. withObject: ev
  230705. waitUntilDone: NO];
  230706. }
  230707. - (void) asyncMouseUp: (NSEvent*) ev
  230708. {
  230709. if (owner != 0)
  230710. owner->redirectMouseUp (ev);
  230711. }
  230712. - (void) mouseDragged: (NSEvent*) ev
  230713. {
  230714. if (owner != 0)
  230715. owner->redirectMouseDrag (ev);
  230716. }
  230717. - (void) mouseMoved: (NSEvent*) ev
  230718. {
  230719. if (owner != 0)
  230720. owner->redirectMouseMove (ev);
  230721. }
  230722. - (void) mouseEntered: (NSEvent*) ev
  230723. {
  230724. if (owner != 0)
  230725. owner->redirectMouseEnter (ev);
  230726. }
  230727. - (void) mouseExited: (NSEvent*) ev
  230728. {
  230729. if (owner != 0)
  230730. owner->redirectMouseExit (ev);
  230731. }
  230732. - (void) rightMouseDown: (NSEvent*) ev
  230733. {
  230734. [self mouseDown: ev];
  230735. }
  230736. - (void) rightMouseDragged: (NSEvent*) ev
  230737. {
  230738. [self mouseDragged: ev];
  230739. }
  230740. - (void) rightMouseUp: (NSEvent*) ev
  230741. {
  230742. [self mouseUp: ev];
  230743. }
  230744. - (void) otherMouseDown: (NSEvent*) ev
  230745. {
  230746. [self mouseDown: ev];
  230747. }
  230748. - (void) otherMouseDragged: (NSEvent*) ev
  230749. {
  230750. [self mouseDragged: ev];
  230751. }
  230752. - (void) otherMouseUp: (NSEvent*) ev
  230753. {
  230754. [self mouseUp: ev];
  230755. }
  230756. - (void) scrollWheel: (NSEvent*) ev
  230757. {
  230758. if (owner != 0)
  230759. owner->redirectMouseWheel (ev);
  230760. }
  230761. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230762. {
  230763. (void) ev;
  230764. return YES;
  230765. }
  230766. - (void) frameChanged: (NSNotification*) n
  230767. {
  230768. (void) n;
  230769. if (owner != 0)
  230770. owner->redirectMovedOrResized();
  230771. }
  230772. - (void) viewDidMoveToWindow
  230773. {
  230774. if (owner != 0)
  230775. owner->viewMovedToWindow();
  230776. }
  230777. - (void) asyncRepaint: (id) rect
  230778. {
  230779. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230780. [self setNeedsDisplayInRect: *r];
  230781. }
  230782. - (void) keyDown: (NSEvent*) ev
  230783. {
  230784. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230785. textWasInserted = false;
  230786. if (target != 0)
  230787. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230788. else
  230789. deleteAndZero (stringBeingComposed);
  230790. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230791. [super keyDown: ev];
  230792. }
  230793. - (void) keyUp: (NSEvent*) ev
  230794. {
  230795. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230796. [super keyUp: ev];
  230797. }
  230798. - (void) insertText: (id) aString
  230799. {
  230800. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230801. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230802. if ([newText length] > 0)
  230803. {
  230804. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230805. if (target != 0)
  230806. {
  230807. target->insertTextAtCaret (nsStringToJuce (newText));
  230808. textWasInserted = true;
  230809. }
  230810. }
  230811. deleteAndZero (stringBeingComposed);
  230812. }
  230813. - (void) doCommandBySelector: (SEL) aSelector
  230814. {
  230815. (void) aSelector;
  230816. }
  230817. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230818. {
  230819. (void) selectionRange;
  230820. if (stringBeingComposed == 0)
  230821. stringBeingComposed = new String();
  230822. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230823. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230824. if (target != 0)
  230825. {
  230826. const Range<int> currentHighlight (target->getHighlightedRegion());
  230827. target->insertTextAtCaret (*stringBeingComposed);
  230828. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230829. textWasInserted = true;
  230830. }
  230831. }
  230832. - (void) unmarkText
  230833. {
  230834. if (stringBeingComposed != 0)
  230835. {
  230836. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230837. if (target != 0)
  230838. {
  230839. target->insertTextAtCaret (*stringBeingComposed);
  230840. textWasInserted = true;
  230841. }
  230842. }
  230843. deleteAndZero (stringBeingComposed);
  230844. }
  230845. - (BOOL) hasMarkedText
  230846. {
  230847. return stringBeingComposed != 0;
  230848. }
  230849. - (long) conversationIdentifier
  230850. {
  230851. return (long) (pointer_sized_int) self;
  230852. }
  230853. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230854. {
  230855. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230856. if (target != 0)
  230857. {
  230858. const Range<int> r ((int) theRange.location,
  230859. (int) (theRange.location + theRange.length));
  230860. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230861. }
  230862. return nil;
  230863. }
  230864. - (NSRange) markedRange
  230865. {
  230866. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230867. : NSMakeRange (NSNotFound, 0);
  230868. }
  230869. - (NSRange) selectedRange
  230870. {
  230871. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230872. if (target != 0)
  230873. {
  230874. const Range<int> highlight (target->getHighlightedRegion());
  230875. if (! highlight.isEmpty())
  230876. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230877. }
  230878. return NSMakeRange (NSNotFound, 0);
  230879. }
  230880. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230881. {
  230882. (void) theRange;
  230883. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230884. if (comp == 0)
  230885. return NSMakeRect (0, 0, 0, 0);
  230886. const Rectangle<int> bounds (comp->getScreenBounds());
  230887. return NSMakeRect (bounds.getX(),
  230888. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230889. bounds.getWidth(),
  230890. bounds.getHeight());
  230891. }
  230892. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230893. {
  230894. (void) thePoint;
  230895. return NSNotFound;
  230896. }
  230897. - (NSArray*) validAttributesForMarkedText
  230898. {
  230899. return [NSArray array];
  230900. }
  230901. - (void) flagsChanged: (NSEvent*) ev
  230902. {
  230903. if (owner != 0)
  230904. owner->redirectModKeyChange (ev);
  230905. }
  230906. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230907. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230908. {
  230909. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230910. return true;
  230911. return [super performKeyEquivalent: ev];
  230912. }
  230913. #endif
  230914. - (BOOL) becomeFirstResponder
  230915. {
  230916. if (owner != 0)
  230917. owner->viewFocusGain();
  230918. return true;
  230919. }
  230920. - (BOOL) resignFirstResponder
  230921. {
  230922. if (owner != 0)
  230923. owner->viewFocusLoss();
  230924. return true;
  230925. }
  230926. - (BOOL) acceptsFirstResponder
  230927. {
  230928. return owner != 0 && owner->canBecomeKeyWindow();
  230929. }
  230930. - (NSArray*) getSupportedDragTypes
  230931. {
  230932. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230933. }
  230934. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230935. {
  230936. return owner != 0 && owner->sendDragCallback (type, sender);
  230937. }
  230938. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230939. {
  230940. if ([self sendDragCallback: 0 sender: sender])
  230941. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230942. else
  230943. return NSDragOperationNone;
  230944. }
  230945. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230946. {
  230947. if ([self sendDragCallback: 0 sender: sender])
  230948. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230949. else
  230950. return NSDragOperationNone;
  230951. }
  230952. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230953. {
  230954. [self sendDragCallback: 1 sender: sender];
  230955. }
  230956. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230957. {
  230958. [self sendDragCallback: 1 sender: sender];
  230959. }
  230960. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230961. {
  230962. (void) sender;
  230963. return YES;
  230964. }
  230965. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230966. {
  230967. return [self sendDragCallback: 2 sender: sender];
  230968. }
  230969. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230970. {
  230971. (void) sender;
  230972. }
  230973. @end
  230974. @implementation JuceNSWindow
  230975. - (void) setOwner: (NSViewComponentPeer*) owner_
  230976. {
  230977. owner = owner_;
  230978. isZooming = false;
  230979. }
  230980. - (BOOL) canBecomeKeyWindow
  230981. {
  230982. return owner != 0 && owner->canBecomeKeyWindow();
  230983. }
  230984. - (void) becomeKeyWindow
  230985. {
  230986. [super becomeKeyWindow];
  230987. if (owner != 0)
  230988. owner->grabFocus();
  230989. }
  230990. - (BOOL) windowShouldClose: (id) window
  230991. {
  230992. (void) window;
  230993. return owner == 0 || owner->windowShouldClose();
  230994. }
  230995. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230996. {
  230997. (void) screen;
  230998. if (owner != 0)
  230999. frameRect = owner->constrainRect (frameRect);
  231000. return frameRect;
  231001. }
  231002. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231003. {
  231004. (void) window;
  231005. if (isZooming)
  231006. return proposedFrameSize;
  231007. NSRect frameRect = [self frame];
  231008. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231009. frameRect.size = proposedFrameSize;
  231010. if (owner != 0)
  231011. frameRect = owner->constrainRect (frameRect);
  231012. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231013. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231014. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231015. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231016. return frameRect.size;
  231017. }
  231018. - (void) zoom: (id) sender
  231019. {
  231020. isZooming = true;
  231021. [super zoom: sender];
  231022. isZooming = false;
  231023. }
  231024. - (void) windowWillMove: (NSNotification*) notification
  231025. {
  231026. (void) notification;
  231027. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231028. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231029. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231030. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231031. }
  231032. @end
  231033. BEGIN_JUCE_NAMESPACE
  231034. ModifierKeys NSViewComponentPeer::currentModifiers;
  231035. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231036. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231037. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231038. {
  231039. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231040. return true;
  231041. if (keyCode >= 'A' && keyCode <= 'Z'
  231042. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231043. return true;
  231044. if (keyCode >= 'a' && keyCode <= 'z'
  231045. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231046. return true;
  231047. return false;
  231048. }
  231049. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231050. {
  231051. int m = 0;
  231052. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231053. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231054. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231055. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231056. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231057. }
  231058. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231059. {
  231060. updateModifiers (ev);
  231061. int keyCode = getKeyCodeFromEvent (ev);
  231062. if (keyCode != 0)
  231063. {
  231064. if (isKeyDown)
  231065. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231066. else
  231067. keysCurrentlyDown.removeValue (keyCode);
  231068. }
  231069. }
  231070. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231071. {
  231072. return NSViewComponentPeer::currentModifiers;
  231073. }
  231074. void ModifierKeys::updateCurrentModifiers() throw()
  231075. {
  231076. currentModifiers = NSViewComponentPeer::currentModifiers;
  231077. }
  231078. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231079. const int windowStyleFlags,
  231080. NSView* viewToAttachTo)
  231081. : ComponentPeer (component_, windowStyleFlags),
  231082. window (0),
  231083. view (0),
  231084. isSharedWindow (viewToAttachTo != 0),
  231085. fullScreen (false),
  231086. insideDrawRect (false),
  231087. #if USE_COREGRAPHICS_RENDERING
  231088. usingCoreGraphics (true),
  231089. #else
  231090. usingCoreGraphics (false),
  231091. #endif
  231092. recursiveToFrontCall (false)
  231093. {
  231094. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231095. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231096. [view setPostsFrameChangedNotifications: YES];
  231097. if (isSharedWindow)
  231098. {
  231099. window = [viewToAttachTo window];
  231100. [viewToAttachTo addSubview: view];
  231101. }
  231102. else
  231103. {
  231104. r.origin.x = (float) component->getX();
  231105. r.origin.y = (float) component->getY();
  231106. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231107. unsigned int style = 0;
  231108. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231109. style = NSBorderlessWindowMask;
  231110. else
  231111. style = NSTitledWindowMask;
  231112. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231113. style |= NSMiniaturizableWindowMask;
  231114. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231115. style |= NSClosableWindowMask;
  231116. if ((windowStyleFlags & windowIsResizable) != 0)
  231117. style |= NSResizableWindowMask;
  231118. window = [[JuceNSWindow alloc] initWithContentRect: r
  231119. styleMask: style
  231120. backing: NSBackingStoreBuffered
  231121. defer: YES];
  231122. [((JuceNSWindow*) window) setOwner: this];
  231123. [window orderOut: nil];
  231124. [window setDelegate: (JuceNSWindow*) window];
  231125. [window setOpaque: component->isOpaque()];
  231126. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231127. if (component->isAlwaysOnTop())
  231128. [window setLevel: NSFloatingWindowLevel];
  231129. [window setContentView: view];
  231130. [window setAutodisplay: YES];
  231131. [window setAcceptsMouseMovedEvents: YES];
  231132. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231133. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231134. [window setReleasedWhenClosed: YES];
  231135. [window retain];
  231136. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231137. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231138. }
  231139. const float alpha = component->getAlpha();
  231140. if (alpha < 1.0f)
  231141. setAlpha (alpha);
  231142. setTitle (component->getName());
  231143. }
  231144. NSViewComponentPeer::~NSViewComponentPeer()
  231145. {
  231146. view->owner = 0;
  231147. [view removeFromSuperview];
  231148. [view release];
  231149. if (! isSharedWindow)
  231150. {
  231151. [((JuceNSWindow*) window) setOwner: 0];
  231152. [window close];
  231153. [window release];
  231154. }
  231155. }
  231156. void* NSViewComponentPeer::getNativeHandle() const
  231157. {
  231158. return view;
  231159. }
  231160. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231161. {
  231162. if (isSharedWindow)
  231163. {
  231164. [view setHidden: ! shouldBeVisible];
  231165. }
  231166. else
  231167. {
  231168. if (shouldBeVisible)
  231169. {
  231170. [window orderFront: nil];
  231171. handleBroughtToFront();
  231172. }
  231173. else
  231174. {
  231175. [window orderOut: nil];
  231176. }
  231177. }
  231178. }
  231179. void NSViewComponentPeer::setTitle (const String& title)
  231180. {
  231181. const ScopedAutoReleasePool pool;
  231182. if (! isSharedWindow)
  231183. [window setTitle: juceStringToNS (title)];
  231184. }
  231185. void NSViewComponentPeer::setPosition (int x, int y)
  231186. {
  231187. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231188. }
  231189. void NSViewComponentPeer::setSize (int w, int h)
  231190. {
  231191. setBounds (component->getX(), component->getY(), w, h, false);
  231192. }
  231193. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231194. {
  231195. fullScreen = isNowFullScreen;
  231196. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231197. if (isSharedWindow)
  231198. {
  231199. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231200. if ([view frame].size.width != r.size.width
  231201. || [view frame].size.height != r.size.height)
  231202. [view setNeedsDisplay: true];
  231203. [view setFrame: r];
  231204. }
  231205. else
  231206. {
  231207. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231208. [window setFrame: [window frameRectForContentRect: r]
  231209. display: true];
  231210. }
  231211. }
  231212. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231213. {
  231214. NSRect r = [view frame];
  231215. if (global && [view window] != 0)
  231216. {
  231217. r = [view convertRect: r toView: nil];
  231218. NSRect wr = [[view window] frame];
  231219. r.origin.x += wr.origin.x;
  231220. r.origin.y += wr.origin.y;
  231221. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231222. }
  231223. else
  231224. {
  231225. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231226. }
  231227. return Rectangle<int> (convertToRectInt (r));
  231228. }
  231229. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231230. {
  231231. return getBounds (! isSharedWindow);
  231232. }
  231233. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231234. {
  231235. return getBounds (true).getPosition();
  231236. }
  231237. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231238. {
  231239. return relativePosition + getScreenPosition();
  231240. }
  231241. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231242. {
  231243. return screenPosition - getScreenPosition();
  231244. }
  231245. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231246. {
  231247. if (constrainer != 0)
  231248. {
  231249. NSRect current = [window frame];
  231250. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231251. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231252. Rectangle<int> pos (convertToRectInt (r));
  231253. Rectangle<int> original (convertToRectInt (current));
  231254. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231255. if ([window inLiveResize])
  231256. #else
  231257. if ([window respondsToSelector: @selector (inLiveResize)]
  231258. && [window performSelector: @selector (inLiveResize)])
  231259. #endif
  231260. {
  231261. constrainer->checkBounds (pos, original,
  231262. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231263. false, false, true, true);
  231264. }
  231265. else
  231266. {
  231267. constrainer->checkBounds (pos, original,
  231268. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231269. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231270. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231271. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231272. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231273. }
  231274. r.origin.x = pos.getX();
  231275. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231276. r.size.width = pos.getWidth();
  231277. r.size.height = pos.getHeight();
  231278. }
  231279. return r;
  231280. }
  231281. void NSViewComponentPeer::setAlpha (float newAlpha)
  231282. {
  231283. if (! isSharedWindow)
  231284. [window setAlphaValue: (CGFloat) newAlpha];
  231285. else
  231286. [view setAlphaValue: (CGFloat) newAlpha];
  231287. }
  231288. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231289. {
  231290. if (! isSharedWindow)
  231291. {
  231292. if (shouldBeMinimised)
  231293. [window miniaturize: nil];
  231294. else
  231295. [window deminiaturize: nil];
  231296. }
  231297. }
  231298. bool NSViewComponentPeer::isMinimised() const
  231299. {
  231300. return window != 0 && [window isMiniaturized];
  231301. }
  231302. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231303. {
  231304. if (! isSharedWindow)
  231305. {
  231306. Rectangle<int> r (lastNonFullscreenBounds);
  231307. setMinimised (false);
  231308. if (fullScreen != shouldBeFullScreen)
  231309. {
  231310. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231311. {
  231312. fullScreen = true;
  231313. [window performZoom: nil];
  231314. }
  231315. else
  231316. {
  231317. if (shouldBeFullScreen)
  231318. r = Desktop::getInstance().getMainMonitorArea();
  231319. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231320. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231321. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231322. }
  231323. }
  231324. }
  231325. }
  231326. bool NSViewComponentPeer::isFullScreen() const
  231327. {
  231328. return fullScreen;
  231329. }
  231330. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231331. {
  231332. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231333. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231334. return false;
  231335. NSPoint p;
  231336. p.x = (float) position.getX();
  231337. p.y = (float) position.getY();
  231338. NSView* v = [view hitTest: p];
  231339. if (trueIfInAChildWindow)
  231340. return v != nil;
  231341. return v == view;
  231342. }
  231343. const BorderSize NSViewComponentPeer::getFrameSize() const
  231344. {
  231345. BorderSize b;
  231346. if (! isSharedWindow)
  231347. {
  231348. NSRect v = [view convertRect: [view frame] toView: nil];
  231349. NSRect w = [window frame];
  231350. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231351. b.setBottom ((int) v.origin.y);
  231352. b.setLeft ((int) v.origin.x);
  231353. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231354. }
  231355. return b;
  231356. }
  231357. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231358. {
  231359. if (! isSharedWindow)
  231360. {
  231361. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231362. : NSNormalWindowLevel];
  231363. }
  231364. return true;
  231365. }
  231366. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231367. {
  231368. if (isSharedWindow)
  231369. {
  231370. [[view superview] addSubview: view
  231371. positioned: NSWindowAbove
  231372. relativeTo: nil];
  231373. }
  231374. if (window != 0 && component->isVisible())
  231375. {
  231376. if (makeActiveWindow)
  231377. [window makeKeyAndOrderFront: nil];
  231378. else
  231379. [window orderFront: nil];
  231380. if (! recursiveToFrontCall)
  231381. {
  231382. recursiveToFrontCall = true;
  231383. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231384. handleBroughtToFront();
  231385. recursiveToFrontCall = false;
  231386. }
  231387. }
  231388. }
  231389. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231390. {
  231391. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231392. jassert (otherPeer != 0); // wrong type of window?
  231393. if (otherPeer != 0)
  231394. {
  231395. if (isSharedWindow)
  231396. {
  231397. [[view superview] addSubview: view
  231398. positioned: NSWindowBelow
  231399. relativeTo: otherPeer->view];
  231400. }
  231401. else
  231402. {
  231403. [window orderWindow: NSWindowBelow
  231404. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231405. : nil ];
  231406. }
  231407. }
  231408. }
  231409. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231410. {
  231411. // to do..
  231412. }
  231413. void NSViewComponentPeer::viewFocusGain()
  231414. {
  231415. if (currentlyFocusedPeer != this)
  231416. {
  231417. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231418. currentlyFocusedPeer->handleFocusLoss();
  231419. currentlyFocusedPeer = this;
  231420. handleFocusGain();
  231421. }
  231422. }
  231423. void NSViewComponentPeer::viewFocusLoss()
  231424. {
  231425. if (currentlyFocusedPeer == this)
  231426. {
  231427. currentlyFocusedPeer = 0;
  231428. handleFocusLoss();
  231429. }
  231430. }
  231431. void juce_HandleProcessFocusChange()
  231432. {
  231433. NSViewComponentPeer::keysCurrentlyDown.clear();
  231434. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231435. {
  231436. if (Process::isForegroundProcess())
  231437. {
  231438. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231439. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231440. }
  231441. else
  231442. {
  231443. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231444. // turn kiosk mode off if we lose focus..
  231445. Desktop::getInstance().setKioskModeComponent (0);
  231446. }
  231447. }
  231448. }
  231449. bool NSViewComponentPeer::isFocused() const
  231450. {
  231451. return isSharedWindow ? this == currentlyFocusedPeer
  231452. : (window != 0 && [window isKeyWindow]);
  231453. }
  231454. void NSViewComponentPeer::grabFocus()
  231455. {
  231456. if (window != 0)
  231457. {
  231458. [window makeKeyWindow];
  231459. [window makeFirstResponder: view];
  231460. viewFocusGain();
  231461. }
  231462. }
  231463. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231464. {
  231465. }
  231466. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231467. {
  231468. String unicode (nsStringToJuce ([ev characters]));
  231469. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231470. int keyCode = getKeyCodeFromEvent (ev);
  231471. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231472. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231473. if (unicode.isNotEmpty() || keyCode != 0)
  231474. {
  231475. if (isKeyDown)
  231476. {
  231477. bool used = false;
  231478. while (unicode.length() > 0)
  231479. {
  231480. juce_wchar textCharacter = unicode[0];
  231481. unicode = unicode.substring (1);
  231482. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231483. textCharacter = 0;
  231484. used = handleKeyUpOrDown (true) || used;
  231485. used = handleKeyPress (keyCode, textCharacter) || used;
  231486. }
  231487. return used;
  231488. }
  231489. else
  231490. {
  231491. if (handleKeyUpOrDown (false))
  231492. return true;
  231493. }
  231494. }
  231495. return false;
  231496. }
  231497. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231498. {
  231499. updateKeysDown (ev, true);
  231500. bool used = handleKeyEvent (ev, true);
  231501. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231502. {
  231503. // for command keys, the key-up event is thrown away, so simulate one..
  231504. updateKeysDown (ev, false);
  231505. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231506. }
  231507. // (If we're running modally, don't allow unused keystrokes to be passed
  231508. // along to other blocked views..)
  231509. if (Component::getCurrentlyModalComponent() != 0)
  231510. used = true;
  231511. return used;
  231512. }
  231513. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231514. {
  231515. updateKeysDown (ev, false);
  231516. return handleKeyEvent (ev, false)
  231517. || Component::getCurrentlyModalComponent() != 0;
  231518. }
  231519. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231520. {
  231521. keysCurrentlyDown.clear();
  231522. handleKeyUpOrDown (true);
  231523. updateModifiers (ev);
  231524. handleModifierKeysChange();
  231525. }
  231526. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231527. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231528. {
  231529. if ([ev type] == NSKeyDown)
  231530. return redirectKeyDown (ev);
  231531. else if ([ev type] == NSKeyUp)
  231532. return redirectKeyUp (ev);
  231533. return false;
  231534. }
  231535. #endif
  231536. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231537. {
  231538. updateModifiers (ev);
  231539. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231540. }
  231541. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231542. {
  231543. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231544. sendMouseEvent (ev);
  231545. }
  231546. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231547. {
  231548. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231549. sendMouseEvent (ev);
  231550. showArrowCursorIfNeeded();
  231551. }
  231552. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231553. {
  231554. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231555. sendMouseEvent (ev);
  231556. }
  231557. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231558. {
  231559. currentModifiers = currentModifiers.withoutMouseButtons();
  231560. sendMouseEvent (ev);
  231561. showArrowCursorIfNeeded();
  231562. }
  231563. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231564. {
  231565. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231566. currentModifiers = currentModifiers.withoutMouseButtons();
  231567. sendMouseEvent (ev);
  231568. }
  231569. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231570. {
  231571. currentModifiers = currentModifiers.withoutMouseButtons();
  231572. sendMouseEvent (ev);
  231573. }
  231574. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231575. {
  231576. updateModifiers (ev);
  231577. float x = 0, y = 0;
  231578. @try
  231579. {
  231580. x = [ev deviceDeltaX] * 0.5f;
  231581. y = [ev deviceDeltaY] * 0.5f;
  231582. }
  231583. @catch (...)
  231584. {}
  231585. if (x == 0 && y == 0)
  231586. {
  231587. x = [ev deltaX] * 10.0f;
  231588. y = [ev deltaY] * 10.0f;
  231589. }
  231590. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231591. }
  231592. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231593. {
  231594. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231595. if (mouse.getComponentUnderMouse() == 0
  231596. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231597. {
  231598. [[NSCursor arrowCursor] set];
  231599. }
  231600. }
  231601. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231602. {
  231603. NSString* bestType
  231604. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231605. if (bestType == nil)
  231606. return false;
  231607. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231608. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231609. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231610. if (list == nil)
  231611. return false;
  231612. StringArray files;
  231613. if ([list isKindOfClass: [NSArray class]])
  231614. {
  231615. NSArray* items = (NSArray*) list;
  231616. for (unsigned int i = 0; i < [items count]; ++i)
  231617. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231618. }
  231619. if (files.size() == 0)
  231620. return false;
  231621. if (type == 0)
  231622. handleFileDragMove (files, pos);
  231623. else if (type == 1)
  231624. handleFileDragExit (files);
  231625. else if (type == 2)
  231626. handleFileDragDrop (files, pos);
  231627. return true;
  231628. }
  231629. bool NSViewComponentPeer::isOpaque()
  231630. {
  231631. return component == 0 || component->isOpaque();
  231632. }
  231633. void NSViewComponentPeer::drawRect (NSRect r)
  231634. {
  231635. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231636. return;
  231637. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231638. if (! component->isOpaque())
  231639. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231640. #if USE_COREGRAPHICS_RENDERING
  231641. if (usingCoreGraphics)
  231642. {
  231643. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231644. insideDrawRect = true;
  231645. handlePaint (context);
  231646. insideDrawRect = false;
  231647. }
  231648. else
  231649. #endif
  231650. {
  231651. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231652. (int) (r.size.width + 0.5f),
  231653. (int) (r.size.height + 0.5f),
  231654. ! getComponent()->isOpaque());
  231655. const int xOffset = -roundToInt (r.origin.x);
  231656. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231657. const NSRect* rects = 0;
  231658. NSInteger numRects = 0;
  231659. [view getRectsBeingDrawn: &rects count: &numRects];
  231660. const Rectangle<int> clipBounds (temp.getBounds());
  231661. RectangleList clip;
  231662. for (int i = 0; i < numRects; ++i)
  231663. {
  231664. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231665. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231666. roundToInt (rects[i].size.width),
  231667. roundToInt (rects[i].size.height))));
  231668. }
  231669. if (! clip.isEmpty())
  231670. {
  231671. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231672. insideDrawRect = true;
  231673. handlePaint (context);
  231674. insideDrawRect = false;
  231675. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231676. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  231677. CGColorSpaceRelease (colourSpace);
  231678. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231679. CGImageRelease (image);
  231680. }
  231681. }
  231682. }
  231683. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231684. {
  231685. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231686. #if USE_COREGRAPHICS_RENDERING
  231687. s.add ("CoreGraphics Renderer");
  231688. #endif
  231689. return s;
  231690. }
  231691. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231692. {
  231693. return usingCoreGraphics ? 1 : 0;
  231694. }
  231695. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231696. {
  231697. #if USE_COREGRAPHICS_RENDERING
  231698. if (usingCoreGraphics != (index > 0))
  231699. {
  231700. usingCoreGraphics = index > 0;
  231701. [view setNeedsDisplay: true];
  231702. }
  231703. #endif
  231704. }
  231705. bool NSViewComponentPeer::canBecomeKeyWindow()
  231706. {
  231707. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231708. }
  231709. bool NSViewComponentPeer::windowShouldClose()
  231710. {
  231711. if (! isValidPeer (this))
  231712. return YES;
  231713. handleUserClosingWindow();
  231714. return NO;
  231715. }
  231716. void NSViewComponentPeer::redirectMovedOrResized()
  231717. {
  231718. handleMovedOrResized();
  231719. }
  231720. void NSViewComponentPeer::viewMovedToWindow()
  231721. {
  231722. if (isSharedWindow)
  231723. window = [view window];
  231724. }
  231725. void Desktop::createMouseInputSources()
  231726. {
  231727. mouseSources.add (new MouseInputSource (0, true));
  231728. }
  231729. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231730. {
  231731. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  231732. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  231733. // is apparently still available in 64-bit apps..
  231734. if (enableOrDisable)
  231735. {
  231736. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231737. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231738. }
  231739. else
  231740. {
  231741. SetSystemUIMode (kUIModeNormal, 0);
  231742. }
  231743. }
  231744. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231745. {
  231746. if (insideDrawRect)
  231747. {
  231748. class AsyncRepaintMessage : public CallbackMessage
  231749. {
  231750. public:
  231751. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231752. : peer (peer_), rect (rect_)
  231753. {
  231754. }
  231755. void messageCallback()
  231756. {
  231757. if (ComponentPeer::isValidPeer (peer))
  231758. peer->repaint (rect);
  231759. }
  231760. private:
  231761. NSViewComponentPeer* const peer;
  231762. const Rectangle<int> rect;
  231763. };
  231764. (new AsyncRepaintMessage (this, area))->post();
  231765. }
  231766. else
  231767. {
  231768. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231769. (float) area.getWidth(), (float) area.getHeight())];
  231770. }
  231771. }
  231772. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231773. {
  231774. [view displayIfNeeded];
  231775. }
  231776. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231777. {
  231778. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231779. }
  231780. const Image juce_createIconForFile (const File& file)
  231781. {
  231782. const ScopedAutoReleasePool pool;
  231783. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231784. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231785. [NSGraphicsContext saveGraphicsState];
  231786. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231787. [image drawAtPoint: NSMakePoint (0, 0)
  231788. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231789. operation: NSCompositeSourceOver fraction: 1.0f];
  231790. [[NSGraphicsContext currentContext] flushGraphics];
  231791. [NSGraphicsContext restoreGraphicsState];
  231792. return Image (result);
  231793. }
  231794. const int KeyPress::spaceKey = ' ';
  231795. const int KeyPress::returnKey = 0x0d;
  231796. const int KeyPress::escapeKey = 0x1b;
  231797. const int KeyPress::backspaceKey = 0x7f;
  231798. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231799. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231800. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231801. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231802. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231803. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231804. const int KeyPress::endKey = NSEndFunctionKey;
  231805. const int KeyPress::homeKey = NSHomeFunctionKey;
  231806. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231807. const int KeyPress::insertKey = -1;
  231808. const int KeyPress::tabKey = 9;
  231809. const int KeyPress::F1Key = NSF1FunctionKey;
  231810. const int KeyPress::F2Key = NSF2FunctionKey;
  231811. const int KeyPress::F3Key = NSF3FunctionKey;
  231812. const int KeyPress::F4Key = NSF4FunctionKey;
  231813. const int KeyPress::F5Key = NSF5FunctionKey;
  231814. const int KeyPress::F6Key = NSF6FunctionKey;
  231815. const int KeyPress::F7Key = NSF7FunctionKey;
  231816. const int KeyPress::F8Key = NSF8FunctionKey;
  231817. const int KeyPress::F9Key = NSF9FunctionKey;
  231818. const int KeyPress::F10Key = NSF10FunctionKey;
  231819. const int KeyPress::F11Key = NSF1FunctionKey;
  231820. const int KeyPress::F12Key = NSF12FunctionKey;
  231821. const int KeyPress::F13Key = NSF13FunctionKey;
  231822. const int KeyPress::F14Key = NSF14FunctionKey;
  231823. const int KeyPress::F15Key = NSF15FunctionKey;
  231824. const int KeyPress::F16Key = NSF16FunctionKey;
  231825. const int KeyPress::numberPad0 = 0x30020;
  231826. const int KeyPress::numberPad1 = 0x30021;
  231827. const int KeyPress::numberPad2 = 0x30022;
  231828. const int KeyPress::numberPad3 = 0x30023;
  231829. const int KeyPress::numberPad4 = 0x30024;
  231830. const int KeyPress::numberPad5 = 0x30025;
  231831. const int KeyPress::numberPad6 = 0x30026;
  231832. const int KeyPress::numberPad7 = 0x30027;
  231833. const int KeyPress::numberPad8 = 0x30028;
  231834. const int KeyPress::numberPad9 = 0x30029;
  231835. const int KeyPress::numberPadAdd = 0x3002a;
  231836. const int KeyPress::numberPadSubtract = 0x3002b;
  231837. const int KeyPress::numberPadMultiply = 0x3002c;
  231838. const int KeyPress::numberPadDivide = 0x3002d;
  231839. const int KeyPress::numberPadSeparator = 0x3002e;
  231840. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231841. const int KeyPress::numberPadEquals = 0x30030;
  231842. const int KeyPress::numberPadDelete = 0x30031;
  231843. const int KeyPress::playKey = 0x30000;
  231844. const int KeyPress::stopKey = 0x30001;
  231845. const int KeyPress::fastForwardKey = 0x30002;
  231846. const int KeyPress::rewindKey = 0x30003;
  231847. #endif
  231848. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231849. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231850. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231851. // compiled on its own).
  231852. #if JUCE_INCLUDED_FILE
  231853. #if JUCE_MAC
  231854. namespace MouseCursorHelpers
  231855. {
  231856. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231857. {
  231858. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231859. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231860. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231861. [im release];
  231862. return c;
  231863. }
  231864. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231865. {
  231866. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231867. BufferedInputStream buf (fileStream, 4096);
  231868. PNGImageFormat pngFormat;
  231869. Image im (pngFormat.decodeImage (buf));
  231870. if (im.isValid())
  231871. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231872. jassertfalse;
  231873. return 0;
  231874. }
  231875. }
  231876. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231877. {
  231878. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231879. }
  231880. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231881. {
  231882. const ScopedAutoReleasePool pool;
  231883. NSCursor* c = 0;
  231884. switch (type)
  231885. {
  231886. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231887. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231888. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231889. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231890. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231891. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231892. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231893. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231894. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231895. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231896. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231897. case UpDownResizeCursor:
  231898. case TopEdgeResizeCursor:
  231899. case BottomEdgeResizeCursor:
  231900. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231901. case TopLeftCornerResizeCursor:
  231902. case BottomRightCornerResizeCursor:
  231903. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231904. case TopRightCornerResizeCursor:
  231905. case BottomLeftCornerResizeCursor:
  231906. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231907. case UpDownLeftRightResizeCursor:
  231908. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231909. default:
  231910. jassertfalse;
  231911. break;
  231912. }
  231913. [c retain];
  231914. return c;
  231915. }
  231916. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231917. {
  231918. [((NSCursor*) cursorHandle) release];
  231919. }
  231920. void MouseCursor::showInAllWindows() const
  231921. {
  231922. showInWindow (0);
  231923. }
  231924. void MouseCursor::showInWindow (ComponentPeer*) const
  231925. {
  231926. NSCursor* c = (NSCursor*) getHandle();
  231927. if (c == 0)
  231928. c = [NSCursor arrowCursor];
  231929. [c set];
  231930. }
  231931. #else
  231932. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231933. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231934. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231935. void MouseCursor::showInAllWindows() const {}
  231936. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231937. #endif
  231938. #endif
  231939. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231940. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231941. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231942. // compiled on its own).
  231943. #if JUCE_INCLUDED_FILE
  231944. class NSViewComponentInternal : public ComponentMovementWatcher
  231945. {
  231946. Component* const owner;
  231947. NSViewComponentPeer* currentPeer;
  231948. bool wasShowing;
  231949. public:
  231950. NSView* const view;
  231951. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  231952. : ComponentMovementWatcher (owner_),
  231953. owner (owner_),
  231954. currentPeer (0),
  231955. wasShowing (false),
  231956. view (view_)
  231957. {
  231958. [view_ retain];
  231959. if (owner_->isShowing())
  231960. componentPeerChanged();
  231961. }
  231962. ~NSViewComponentInternal()
  231963. {
  231964. [view removeFromSuperview];
  231965. [view release];
  231966. }
  231967. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231968. {
  231969. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231970. // The ComponentMovementWatcher version of this method avoids calling
  231971. // us when the top-level comp is resized, but for an NSView we need to know this
  231972. // because with inverted co-ords, we need to update the position even if the
  231973. // top-left pos hasn't changed
  231974. if (comp.isOnDesktop() && wasResized)
  231975. componentMovedOrResized (wasMoved, wasResized);
  231976. }
  231977. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231978. {
  231979. Component* const topComp = owner->getTopLevelComponent();
  231980. if (topComp->getPeer() != 0)
  231981. {
  231982. const Point<int> pos (topComp->getLocalPoint (owner, Point<int>()));
  231983. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  231984. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231985. [view setFrame: r];
  231986. }
  231987. }
  231988. void componentPeerChanged()
  231989. {
  231990. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  231991. if (currentPeer != peer)
  231992. {
  231993. if ([view superview] != nil)
  231994. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231995. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231996. currentPeer = peer;
  231997. if (peer != 0)
  231998. {
  231999. [peer->view addSubview: view];
  232000. componentMovedOrResized (false, false);
  232001. }
  232002. }
  232003. [view setHidden: ! owner->isShowing()];
  232004. }
  232005. void componentVisibilityChanged (Component&)
  232006. {
  232007. componentPeerChanged();
  232008. }
  232009. const Rectangle<int> getViewBounds() const
  232010. {
  232011. NSRect r = [view frame];
  232012. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232013. }
  232014. private:
  232015. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232016. };
  232017. NSViewComponent::NSViewComponent()
  232018. {
  232019. }
  232020. NSViewComponent::~NSViewComponent()
  232021. {
  232022. }
  232023. void NSViewComponent::setView (void* view)
  232024. {
  232025. if (view != getView())
  232026. {
  232027. if (view != 0)
  232028. info = new NSViewComponentInternal ((NSView*) view, this);
  232029. else
  232030. info = 0;
  232031. }
  232032. }
  232033. void* NSViewComponent::getView() const
  232034. {
  232035. return info == 0 ? 0 : info->view;
  232036. }
  232037. void NSViewComponent::resizeToFitView()
  232038. {
  232039. if (info != 0)
  232040. setBounds (info->getViewBounds());
  232041. }
  232042. void NSViewComponent::paint (Graphics&)
  232043. {
  232044. }
  232045. #endif
  232046. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232047. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232048. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232049. // compiled on its own).
  232050. #if JUCE_INCLUDED_FILE
  232051. AppleRemoteDevice::AppleRemoteDevice()
  232052. : device (0),
  232053. queue (0),
  232054. remoteId (0)
  232055. {
  232056. }
  232057. AppleRemoteDevice::~AppleRemoteDevice()
  232058. {
  232059. stop();
  232060. }
  232061. namespace
  232062. {
  232063. io_object_t getAppleRemoteDevice()
  232064. {
  232065. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232066. io_iterator_t iter = 0;
  232067. io_object_t iod = 0;
  232068. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232069. && iter != 0)
  232070. {
  232071. iod = IOIteratorNext (iter);
  232072. }
  232073. IOObjectRelease (iter);
  232074. return iod;
  232075. }
  232076. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232077. {
  232078. jassert (*device == 0);
  232079. io_name_t classname;
  232080. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232081. {
  232082. IOCFPlugInInterface** cfPlugInInterface = 0;
  232083. SInt32 score = 0;
  232084. if (IOCreatePlugInInterfaceForService (iod,
  232085. kIOHIDDeviceUserClientTypeID,
  232086. kIOCFPlugInInterfaceID,
  232087. &cfPlugInInterface,
  232088. &score) == kIOReturnSuccess)
  232089. {
  232090. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232091. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232092. device);
  232093. (void) hr;
  232094. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232095. }
  232096. }
  232097. return *device != 0;
  232098. }
  232099. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232100. {
  232101. if (result == kIOReturnSuccess)
  232102. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232103. }
  232104. }
  232105. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232106. {
  232107. if (queue != 0)
  232108. return true;
  232109. stop();
  232110. bool result = false;
  232111. io_object_t iod = getAppleRemoteDevice();
  232112. if (iod != 0)
  232113. {
  232114. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232115. result = true;
  232116. else
  232117. stop();
  232118. IOObjectRelease (iod);
  232119. }
  232120. return result;
  232121. }
  232122. void AppleRemoteDevice::stop()
  232123. {
  232124. if (queue != 0)
  232125. {
  232126. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232127. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232128. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232129. queue = 0;
  232130. }
  232131. if (device != 0)
  232132. {
  232133. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232134. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232135. device = 0;
  232136. }
  232137. }
  232138. bool AppleRemoteDevice::isActive() const
  232139. {
  232140. return queue != 0;
  232141. }
  232142. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232143. {
  232144. Array <int> cookies;
  232145. CFArrayRef elements;
  232146. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232147. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232148. return false;
  232149. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232150. {
  232151. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232152. // get the cookie
  232153. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232154. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232155. continue;
  232156. long number;
  232157. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232158. continue;
  232159. cookies.add ((int) number);
  232160. }
  232161. CFRelease (elements);
  232162. if ((*(IOHIDDeviceInterface**) device)
  232163. ->open ((IOHIDDeviceInterface**) device,
  232164. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232165. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232166. {
  232167. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232168. if (queue != 0)
  232169. {
  232170. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232171. for (int i = 0; i < cookies.size(); ++i)
  232172. {
  232173. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232174. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232175. }
  232176. CFRunLoopSourceRef eventSource;
  232177. if ((*(IOHIDQueueInterface**) queue)
  232178. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232179. {
  232180. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232181. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232182. {
  232183. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232184. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232185. return true;
  232186. }
  232187. }
  232188. }
  232189. }
  232190. return false;
  232191. }
  232192. void AppleRemoteDevice::handleCallbackInternal()
  232193. {
  232194. int totalValues = 0;
  232195. AbsoluteTime nullTime = { 0, 0 };
  232196. char cookies [12];
  232197. int numCookies = 0;
  232198. while (numCookies < numElementsInArray (cookies))
  232199. {
  232200. IOHIDEventStruct e;
  232201. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232202. break;
  232203. if ((int) e.elementCookie == 19)
  232204. {
  232205. remoteId = e.value;
  232206. buttonPressed (switched, false);
  232207. }
  232208. else
  232209. {
  232210. totalValues += e.value;
  232211. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232212. }
  232213. }
  232214. cookies [numCookies++] = 0;
  232215. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232216. static const char buttonPatterns[] =
  232217. {
  232218. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232219. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232220. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232221. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232222. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232223. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232224. 0x1f, 0x12, 0x04, 0x02, 0,
  232225. 0x1f, 0x12, 0x03, 0x02, 0,
  232226. 0x1f, 0x12, 0x1f, 0x12, 0,
  232227. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232228. 19, 0
  232229. };
  232230. int buttonNum = (int) menuButton;
  232231. int i = 0;
  232232. while (i < numElementsInArray (buttonPatterns))
  232233. {
  232234. if (strcmp (cookies, buttonPatterns + i) == 0)
  232235. {
  232236. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232237. break;
  232238. }
  232239. i += (int) strlen (buttonPatterns + i) + 1;
  232240. ++buttonNum;
  232241. }
  232242. }
  232243. #endif
  232244. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232245. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232246. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232247. // compiled on its own).
  232248. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232249. #if JUCE_MAC
  232250. END_JUCE_NAMESPACE
  232251. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232252. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232253. {
  232254. CriticalSection* contextLock;
  232255. bool needsUpdate;
  232256. }
  232257. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232258. - (bool) makeActive;
  232259. - (void) makeInactive;
  232260. - (void) reshape;
  232261. @end
  232262. @implementation ThreadSafeNSOpenGLView
  232263. - (id) initWithFrame: (NSRect) frameRect
  232264. pixelFormat: (NSOpenGLPixelFormat*) format
  232265. {
  232266. contextLock = new CriticalSection();
  232267. self = [super initWithFrame: frameRect pixelFormat: format];
  232268. if (self != nil)
  232269. [[NSNotificationCenter defaultCenter] addObserver: self
  232270. selector: @selector (_surfaceNeedsUpdate:)
  232271. name: NSViewGlobalFrameDidChangeNotification
  232272. object: self];
  232273. return self;
  232274. }
  232275. - (void) dealloc
  232276. {
  232277. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232278. delete contextLock;
  232279. [super dealloc];
  232280. }
  232281. - (bool) makeActive
  232282. {
  232283. const ScopedLock sl (*contextLock);
  232284. if ([self openGLContext] == 0)
  232285. return false;
  232286. [[self openGLContext] makeCurrentContext];
  232287. if (needsUpdate)
  232288. {
  232289. [super update];
  232290. needsUpdate = false;
  232291. }
  232292. return true;
  232293. }
  232294. - (void) makeInactive
  232295. {
  232296. const ScopedLock sl (*contextLock);
  232297. [NSOpenGLContext clearCurrentContext];
  232298. }
  232299. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232300. {
  232301. const ScopedLock sl (*contextLock);
  232302. needsUpdate = true;
  232303. }
  232304. - (void) update
  232305. {
  232306. const ScopedLock sl (*contextLock);
  232307. needsUpdate = true;
  232308. }
  232309. - (void) reshape
  232310. {
  232311. const ScopedLock sl (*contextLock);
  232312. needsUpdate = true;
  232313. }
  232314. @end
  232315. BEGIN_JUCE_NAMESPACE
  232316. class WindowedGLContext : public OpenGLContext
  232317. {
  232318. public:
  232319. WindowedGLContext (Component* const component,
  232320. const OpenGLPixelFormat& pixelFormat_,
  232321. NSOpenGLContext* sharedContext)
  232322. : renderContext (0),
  232323. pixelFormat (pixelFormat_)
  232324. {
  232325. jassert (component != 0);
  232326. NSOpenGLPixelFormatAttribute attribs [64];
  232327. int n = 0;
  232328. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232329. attribs[n++] = NSOpenGLPFAAccelerated;
  232330. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232331. attribs[n++] = NSOpenGLPFAColorSize;
  232332. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232333. pixelFormat.greenBits,
  232334. pixelFormat.blueBits);
  232335. attribs[n++] = NSOpenGLPFAAlphaSize;
  232336. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232337. attribs[n++] = NSOpenGLPFADepthSize;
  232338. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232339. attribs[n++] = NSOpenGLPFAStencilSize;
  232340. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232341. attribs[n++] = NSOpenGLPFAAccumSize;
  232342. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232343. pixelFormat.accumulationBufferGreenBits,
  232344. pixelFormat.accumulationBufferBlueBits,
  232345. pixelFormat.accumulationBufferAlphaBits);
  232346. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232347. attribs[n++] = NSOpenGLPFASampleBuffers;
  232348. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232349. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232350. attribs[n++] = NSOpenGLPFANoRecovery;
  232351. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232352. NSOpenGLPixelFormat* format
  232353. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232354. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232355. pixelFormat: format];
  232356. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232357. shareContext: sharedContext] autorelease];
  232358. const GLint swapInterval = 1;
  232359. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232360. [view setOpenGLContext: renderContext];
  232361. [format release];
  232362. viewHolder = new NSViewComponentInternal (view, component);
  232363. }
  232364. ~WindowedGLContext()
  232365. {
  232366. deleteContext();
  232367. viewHolder = 0;
  232368. }
  232369. void deleteContext()
  232370. {
  232371. makeInactive();
  232372. [renderContext clearDrawable];
  232373. [renderContext setView: nil];
  232374. [view setOpenGLContext: nil];
  232375. renderContext = nil;
  232376. }
  232377. bool makeActive() const throw()
  232378. {
  232379. jassert (renderContext != 0);
  232380. if ([renderContext view] != view)
  232381. [renderContext setView: view];
  232382. [view makeActive];
  232383. return isActive();
  232384. }
  232385. bool makeInactive() const throw()
  232386. {
  232387. [view makeInactive];
  232388. return true;
  232389. }
  232390. bool isActive() const throw()
  232391. {
  232392. return [NSOpenGLContext currentContext] == renderContext;
  232393. }
  232394. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232395. void* getRawContext() const throw() { return renderContext; }
  232396. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232397. {
  232398. }
  232399. void swapBuffers()
  232400. {
  232401. [renderContext flushBuffer];
  232402. }
  232403. bool setSwapInterval (const int numFramesPerSwap)
  232404. {
  232405. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232406. forParameter: NSOpenGLCPSwapInterval];
  232407. return true;
  232408. }
  232409. int getSwapInterval() const
  232410. {
  232411. GLint numFrames = 0;
  232412. [renderContext getValues: &numFrames
  232413. forParameter: NSOpenGLCPSwapInterval];
  232414. return numFrames;
  232415. }
  232416. void repaint()
  232417. {
  232418. // we need to invalidate the juce view that holds this gl view, to make it
  232419. // cause a repaint callback
  232420. NSView* v = (NSView*) viewHolder->view;
  232421. NSRect r = [v frame];
  232422. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232423. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232424. // repaint message, thus never causing our paint() callback, and never repainting
  232425. // the comp. So invalidating just a little bit around the edge helps..
  232426. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232427. }
  232428. void* getNativeWindowHandle() const { return viewHolder->view; }
  232429. NSOpenGLContext* renderContext;
  232430. ThreadSafeNSOpenGLView* view;
  232431. private:
  232432. OpenGLPixelFormat pixelFormat;
  232433. ScopedPointer <NSViewComponentInternal> viewHolder;
  232434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232435. };
  232436. OpenGLContext* OpenGLComponent::createContext()
  232437. {
  232438. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232439. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232440. return (c->renderContext != 0) ? c.release() : 0;
  232441. }
  232442. void* OpenGLComponent::getNativeWindowHandle() const
  232443. {
  232444. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232445. : 0;
  232446. }
  232447. void juce_glViewport (const int w, const int h)
  232448. {
  232449. glViewport (0, 0, w, h);
  232450. }
  232451. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232452. OwnedArray <OpenGLPixelFormat>& results)
  232453. {
  232454. /* GLint attribs [64];
  232455. int n = 0;
  232456. attribs[n++] = AGL_RGBA;
  232457. attribs[n++] = AGL_DOUBLEBUFFER;
  232458. attribs[n++] = AGL_ACCELERATED;
  232459. attribs[n++] = AGL_NO_RECOVERY;
  232460. attribs[n++] = AGL_NONE;
  232461. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232462. while (p != 0)
  232463. {
  232464. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232465. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232466. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232467. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232468. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232469. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232470. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232471. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232472. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232473. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232474. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232475. results.add (pf);
  232476. p = aglNextPixelFormat (p);
  232477. }*/
  232478. //jassertfalse // can't see how you do this in cocoa!
  232479. }
  232480. #else
  232481. END_JUCE_NAMESPACE
  232482. @interface JuceGLView : UIView
  232483. {
  232484. }
  232485. + (Class) layerClass;
  232486. @end
  232487. @implementation JuceGLView
  232488. + (Class) layerClass
  232489. {
  232490. return [CAEAGLLayer class];
  232491. }
  232492. @end
  232493. BEGIN_JUCE_NAMESPACE
  232494. class GLESContext : public OpenGLContext
  232495. {
  232496. public:
  232497. GLESContext (UIViewComponentPeer* peer,
  232498. Component* const component_,
  232499. const OpenGLPixelFormat& pixelFormat_,
  232500. const GLESContext* const sharedContext,
  232501. NSUInteger apiType)
  232502. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232503. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232504. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232505. {
  232506. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232507. view.opaque = YES;
  232508. view.hidden = NO;
  232509. view.backgroundColor = [UIColor blackColor];
  232510. view.userInteractionEnabled = NO;
  232511. glLayer = (CAEAGLLayer*) [view layer];
  232512. [peer->view addSubview: view];
  232513. if (sharedContext != 0)
  232514. context = [[EAGLContext alloc] initWithAPI: apiType
  232515. sharegroup: [sharedContext->context sharegroup]];
  232516. else
  232517. context = [[EAGLContext alloc] initWithAPI: apiType];
  232518. createGLBuffers();
  232519. }
  232520. ~GLESContext()
  232521. {
  232522. deleteContext();
  232523. [view removeFromSuperview];
  232524. [view release];
  232525. freeGLBuffers();
  232526. }
  232527. void deleteContext()
  232528. {
  232529. makeInactive();
  232530. [context release];
  232531. context = nil;
  232532. }
  232533. bool makeActive() const throw()
  232534. {
  232535. jassert (context != 0);
  232536. [EAGLContext setCurrentContext: context];
  232537. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232538. return true;
  232539. }
  232540. void swapBuffers()
  232541. {
  232542. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232543. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232544. }
  232545. bool makeInactive() const throw()
  232546. {
  232547. return [EAGLContext setCurrentContext: nil];
  232548. }
  232549. bool isActive() const throw()
  232550. {
  232551. return [EAGLContext currentContext] == context;
  232552. }
  232553. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232554. void* getRawContext() const throw() { return glLayer; }
  232555. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232556. {
  232557. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232558. if (lastWidth != w || lastHeight != h)
  232559. {
  232560. lastWidth = w;
  232561. lastHeight = h;
  232562. freeGLBuffers();
  232563. createGLBuffers();
  232564. }
  232565. }
  232566. bool setSwapInterval (const int numFramesPerSwap)
  232567. {
  232568. numFrames = numFramesPerSwap;
  232569. return true;
  232570. }
  232571. int getSwapInterval() const
  232572. {
  232573. return numFrames;
  232574. }
  232575. void repaint()
  232576. {
  232577. }
  232578. void createGLBuffers()
  232579. {
  232580. makeActive();
  232581. glGenFramebuffersOES (1, &frameBufferHandle);
  232582. glGenRenderbuffersOES (1, &colorBufferHandle);
  232583. glGenRenderbuffersOES (1, &depthBufferHandle);
  232584. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232585. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232586. GLint width, height;
  232587. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232588. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232589. if (useDepthBuffer)
  232590. {
  232591. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232592. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232593. }
  232594. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232595. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232596. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232597. if (useDepthBuffer)
  232598. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232599. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232600. }
  232601. void freeGLBuffers()
  232602. {
  232603. if (frameBufferHandle != 0)
  232604. {
  232605. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232606. frameBufferHandle = 0;
  232607. }
  232608. if (colorBufferHandle != 0)
  232609. {
  232610. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232611. colorBufferHandle = 0;
  232612. }
  232613. if (depthBufferHandle != 0)
  232614. {
  232615. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232616. depthBufferHandle = 0;
  232617. }
  232618. }
  232619. private:
  232620. Component::SafePointer<Component> component;
  232621. OpenGLPixelFormat pixelFormat;
  232622. JuceGLView* view;
  232623. CAEAGLLayer* glLayer;
  232624. EAGLContext* context;
  232625. bool useDepthBuffer;
  232626. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232627. int numFrames;
  232628. int lastWidth, lastHeight;
  232629. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232630. };
  232631. OpenGLContext* OpenGLComponent::createContext()
  232632. {
  232633. ScopedAutoReleasePool pool;
  232634. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232635. if (peer != 0)
  232636. return new GLESContext (peer, this, preferredPixelFormat,
  232637. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232638. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232639. return 0;
  232640. }
  232641. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232642. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232643. {
  232644. }
  232645. void juce_glViewport (const int w, const int h)
  232646. {
  232647. glViewport (0, 0, w, h);
  232648. }
  232649. #endif
  232650. #endif
  232651. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232652. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232653. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232654. // compiled on its own).
  232655. #if JUCE_INCLUDED_FILE
  232656. class JuceMainMenuHandler;
  232657. END_JUCE_NAMESPACE
  232658. using namespace JUCE_NAMESPACE;
  232659. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232660. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232661. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232662. #else
  232663. @interface JuceMenuCallback : NSObject
  232664. #endif
  232665. {
  232666. JuceMainMenuHandler* owner;
  232667. }
  232668. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232669. - (void) dealloc;
  232670. - (void) menuItemInvoked: (id) menu;
  232671. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232672. @end
  232673. BEGIN_JUCE_NAMESPACE
  232674. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232675. private DeletedAtShutdown
  232676. {
  232677. public:
  232678. JuceMainMenuHandler()
  232679. : currentModel (0),
  232680. lastUpdateTime (0)
  232681. {
  232682. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232683. }
  232684. ~JuceMainMenuHandler()
  232685. {
  232686. setMenu (0);
  232687. jassert (instance == this);
  232688. instance = 0;
  232689. [callback release];
  232690. }
  232691. void setMenu (MenuBarModel* const newMenuBarModel)
  232692. {
  232693. if (currentModel != newMenuBarModel)
  232694. {
  232695. if (currentModel != 0)
  232696. currentModel->removeListener (this);
  232697. currentModel = newMenuBarModel;
  232698. if (currentModel != 0)
  232699. currentModel->addListener (this);
  232700. menuBarItemsChanged (0);
  232701. }
  232702. }
  232703. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232704. const String& name, const int menuId, const int tag)
  232705. {
  232706. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232707. action: nil
  232708. keyEquivalent: @""];
  232709. [item setTag: tag];
  232710. NSMenu* sub = createMenu (child, name, menuId, tag);
  232711. [parent setSubmenu: sub forItem: item];
  232712. [sub setAutoenablesItems: false];
  232713. [sub release];
  232714. }
  232715. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232716. const String& name, const int menuId, const int tag)
  232717. {
  232718. [parentItem setTag: tag];
  232719. NSMenu* menu = [parentItem submenu];
  232720. [menu setTitle: juceStringToNS (name)];
  232721. while ([menu numberOfItems] > 0)
  232722. [menu removeItemAtIndex: 0];
  232723. PopupMenu::MenuItemIterator iter (menuToCopy);
  232724. while (iter.next())
  232725. addMenuItem (iter, menu, menuId, tag);
  232726. [menu setAutoenablesItems: false];
  232727. [menu update];
  232728. }
  232729. void menuBarItemsChanged (MenuBarModel*)
  232730. {
  232731. lastUpdateTime = Time::getMillisecondCounter();
  232732. StringArray menuNames;
  232733. if (currentModel != 0)
  232734. menuNames = currentModel->getMenuBarNames();
  232735. NSMenu* menuBar = [NSApp mainMenu];
  232736. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232737. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232738. int menuId = 1;
  232739. for (int i = 0; i < menuNames.size(); ++i)
  232740. {
  232741. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232742. if (i >= [menuBar numberOfItems] - 1)
  232743. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232744. else
  232745. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232746. }
  232747. }
  232748. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232749. {
  232750. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232751. if (item != 0)
  232752. flashMenuBar ([item menu]);
  232753. }
  232754. void updateMenus (NSMenu* menu)
  232755. {
  232756. if (PopupMenu::dismissAllActiveMenus())
  232757. {
  232758. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232759. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232760. if ([menu respondsToSelector: @selector (cancelTracking)])
  232761. [menu performSelector: @selector (cancelTracking)];
  232762. }
  232763. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232764. menuBarItemsChanged (0);
  232765. }
  232766. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232767. {
  232768. if (currentModel != 0)
  232769. {
  232770. if (commandManager != 0)
  232771. {
  232772. ApplicationCommandTarget::InvocationInfo info (commandId);
  232773. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232774. commandManager->invoke (info, true);
  232775. }
  232776. currentModel->menuItemSelected (commandId, topLevelIndex);
  232777. }
  232778. }
  232779. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232780. const int topLevelMenuId, const int topLevelIndex)
  232781. {
  232782. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232783. if (text == 0)
  232784. text = @"";
  232785. if (iter.isSeparator)
  232786. {
  232787. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232788. }
  232789. else if (iter.isSectionHeader)
  232790. {
  232791. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232792. action: nil
  232793. keyEquivalent: @""];
  232794. [item setEnabled: false];
  232795. }
  232796. else if (iter.subMenu != 0)
  232797. {
  232798. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232799. action: nil
  232800. keyEquivalent: @""];
  232801. [item setTag: iter.itemId];
  232802. [item setEnabled: iter.isEnabled];
  232803. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232804. [sub setDelegate: nil];
  232805. [menuToAddTo setSubmenu: sub forItem: item];
  232806. [sub release];
  232807. }
  232808. else
  232809. {
  232810. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232811. action: @selector (menuItemInvoked:)
  232812. keyEquivalent: @""];
  232813. [item setTag: iter.itemId];
  232814. [item setEnabled: iter.isEnabled];
  232815. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232816. [item setTarget: (id) callback];
  232817. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232818. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232819. [item setRepresentedObject: info];
  232820. if (iter.commandManager != 0)
  232821. {
  232822. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232823. ->getKeyPressesAssignedToCommand (iter.itemId));
  232824. if (keyPresses.size() > 0)
  232825. {
  232826. const KeyPress& kp = keyPresses.getReference(0);
  232827. if (kp.getKeyCode() != KeyPress::backspaceKey
  232828. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232829. // every time you press the key while editing text)
  232830. {
  232831. juce_wchar key = kp.getTextCharacter();
  232832. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232833. key = NSBackspaceCharacter;
  232834. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232835. key = NSDeleteCharacter;
  232836. else if (key == 0)
  232837. key = (juce_wchar) kp.getKeyCode();
  232838. unsigned int mods = 0;
  232839. if (kp.getModifiers().isShiftDown())
  232840. mods |= NSShiftKeyMask;
  232841. if (kp.getModifiers().isCtrlDown())
  232842. mods |= NSControlKeyMask;
  232843. if (kp.getModifiers().isAltDown())
  232844. mods |= NSAlternateKeyMask;
  232845. if (kp.getModifiers().isCommandDown())
  232846. mods |= NSCommandKeyMask;
  232847. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232848. [item setKeyEquivalentModifierMask: mods];
  232849. }
  232850. }
  232851. }
  232852. }
  232853. }
  232854. static JuceMainMenuHandler* instance;
  232855. MenuBarModel* currentModel;
  232856. uint32 lastUpdateTime;
  232857. JuceMenuCallback* callback;
  232858. private:
  232859. NSMenu* createMenu (const PopupMenu menu,
  232860. const String& menuName,
  232861. const int topLevelMenuId,
  232862. const int topLevelIndex)
  232863. {
  232864. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232865. [m setAutoenablesItems: false];
  232866. [m setDelegate: callback];
  232867. PopupMenu::MenuItemIterator iter (menu);
  232868. while (iter.next())
  232869. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232870. [m update];
  232871. return m;
  232872. }
  232873. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232874. {
  232875. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232876. {
  232877. NSMenuItem* m = [menu itemAtIndex: i];
  232878. if ([m tag] == info.commandID)
  232879. return m;
  232880. if ([m submenu] != 0)
  232881. {
  232882. NSMenuItem* found = findMenuItem ([m submenu], info);
  232883. if (found != 0)
  232884. return found;
  232885. }
  232886. }
  232887. return 0;
  232888. }
  232889. static void flashMenuBar (NSMenu* menu)
  232890. {
  232891. if ([[menu title] isEqualToString: @"Apple"])
  232892. return;
  232893. [menu retain];
  232894. const unichar f35Key = NSF35FunctionKey;
  232895. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232896. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232897. action: nil
  232898. keyEquivalent: f35String];
  232899. [item setTarget: nil];
  232900. [menu insertItem: item atIndex: [menu numberOfItems]];
  232901. [item release];
  232902. if ([menu indexOfItem: item] >= 0)
  232903. {
  232904. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232905. location: NSZeroPoint
  232906. modifierFlags: NSCommandKeyMask
  232907. timestamp: 0
  232908. windowNumber: 0
  232909. context: [NSGraphicsContext currentContext]
  232910. characters: f35String
  232911. charactersIgnoringModifiers: f35String
  232912. isARepeat: NO
  232913. keyCode: 0];
  232914. [menu performKeyEquivalent: f35Event];
  232915. if ([menu indexOfItem: item] >= 0)
  232916. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232917. }
  232918. [menu release];
  232919. }
  232920. };
  232921. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232922. END_JUCE_NAMESPACE
  232923. @implementation JuceMenuCallback
  232924. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232925. {
  232926. [super init];
  232927. owner = owner_;
  232928. return self;
  232929. }
  232930. - (void) dealloc
  232931. {
  232932. [super dealloc];
  232933. }
  232934. - (void) menuItemInvoked: (id) menu
  232935. {
  232936. NSMenuItem* item = (NSMenuItem*) menu;
  232937. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232938. {
  232939. // 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
  232940. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232941. // into the focused component and let it trigger the menu item indirectly.
  232942. NSEvent* e = [NSApp currentEvent];
  232943. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232944. {
  232945. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232946. {
  232947. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232948. if (peer != 0)
  232949. {
  232950. if ([e type] == NSKeyDown)
  232951. peer->redirectKeyDown (e);
  232952. else
  232953. peer->redirectKeyUp (e);
  232954. return;
  232955. }
  232956. }
  232957. }
  232958. NSArray* info = (NSArray*) [item representedObject];
  232959. owner->invoke ((int) [item tag],
  232960. (ApplicationCommandManager*) (pointer_sized_int)
  232961. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232962. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232963. }
  232964. }
  232965. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232966. {
  232967. if (JuceMainMenuHandler::instance != 0)
  232968. JuceMainMenuHandler::instance->updateMenus (menu);
  232969. }
  232970. @end
  232971. BEGIN_JUCE_NAMESPACE
  232972. namespace MainMenuHelpers
  232973. {
  232974. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232975. {
  232976. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232977. {
  232978. PopupMenu::MenuItemIterator iter (*extraItems);
  232979. while (iter.next())
  232980. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232981. [menu addItem: [NSMenuItem separatorItem]];
  232982. }
  232983. NSMenuItem* item;
  232984. // Services...
  232985. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232986. action: nil keyEquivalent: @""];
  232987. [menu addItem: item];
  232988. [item release];
  232989. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232990. [menu setSubmenu: servicesMenu forItem: item];
  232991. [NSApp setServicesMenu: servicesMenu];
  232992. [servicesMenu release];
  232993. [menu addItem: [NSMenuItem separatorItem]];
  232994. // Hide + Show stuff...
  232995. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232996. action: @selector (hide:) keyEquivalent: @"h"];
  232997. [item setTarget: NSApp];
  232998. [menu addItem: item];
  232999. [item release];
  233000. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233001. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233002. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233003. [item setTarget: NSApp];
  233004. [menu addItem: item];
  233005. [item release];
  233006. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233007. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233008. [item setTarget: NSApp];
  233009. [menu addItem: item];
  233010. [item release];
  233011. [menu addItem: [NSMenuItem separatorItem]];
  233012. // Quit item....
  233013. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233014. action: @selector (terminate:) keyEquivalent: @"q"];
  233015. [item setTarget: NSApp];
  233016. [menu addItem: item];
  233017. [item release];
  233018. return menu;
  233019. }
  233020. // Since our app has no NIB, this initialises a standard app menu...
  233021. void rebuildMainMenu (const PopupMenu* extraItems)
  233022. {
  233023. // this can't be used in a plugin!
  233024. jassert (JUCEApplication::isStandaloneApp());
  233025. if (JUCEApplication::getInstance() != 0)
  233026. {
  233027. const ScopedAutoReleasePool pool;
  233028. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233029. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233030. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233031. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233032. [mainMenu setSubmenu: appMenu forItem: item];
  233033. [NSApp setMainMenu: mainMenu];
  233034. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233035. [appMenu release];
  233036. [mainMenu release];
  233037. }
  233038. }
  233039. }
  233040. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233041. const PopupMenu* extraAppleMenuItems)
  233042. {
  233043. if (getMacMainMenu() != newMenuBarModel)
  233044. {
  233045. const ScopedAutoReleasePool pool;
  233046. if (newMenuBarModel == 0)
  233047. {
  233048. delete JuceMainMenuHandler::instance;
  233049. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233050. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233051. extraAppleMenuItems = 0;
  233052. }
  233053. else
  233054. {
  233055. if (JuceMainMenuHandler::instance == 0)
  233056. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233057. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233058. }
  233059. }
  233060. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233061. if (newMenuBarModel != 0)
  233062. newMenuBarModel->menuItemsChanged();
  233063. }
  233064. MenuBarModel* MenuBarModel::getMacMainMenu()
  233065. {
  233066. return JuceMainMenuHandler::instance != 0
  233067. ? JuceMainMenuHandler::instance->currentModel : 0;
  233068. }
  233069. void juce_initialiseMacMainMenu()
  233070. {
  233071. if (JuceMainMenuHandler::instance == 0)
  233072. MainMenuHelpers::rebuildMainMenu (0);
  233073. }
  233074. #endif
  233075. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233076. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233077. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233078. // compiled on its own).
  233079. #if JUCE_INCLUDED_FILE
  233080. #if JUCE_MAC
  233081. END_JUCE_NAMESPACE
  233082. using namespace JUCE_NAMESPACE;
  233083. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233084. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233085. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233086. #else
  233087. @interface JuceFileChooserDelegate : NSObject
  233088. #endif
  233089. {
  233090. StringArray* filters;
  233091. }
  233092. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233093. - (void) dealloc;
  233094. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233095. @end
  233096. @implementation JuceFileChooserDelegate
  233097. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233098. {
  233099. [super init];
  233100. filters = filters_;
  233101. return self;
  233102. }
  233103. - (void) dealloc
  233104. {
  233105. delete filters;
  233106. [super dealloc];
  233107. }
  233108. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233109. {
  233110. (void) sender;
  233111. const File f (nsStringToJuce (filename));
  233112. for (int i = filters->size(); --i >= 0;)
  233113. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233114. return true;
  233115. return f.isDirectory();
  233116. }
  233117. @end
  233118. BEGIN_JUCE_NAMESPACE
  233119. void FileChooser::showPlatformDialog (Array<File>& results,
  233120. const String& title,
  233121. const File& currentFileOrDirectory,
  233122. const String& filter,
  233123. bool selectsDirectory,
  233124. bool selectsFiles,
  233125. bool isSaveDialogue,
  233126. bool warnAboutOverwritingExistingFiles,
  233127. bool selectMultipleFiles,
  233128. FilePreviewComponent* extraInfoComponent)
  233129. {
  233130. const ScopedAutoReleasePool pool;
  233131. StringArray* filters = new StringArray();
  233132. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233133. filters->trim();
  233134. filters->removeEmptyStrings();
  233135. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233136. [delegate autorelease];
  233137. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233138. : [NSOpenPanel openPanel];
  233139. [panel setTitle: juceStringToNS (title)];
  233140. if (! isSaveDialogue)
  233141. {
  233142. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233143. [openPanel setCanChooseDirectories: selectsDirectory];
  233144. [openPanel setCanChooseFiles: selectsFiles];
  233145. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233146. }
  233147. [panel setDelegate: delegate];
  233148. if (isSaveDialogue || selectsDirectory)
  233149. [panel setCanCreateDirectories: YES];
  233150. String directory, filename;
  233151. if (currentFileOrDirectory.isDirectory())
  233152. {
  233153. directory = currentFileOrDirectory.getFullPathName();
  233154. }
  233155. else
  233156. {
  233157. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233158. filename = currentFileOrDirectory.getFileName();
  233159. }
  233160. if ([panel runModalForDirectory: juceStringToNS (directory)
  233161. file: juceStringToNS (filename)]
  233162. == NSOKButton)
  233163. {
  233164. if (isSaveDialogue)
  233165. {
  233166. results.add (File (nsStringToJuce ([panel filename])));
  233167. }
  233168. else
  233169. {
  233170. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233171. NSArray* urls = [openPanel filenames];
  233172. for (unsigned int i = 0; i < [urls count]; ++i)
  233173. {
  233174. NSString* f = [urls objectAtIndex: i];
  233175. results.add (File (nsStringToJuce (f)));
  233176. }
  233177. }
  233178. }
  233179. [panel setDelegate: nil];
  233180. }
  233181. #else
  233182. void FileChooser::showPlatformDialog (Array<File>& results,
  233183. const String& title,
  233184. const File& currentFileOrDirectory,
  233185. const String& filter,
  233186. bool selectsDirectory,
  233187. bool selectsFiles,
  233188. bool isSaveDialogue,
  233189. bool warnAboutOverwritingExistingFiles,
  233190. bool selectMultipleFiles,
  233191. FilePreviewComponent* extraInfoComponent)
  233192. {
  233193. const ScopedAutoReleasePool pool;
  233194. jassertfalse; //xxx to do
  233195. }
  233196. #endif
  233197. #endif
  233198. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233199. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233200. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233201. // compiled on its own).
  233202. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233203. END_JUCE_NAMESPACE
  233204. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233205. @interface NonInterceptingQTMovieView : QTMovieView
  233206. {
  233207. }
  233208. - (id) initWithFrame: (NSRect) frame;
  233209. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233210. - (NSView*) hitTest: (NSPoint) p;
  233211. @end
  233212. @implementation NonInterceptingQTMovieView
  233213. - (id) initWithFrame: (NSRect) frame
  233214. {
  233215. self = [super initWithFrame: frame];
  233216. [self setNextResponder: [self superview]];
  233217. return self;
  233218. }
  233219. - (void) dealloc
  233220. {
  233221. [super dealloc];
  233222. }
  233223. - (NSView*) hitTest: (NSPoint) point
  233224. {
  233225. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233226. }
  233227. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233228. {
  233229. return YES;
  233230. }
  233231. @end
  233232. BEGIN_JUCE_NAMESPACE
  233233. #define theMovie (static_cast <QTMovie*> (movie))
  233234. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233235. : movie (0)
  233236. {
  233237. setOpaque (true);
  233238. setVisible (true);
  233239. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233240. setView (view);
  233241. [view release];
  233242. }
  233243. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233244. {
  233245. closeMovie();
  233246. setView (0);
  233247. }
  233248. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233249. {
  233250. return true;
  233251. }
  233252. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233253. {
  233254. // unfortunately, QTMovie objects can only be created on the main thread..
  233255. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233256. QTMovie* movie = 0;
  233257. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233258. if (fin != 0)
  233259. {
  233260. movieFile = fin->getFile();
  233261. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233262. error: nil];
  233263. }
  233264. else
  233265. {
  233266. MemoryBlock temp;
  233267. movieStream->readIntoMemoryBlock (temp);
  233268. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233269. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233270. {
  233271. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233272. length: temp.getSize()]
  233273. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233274. MIMEType: @""]
  233275. error: nil];
  233276. if (movie != 0)
  233277. break;
  233278. }
  233279. }
  233280. return movie;
  233281. }
  233282. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233283. const bool isControllerVisible_)
  233284. {
  233285. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233286. }
  233287. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233288. const bool controllerVisible_)
  233289. {
  233290. closeMovie();
  233291. if (getPeer() == 0)
  233292. {
  233293. // To open a movie, this component must be visible inside a functioning window, so that
  233294. // the QT control can be assigned to the window.
  233295. jassertfalse;
  233296. return false;
  233297. }
  233298. movie = openMovieFromStream (movieStream, movieFile);
  233299. [theMovie retain];
  233300. QTMovieView* view = (QTMovieView*) getView();
  233301. [view setMovie: theMovie];
  233302. [view setControllerVisible: controllerVisible_];
  233303. setLooping (looping);
  233304. return movie != nil;
  233305. }
  233306. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233307. const bool isControllerVisible_)
  233308. {
  233309. // unfortunately, QTMovie objects can only be created on the main thread..
  233310. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233311. closeMovie();
  233312. if (getPeer() == 0)
  233313. {
  233314. // To open a movie, this component must be visible inside a functioning window, so that
  233315. // the QT control can be assigned to the window.
  233316. jassertfalse;
  233317. return false;
  233318. }
  233319. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233320. NSError* err;
  233321. if ([QTMovie canInitWithURL: url])
  233322. movie = [QTMovie movieWithURL: url error: &err];
  233323. [theMovie retain];
  233324. QTMovieView* view = (QTMovieView*) getView();
  233325. [view setMovie: theMovie];
  233326. [view setControllerVisible: controllerVisible];
  233327. setLooping (looping);
  233328. return movie != nil;
  233329. }
  233330. void QuickTimeMovieComponent::closeMovie()
  233331. {
  233332. stop();
  233333. QTMovieView* view = (QTMovieView*) getView();
  233334. [view setMovie: nil];
  233335. [theMovie release];
  233336. movie = 0;
  233337. movieFile = File::nonexistent;
  233338. }
  233339. bool QuickTimeMovieComponent::isMovieOpen() const
  233340. {
  233341. return movie != nil;
  233342. }
  233343. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233344. {
  233345. return movieFile;
  233346. }
  233347. void QuickTimeMovieComponent::play()
  233348. {
  233349. [theMovie play];
  233350. }
  233351. void QuickTimeMovieComponent::stop()
  233352. {
  233353. [theMovie stop];
  233354. }
  233355. bool QuickTimeMovieComponent::isPlaying() const
  233356. {
  233357. return movie != 0 && [theMovie rate] != 0;
  233358. }
  233359. void QuickTimeMovieComponent::setPosition (const double seconds)
  233360. {
  233361. if (movie != 0)
  233362. {
  233363. QTTime t;
  233364. t.timeValue = (uint64) (100000.0 * seconds);
  233365. t.timeScale = 100000;
  233366. t.flags = 0;
  233367. [theMovie setCurrentTime: t];
  233368. }
  233369. }
  233370. double QuickTimeMovieComponent::getPosition() const
  233371. {
  233372. if (movie == 0)
  233373. return 0.0;
  233374. QTTime t = [theMovie currentTime];
  233375. return t.timeValue / (double) t.timeScale;
  233376. }
  233377. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233378. {
  233379. [theMovie setRate: newSpeed];
  233380. }
  233381. double QuickTimeMovieComponent::getMovieDuration() const
  233382. {
  233383. if (movie == 0)
  233384. return 0.0;
  233385. QTTime t = [theMovie duration];
  233386. return t.timeValue / (double) t.timeScale;
  233387. }
  233388. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233389. {
  233390. looping = shouldLoop;
  233391. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233392. forKey: QTMovieLoopsAttribute];
  233393. }
  233394. bool QuickTimeMovieComponent::isLooping() const
  233395. {
  233396. return looping;
  233397. }
  233398. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233399. {
  233400. [theMovie setVolume: newVolume];
  233401. }
  233402. float QuickTimeMovieComponent::getMovieVolume() const
  233403. {
  233404. return movie != 0 ? [theMovie volume] : 0.0f;
  233405. }
  233406. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233407. {
  233408. width = 0;
  233409. height = 0;
  233410. if (movie != 0)
  233411. {
  233412. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233413. width = (int) s.width;
  233414. height = (int) s.height;
  233415. }
  233416. }
  233417. void QuickTimeMovieComponent::paint (Graphics& g)
  233418. {
  233419. if (movie == 0)
  233420. g.fillAll (Colours::black);
  233421. }
  233422. bool QuickTimeMovieComponent::isControllerVisible() const
  233423. {
  233424. return controllerVisible;
  233425. }
  233426. void QuickTimeMovieComponent::goToStart()
  233427. {
  233428. setPosition (0.0);
  233429. }
  233430. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233431. const RectanglePlacement& placement)
  233432. {
  233433. int normalWidth, normalHeight;
  233434. getMovieNormalSize (normalWidth, normalHeight);
  233435. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233436. {
  233437. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233438. placement.applyTo (x, y, w, h,
  233439. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233440. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233441. if (w > 0 && h > 0)
  233442. {
  233443. setBounds (roundToInt (x), roundToInt (y),
  233444. roundToInt (w), roundToInt (h));
  233445. }
  233446. }
  233447. else
  233448. {
  233449. setBounds (spaceToFitWithin);
  233450. }
  233451. }
  233452. #if ! (JUCE_MAC && JUCE_64BIT)
  233453. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233454. {
  233455. if (movieStream == 0)
  233456. return false;
  233457. File file;
  233458. QTMovie* movie = openMovieFromStream (movieStream, file);
  233459. if (movie != nil)
  233460. result = [movie quickTimeMovie];
  233461. return movie != nil;
  233462. }
  233463. #endif
  233464. #endif
  233465. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233466. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233467. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233468. // compiled on its own).
  233469. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233470. const int kilobytesPerSecond1x = 176;
  233471. END_JUCE_NAMESPACE
  233472. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233473. @interface OpenDiskDevice : NSObject
  233474. {
  233475. @public
  233476. DRDevice* device;
  233477. NSMutableArray* tracks;
  233478. bool underrunProtection;
  233479. }
  233480. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233481. - (void) dealloc;
  233482. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233483. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233484. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233485. @end
  233486. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233487. @interface AudioTrackProducer : NSObject
  233488. {
  233489. JUCE_NAMESPACE::AudioSource* source;
  233490. int readPosition, lengthInFrames;
  233491. }
  233492. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233493. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233494. - (void) dealloc;
  233495. - (void) setupTrackProperties: (DRTrack*) track;
  233496. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233497. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233498. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233499. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233500. toMedia:(NSDictionary*)mediaInfo;
  233501. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233502. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233503. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233504. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233505. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233506. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233507. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233508. ioFlags:(uint32_t*)flags;
  233509. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233510. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233511. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233512. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233513. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233514. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233515. ioFlags:(uint32_t*)flags;
  233516. @end
  233517. @implementation OpenDiskDevice
  233518. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233519. {
  233520. [super init];
  233521. device = device_;
  233522. tracks = [[NSMutableArray alloc] init];
  233523. underrunProtection = true;
  233524. return self;
  233525. }
  233526. - (void) dealloc
  233527. {
  233528. [tracks release];
  233529. [super dealloc];
  233530. }
  233531. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233532. {
  233533. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233534. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233535. [p setupTrackProperties: t];
  233536. [tracks addObject: t];
  233537. [t release];
  233538. [p release];
  233539. }
  233540. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233541. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233542. {
  233543. DRBurn* burn = [DRBurn burnForDevice: device];
  233544. if (! [device acquireExclusiveAccess])
  233545. {
  233546. *error = "Couldn't open or write to the CD device";
  233547. return;
  233548. }
  233549. [device acquireMediaReservation];
  233550. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233551. [d autorelease];
  233552. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233553. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233554. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233555. if (burnSpeed > 0)
  233556. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233557. if (! underrunProtection)
  233558. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233559. [burn setProperties: d];
  233560. [burn writeLayout: tracks];
  233561. for (;;)
  233562. {
  233563. JUCE_NAMESPACE::Thread::sleep (300);
  233564. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233565. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233566. {
  233567. [burn abort];
  233568. *error = "User cancelled the write operation";
  233569. break;
  233570. }
  233571. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233572. {
  233573. *error = "Write operation failed";
  233574. break;
  233575. }
  233576. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233577. {
  233578. break;
  233579. }
  233580. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233581. objectForKey: DRErrorStatusErrorStringKey];
  233582. if ([err length] > 0)
  233583. {
  233584. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233585. break;
  233586. }
  233587. }
  233588. [device releaseMediaReservation];
  233589. [device releaseExclusiveAccess];
  233590. }
  233591. @end
  233592. @implementation AudioTrackProducer
  233593. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233594. {
  233595. lengthInFrames = lengthInFrames_;
  233596. readPosition = 0;
  233597. return self;
  233598. }
  233599. - (void) setupTrackProperties: (DRTrack*) track
  233600. {
  233601. NSMutableDictionary* p = [[track properties] mutableCopy];
  233602. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233603. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233604. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233605. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233606. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233607. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233608. [track setProperties: p];
  233609. [p release];
  233610. }
  233611. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233612. {
  233613. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233614. if (s != nil)
  233615. s->source = source_;
  233616. return s;
  233617. }
  233618. - (void) dealloc
  233619. {
  233620. if (source != 0)
  233621. {
  233622. source->releaseResources();
  233623. delete source;
  233624. }
  233625. [super dealloc];
  233626. }
  233627. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233628. {
  233629. }
  233630. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233631. {
  233632. return true;
  233633. }
  233634. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233635. {
  233636. return lengthInFrames;
  233637. }
  233638. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233639. toMedia: (NSDictionary*) mediaInfo
  233640. {
  233641. if (source != 0)
  233642. source->prepareToPlay (44100 / 75, 44100);
  233643. readPosition = 0;
  233644. return true;
  233645. }
  233646. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233647. {
  233648. if (source != 0)
  233649. source->prepareToPlay (44100 / 75, 44100);
  233650. return true;
  233651. }
  233652. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233653. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233654. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233655. {
  233656. if (source != 0)
  233657. {
  233658. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233659. if (numSamples > 0)
  233660. {
  233661. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233662. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233663. info.buffer = &tempBuffer;
  233664. info.startSample = 0;
  233665. info.numSamples = numSamples;
  233666. source->getNextAudioBlock (info);
  233667. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233668. JUCE_NAMESPACE::AudioData::LittleEndian,
  233669. JUCE_NAMESPACE::AudioData::Interleaved,
  233670. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233671. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233672. JUCE_NAMESPACE::AudioData::NativeEndian,
  233673. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233674. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233675. CDSampleFormat left (buffer, 2);
  233676. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233677. CDSampleFormat right (buffer + 2, 2);
  233678. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233679. readPosition += numSamples;
  233680. }
  233681. return numSamples * 4;
  233682. }
  233683. return 0;
  233684. }
  233685. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233686. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233687. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233688. ioFlags: (uint32_t*) flags
  233689. {
  233690. zeromem (buffer, bufferLength);
  233691. return bufferLength;
  233692. }
  233693. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233694. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233695. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233696. {
  233697. return true;
  233698. }
  233699. @end
  233700. BEGIN_JUCE_NAMESPACE
  233701. class AudioCDBurner::Pimpl : public Timer
  233702. {
  233703. public:
  233704. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233705. : device (0), owner (owner_)
  233706. {
  233707. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233708. if (dev != 0)
  233709. {
  233710. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233711. lastState = getDiskState();
  233712. startTimer (1000);
  233713. }
  233714. }
  233715. ~Pimpl()
  233716. {
  233717. stopTimer();
  233718. [device release];
  233719. }
  233720. void timerCallback()
  233721. {
  233722. const DiskState state = getDiskState();
  233723. if (state != lastState)
  233724. {
  233725. lastState = state;
  233726. owner.sendChangeMessage();
  233727. }
  233728. }
  233729. DiskState getDiskState() const
  233730. {
  233731. if ([device->device isValid])
  233732. {
  233733. NSDictionary* status = [device->device status];
  233734. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233735. if ([state isEqualTo: DRDeviceMediaStateNone])
  233736. {
  233737. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233738. return trayOpen;
  233739. return noDisc;
  233740. }
  233741. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233742. {
  233743. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233744. return writableDiskPresent;
  233745. else
  233746. return readOnlyDiskPresent;
  233747. }
  233748. }
  233749. return unknown;
  233750. }
  233751. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233752. const Array<int> getAvailableWriteSpeeds() const
  233753. {
  233754. Array<int> results;
  233755. if ([device->device isValid])
  233756. {
  233757. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233758. for (unsigned int i = 0; i < [speeds count]; ++i)
  233759. {
  233760. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233761. results.add (kbPerSec / kilobytesPerSecond1x);
  233762. }
  233763. }
  233764. return results;
  233765. }
  233766. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233767. {
  233768. if ([device->device isValid])
  233769. {
  233770. device->underrunProtection = shouldBeEnabled;
  233771. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233772. }
  233773. return false;
  233774. }
  233775. int getNumAvailableAudioBlocks() const
  233776. {
  233777. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233778. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233779. }
  233780. OpenDiskDevice* device;
  233781. private:
  233782. DiskState lastState;
  233783. AudioCDBurner& owner;
  233784. };
  233785. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233786. {
  233787. pimpl = new Pimpl (*this, deviceIndex);
  233788. }
  233789. AudioCDBurner::~AudioCDBurner()
  233790. {
  233791. }
  233792. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233793. {
  233794. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233795. if (b->pimpl->device == 0)
  233796. b = 0;
  233797. return b.release();
  233798. }
  233799. namespace
  233800. {
  233801. NSArray* findDiskBurnerDevices()
  233802. {
  233803. NSMutableArray* results = [NSMutableArray array];
  233804. NSArray* devs = [DRDevice devices];
  233805. for (int i = 0; i < [devs count]; ++i)
  233806. {
  233807. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233808. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233809. if (name != nil)
  233810. [results addObject: name];
  233811. }
  233812. return results;
  233813. }
  233814. }
  233815. const StringArray AudioCDBurner::findAvailableDevices()
  233816. {
  233817. NSArray* names = findDiskBurnerDevices();
  233818. StringArray s;
  233819. for (unsigned int i = 0; i < [names count]; ++i)
  233820. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233821. return s;
  233822. }
  233823. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233824. {
  233825. return pimpl->getDiskState();
  233826. }
  233827. bool AudioCDBurner::isDiskPresent() const
  233828. {
  233829. return getDiskState() == writableDiskPresent;
  233830. }
  233831. bool AudioCDBurner::openTray()
  233832. {
  233833. return pimpl->openTray();
  233834. }
  233835. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233836. {
  233837. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233838. DiskState oldState = getDiskState();
  233839. DiskState newState = oldState;
  233840. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233841. {
  233842. newState = getDiskState();
  233843. Thread::sleep (100);
  233844. }
  233845. return newState;
  233846. }
  233847. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233848. {
  233849. return pimpl->getAvailableWriteSpeeds();
  233850. }
  233851. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233852. {
  233853. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233854. }
  233855. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233856. {
  233857. return pimpl->getNumAvailableAudioBlocks();
  233858. }
  233859. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233860. {
  233861. if ([pimpl->device->device isValid])
  233862. {
  233863. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233864. return true;
  233865. }
  233866. return false;
  233867. }
  233868. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233869. bool ejectDiscAfterwards,
  233870. bool performFakeBurnForTesting,
  233871. int writeSpeed)
  233872. {
  233873. String error ("Couldn't open or write to the CD device");
  233874. if ([pimpl->device->device isValid])
  233875. {
  233876. error = String::empty;
  233877. [pimpl->device burn: listener
  233878. errorString: &error
  233879. ejectAfterwards: ejectDiscAfterwards
  233880. isFake: performFakeBurnForTesting
  233881. speed: writeSpeed];
  233882. }
  233883. return error;
  233884. }
  233885. #endif
  233886. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233887. void AudioCDReader::ejectDisk()
  233888. {
  233889. const ScopedAutoReleasePool p;
  233890. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233891. }
  233892. #endif
  233893. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233894. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233895. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233896. // compiled on its own).
  233897. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233898. namespace CDReaderHelpers
  233899. {
  233900. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233901. {
  233902. forEachXmlChildElementWithTagName (xml, child, "key")
  233903. if (child->getAllSubText().trim() == key)
  233904. return child->getNextElement();
  233905. return 0;
  233906. }
  233907. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233908. {
  233909. const XmlElement* const block = getElementForKey (xml, key);
  233910. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233911. }
  233912. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233913. // Returns NULL on success, otherwise a const char* representing an error.
  233914. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233915. {
  233916. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233917. if (xml == 0)
  233918. return "Couldn't parse XML in file";
  233919. const XmlElement* const dict = xml->getChildByName ("dict");
  233920. if (dict == 0)
  233921. return "Couldn't get top level dictionary";
  233922. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233923. if (sessions == 0)
  233924. return "Couldn't find sessions key";
  233925. const XmlElement* const session = sessions->getFirstChildElement();
  233926. if (session == 0)
  233927. return "Couldn't find first session";
  233928. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233929. if (leadOut < 0)
  233930. return "Couldn't find Leadout Block";
  233931. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233932. if (trackArray == 0)
  233933. return "Couldn't find Track Array";
  233934. forEachXmlChildElement (*trackArray, track)
  233935. {
  233936. const int trackValue = getIntValueForKey (*track, "Start Block");
  233937. if (trackValue < 0)
  233938. return "Couldn't find Start Block in the track";
  233939. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233940. }
  233941. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233942. return 0;
  233943. }
  233944. static void findDevices (Array<File>& cds)
  233945. {
  233946. File volumes ("/Volumes");
  233947. volumes.findChildFiles (cds, File::findDirectories, false);
  233948. for (int i = cds.size(); --i >= 0;)
  233949. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233950. cds.remove (i);
  233951. }
  233952. struct TrackSorter
  233953. {
  233954. static int getCDTrackNumber (const File& file)
  233955. {
  233956. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233957. }
  233958. static int compareElements (const File& first, const File& second)
  233959. {
  233960. const int firstTrack = getCDTrackNumber (first);
  233961. const int secondTrack = getCDTrackNumber (second);
  233962. jassert (firstTrack > 0 && secondTrack > 0);
  233963. return firstTrack - secondTrack;
  233964. }
  233965. };
  233966. }
  233967. const StringArray AudioCDReader::getAvailableCDNames()
  233968. {
  233969. Array<File> cds;
  233970. CDReaderHelpers::findDevices (cds);
  233971. StringArray names;
  233972. for (int i = 0; i < cds.size(); ++i)
  233973. names.add (cds.getReference(i).getFileName());
  233974. return names;
  233975. }
  233976. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233977. {
  233978. Array<File> cds;
  233979. CDReaderHelpers::findDevices (cds);
  233980. if (cds[index].exists())
  233981. return new AudioCDReader (cds[index]);
  233982. return 0;
  233983. }
  233984. AudioCDReader::AudioCDReader (const File& volume)
  233985. : AudioFormatReader (0, "CD Audio"),
  233986. volumeDir (volume),
  233987. currentReaderTrack (-1),
  233988. reader (0)
  233989. {
  233990. sampleRate = 44100.0;
  233991. bitsPerSample = 16;
  233992. numChannels = 2;
  233993. usesFloatingPointData = false;
  233994. refreshTrackLengths();
  233995. }
  233996. AudioCDReader::~AudioCDReader()
  233997. {
  233998. }
  233999. void AudioCDReader::refreshTrackLengths()
  234000. {
  234001. tracks.clear();
  234002. trackStartSamples.clear();
  234003. lengthInSamples = 0;
  234004. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234005. CDReaderHelpers::TrackSorter sorter;
  234006. tracks.sort (sorter);
  234007. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234008. if (toc.exists())
  234009. {
  234010. XmlDocument doc (toc);
  234011. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234012. (void) error; // could be logged..
  234013. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234014. }
  234015. }
  234016. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234017. int64 startSampleInFile, int numSamples)
  234018. {
  234019. while (numSamples > 0)
  234020. {
  234021. int track = -1;
  234022. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234023. {
  234024. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234025. {
  234026. track = i;
  234027. break;
  234028. }
  234029. }
  234030. if (track < 0)
  234031. return false;
  234032. if (track != currentReaderTrack)
  234033. {
  234034. reader = 0;
  234035. FileInputStream* const in = tracks [track].createInputStream();
  234036. if (in != 0)
  234037. {
  234038. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234039. AiffAudioFormat format;
  234040. reader = format.createReaderFor (bin, true);
  234041. if (reader == 0)
  234042. currentReaderTrack = -1;
  234043. else
  234044. currentReaderTrack = track;
  234045. }
  234046. }
  234047. if (reader == 0)
  234048. return false;
  234049. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234050. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234051. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234052. numSamples -= numAvailable;
  234053. startSampleInFile += numAvailable;
  234054. }
  234055. return true;
  234056. }
  234057. bool AudioCDReader::isCDStillPresent() const
  234058. {
  234059. return volumeDir.exists();
  234060. }
  234061. bool AudioCDReader::isTrackAudio (int trackNum) const
  234062. {
  234063. return tracks [trackNum].hasFileExtension (".aiff");
  234064. }
  234065. void AudioCDReader::enableIndexScanning (bool b)
  234066. {
  234067. // any way to do this on a Mac??
  234068. }
  234069. int AudioCDReader::getLastIndex() const
  234070. {
  234071. return 0;
  234072. }
  234073. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234074. {
  234075. return Array <int>();
  234076. }
  234077. #endif
  234078. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234079. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234080. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234081. // compiled on its own).
  234082. #if JUCE_INCLUDED_FILE
  234083. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234084. for example having more than one juce plugin loaded into a host, then when a
  234085. method is called, the actual code that runs might actually be in a different module
  234086. than the one you expect... So any calls to library functions or statics that are
  234087. made inside obj-c methods will probably end up getting executed in a different DLL's
  234088. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234089. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234090. virtual methods of an object that's known to live inside the right module's space.
  234091. */
  234092. class AppDelegateRedirector
  234093. {
  234094. public:
  234095. AppDelegateRedirector()
  234096. {
  234097. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234098. runLoop = CFRunLoopGetMain();
  234099. #else
  234100. runLoop = CFRunLoopGetCurrent();
  234101. #endif
  234102. CFRunLoopSourceContext sourceContext;
  234103. zerostruct (sourceContext);
  234104. sourceContext.info = this;
  234105. sourceContext.perform = runLoopSourceCallback;
  234106. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234107. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234108. }
  234109. virtual ~AppDelegateRedirector()
  234110. {
  234111. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234112. CFRunLoopSourceInvalidate (runLoopSource);
  234113. CFRelease (runLoopSource);
  234114. }
  234115. virtual NSApplicationTerminateReply shouldTerminate()
  234116. {
  234117. if (JUCEApplication::getInstance() != 0)
  234118. {
  234119. JUCEApplication::getInstance()->systemRequestedQuit();
  234120. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234121. return NSTerminateCancel;
  234122. }
  234123. return NSTerminateNow;
  234124. }
  234125. virtual void willTerminate()
  234126. {
  234127. JUCEApplication::appWillTerminateByForce();
  234128. }
  234129. virtual BOOL openFile (NSString* filename)
  234130. {
  234131. if (JUCEApplication::getInstance() != 0)
  234132. {
  234133. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234134. return YES;
  234135. }
  234136. return NO;
  234137. }
  234138. virtual void openFiles (NSArray* filenames)
  234139. {
  234140. StringArray files;
  234141. for (unsigned int i = 0; i < [filenames count]; ++i)
  234142. {
  234143. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234144. if (filename.containsChar (' '))
  234145. filename = filename.quoted('"');
  234146. files.add (filename);
  234147. }
  234148. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234149. {
  234150. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234151. }
  234152. }
  234153. virtual void focusChanged()
  234154. {
  234155. juce_HandleProcessFocusChange();
  234156. }
  234157. struct CallbackMessagePayload
  234158. {
  234159. MessageCallbackFunction* function;
  234160. void* parameter;
  234161. void* volatile result;
  234162. bool volatile hasBeenExecuted;
  234163. };
  234164. virtual void performCallback (CallbackMessagePayload* pl)
  234165. {
  234166. pl->result = (*pl->function) (pl->parameter);
  234167. pl->hasBeenExecuted = true;
  234168. }
  234169. virtual void deleteSelf()
  234170. {
  234171. delete this;
  234172. }
  234173. void postMessage (Message* const m)
  234174. {
  234175. messages.add (m);
  234176. CFRunLoopSourceSignal (runLoopSource);
  234177. CFRunLoopWakeUp (runLoop);
  234178. }
  234179. private:
  234180. CFRunLoopRef runLoop;
  234181. CFRunLoopSourceRef runLoopSource;
  234182. OwnedArray <Message, CriticalSection> messages;
  234183. void runLoopCallback()
  234184. {
  234185. int numDispatched = 0;
  234186. do
  234187. {
  234188. Message* const nextMessage = messages.removeAndReturn (0);
  234189. if (nextMessage == 0)
  234190. return;
  234191. const ScopedAutoReleasePool pool;
  234192. MessageManager::getInstance()->deliverMessage (nextMessage);
  234193. } while (++numDispatched <= 4);
  234194. CFRunLoopSourceSignal (runLoopSource);
  234195. CFRunLoopWakeUp (runLoop);
  234196. }
  234197. static void runLoopSourceCallback (void* info)
  234198. {
  234199. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234200. }
  234201. };
  234202. END_JUCE_NAMESPACE
  234203. using namespace JUCE_NAMESPACE;
  234204. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234205. @interface JuceAppDelegate : NSObject
  234206. {
  234207. @private
  234208. id oldDelegate;
  234209. @public
  234210. AppDelegateRedirector* redirector;
  234211. }
  234212. - (JuceAppDelegate*) init;
  234213. - (void) dealloc;
  234214. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234215. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234216. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234217. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234218. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234219. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234220. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234221. - (void) performCallback: (id) info;
  234222. - (void) dummyMethod;
  234223. @end
  234224. @implementation JuceAppDelegate
  234225. - (JuceAppDelegate*) init
  234226. {
  234227. [super init];
  234228. redirector = new AppDelegateRedirector();
  234229. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234230. if (JUCEApplication::isStandaloneApp())
  234231. {
  234232. oldDelegate = [NSApp delegate];
  234233. [NSApp setDelegate: self];
  234234. }
  234235. else
  234236. {
  234237. oldDelegate = 0;
  234238. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234239. name: NSApplicationDidResignActiveNotification object: NSApp];
  234240. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234241. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234242. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234243. name: NSApplicationWillUnhideNotification object: NSApp];
  234244. }
  234245. return self;
  234246. }
  234247. - (void) dealloc
  234248. {
  234249. if (oldDelegate != 0)
  234250. [NSApp setDelegate: oldDelegate];
  234251. redirector->deleteSelf();
  234252. [super dealloc];
  234253. }
  234254. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234255. {
  234256. (void) app;
  234257. return redirector->shouldTerminate();
  234258. }
  234259. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234260. {
  234261. (void) aNotification;
  234262. redirector->willTerminate();
  234263. }
  234264. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234265. {
  234266. (void) app;
  234267. return redirector->openFile (filename);
  234268. }
  234269. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234270. {
  234271. (void) sender;
  234272. return redirector->openFiles (filenames);
  234273. }
  234274. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234275. {
  234276. (void) notification;
  234277. redirector->focusChanged();
  234278. }
  234279. - (void) applicationDidResignActive: (NSNotification*) notification
  234280. {
  234281. (void) notification;
  234282. redirector->focusChanged();
  234283. }
  234284. - (void) applicationWillUnhide: (NSNotification*) notification
  234285. {
  234286. (void) notification;
  234287. redirector->focusChanged();
  234288. }
  234289. - (void) performCallback: (id) info
  234290. {
  234291. if ([info isKindOfClass: [NSData class]])
  234292. {
  234293. AppDelegateRedirector::CallbackMessagePayload* pl
  234294. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234295. if (pl != 0)
  234296. redirector->performCallback (pl);
  234297. }
  234298. else
  234299. {
  234300. jassertfalse; // should never get here!
  234301. }
  234302. }
  234303. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234304. @end
  234305. BEGIN_JUCE_NAMESPACE
  234306. static JuceAppDelegate* juceAppDelegate = 0;
  234307. void MessageManager::runDispatchLoop()
  234308. {
  234309. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234310. {
  234311. const ScopedAutoReleasePool pool;
  234312. // must only be called by the message thread!
  234313. jassert (isThisTheMessageThread());
  234314. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234315. @try
  234316. {
  234317. [NSApp run];
  234318. }
  234319. @catch (NSException* e)
  234320. {
  234321. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234322. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234323. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234324. }
  234325. @finally
  234326. {
  234327. }
  234328. #else
  234329. [NSApp run];
  234330. #endif
  234331. }
  234332. }
  234333. void MessageManager::stopDispatchLoop()
  234334. {
  234335. quitMessagePosted = true;
  234336. [NSApp stop: nil];
  234337. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234338. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234339. }
  234340. namespace
  234341. {
  234342. bool isEventBlockedByModalComps (NSEvent* e)
  234343. {
  234344. if (Component::getNumCurrentlyModalComponents() == 0)
  234345. return false;
  234346. NSWindow* const w = [e window];
  234347. if (w == 0 || [w worksWhenModal])
  234348. return false;
  234349. bool isKey = false, isInputAttempt = false;
  234350. switch ([e type])
  234351. {
  234352. case NSKeyDown:
  234353. case NSKeyUp:
  234354. isKey = isInputAttempt = true;
  234355. break;
  234356. case NSLeftMouseDown:
  234357. case NSRightMouseDown:
  234358. case NSOtherMouseDown:
  234359. isInputAttempt = true;
  234360. break;
  234361. case NSLeftMouseDragged:
  234362. case NSRightMouseDragged:
  234363. case NSLeftMouseUp:
  234364. case NSRightMouseUp:
  234365. case NSOtherMouseUp:
  234366. case NSOtherMouseDragged:
  234367. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234368. return false;
  234369. break;
  234370. case NSMouseMoved:
  234371. case NSMouseEntered:
  234372. case NSMouseExited:
  234373. case NSCursorUpdate:
  234374. case NSScrollWheel:
  234375. case NSTabletPoint:
  234376. case NSTabletProximity:
  234377. break;
  234378. default:
  234379. return false;
  234380. }
  234381. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234382. {
  234383. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234384. NSView* const compView = (NSView*) peer->getNativeHandle();
  234385. if ([compView window] == w)
  234386. {
  234387. if (isKey)
  234388. {
  234389. if (compView == [w firstResponder])
  234390. return false;
  234391. }
  234392. else
  234393. {
  234394. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234395. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234396. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234397. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234398. return false;
  234399. }
  234400. }
  234401. }
  234402. if (isInputAttempt)
  234403. {
  234404. if (! [NSApp isActive])
  234405. [NSApp activateIgnoringOtherApps: YES];
  234406. Component* const modal = Component::getCurrentlyModalComponent (0);
  234407. if (modal != 0)
  234408. modal->inputAttemptWhenModal();
  234409. }
  234410. return true;
  234411. }
  234412. }
  234413. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234414. {
  234415. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234416. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234417. while (! quitMessagePosted)
  234418. {
  234419. const ScopedAutoReleasePool pool;
  234420. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234421. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234422. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234423. inMode: NSDefaultRunLoopMode
  234424. dequeue: YES];
  234425. if (e != 0 && ! isEventBlockedByModalComps (e))
  234426. [NSApp sendEvent: e];
  234427. if (Time::getMillisecondCounter() >= endTime)
  234428. break;
  234429. }
  234430. return ! quitMessagePosted;
  234431. }
  234432. void MessageManager::doPlatformSpecificInitialisation()
  234433. {
  234434. if (juceAppDelegate == 0)
  234435. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234436. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234437. // correctly (needed prior to 10.5)
  234438. if (! [NSThread isMultiThreaded])
  234439. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234440. toTarget: juceAppDelegate
  234441. withObject: nil];
  234442. }
  234443. void MessageManager::doPlatformSpecificShutdown()
  234444. {
  234445. if (juceAppDelegate != 0)
  234446. {
  234447. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234448. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234449. [juceAppDelegate release];
  234450. juceAppDelegate = 0;
  234451. }
  234452. }
  234453. bool juce_postMessageToSystemQueue (Message* message)
  234454. {
  234455. juceAppDelegate->redirector->postMessage (message);
  234456. return true;
  234457. }
  234458. void MessageManager::broadcastMessage (const String& value)
  234459. {
  234460. }
  234461. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234462. {
  234463. if (isThisTheMessageThread())
  234464. {
  234465. return (*callback) (data);
  234466. }
  234467. else
  234468. {
  234469. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234470. // deadlock because the message manager is blocked from running, so can never
  234471. // call your function..
  234472. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234473. const ScopedAutoReleasePool pool;
  234474. AppDelegateRedirector::CallbackMessagePayload cmp;
  234475. cmp.function = callback;
  234476. cmp.parameter = data;
  234477. cmp.result = 0;
  234478. cmp.hasBeenExecuted = false;
  234479. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234480. withObject: [NSData dataWithBytesNoCopy: &cmp
  234481. length: sizeof (cmp)
  234482. freeWhenDone: NO]
  234483. waitUntilDone: YES];
  234484. return cmp.result;
  234485. }
  234486. }
  234487. #endif
  234488. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234489. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234490. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234491. // compiled on its own).
  234492. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234493. #if JUCE_MAC
  234494. END_JUCE_NAMESPACE
  234495. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234496. @interface DownloadClickDetector : NSObject
  234497. {
  234498. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234499. }
  234500. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234501. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234502. request: (NSURLRequest*) request
  234503. frame: (WebFrame*) frame
  234504. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234505. @end
  234506. @implementation DownloadClickDetector
  234507. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234508. {
  234509. [super init];
  234510. ownerComponent = ownerComponent_;
  234511. return self;
  234512. }
  234513. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234514. request: (NSURLRequest*) request
  234515. frame: (WebFrame*) frame
  234516. decisionListener: (id <WebPolicyDecisionListener>) listener
  234517. {
  234518. (void) sender;
  234519. (void) request;
  234520. (void) frame;
  234521. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234522. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234523. [listener use];
  234524. else
  234525. [listener ignore];
  234526. }
  234527. @end
  234528. BEGIN_JUCE_NAMESPACE
  234529. class WebBrowserComponentInternal : public NSViewComponent
  234530. {
  234531. public:
  234532. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234533. {
  234534. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234535. frameName: @""
  234536. groupName: @""];
  234537. setView (webView);
  234538. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234539. [webView setPolicyDelegate: clickListener];
  234540. }
  234541. ~WebBrowserComponentInternal()
  234542. {
  234543. [webView setPolicyDelegate: nil];
  234544. [clickListener release];
  234545. setView (0);
  234546. }
  234547. void goToURL (const String& url,
  234548. const StringArray* headers,
  234549. const MemoryBlock* postData)
  234550. {
  234551. NSMutableURLRequest* r
  234552. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234553. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234554. timeoutInterval: 30.0];
  234555. if (postData != 0 && postData->getSize() > 0)
  234556. {
  234557. [r setHTTPMethod: @"POST"];
  234558. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234559. length: postData->getSize()]];
  234560. }
  234561. if (headers != 0)
  234562. {
  234563. for (int i = 0; i < headers->size(); ++i)
  234564. {
  234565. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234566. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234567. [r setValue: juceStringToNS (headerValue)
  234568. forHTTPHeaderField: juceStringToNS (headerName)];
  234569. }
  234570. }
  234571. stop();
  234572. [[webView mainFrame] loadRequest: r];
  234573. }
  234574. void goBack()
  234575. {
  234576. [webView goBack];
  234577. }
  234578. void goForward()
  234579. {
  234580. [webView goForward];
  234581. }
  234582. void stop()
  234583. {
  234584. [webView stopLoading: nil];
  234585. }
  234586. void refresh()
  234587. {
  234588. [webView reload: nil];
  234589. }
  234590. void mouseMove (const MouseEvent&)
  234591. {
  234592. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234593. // them work is to push them via this non-public method..
  234594. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234595. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234596. }
  234597. private:
  234598. WebView* webView;
  234599. DownloadClickDetector* clickListener;
  234600. };
  234601. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234602. : browser (0),
  234603. blankPageShown (false),
  234604. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234605. {
  234606. setOpaque (true);
  234607. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234608. }
  234609. WebBrowserComponent::~WebBrowserComponent()
  234610. {
  234611. deleteAndZero (browser);
  234612. }
  234613. void WebBrowserComponent::goToURL (const String& url,
  234614. const StringArray* headers,
  234615. const MemoryBlock* postData)
  234616. {
  234617. lastURL = url;
  234618. lastHeaders.clear();
  234619. if (headers != 0)
  234620. lastHeaders = *headers;
  234621. lastPostData.setSize (0);
  234622. if (postData != 0)
  234623. lastPostData = *postData;
  234624. blankPageShown = false;
  234625. browser->goToURL (url, headers, postData);
  234626. }
  234627. void WebBrowserComponent::stop()
  234628. {
  234629. browser->stop();
  234630. }
  234631. void WebBrowserComponent::goBack()
  234632. {
  234633. lastURL = String::empty;
  234634. blankPageShown = false;
  234635. browser->goBack();
  234636. }
  234637. void WebBrowserComponent::goForward()
  234638. {
  234639. lastURL = String::empty;
  234640. browser->goForward();
  234641. }
  234642. void WebBrowserComponent::refresh()
  234643. {
  234644. browser->refresh();
  234645. }
  234646. void WebBrowserComponent::paint (Graphics&)
  234647. {
  234648. }
  234649. void WebBrowserComponent::checkWindowAssociation()
  234650. {
  234651. if (isShowing())
  234652. {
  234653. if (blankPageShown)
  234654. goBack();
  234655. }
  234656. else
  234657. {
  234658. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234659. {
  234660. // when the component becomes invisible, some stuff like flash
  234661. // carries on playing audio, so we need to force it onto a blank
  234662. // page to avoid this, (and send it back when it's made visible again).
  234663. blankPageShown = true;
  234664. browser->goToURL ("about:blank", 0, 0);
  234665. }
  234666. }
  234667. }
  234668. void WebBrowserComponent::reloadLastURL()
  234669. {
  234670. if (lastURL.isNotEmpty())
  234671. {
  234672. goToURL (lastURL, &lastHeaders, &lastPostData);
  234673. lastURL = String::empty;
  234674. }
  234675. }
  234676. void WebBrowserComponent::parentHierarchyChanged()
  234677. {
  234678. checkWindowAssociation();
  234679. }
  234680. void WebBrowserComponent::resized()
  234681. {
  234682. browser->setSize (getWidth(), getHeight());
  234683. }
  234684. void WebBrowserComponent::visibilityChanged()
  234685. {
  234686. checkWindowAssociation();
  234687. }
  234688. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234689. {
  234690. return true;
  234691. }
  234692. #else
  234693. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234694. {
  234695. }
  234696. WebBrowserComponent::~WebBrowserComponent()
  234697. {
  234698. }
  234699. void WebBrowserComponent::goToURL (const String& url,
  234700. const StringArray* headers,
  234701. const MemoryBlock* postData)
  234702. {
  234703. }
  234704. void WebBrowserComponent::stop()
  234705. {
  234706. }
  234707. void WebBrowserComponent::goBack()
  234708. {
  234709. }
  234710. void WebBrowserComponent::goForward()
  234711. {
  234712. }
  234713. void WebBrowserComponent::refresh()
  234714. {
  234715. }
  234716. void WebBrowserComponent::paint (Graphics& g)
  234717. {
  234718. }
  234719. void WebBrowserComponent::checkWindowAssociation()
  234720. {
  234721. }
  234722. void WebBrowserComponent::reloadLastURL()
  234723. {
  234724. }
  234725. void WebBrowserComponent::parentHierarchyChanged()
  234726. {
  234727. }
  234728. void WebBrowserComponent::resized()
  234729. {
  234730. }
  234731. void WebBrowserComponent::visibilityChanged()
  234732. {
  234733. }
  234734. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234735. {
  234736. return true;
  234737. }
  234738. #endif
  234739. #endif
  234740. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234741. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234742. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234743. // compiled on its own).
  234744. #if JUCE_INCLUDED_FILE
  234745. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234746. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234747. #endif
  234748. #undef log
  234749. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234750. #define log(a) Logger::writeToLog (a)
  234751. #else
  234752. #define log(a)
  234753. #endif
  234754. #undef OK
  234755. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234756. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234757. {
  234758. if (err == noErr)
  234759. return true;
  234760. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234761. jassertfalse;
  234762. return false;
  234763. }
  234764. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234765. #else
  234766. #define OK(a) (a == noErr)
  234767. #endif
  234768. class CoreAudioInternal : public Timer
  234769. {
  234770. public:
  234771. CoreAudioInternal (AudioDeviceID id)
  234772. : inputLatency (0),
  234773. outputLatency (0),
  234774. callback (0),
  234775. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234776. audioProcID (0),
  234777. #endif
  234778. isSlaveDevice (false),
  234779. deviceID (id),
  234780. started (false),
  234781. sampleRate (0),
  234782. bufferSize (512),
  234783. numInputChans (0),
  234784. numOutputChans (0),
  234785. callbacksAllowed (true),
  234786. numInputChannelInfos (0),
  234787. numOutputChannelInfos (0)
  234788. {
  234789. jassert (deviceID != 0);
  234790. updateDetailsFromDevice();
  234791. AudioObjectPropertyAddress pa;
  234792. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234793. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234794. pa.mElement = kAudioObjectPropertyElementWildcard;
  234795. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234796. }
  234797. ~CoreAudioInternal()
  234798. {
  234799. AudioObjectPropertyAddress pa;
  234800. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234801. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234802. pa.mElement = kAudioObjectPropertyElementWildcard;
  234803. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234804. stop (false);
  234805. }
  234806. void allocateTempBuffers()
  234807. {
  234808. const int tempBufSize = bufferSize + 4;
  234809. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234810. tempInputBuffers.calloc (numInputChans + 2);
  234811. tempOutputBuffers.calloc (numOutputChans + 2);
  234812. int i, count = 0;
  234813. for (i = 0; i < numInputChans; ++i)
  234814. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234815. for (i = 0; i < numOutputChans; ++i)
  234816. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234817. }
  234818. // returns the number of actual available channels
  234819. void fillInChannelInfo (const bool input)
  234820. {
  234821. int chanNum = 0;
  234822. UInt32 size;
  234823. AudioObjectPropertyAddress pa;
  234824. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234825. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234826. pa.mElement = kAudioObjectPropertyElementMaster;
  234827. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234828. {
  234829. HeapBlock <AudioBufferList> bufList;
  234830. bufList.calloc (size, 1);
  234831. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234832. {
  234833. const int numStreams = bufList->mNumberBuffers;
  234834. for (int i = 0; i < numStreams; ++i)
  234835. {
  234836. const AudioBuffer& b = bufList->mBuffers[i];
  234837. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234838. {
  234839. String name;
  234840. {
  234841. char channelName [256];
  234842. zerostruct (channelName);
  234843. UInt32 nameSize = sizeof (channelName);
  234844. UInt32 channelNum = chanNum + 1;
  234845. pa.mSelector = kAudioDevicePropertyChannelName;
  234846. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234847. name = String::fromUTF8 (channelName, nameSize);
  234848. }
  234849. if (input)
  234850. {
  234851. if (activeInputChans[chanNum])
  234852. {
  234853. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234854. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234855. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234856. ++numInputChannelInfos;
  234857. }
  234858. if (name.isEmpty())
  234859. name << "Input " << (chanNum + 1);
  234860. inChanNames.add (name);
  234861. }
  234862. else
  234863. {
  234864. if (activeOutputChans[chanNum])
  234865. {
  234866. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234867. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234868. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234869. ++numOutputChannelInfos;
  234870. }
  234871. if (name.isEmpty())
  234872. name << "Output " << (chanNum + 1);
  234873. outChanNames.add (name);
  234874. }
  234875. ++chanNum;
  234876. }
  234877. }
  234878. }
  234879. }
  234880. }
  234881. void updateDetailsFromDevice()
  234882. {
  234883. stopTimer();
  234884. if (deviceID == 0)
  234885. return;
  234886. const ScopedLock sl (callbackLock);
  234887. Float64 sr;
  234888. UInt32 size = sizeof (Float64);
  234889. AudioObjectPropertyAddress pa;
  234890. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234891. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234892. pa.mElement = kAudioObjectPropertyElementMaster;
  234893. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234894. sampleRate = sr;
  234895. UInt32 framesPerBuf;
  234896. size = sizeof (framesPerBuf);
  234897. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234898. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234899. {
  234900. bufferSize = framesPerBuf;
  234901. allocateTempBuffers();
  234902. }
  234903. bufferSizes.clear();
  234904. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234905. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234906. {
  234907. HeapBlock <AudioValueRange> ranges;
  234908. ranges.calloc (size, 1);
  234909. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234910. {
  234911. bufferSizes.add ((int) ranges[0].mMinimum);
  234912. for (int i = 32; i < 2048; i += 32)
  234913. {
  234914. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234915. {
  234916. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234917. {
  234918. bufferSizes.addIfNotAlreadyThere (i);
  234919. break;
  234920. }
  234921. }
  234922. }
  234923. if (bufferSize > 0)
  234924. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234925. }
  234926. }
  234927. if (bufferSizes.size() == 0 && bufferSize > 0)
  234928. bufferSizes.add (bufferSize);
  234929. sampleRates.clear();
  234930. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234931. String rates;
  234932. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234933. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234934. {
  234935. HeapBlock <AudioValueRange> ranges;
  234936. ranges.calloc (size, 1);
  234937. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234938. {
  234939. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234940. {
  234941. bool ok = false;
  234942. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234943. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234944. ok = true;
  234945. if (ok)
  234946. {
  234947. sampleRates.add (possibleRates[i]);
  234948. rates << possibleRates[i] << ' ';
  234949. }
  234950. }
  234951. }
  234952. }
  234953. if (sampleRates.size() == 0 && sampleRate > 0)
  234954. {
  234955. sampleRates.add (sampleRate);
  234956. rates << sampleRate;
  234957. }
  234958. log ("sr: " + rates);
  234959. inputLatency = 0;
  234960. outputLatency = 0;
  234961. UInt32 lat;
  234962. size = sizeof (lat);
  234963. pa.mSelector = kAudioDevicePropertyLatency;
  234964. pa.mScope = kAudioDevicePropertyScopeInput;
  234965. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234966. inputLatency = (int) lat;
  234967. pa.mScope = kAudioDevicePropertyScopeOutput;
  234968. size = sizeof (lat);
  234969. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234970. outputLatency = (int) lat;
  234971. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234972. inChanNames.clear();
  234973. outChanNames.clear();
  234974. inputChannelInfo.calloc (numInputChans + 2);
  234975. numInputChannelInfos = 0;
  234976. outputChannelInfo.calloc (numOutputChans + 2);
  234977. numOutputChannelInfos = 0;
  234978. fillInChannelInfo (true);
  234979. fillInChannelInfo (false);
  234980. }
  234981. const StringArray getSources (bool input)
  234982. {
  234983. StringArray s;
  234984. HeapBlock <OSType> types;
  234985. const int num = getAllDataSourcesForDevice (deviceID, types);
  234986. for (int i = 0; i < num; ++i)
  234987. {
  234988. AudioValueTranslation avt;
  234989. char buffer[256];
  234990. avt.mInputData = &(types[i]);
  234991. avt.mInputDataSize = sizeof (UInt32);
  234992. avt.mOutputData = buffer;
  234993. avt.mOutputDataSize = 256;
  234994. UInt32 transSize = sizeof (avt);
  234995. AudioObjectPropertyAddress pa;
  234996. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234997. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234998. pa.mElement = kAudioObjectPropertyElementMaster;
  234999. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235000. {
  235001. DBG (buffer);
  235002. s.add (buffer);
  235003. }
  235004. }
  235005. return s;
  235006. }
  235007. int getCurrentSourceIndex (bool input) const
  235008. {
  235009. OSType currentSourceID = 0;
  235010. UInt32 size = sizeof (currentSourceID);
  235011. int result = -1;
  235012. AudioObjectPropertyAddress pa;
  235013. pa.mSelector = kAudioDevicePropertyDataSource;
  235014. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235015. pa.mElement = kAudioObjectPropertyElementMaster;
  235016. if (deviceID != 0)
  235017. {
  235018. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235019. {
  235020. HeapBlock <OSType> types;
  235021. const int num = getAllDataSourcesForDevice (deviceID, types);
  235022. for (int i = 0; i < num; ++i)
  235023. {
  235024. if (types[num] == currentSourceID)
  235025. {
  235026. result = i;
  235027. break;
  235028. }
  235029. }
  235030. }
  235031. }
  235032. return result;
  235033. }
  235034. void setCurrentSourceIndex (int index, bool input)
  235035. {
  235036. if (deviceID != 0)
  235037. {
  235038. HeapBlock <OSType> types;
  235039. const int num = getAllDataSourcesForDevice (deviceID, types);
  235040. if (isPositiveAndBelow (index, num))
  235041. {
  235042. AudioObjectPropertyAddress pa;
  235043. pa.mSelector = kAudioDevicePropertyDataSource;
  235044. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235045. pa.mElement = kAudioObjectPropertyElementMaster;
  235046. OSType typeId = types[index];
  235047. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235048. }
  235049. }
  235050. }
  235051. const String reopen (const BigInteger& inputChannels,
  235052. const BigInteger& outputChannels,
  235053. double newSampleRate,
  235054. int bufferSizeSamples)
  235055. {
  235056. String error;
  235057. log ("CoreAudio reopen");
  235058. callbacksAllowed = false;
  235059. stopTimer();
  235060. stop (false);
  235061. activeInputChans = inputChannels;
  235062. activeInputChans.setRange (inChanNames.size(),
  235063. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235064. false);
  235065. activeOutputChans = outputChannels;
  235066. activeOutputChans.setRange (outChanNames.size(),
  235067. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235068. false);
  235069. numInputChans = activeInputChans.countNumberOfSetBits();
  235070. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235071. // set sample rate
  235072. AudioObjectPropertyAddress pa;
  235073. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235074. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235075. pa.mElement = kAudioObjectPropertyElementMaster;
  235076. Float64 sr = newSampleRate;
  235077. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235078. {
  235079. error = "Couldn't change sample rate";
  235080. }
  235081. else
  235082. {
  235083. // change buffer size
  235084. UInt32 framesPerBuf = bufferSizeSamples;
  235085. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235086. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235087. {
  235088. error = "Couldn't change buffer size";
  235089. }
  235090. else
  235091. {
  235092. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235093. // correctly report their new settings until some random time in the future, so
  235094. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235095. // to make sure we're using the correct numbers..
  235096. updateDetailsFromDevice();
  235097. sampleRate = newSampleRate;
  235098. bufferSize = bufferSizeSamples;
  235099. if (sampleRates.size() == 0)
  235100. error = "Device has no available sample-rates";
  235101. else if (bufferSizes.size() == 0)
  235102. error = "Device has no available buffer-sizes";
  235103. else if (inputDevice != 0)
  235104. error = inputDevice->reopen (inputChannels,
  235105. outputChannels,
  235106. newSampleRate,
  235107. bufferSizeSamples);
  235108. }
  235109. }
  235110. callbacksAllowed = true;
  235111. return error;
  235112. }
  235113. bool start (AudioIODeviceCallback* cb)
  235114. {
  235115. if (! started)
  235116. {
  235117. callback = 0;
  235118. if (deviceID != 0)
  235119. {
  235120. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235121. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235122. #else
  235123. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235124. #endif
  235125. {
  235126. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235127. {
  235128. started = true;
  235129. }
  235130. else
  235131. {
  235132. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235133. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235134. #else
  235135. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235136. audioProcID = 0;
  235137. #endif
  235138. }
  235139. }
  235140. }
  235141. }
  235142. if (started)
  235143. {
  235144. const ScopedLock sl (callbackLock);
  235145. callback = cb;
  235146. }
  235147. if (inputDevice != 0)
  235148. return started && inputDevice->start (cb);
  235149. else
  235150. return started;
  235151. }
  235152. void stop (bool leaveInterruptRunning)
  235153. {
  235154. {
  235155. const ScopedLock sl (callbackLock);
  235156. callback = 0;
  235157. }
  235158. if (started
  235159. && (deviceID != 0)
  235160. && ! leaveInterruptRunning)
  235161. {
  235162. OK (AudioDeviceStop (deviceID, audioIOProc));
  235163. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235164. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235165. #else
  235166. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235167. audioProcID = 0;
  235168. #endif
  235169. started = false;
  235170. { const ScopedLock sl (callbackLock); }
  235171. // wait until it's definately stopped calling back..
  235172. for (int i = 40; --i >= 0;)
  235173. {
  235174. Thread::sleep (50);
  235175. UInt32 running = 0;
  235176. UInt32 size = sizeof (running);
  235177. AudioObjectPropertyAddress pa;
  235178. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235179. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235180. pa.mElement = kAudioObjectPropertyElementMaster;
  235181. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235182. if (running == 0)
  235183. break;
  235184. }
  235185. const ScopedLock sl (callbackLock);
  235186. }
  235187. if (inputDevice != 0)
  235188. inputDevice->stop (leaveInterruptRunning);
  235189. }
  235190. double getSampleRate() const
  235191. {
  235192. return sampleRate;
  235193. }
  235194. int getBufferSize() const
  235195. {
  235196. return bufferSize;
  235197. }
  235198. void audioCallback (const AudioBufferList* inInputData,
  235199. AudioBufferList* outOutputData)
  235200. {
  235201. int i;
  235202. const ScopedLock sl (callbackLock);
  235203. if (callback != 0)
  235204. {
  235205. if (inputDevice == 0)
  235206. {
  235207. for (i = numInputChans; --i >= 0;)
  235208. {
  235209. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235210. float* dest = tempInputBuffers [i];
  235211. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235212. + info.dataOffsetSamples;
  235213. const int stride = info.dataStrideSamples;
  235214. if (stride != 0) // if this is zero, info is invalid
  235215. {
  235216. for (int j = bufferSize; --j >= 0;)
  235217. {
  235218. *dest++ = *src;
  235219. src += stride;
  235220. }
  235221. }
  235222. }
  235223. }
  235224. if (! isSlaveDevice)
  235225. {
  235226. if (inputDevice == 0)
  235227. {
  235228. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235229. numInputChans,
  235230. tempOutputBuffers,
  235231. numOutputChans,
  235232. bufferSize);
  235233. }
  235234. else
  235235. {
  235236. jassert (inputDevice->bufferSize == bufferSize);
  235237. // Sometimes the two linked devices seem to get their callbacks in
  235238. // parallel, so we need to lock both devices to stop the input data being
  235239. // changed while inside our callback..
  235240. const ScopedLock sl2 (inputDevice->callbackLock);
  235241. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235242. inputDevice->numInputChans,
  235243. tempOutputBuffers,
  235244. numOutputChans,
  235245. bufferSize);
  235246. }
  235247. for (i = numOutputChans; --i >= 0;)
  235248. {
  235249. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235250. const float* src = tempOutputBuffers [i];
  235251. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235252. + info.dataOffsetSamples;
  235253. const int stride = info.dataStrideSamples;
  235254. if (stride != 0) // if this is zero, info is invalid
  235255. {
  235256. for (int j = bufferSize; --j >= 0;)
  235257. {
  235258. *dest = *src++;
  235259. dest += stride;
  235260. }
  235261. }
  235262. }
  235263. }
  235264. }
  235265. else
  235266. {
  235267. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235268. {
  235269. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235270. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235271. + info.dataOffsetSamples;
  235272. const int stride = info.dataStrideSamples;
  235273. if (stride != 0) // if this is zero, info is invalid
  235274. {
  235275. for (int j = bufferSize; --j >= 0;)
  235276. {
  235277. *dest = 0.0f;
  235278. dest += stride;
  235279. }
  235280. }
  235281. }
  235282. }
  235283. }
  235284. // called by callbacks
  235285. void deviceDetailsChanged()
  235286. {
  235287. if (callbacksAllowed)
  235288. startTimer (100);
  235289. }
  235290. void timerCallback()
  235291. {
  235292. stopTimer();
  235293. log ("CoreAudio device changed callback");
  235294. const double oldSampleRate = sampleRate;
  235295. const int oldBufferSize = bufferSize;
  235296. updateDetailsFromDevice();
  235297. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235298. {
  235299. callbacksAllowed = false;
  235300. stop (false);
  235301. updateDetailsFromDevice();
  235302. callbacksAllowed = true;
  235303. }
  235304. }
  235305. CoreAudioInternal* getRelatedDevice() const
  235306. {
  235307. UInt32 size = 0;
  235308. ScopedPointer <CoreAudioInternal> result;
  235309. AudioObjectPropertyAddress pa;
  235310. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235311. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235312. pa.mElement = kAudioObjectPropertyElementMaster;
  235313. if (deviceID != 0
  235314. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235315. && size > 0)
  235316. {
  235317. HeapBlock <AudioDeviceID> devs;
  235318. devs.calloc (size, 1);
  235319. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235320. {
  235321. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235322. {
  235323. if (devs[i] != deviceID && devs[i] != 0)
  235324. {
  235325. result = new CoreAudioInternal (devs[i]);
  235326. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235327. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235328. if (thisIsInput != otherIsInput
  235329. || (inChanNames.size() + outChanNames.size() == 0)
  235330. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235331. break;
  235332. result = 0;
  235333. }
  235334. }
  235335. }
  235336. }
  235337. return result.release();
  235338. }
  235339. int inputLatency, outputLatency;
  235340. BigInteger activeInputChans, activeOutputChans;
  235341. StringArray inChanNames, outChanNames;
  235342. Array <double> sampleRates;
  235343. Array <int> bufferSizes;
  235344. AudioIODeviceCallback* callback;
  235345. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235346. AudioDeviceIOProcID audioProcID;
  235347. #endif
  235348. ScopedPointer<CoreAudioInternal> inputDevice;
  235349. bool isSlaveDevice;
  235350. private:
  235351. CriticalSection callbackLock;
  235352. AudioDeviceID deviceID;
  235353. bool started;
  235354. double sampleRate;
  235355. int bufferSize;
  235356. HeapBlock <float> audioBuffer;
  235357. int numInputChans, numOutputChans;
  235358. bool callbacksAllowed;
  235359. struct CallbackDetailsForChannel
  235360. {
  235361. int streamNum;
  235362. int dataOffsetSamples;
  235363. int dataStrideSamples;
  235364. };
  235365. int numInputChannelInfos, numOutputChannelInfos;
  235366. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235367. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235368. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235369. const AudioTimeStamp* /*inNow*/,
  235370. const AudioBufferList* inInputData,
  235371. const AudioTimeStamp* /*inInputTime*/,
  235372. AudioBufferList* outOutputData,
  235373. const AudioTimeStamp* /*inOutputTime*/,
  235374. void* device)
  235375. {
  235376. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235377. return noErr;
  235378. }
  235379. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235380. {
  235381. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235382. switch (pa->mSelector)
  235383. {
  235384. case kAudioDevicePropertyBufferSize:
  235385. case kAudioDevicePropertyBufferFrameSize:
  235386. case kAudioDevicePropertyNominalSampleRate:
  235387. case kAudioDevicePropertyStreamFormat:
  235388. case kAudioDevicePropertyDeviceIsAlive:
  235389. intern->deviceDetailsChanged();
  235390. break;
  235391. case kAudioDevicePropertyBufferSizeRange:
  235392. case kAudioDevicePropertyVolumeScalar:
  235393. case kAudioDevicePropertyMute:
  235394. case kAudioDevicePropertyPlayThru:
  235395. case kAudioDevicePropertyDataSource:
  235396. case kAudioDevicePropertyDeviceIsRunning:
  235397. break;
  235398. }
  235399. return noErr;
  235400. }
  235401. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235402. {
  235403. AudioObjectPropertyAddress pa;
  235404. pa.mSelector = kAudioDevicePropertyDataSources;
  235405. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235406. pa.mElement = kAudioObjectPropertyElementMaster;
  235407. UInt32 size = 0;
  235408. if (deviceID != 0
  235409. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235410. {
  235411. types.calloc (size, 1);
  235412. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235413. return size / (int) sizeof (OSType);
  235414. }
  235415. return 0;
  235416. }
  235417. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235418. };
  235419. class CoreAudioIODevice : public AudioIODevice
  235420. {
  235421. public:
  235422. CoreAudioIODevice (const String& deviceName,
  235423. AudioDeviceID inputDeviceId,
  235424. const int inputIndex_,
  235425. AudioDeviceID outputDeviceId,
  235426. const int outputIndex_)
  235427. : AudioIODevice (deviceName, "CoreAudio"),
  235428. inputIndex (inputIndex_),
  235429. outputIndex (outputIndex_),
  235430. isOpen_ (false),
  235431. isStarted (false)
  235432. {
  235433. CoreAudioInternal* device = 0;
  235434. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235435. {
  235436. jassert (inputDeviceId != 0);
  235437. device = new CoreAudioInternal (inputDeviceId);
  235438. }
  235439. else
  235440. {
  235441. device = new CoreAudioInternal (outputDeviceId);
  235442. if (inputDeviceId != 0)
  235443. {
  235444. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235445. device->inputDevice = secondDevice;
  235446. secondDevice->isSlaveDevice = true;
  235447. }
  235448. }
  235449. internal = device;
  235450. AudioObjectPropertyAddress pa;
  235451. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235452. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235453. pa.mElement = kAudioObjectPropertyElementWildcard;
  235454. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235455. }
  235456. ~CoreAudioIODevice()
  235457. {
  235458. AudioObjectPropertyAddress pa;
  235459. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235460. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235461. pa.mElement = kAudioObjectPropertyElementWildcard;
  235462. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235463. }
  235464. const StringArray getOutputChannelNames()
  235465. {
  235466. return internal->outChanNames;
  235467. }
  235468. const StringArray getInputChannelNames()
  235469. {
  235470. if (internal->inputDevice != 0)
  235471. return internal->inputDevice->inChanNames;
  235472. else
  235473. return internal->inChanNames;
  235474. }
  235475. int getNumSampleRates()
  235476. {
  235477. return internal->sampleRates.size();
  235478. }
  235479. double getSampleRate (int index)
  235480. {
  235481. return internal->sampleRates [index];
  235482. }
  235483. int getNumBufferSizesAvailable()
  235484. {
  235485. return internal->bufferSizes.size();
  235486. }
  235487. int getBufferSizeSamples (int index)
  235488. {
  235489. return internal->bufferSizes [index];
  235490. }
  235491. int getDefaultBufferSize()
  235492. {
  235493. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235494. if (getBufferSizeSamples(i) >= 512)
  235495. return getBufferSizeSamples(i);
  235496. return 512;
  235497. }
  235498. const String open (const BigInteger& inputChannels,
  235499. const BigInteger& outputChannels,
  235500. double sampleRate,
  235501. int bufferSizeSamples)
  235502. {
  235503. isOpen_ = true;
  235504. if (bufferSizeSamples <= 0)
  235505. bufferSizeSamples = getDefaultBufferSize();
  235506. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235507. isOpen_ = lastError.isEmpty();
  235508. return lastError;
  235509. }
  235510. void close()
  235511. {
  235512. isOpen_ = false;
  235513. internal->stop (false);
  235514. }
  235515. bool isOpen()
  235516. {
  235517. return isOpen_;
  235518. }
  235519. int getCurrentBufferSizeSamples()
  235520. {
  235521. return internal != 0 ? internal->getBufferSize() : 512;
  235522. }
  235523. double getCurrentSampleRate()
  235524. {
  235525. return internal != 0 ? internal->getSampleRate() : 0;
  235526. }
  235527. int getCurrentBitDepth()
  235528. {
  235529. return 32; // no way to find out, so just assume it's high..
  235530. }
  235531. const BigInteger getActiveOutputChannels() const
  235532. {
  235533. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235534. }
  235535. const BigInteger getActiveInputChannels() const
  235536. {
  235537. BigInteger chans;
  235538. if (internal != 0)
  235539. {
  235540. chans = internal->activeInputChans;
  235541. if (internal->inputDevice != 0)
  235542. chans |= internal->inputDevice->activeInputChans;
  235543. }
  235544. return chans;
  235545. }
  235546. int getOutputLatencyInSamples()
  235547. {
  235548. if (internal == 0)
  235549. return 0;
  235550. // this seems like a good guess at getting the latency right - comparing
  235551. // this with a round-trip measurement, it gets it to within a few millisecs
  235552. // for the built-in mac soundcard
  235553. return internal->outputLatency + internal->getBufferSize() * 2;
  235554. }
  235555. int getInputLatencyInSamples()
  235556. {
  235557. if (internal == 0)
  235558. return 0;
  235559. return internal->inputLatency + internal->getBufferSize() * 2;
  235560. }
  235561. void start (AudioIODeviceCallback* callback)
  235562. {
  235563. if (internal != 0 && ! isStarted)
  235564. {
  235565. if (callback != 0)
  235566. callback->audioDeviceAboutToStart (this);
  235567. isStarted = true;
  235568. internal->start (callback);
  235569. }
  235570. }
  235571. void stop()
  235572. {
  235573. if (isStarted && internal != 0)
  235574. {
  235575. AudioIODeviceCallback* const lastCallback = internal->callback;
  235576. isStarted = false;
  235577. internal->stop (true);
  235578. if (lastCallback != 0)
  235579. lastCallback->audioDeviceStopped();
  235580. }
  235581. }
  235582. bool isPlaying()
  235583. {
  235584. if (internal->callback == 0)
  235585. isStarted = false;
  235586. return isStarted;
  235587. }
  235588. const String getLastError()
  235589. {
  235590. return lastError;
  235591. }
  235592. int inputIndex, outputIndex;
  235593. private:
  235594. ScopedPointer<CoreAudioInternal> internal;
  235595. bool isOpen_, isStarted;
  235596. String lastError;
  235597. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235598. {
  235599. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235600. switch (pa->mSelector)
  235601. {
  235602. case kAudioHardwarePropertyDevices:
  235603. intern->deviceDetailsChanged();
  235604. break;
  235605. case kAudioHardwarePropertyDefaultOutputDevice:
  235606. case kAudioHardwarePropertyDefaultInputDevice:
  235607. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235608. break;
  235609. }
  235610. return noErr;
  235611. }
  235612. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235613. };
  235614. class CoreAudioIODeviceType : public AudioIODeviceType
  235615. {
  235616. public:
  235617. CoreAudioIODeviceType()
  235618. : AudioIODeviceType ("CoreAudio"),
  235619. hasScanned (false)
  235620. {
  235621. }
  235622. ~CoreAudioIODeviceType()
  235623. {
  235624. }
  235625. void scanForDevices()
  235626. {
  235627. hasScanned = true;
  235628. inputDeviceNames.clear();
  235629. outputDeviceNames.clear();
  235630. inputIds.clear();
  235631. outputIds.clear();
  235632. UInt32 size;
  235633. AudioObjectPropertyAddress pa;
  235634. pa.mSelector = kAudioHardwarePropertyDevices;
  235635. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235636. pa.mElement = kAudioObjectPropertyElementMaster;
  235637. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235638. {
  235639. HeapBlock <AudioDeviceID> devs;
  235640. devs.calloc (size, 1);
  235641. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235642. {
  235643. const int num = size / (int) sizeof (AudioDeviceID);
  235644. for (int i = 0; i < num; ++i)
  235645. {
  235646. char name [1024];
  235647. size = sizeof (name);
  235648. pa.mSelector = kAudioDevicePropertyDeviceName;
  235649. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235650. {
  235651. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235652. const int numIns = getNumChannels (devs[i], true);
  235653. const int numOuts = getNumChannels (devs[i], false);
  235654. if (numIns > 0)
  235655. {
  235656. inputDeviceNames.add (nameString);
  235657. inputIds.add (devs[i]);
  235658. }
  235659. if (numOuts > 0)
  235660. {
  235661. outputDeviceNames.add (nameString);
  235662. outputIds.add (devs[i]);
  235663. }
  235664. }
  235665. }
  235666. }
  235667. }
  235668. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235669. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235670. }
  235671. const StringArray getDeviceNames (bool wantInputNames) const
  235672. {
  235673. jassert (hasScanned); // need to call scanForDevices() before doing this
  235674. if (wantInputNames)
  235675. return inputDeviceNames;
  235676. else
  235677. return outputDeviceNames;
  235678. }
  235679. int getDefaultDeviceIndex (bool forInput) const
  235680. {
  235681. jassert (hasScanned); // need to call scanForDevices() before doing this
  235682. AudioDeviceID deviceID;
  235683. UInt32 size = sizeof (deviceID);
  235684. // if they're asking for any input channels at all, use the default input, so we
  235685. // get the built-in mic rather than the built-in output with no inputs..
  235686. AudioObjectPropertyAddress pa;
  235687. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235688. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235689. pa.mElement = kAudioObjectPropertyElementMaster;
  235690. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235691. {
  235692. if (forInput)
  235693. {
  235694. for (int i = inputIds.size(); --i >= 0;)
  235695. if (inputIds[i] == deviceID)
  235696. return i;
  235697. }
  235698. else
  235699. {
  235700. for (int i = outputIds.size(); --i >= 0;)
  235701. if (outputIds[i] == deviceID)
  235702. return i;
  235703. }
  235704. }
  235705. return 0;
  235706. }
  235707. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235708. {
  235709. jassert (hasScanned); // need to call scanForDevices() before doing this
  235710. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235711. if (d == 0)
  235712. return -1;
  235713. return asInput ? d->inputIndex
  235714. : d->outputIndex;
  235715. }
  235716. bool hasSeparateInputsAndOutputs() const { return true; }
  235717. AudioIODevice* createDevice (const String& outputDeviceName,
  235718. const String& inputDeviceName)
  235719. {
  235720. jassert (hasScanned); // need to call scanForDevices() before doing this
  235721. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235722. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235723. String deviceName (outputDeviceName);
  235724. if (deviceName.isEmpty())
  235725. deviceName = inputDeviceName;
  235726. if (index >= 0)
  235727. return new CoreAudioIODevice (deviceName,
  235728. inputIds [inputIndex],
  235729. inputIndex,
  235730. outputIds [outputIndex],
  235731. outputIndex);
  235732. return 0;
  235733. }
  235734. private:
  235735. StringArray inputDeviceNames, outputDeviceNames;
  235736. Array <AudioDeviceID> inputIds, outputIds;
  235737. bool hasScanned;
  235738. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235739. {
  235740. int total = 0;
  235741. UInt32 size;
  235742. AudioObjectPropertyAddress pa;
  235743. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235744. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235745. pa.mElement = kAudioObjectPropertyElementMaster;
  235746. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235747. {
  235748. HeapBlock <AudioBufferList> bufList;
  235749. bufList.calloc (size, 1);
  235750. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235751. {
  235752. const int numStreams = bufList->mNumberBuffers;
  235753. for (int i = 0; i < numStreams; ++i)
  235754. {
  235755. const AudioBuffer& b = bufList->mBuffers[i];
  235756. total += b.mNumberChannels;
  235757. }
  235758. }
  235759. }
  235760. return total;
  235761. }
  235762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235763. };
  235764. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235765. {
  235766. return new CoreAudioIODeviceType();
  235767. }
  235768. #undef log
  235769. #endif
  235770. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235771. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235772. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235773. // compiled on its own).
  235774. #if JUCE_INCLUDED_FILE
  235775. #if JUCE_MAC
  235776. namespace CoreMidiHelpers
  235777. {
  235778. bool logError (const OSStatus err, const int lineNum)
  235779. {
  235780. if (err == noErr)
  235781. return true;
  235782. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235783. jassertfalse;
  235784. return false;
  235785. }
  235786. #undef CHECK_ERROR
  235787. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235788. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235789. {
  235790. String result;
  235791. CFStringRef str = 0;
  235792. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235793. if (str != 0)
  235794. {
  235795. result = PlatformUtilities::cfStringToJuceString (str);
  235796. CFRelease (str);
  235797. str = 0;
  235798. }
  235799. MIDIEntityRef entity = 0;
  235800. MIDIEndpointGetEntity (endpoint, &entity);
  235801. if (entity == 0)
  235802. return result; // probably virtual
  235803. if (result.isEmpty())
  235804. {
  235805. // endpoint name has zero length - try the entity
  235806. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235807. if (str != 0)
  235808. {
  235809. result += PlatformUtilities::cfStringToJuceString (str);
  235810. CFRelease (str);
  235811. str = 0;
  235812. }
  235813. }
  235814. // now consider the device's name
  235815. MIDIDeviceRef device = 0;
  235816. MIDIEntityGetDevice (entity, &device);
  235817. if (device == 0)
  235818. return result;
  235819. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235820. if (str != 0)
  235821. {
  235822. const String s (PlatformUtilities::cfStringToJuceString (str));
  235823. CFRelease (str);
  235824. // if an external device has only one entity, throw away
  235825. // the endpoint name and just use the device name
  235826. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235827. {
  235828. result = s;
  235829. }
  235830. else if (! result.startsWithIgnoreCase (s))
  235831. {
  235832. // prepend the device name to the entity name
  235833. result = (s + " " + result).trimEnd();
  235834. }
  235835. }
  235836. return result;
  235837. }
  235838. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235839. {
  235840. String result;
  235841. // Does the endpoint have connections?
  235842. CFDataRef connections = 0;
  235843. int numConnections = 0;
  235844. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235845. if (connections != 0)
  235846. {
  235847. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235848. if (numConnections > 0)
  235849. {
  235850. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235851. for (int i = 0; i < numConnections; ++i, ++pid)
  235852. {
  235853. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235854. MIDIObjectRef connObject;
  235855. MIDIObjectType connObjectType;
  235856. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235857. if (err == noErr)
  235858. {
  235859. String s;
  235860. if (connObjectType == kMIDIObjectType_ExternalSource
  235861. || connObjectType == kMIDIObjectType_ExternalDestination)
  235862. {
  235863. // Connected to an external device's endpoint (10.3 and later).
  235864. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235865. }
  235866. else
  235867. {
  235868. // Connected to an external device (10.2) (or something else, catch-all)
  235869. CFStringRef str = 0;
  235870. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235871. if (str != 0)
  235872. {
  235873. s = PlatformUtilities::cfStringToJuceString (str);
  235874. CFRelease (str);
  235875. }
  235876. }
  235877. if (s.isNotEmpty())
  235878. {
  235879. if (result.isNotEmpty())
  235880. result += ", ";
  235881. result += s;
  235882. }
  235883. }
  235884. }
  235885. }
  235886. CFRelease (connections);
  235887. }
  235888. if (result.isNotEmpty())
  235889. return result;
  235890. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235891. return getEndpointName (endpoint, false);
  235892. }
  235893. MIDIClientRef getGlobalMidiClient()
  235894. {
  235895. static MIDIClientRef globalMidiClient = 0;
  235896. if (globalMidiClient == 0)
  235897. {
  235898. String name ("JUCE");
  235899. if (JUCEApplication::getInstance() != 0)
  235900. name = JUCEApplication::getInstance()->getApplicationName();
  235901. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235902. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235903. CFRelease (appName);
  235904. }
  235905. return globalMidiClient;
  235906. }
  235907. class MidiPortAndEndpoint
  235908. {
  235909. public:
  235910. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235911. : port (port_), endPoint (endPoint_)
  235912. {
  235913. }
  235914. ~MidiPortAndEndpoint()
  235915. {
  235916. if (port != 0)
  235917. MIDIPortDispose (port);
  235918. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235919. MIDIEndpointDispose (endPoint);
  235920. }
  235921. void send (const MIDIPacketList* const packets)
  235922. {
  235923. if (port != 0)
  235924. MIDISend (port, endPoint, packets);
  235925. else
  235926. MIDIReceived (endPoint, packets);
  235927. }
  235928. MIDIPortRef port;
  235929. MIDIEndpointRef endPoint;
  235930. };
  235931. class MidiPortAndCallback;
  235932. CriticalSection callbackLock;
  235933. Array<MidiPortAndCallback*> activeCallbacks;
  235934. class MidiPortAndCallback
  235935. {
  235936. public:
  235937. MidiPortAndCallback (MidiInputCallback& callback_)
  235938. : input (0), active (false), callback (callback_), concatenator (2048)
  235939. {
  235940. }
  235941. ~MidiPortAndCallback()
  235942. {
  235943. active = false;
  235944. {
  235945. const ScopedLock sl (callbackLock);
  235946. activeCallbacks.removeValue (this);
  235947. }
  235948. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235949. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235950. }
  235951. void handlePackets (const MIDIPacketList* const pktlist)
  235952. {
  235953. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235954. const ScopedLock sl (callbackLock);
  235955. if (activeCallbacks.contains (this) && active)
  235956. {
  235957. const MIDIPacket* packet = &pktlist->packet[0];
  235958. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235959. {
  235960. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235961. input, callback);
  235962. packet = MIDIPacketNext (packet);
  235963. }
  235964. }
  235965. }
  235966. MidiInput* input;
  235967. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235968. volatile bool active;
  235969. private:
  235970. MidiInputCallback& callback;
  235971. MidiDataConcatenator concatenator;
  235972. };
  235973. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235974. {
  235975. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235976. }
  235977. }
  235978. const StringArray MidiOutput::getDevices()
  235979. {
  235980. StringArray s;
  235981. const ItemCount num = MIDIGetNumberOfDestinations();
  235982. for (ItemCount i = 0; i < num; ++i)
  235983. {
  235984. MIDIEndpointRef dest = MIDIGetDestination (i);
  235985. if (dest != 0)
  235986. {
  235987. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235988. if (name.isEmpty())
  235989. name = "<error>";
  235990. s.add (name);
  235991. }
  235992. else
  235993. {
  235994. s.add ("<error>");
  235995. }
  235996. }
  235997. return s;
  235998. }
  235999. int MidiOutput::getDefaultDeviceIndex()
  236000. {
  236001. return 0;
  236002. }
  236003. MidiOutput* MidiOutput::openDevice (int index)
  236004. {
  236005. MidiOutput* mo = 0;
  236006. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  236007. {
  236008. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236009. CFStringRef pname;
  236010. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236011. {
  236012. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236013. MIDIPortRef port;
  236014. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236015. {
  236016. mo = new MidiOutput();
  236017. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236018. }
  236019. CFRelease (pname);
  236020. }
  236021. }
  236022. return mo;
  236023. }
  236024. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236025. {
  236026. MidiOutput* mo = 0;
  236027. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236028. MIDIEndpointRef endPoint;
  236029. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236030. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236031. {
  236032. mo = new MidiOutput();
  236033. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236034. }
  236035. CFRelease (name);
  236036. return mo;
  236037. }
  236038. MidiOutput::~MidiOutput()
  236039. {
  236040. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236041. }
  236042. void MidiOutput::reset()
  236043. {
  236044. }
  236045. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236046. {
  236047. return false;
  236048. }
  236049. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236050. {
  236051. }
  236052. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236053. {
  236054. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236055. if (message.isSysEx())
  236056. {
  236057. const int maxPacketSize = 256;
  236058. int pos = 0, bytesLeft = message.getRawDataSize();
  236059. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236060. HeapBlock <MIDIPacketList> packets;
  236061. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236062. packets->numPackets = numPackets;
  236063. MIDIPacket* p = packets->packet;
  236064. for (int i = 0; i < numPackets; ++i)
  236065. {
  236066. p->timeStamp = 0;
  236067. p->length = jmin (maxPacketSize, bytesLeft);
  236068. memcpy (p->data, message.getRawData() + pos, p->length);
  236069. pos += p->length;
  236070. bytesLeft -= p->length;
  236071. p = MIDIPacketNext (p);
  236072. }
  236073. mpe->send (packets);
  236074. }
  236075. else
  236076. {
  236077. MIDIPacketList packets;
  236078. packets.numPackets = 1;
  236079. packets.packet[0].timeStamp = 0;
  236080. packets.packet[0].length = message.getRawDataSize();
  236081. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236082. mpe->send (&packets);
  236083. }
  236084. }
  236085. const StringArray MidiInput::getDevices()
  236086. {
  236087. StringArray s;
  236088. const ItemCount num = MIDIGetNumberOfSources();
  236089. for (ItemCount i = 0; i < num; ++i)
  236090. {
  236091. MIDIEndpointRef source = MIDIGetSource (i);
  236092. if (source != 0)
  236093. {
  236094. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236095. if (name.isEmpty())
  236096. name = "<error>";
  236097. s.add (name);
  236098. }
  236099. else
  236100. {
  236101. s.add ("<error>");
  236102. }
  236103. }
  236104. return s;
  236105. }
  236106. int MidiInput::getDefaultDeviceIndex()
  236107. {
  236108. return 0;
  236109. }
  236110. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236111. {
  236112. jassert (callback != 0);
  236113. using namespace CoreMidiHelpers;
  236114. MidiInput* newInput = 0;
  236115. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236116. {
  236117. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236118. if (endPoint != 0)
  236119. {
  236120. CFStringRef name;
  236121. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236122. {
  236123. MIDIClientRef client = getGlobalMidiClient();
  236124. if (client != 0)
  236125. {
  236126. MIDIPortRef port;
  236127. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236128. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236129. {
  236130. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236131. {
  236132. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236133. newInput = new MidiInput (getDevices() [index]);
  236134. mpc->input = newInput;
  236135. newInput->internal = mpc;
  236136. const ScopedLock sl (callbackLock);
  236137. activeCallbacks.add (mpc.release());
  236138. }
  236139. else
  236140. {
  236141. CHECK_ERROR (MIDIPortDispose (port));
  236142. }
  236143. }
  236144. }
  236145. }
  236146. CFRelease (name);
  236147. }
  236148. }
  236149. return newInput;
  236150. }
  236151. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236152. {
  236153. jassert (callback != 0);
  236154. using namespace CoreMidiHelpers;
  236155. MidiInput* mi = 0;
  236156. MIDIClientRef client = getGlobalMidiClient();
  236157. if (client != 0)
  236158. {
  236159. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236160. mpc->active = false;
  236161. MIDIEndpointRef endPoint;
  236162. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236163. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236164. {
  236165. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236166. mi = new MidiInput (deviceName);
  236167. mpc->input = mi;
  236168. mi->internal = mpc;
  236169. const ScopedLock sl (callbackLock);
  236170. activeCallbacks.add (mpc.release());
  236171. }
  236172. CFRelease (name);
  236173. }
  236174. return mi;
  236175. }
  236176. MidiInput::MidiInput (const String& name_)
  236177. : name (name_)
  236178. {
  236179. }
  236180. MidiInput::~MidiInput()
  236181. {
  236182. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236183. }
  236184. void MidiInput::start()
  236185. {
  236186. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236187. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236188. }
  236189. void MidiInput::stop()
  236190. {
  236191. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236192. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236193. }
  236194. #undef CHECK_ERROR
  236195. #else // Stubs for iOS...
  236196. MidiOutput::~MidiOutput() {}
  236197. void MidiOutput::reset() {}
  236198. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236199. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236200. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236201. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236202. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236203. const StringArray MidiInput::getDevices() { return StringArray(); }
  236204. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236205. #endif
  236206. #endif
  236207. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236208. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236209. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236210. // compiled on its own).
  236211. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236212. #if ! JUCE_QUICKTIME
  236213. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236214. #endif
  236215. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236216. class QTCameraDeviceInteral;
  236217. END_JUCE_NAMESPACE
  236218. @interface QTCaptureCallbackDelegate : NSObject
  236219. {
  236220. @public
  236221. CameraDevice* owner;
  236222. QTCameraDeviceInteral* internal;
  236223. int64 firstPresentationTime;
  236224. int64 averageTimeOffset;
  236225. }
  236226. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236227. - (void) dealloc;
  236228. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236229. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236230. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236231. fromConnection: (QTCaptureConnection*) connection;
  236232. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236233. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236234. fromConnection: (QTCaptureConnection*) connection;
  236235. @end
  236236. BEGIN_JUCE_NAMESPACE
  236237. class QTCameraDeviceInteral
  236238. {
  236239. public:
  236240. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236241. {
  236242. const ScopedAutoReleasePool pool;
  236243. session = [[QTCaptureSession alloc] init];
  236244. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236245. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236246. input = 0;
  236247. audioInput = 0;
  236248. audioDevice = 0;
  236249. fileOutput = 0;
  236250. imageOutput = 0;
  236251. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236252. internalDev: this];
  236253. NSError* err = 0;
  236254. [device retain];
  236255. [device open: &err];
  236256. if (err == 0)
  236257. {
  236258. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236259. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236260. [session addInput: input error: &err];
  236261. if (err == 0)
  236262. {
  236263. resetFile();
  236264. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236265. [imageOutput setDelegate: callbackDelegate];
  236266. if (err == 0)
  236267. {
  236268. [session startRunning];
  236269. return;
  236270. }
  236271. }
  236272. }
  236273. openingError = nsStringToJuce ([err description]);
  236274. DBG (openingError);
  236275. }
  236276. ~QTCameraDeviceInteral()
  236277. {
  236278. [session stopRunning];
  236279. [session removeOutput: imageOutput];
  236280. [session release];
  236281. [input release];
  236282. [device release];
  236283. [audioDevice release];
  236284. [audioInput release];
  236285. [fileOutput release];
  236286. [imageOutput release];
  236287. [callbackDelegate release];
  236288. }
  236289. void resetFile()
  236290. {
  236291. [fileOutput recordToOutputFileURL: nil];
  236292. [session removeOutput: fileOutput];
  236293. [fileOutput release];
  236294. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236295. [session removeInput: audioInput];
  236296. [audioInput release];
  236297. audioInput = 0;
  236298. [audioDevice release];
  236299. audioDevice = 0;
  236300. [fileOutput setDelegate: callbackDelegate];
  236301. }
  236302. void addDefaultAudioInput()
  236303. {
  236304. NSError* err = nil;
  236305. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236306. if ([audioDevice open: &err])
  236307. [audioDevice retain];
  236308. else
  236309. audioDevice = nil;
  236310. if (audioDevice != 0)
  236311. {
  236312. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236313. [session addInput: audioInput error: &err];
  236314. }
  236315. }
  236316. void addListener (CameraDevice::Listener* listenerToAdd)
  236317. {
  236318. const ScopedLock sl (listenerLock);
  236319. if (listeners.size() == 0)
  236320. [session addOutput: imageOutput error: nil];
  236321. listeners.addIfNotAlreadyThere (listenerToAdd);
  236322. }
  236323. void removeListener (CameraDevice::Listener* listenerToRemove)
  236324. {
  236325. const ScopedLock sl (listenerLock);
  236326. listeners.removeValue (listenerToRemove);
  236327. if (listeners.size() == 0)
  236328. [session removeOutput: imageOutput];
  236329. }
  236330. void callListeners (CIImage* frame, int w, int h)
  236331. {
  236332. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236333. Image image (cgImage);
  236334. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236335. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236336. CGContextFlush (cgImage->context);
  236337. const ScopedLock sl (listenerLock);
  236338. for (int i = listeners.size(); --i >= 0;)
  236339. {
  236340. CameraDevice::Listener* const l = listeners[i];
  236341. if (l != 0)
  236342. l->imageReceived (image);
  236343. }
  236344. }
  236345. QTCaptureDevice* device;
  236346. QTCaptureDeviceInput* input;
  236347. QTCaptureDevice* audioDevice;
  236348. QTCaptureDeviceInput* audioInput;
  236349. QTCaptureSession* session;
  236350. QTCaptureMovieFileOutput* fileOutput;
  236351. QTCaptureDecompressedVideoOutput* imageOutput;
  236352. QTCaptureCallbackDelegate* callbackDelegate;
  236353. String openingError;
  236354. Array<CameraDevice::Listener*> listeners;
  236355. CriticalSection listenerLock;
  236356. };
  236357. END_JUCE_NAMESPACE
  236358. @implementation QTCaptureCallbackDelegate
  236359. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236360. internalDev: (QTCameraDeviceInteral*) d
  236361. {
  236362. [super init];
  236363. owner = owner_;
  236364. internal = d;
  236365. firstPresentationTime = 0;
  236366. averageTimeOffset = 0;
  236367. return self;
  236368. }
  236369. - (void) dealloc
  236370. {
  236371. [super dealloc];
  236372. }
  236373. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236374. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236375. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236376. fromConnection: (QTCaptureConnection*) connection
  236377. {
  236378. if (internal->listeners.size() > 0)
  236379. {
  236380. const ScopedAutoReleasePool pool;
  236381. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236382. CVPixelBufferGetWidth (videoFrame),
  236383. CVPixelBufferGetHeight (videoFrame));
  236384. }
  236385. }
  236386. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236387. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236388. fromConnection: (QTCaptureConnection*) connection
  236389. {
  236390. const Time now (Time::getCurrentTime());
  236391. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236392. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236393. #else
  236394. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236395. #endif
  236396. int64 presentationTime = (hosttime != nil)
  236397. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236398. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236399. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236400. if (firstPresentationTime == 0)
  236401. {
  236402. firstPresentationTime = presentationTime;
  236403. averageTimeOffset = timeDiff;
  236404. }
  236405. else
  236406. {
  236407. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236408. }
  236409. }
  236410. @end
  236411. BEGIN_JUCE_NAMESPACE
  236412. class QTCaptureViewerComp : public NSViewComponent
  236413. {
  236414. public:
  236415. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236416. {
  236417. const ScopedAutoReleasePool pool;
  236418. captureView = [[QTCaptureView alloc] init];
  236419. [captureView setCaptureSession: internal->session];
  236420. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236421. setView (captureView);
  236422. }
  236423. ~QTCaptureViewerComp()
  236424. {
  236425. setView (0);
  236426. [captureView setCaptureSession: nil];
  236427. [captureView release];
  236428. }
  236429. QTCaptureView* captureView;
  236430. };
  236431. CameraDevice::CameraDevice (const String& name_, int index)
  236432. : name (name_)
  236433. {
  236434. isRecording = false;
  236435. internal = new QTCameraDeviceInteral (this, index);
  236436. }
  236437. CameraDevice::~CameraDevice()
  236438. {
  236439. stopRecording();
  236440. delete static_cast <QTCameraDeviceInteral*> (internal);
  236441. internal = 0;
  236442. }
  236443. Component* CameraDevice::createViewerComponent()
  236444. {
  236445. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236446. }
  236447. const String CameraDevice::getFileExtension()
  236448. {
  236449. return ".mov";
  236450. }
  236451. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236452. {
  236453. stopRecording();
  236454. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236455. d->callbackDelegate->firstPresentationTime = 0;
  236456. file.deleteFile();
  236457. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236458. // out wrong, so we'll put some audio in there too..,
  236459. d->addDefaultAudioInput();
  236460. [d->session addOutput: d->fileOutput error: nil];
  236461. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236462. for (;;)
  236463. {
  236464. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236465. if (connection == 0)
  236466. break;
  236467. QTCompressionOptions* options = 0;
  236468. NSString* mediaType = [connection mediaType];
  236469. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236470. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236471. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236472. : @"QTCompressionOptions240SizeH264Video"];
  236473. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236474. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236475. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236476. }
  236477. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236478. isRecording = true;
  236479. }
  236480. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236481. {
  236482. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236483. if (d->callbackDelegate->firstPresentationTime != 0)
  236484. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236485. return Time();
  236486. }
  236487. void CameraDevice::stopRecording()
  236488. {
  236489. if (isRecording)
  236490. {
  236491. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236492. isRecording = false;
  236493. }
  236494. }
  236495. void CameraDevice::addListener (Listener* listenerToAdd)
  236496. {
  236497. if (listenerToAdd != 0)
  236498. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236499. }
  236500. void CameraDevice::removeListener (Listener* listenerToRemove)
  236501. {
  236502. if (listenerToRemove != 0)
  236503. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236504. }
  236505. const StringArray CameraDevice::getAvailableDevices()
  236506. {
  236507. const ScopedAutoReleasePool pool;
  236508. StringArray results;
  236509. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236510. for (int i = 0; i < (int) [devs count]; ++i)
  236511. {
  236512. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236513. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236514. }
  236515. return results;
  236516. }
  236517. CameraDevice* CameraDevice::openDevice (int index,
  236518. int minWidth, int minHeight,
  236519. int maxWidth, int maxHeight)
  236520. {
  236521. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236522. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236523. return d.release();
  236524. return 0;
  236525. }
  236526. #endif
  236527. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236528. #endif
  236529. #endif
  236530. END_JUCE_NAMESPACE
  236531. #endif
  236532. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236533. #endif
  236534. #endif